Open History to see the last commit
1// Generate a seed script
2
3import { generateKeyBetween } from "fractional-indexing";
4import { nanoid } from "nanoid";
5import { db } from ".";
6import {
7 type BoardRecord,
8 boardsTable,
9 type ProjectRecord,
10 projectsTable,
11 seedTable,
12 type TodoItemRecord,
13 todoItemsTable,
14 type UserRecord,
15 usersTable,
16} from "./schema";
17
18type BoardName = "Todo" | "In Progress" | "Done";
19type TodoItemBase = Omit<
20 TodoItemRecord,
21 "id" | "boardId" | "projectId" | "tempDbId" | "createdAt"
22> & { boardName: BoardName };
23
24type ProjectBase = ProjectRecord & {
25 todoItemsBaseArr: TodoItemBase[];
26};
27
28function* createNextFractionalIndexGenerator(): Generator<string | null> {
29 let prev: null | string = null;
30
31 while (true) {
32 prev = generateKeyBetween(prev, null);
33 yield prev;
34 }
35}
36
37const boardGenerators: Record<string, Generator<string | null>> = {};
38
39function getNextPosition(boardId: string): string {
40 if (!boardGenerators[boardId]) {
41 boardGenerators[boardId] = createNextFractionalIndexGenerator();
42 }
43 return boardGenerators[boardId].next().value as string;
44}
45
46const todoItemsList: TodoItemBase[] = [
47 // Todo board
48 {
49 title: "Buy groceries",
50 description: "Milk, eggs, bread",
51 boardName: "Todo",
52 priority: 3,
53 position: getNextPosition("board-1-todo"),
54 },
55 {
56 title: "Read a book",
57 description: "Finish reading 'Atomic Habits'",
58 boardName: "Todo",
59 priority: 0,
60 position: getNextPosition("board-1-todo"),
61 },
62 // In Progress board
63 {
64 title: "Write blog post",
65 description: "Draft for tech blog",
66 boardName: "In Progress",
67 priority: 2,
68 position: getNextPosition("board-1-in-progress"),
69 },
70 {
71 title: "Workout",
72 description: "30 min cardio",
73 boardName: "In Progress",
74 priority: 0,
75 position: getNextPosition("board-1-in-progress"),
76 },
77 {
78 title: "Update resume",
79 description: "Add recent projects",
80 boardName: "In Progress",
81 priority: 0,
82 position: getNextPosition("board-1-in-progress"),
83 },
84 // Done board
85 {
86 title: "Call mom",
87 description: "Weekly check-in",
88 boardName: "Done",
89 priority: 0,
90 position: getNextPosition("board-1-done"),
91 },
92 {
93 title: "Clean desk",
94 description: "Organize workspace",
95 boardName: "Done",
96 priority: 0,
97 position: getNextPosition("board-1-done"),
98 },
99];
100
101const anotherTodoItemsList: TodoItemBase[] = [
102 {
103 title: "Plan vacation",
104 description: "Research destinations and flights",
105 boardName: "Todo",
106 priority: 2,
107 position: getNextPosition("board-2-todo"),
108 },
109 // In Progress board
110 {
111 title: "Schedule dentist appointment",
112 description: "Call clinic for available slots",
113 boardName: "In Progress",
114 priority: 1,
115 position: getNextPosition("board-2-in-progress"),
116 },
117 // Done board
118 {
119 title: "Learn TypeScript",
120 description: "Complete online course modules",
121 boardName: "Done",
122 priority: 3,
123 position: getNextPosition("board-2-done"),
124 },
125 {
126 title: "Organize photos",
127 description: "Sort and backup recent pictures",
128 boardName: "Done",
129 priority: 2,
130 position: getNextPosition("board-2-done"),
131 },
132 {
133 title: "Prepare presentation",
134 description: "Create slides for team meeting",
135 boardName: "Done",
136 priority: 1,
137 position: getNextPosition("board-2-done"),
138 },
139 {
140 title: "Renew library card",
141 description: "Completed renewal online",
142 boardName: "Done",
143 priority: 0,
144 position: getNextPosition("board-2-done"),
145 },
146 {
147 title: "Fix leaky faucet",
148 description: "Replaced washer and tested",
149 boardName: "Done",
150 priority: 0,
151 position: getNextPosition("board-2-done"),
152 },
153];
154
155const largeTodoItemsList: TodoItemBase[] = Array.from({
156 length: 1000,
157}).map((_, index) => {
158 const boardName = (["Todo", "In Progress", "Done"] satisfies BoardName[])[
159 Math.floor(Math.random() * 10) % 3
160 ];
161
162 return {
163 title: `Task ${index + 1}`,
164 description: `Description for task ${index + 1}`,
165 boardName,
166 priority: 0,
167 position: getNextPosition(`large-project-board-${boardName}`),
168 };
169});
170
171function getMockBoardsAndTodoItemsForProject({
172 projectId,
173 now,
174 todoItemBaseArr,
175}: {
176 projectId: ProjectRecord["id"];
177 now: Date;
178 todoItemBaseArr: TodoItemBase[];
179}): {
180 mockBoards: BoardRecord[];
181 mockTodoItems: TodoItemRecord[];
182} {
183 const boardIds: Record<BoardName, string> = {
184 Todo: nanoid(),
185 Done: nanoid(),
186 "In Progress": nanoid(),
187 };
188
189 const boards: BoardRecord[] = [
190 {
191 id: boardIds.Todo,
192 projectId,
193 name: "Todo",
194 description: "Tasks to do",
195 createdAt: now,
196 },
197 {
198 id: boardIds["In Progress"],
199 projectId,
200 name: "In Progress",
201 description: "Tasks in progress",
202 createdAt: now,
203 },
204 {
205 id: boardIds.Done,
206 projectId,
207 name: "Done",
208 description: "Completed tasks",
209 createdAt: now,
210 },
211 ];
212
213 const todoItems: TodoItemRecord[] = todoItemBaseArr.map(
214 ({ boardName, ...item }) => ({
215 ...item,
216 id: nanoid(),
217 boardId: boardIds[boardName],
218 projectId,
219 createdAt: now,
220 }),
221 );
222
223 return { mockBoards: boards, mockTodoItems: todoItems };
224}
225
226function getMockData() {
227 const mockUsers: UserRecord[] = [
228 {
229 id: nanoid(),
230 name: "Alice Smith",
231 age: 28,
232 email: "alice@example.com",
233 },
234 {
235 id: nanoid(),
236 name: "Bob Johnson",
237 age: 35,
238 email: "bob@example.com",
239 },
240 {
241 id: nanoid(),
242 name: "Charlie Lee",
243 age: 22,
244 email: "charlie@example.com",
245 },
246 {
247 id: nanoid(),
248 name: "John Doe",
249 age: 25,
250 email: "john@doe.com",
251 },
252 ];
253
254 const now = new Date();
255
256 const mockProjects: ProjectBase[] = [
257 {
258 id: "aQLI4Nzvmls31l4aep9LqnU", // these are 2 chars longer than nanoid default
259 name: "Project Alpha",
260 description: "First project description",
261 createdAt: new Date(now.getTime() - 2 * 24 * 60 * 60 * 1000), // 2 days ago
262 todoItemsBaseArr: todoItemsList,
263 },
264 {
265 id: "bMv-_1QjNWdfdoZrRp_XmAM",
266 name: "Project Beta",
267 description: "Second project description",
268 createdAt: new Date(now.getTime() - 24 * 60 * 60 * 1000), // 1 day ago
269 todoItemsBaseArr: anotherTodoItemsList,
270 },
271 {
272 id: "cmUxqWMcQ12A0FwfIUEaCa5",
273 name: "Large Project",
274 description: "A large project with a lot of items",
275 createdAt: now,
276 todoItemsBaseArr: largeTodoItemsList,
277 },
278 ];
279
280 const { boards: mockBoards, todoItems: mockTodoItems } = mockProjects
281 .map((project) =>
282 getMockBoardsAndTodoItemsForProject({
283 projectId: project.id,
284 now,
285 todoItemBaseArr: project.todoItemsBaseArr,
286 }),
287 )
288 .reduce(
289 (acc, { mockBoards, mockTodoItems }) => {
290 acc.boards.push(...mockBoards);
291 acc.todoItems.push(...mockTodoItems);
292 return acc;
293 },
294 { boards: [] as BoardRecord[], todoItems: [] as TodoItemRecord[] },
295 );
296
297 return {
298 mockUsers,
299 mockBoards,
300 mockTodoItems,
301 mockProjects,
302 };
303}
304
305// TODO: make it possible to reset the tables
306// async function cleanAllTables() {
307// // Get all user tables
308// const tables = await db.execute(
309// sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT IN ('sqlite_sequence', 'd1_migrations', '_cf_METADATA');`,
310// );
311//
312// for (const { name } of tables) {
313// await db.execute(`DELETE FROM "${name}";`);
314// }
315// console.log("All tables have been cleaned up.");
316// }
317
318export async function seed() {
319 // Make sure the seed script has not been executed before
320 const [existingSeed] = await db.select().from(seedTable).limit(1);
321
322 if (existingSeed) {
323 const [firstProjectId] = await db
324 .select({ id: projectsTable.id })
325 .from(projectsTable)
326 .limit(1);
327 return {
328 firstProjectId: firstProjectId.id,
329 };
330 }
331
332 const { mockUsers, mockBoards, mockTodoItems, mockProjects } = getMockData();
333
334 /*
335 NOTE: transactions are not supported in D1 (https://github.com/drizzle-team/drizzle-orm/issues/2463)
336 use batch API: https://github.com/drizzle-team/drizzle-orm/issues/2463#issuecomment-2155864439
337 no support planned: https://github.com/cloudflare/workers-sdk/issues/2733#issuecomment-271236533
338 */
339 try {
340 await db.transaction(async (tx) => {
341 const seedScriptId = nanoid();
342 await tx.insert(seedTable).values({
343 id: seedScriptId,
344 createdAt: new Date(),
345 state: "in_progress",
346 });
347 await tx.insert(usersTable).values(mockUsers);
348 await tx.insert(projectsTable).values(mockProjects);
349 await tx.insert(boardsTable).values(mockBoards);
350
351 await tx.insert(todoItemsTable).values(mockTodoItems);
352
353 await tx.update(seedTable).set({
354 id: seedScriptId,
355 state: "completed",
356 });
357 });
358
359 return {
360 firstProjectId: mockProjects[0].id,
361 };
362 } catch (error) {
363 console.error("Error during seeding:", error);
364 throw error;
365 }
366}
367
368export async function resetAndSeed() {
369 try {
370 // Find all tables in the database
371 const tablesResult = await db.execute<{ tablename: string }>(
372 `SELECT tablename FROM pg_tables WHERE schemaname = 'public'`,
373 );
374
375 console.log(`Found ${tablesResult.rows.length} tables to clear.`);
376
377 // Delete all records from each table (except drizzle_migrations)
378 for (const { tablename } of tablesResult.rows) {
379 if (tablename === "drizzle_migrations") {
380 console.log(`Skipping table: ${tablename}`);
381 continue;
382 }
383 await db.execute(`DELETE FROM "${tablename}"`);
384 console.log(`Cleared table: ${tablename}`);
385 }
386
387 console.log("All tables have been cleared.");
388
389 // Run the seed function
390 const result = await seed();
391 console.log("Database has been reseeded successfully.");
392
393 return result;
394 } catch (error) {
395 console.error("Error during reset and seed:", error);
396 throw error;
397 }
398}