Skip to content

Commit 652012c

Browse files
authored
Merge pull request #29 from CS3219-AY2425S1/seed-question-data
Chore(Milestone-2): Seed question data
2 parents 82be7fd + f0d6ab1 commit 652012c

File tree

17 files changed

+321
-20
lines changed

17 files changed

+321
-20
lines changed

Makefile

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
setup:
22
./scripts/install-deps.sh
3+
./scripts/ensure-volume.sh
4+
./scripts/migrate-seed-databases.sh
35

46
db-up:
57
./scripts/ensure-volume.sh
File renamed without changes.

backend/question/drizzle/meta/_journal.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
"idx": 0,
77
"version": "7",
88
"when": 1727595727110,
9-
"tag": "0000_bizarre_midnight",
9+
"tag": "0000_initial_schema",
1010
"breakpoints": true
1111
}
1212
]

backend/question/package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@
99
"build:prod": "env-cmd -f .env.prod tsc && tsc-alias",
1010
"start:prod": "env-cmd -f .env.local node dist/index.js",
1111
"db:generate": "env-cmd -f .env.local drizzle-kit generate",
12-
"db:migrate": "env-cmd -f .env.local tsx drizzle.migrate.ts",
12+
"db:migrate": "env-cmd -f .env.local tsx ./src/lib/db/migrate.ts",
13+
"db:seed": "env-cmd -f .env.local tsx ./src/lib/db/seed.ts",
1314
"db:inspect": "env-cmd -f .env.local drizzle-kit studio",
1415
"fmt": "prettier --config .prettierrc src --write",
1516
"test": "echo \"Error: no test specified\" && exit 1"

backend/question/src/controller/question-controller.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,12 @@ import {
44
getQuestionDetailsService,
55
getRandomQuestionService,
66
searchQuestionsByTitleService,
7-
} from '../services/get/index';
8-
import {
7+
} from '@/services/get/index';
8+
import type {
99
IGetQuestionsPayload,
1010
IGetQuestionPayload,
1111
IGetRandomQuestionPayload,
12-
} from '../services/get/types';
12+
} from '@/services/get/types';
1313

1414
export const getQuestions = async (req: Request, res: Response): Promise<Response> => {
1515
const payload: IGetQuestionsPayload = {
File renamed without changes.
Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
1+
export const questionDetails = [
2+
{
3+
id: 1,
4+
title: 'Reverse a String',
5+
description:
6+
'Write a function that reverses a string. The input string is given as an array of characters `s`. You must do this by modifying the input array in-place with O(1) extra memory.\n\n**Example 1:**\n\nInput: `s = ["h","e","l","l","o"]`\n\nOutput: `["o","l","l","e","h"]`\n\n**Example 2:**\n\nInput: `s = ["H","a","n","n","a","h"]`\n\nOutput: `["h","a","n","n","a","H"]`\n\n**Constraints:**\n\n* `1 <= s.length <= 105`\n\n* `s[i]` is a printable ASCII character.',
7+
topics: ['Strings', 'Algorithms'],
8+
difficulty: 'Easy',
9+
leetcode: 'https://leetcode.com/problems/reverse-string/',
10+
},
11+
{
12+
id: 2,
13+
title: 'Linked List Cycle Detection',
14+
description: 'Implement a function to detect if a linked list contains a cycle.',
15+
topics: ['Data Structures', 'Algorithms'],
16+
difficulty: 'Easy',
17+
leetcode: 'https://leetcode.com/problems/linked-list-cycle/',
18+
},
19+
{
20+
id: 3,
21+
title: 'Roman to Integer',
22+
description: 'Given a Roman numeral, convert it to an integer.',
23+
topics: ['Algorithms'],
24+
difficulty: 'Easy',
25+
leetcode: 'https://leetcode.com/problems/roman-to-integer/',
26+
},
27+
{
28+
id: 4,
29+
title: 'Add Binary',
30+
description: 'Given two binary strings `a` and `b`, return their sum as a binary string.',
31+
topics: ['Bit Manipulation', 'Algorithms'],
32+
difficulty: 'Easy',
33+
leetcode: 'https://leetcode.com/problems/add-binary/',
34+
},
35+
{
36+
id: 5,
37+
title: 'Fibonacci Number',
38+
description:
39+
'The Fibonacci numbers, commonly denoted `F(n)`, form a sequence such that each number is the sum of the two preceding ones, starting from 0 and 1. That is:\n\n* `F(0) = 0`, `F(1) = 1`\n\n* `F(n) = F(n - 1) + F(n - 2)`, for `n > 1`\n\nGiven `n`, calculate `F(n)`.',
40+
topics: ['Recursion', 'Algorithms'],
41+
difficulty: 'Easy',
42+
leetcode: 'https://leetcode.com/problems/fibonacci-number/',
43+
},
44+
{
45+
id: 6,
46+
title: 'Implement Stack using Queues',
47+
description:
48+
'Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).',
49+
topics: ['Data Structures'],
50+
difficulty: 'Easy',
51+
leetcode: 'https://leetcode.com/problems/implement-stack-using-queues/',
52+
},
53+
{
54+
id: 7,
55+
title: 'Combine Two Tables',
56+
description:
57+
'Given table `Person` with columns `personId`, `lastName`, and `firstName`, and table `Address` with columns `addressId`, `personId`, `city`, and `state`, write a solution to report the first name, last name, city, and state of each person in the `Person` table. If the address of a `personId` is not present in the `Address` table, report `null` instead.',
58+
topics: ['Databases'],
59+
difficulty: 'Easy',
60+
leetcode: 'https://leetcode.com/problems/combine-two-tables/',
61+
},
62+
{
63+
id: 8,
64+
title: 'Repeated DNA Sequences',
65+
description:
66+
'Given a string `s` that represents a DNA sequence, return all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order.',
67+
topics: ['Algorithms', 'Bit Manipulation'],
68+
difficulty: 'Medium',
69+
leetcode: 'https://leetcode.com/problems/repeated-dna-sequences/',
70+
},
71+
{
72+
id: 9,
73+
title: 'Course Schedule',
74+
description:
75+
'There are a total of `numCourses` courses you have to take, labeled from 0 to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you must take course `bi` first if you want to take course `ai`. Return true if you can finish all courses. Otherwise, return false.',
76+
topics: ['Data Structures', 'Algorithms'],
77+
difficulty: 'Medium',
78+
leetcode: 'https://leetcode.com/problems/course-schedule/',
79+
},
80+
{
81+
id: 10,
82+
title: 'LRU Cache Design',
83+
description: 'Design and implement an LRU (Least Recently Used) cache.',
84+
topics: ['Data Structures'],
85+
difficulty: 'Medium',
86+
leetcode: 'https://leetcode.com/problems/lru-cache/',
87+
},
88+
{
89+
id: 11,
90+
title: 'Longest Common Subsequence',
91+
description:
92+
'Given two strings `text1` and `text2`, return the length of their longest common subsequence. If there is no common subsequence, return 0.\n\nA subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.\n\nFor example, "ace" is a subsequence of "abcde". A common subsequence of two strings is a subsequence that is common to both strings.',
93+
topics: ['Strings', 'Algorithms'],
94+
difficulty: 'Medium',
95+
leetcode: 'https://leetcode.com/problems/longest-common-subsequence/',
96+
},
97+
{
98+
id: 12,
99+
title: 'Rotate Image',
100+
description:
101+
'You are given an `n x n` 2D matrix representing an image, rotate the image by 90 degrees (clockwise).',
102+
topics: ['Arrays', 'Algorithms'],
103+
difficulty: 'Medium',
104+
leetcode: 'https://leetcode.com/problems/rotate-image/',
105+
},
106+
{
107+
id: 13,
108+
title: 'Airplane Seat Assignment Probability',
109+
description:
110+
'n passengers board an airplane with exactly n seats. The first passenger has lost the ticket and picks a seat randomly. After that, the rest of the passengers will:\n\n- Take their own seat if it is still available\n- Pick other seats randomly when they find their seat occupied\n\nReturn the probability that the nth person gets their own seat.',
111+
topics: ['Brainteaser'],
112+
difficulty: 'Medium',
113+
leetcode: 'https://leetcode.com/problems/airplane-seat-assignment-probability/',
114+
},
115+
{
116+
id: 14,
117+
title: 'Validate Binary Search Tree',
118+
description:
119+
'Given the root of a binary tree, determine if it is a valid binary search tree (BST).',
120+
topics: ['Data Structures', 'Algorithms'],
121+
difficulty: 'Medium',
122+
leetcode: 'https://leetcode.com/problems/validate-binary-search-tree/',
123+
},
124+
{
125+
id: 15,
126+
title: 'Sliding Window Maximum',
127+
description:
128+
'You are given an array of integers `nums`. There is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window moves right by one position.\n\nReturn the max sliding window.',
129+
topics: ['Arrays', 'Algorithms'],
130+
difficulty: 'Hard',
131+
leetcode: 'https://leetcode.com/problems/sliding-window-maximum/',
132+
},
133+
{
134+
id: 16,
135+
title: 'N-Queen Problem',
136+
description:
137+
"The n-queens puzzle is the problem of placing n queens on an `n x n` chessboard such that no two queens attack each other.\n\nGiven an integer `n`, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.\n\nEach solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.",
138+
topics: ['Algorithms'],
139+
difficulty: 'Hard',
140+
leetcode: 'https://leetcode.com/problems/n-queens/',
141+
},
142+
{
143+
id: 17,
144+
title: 'Serialize and Deserialize a Binary Tree',
145+
description:
146+
'Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer or transmitted across a network connection link to be reconstructed later in the same or another computer environment.\n\nDesign an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.',
147+
topics: ['Data Structures', 'Algorithms'],
148+
difficulty: 'Hard',
149+
leetcode: 'https://leetcode.com/problems/serialize-and-deserialize-binary-tree/',
150+
},
151+
{
152+
id: 18,
153+
title: 'Wildcard Matching',
154+
description:
155+
"Given an input string `s` and a pattern `p`, implement wildcard pattern matching with support for '?' and '*' where:\n\n- '?' Matches any single character\n- '*' Matches any sequence of characters (including the empty sequence)\n\nThe matching should cover the entire input string (not partial).",
156+
topics: ['Strings', 'Algorithms'],
157+
difficulty: 'Hard',
158+
leetcode: 'https://leetcode.com/problems/wildcard-matching/',
159+
},
160+
{
161+
id: 19,
162+
title: 'Chalkboard XOR Game',
163+
description:
164+
'You are given an array of integers `nums` representing the numbers written on a chalkboard. Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become 0, then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0.\n\nAlso, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to 0, then that player wins.\n\nReturn `true` if and only if Alice wins the game, assuming both players play optimally.',
165+
topics: ['Brainteaser'],
166+
difficulty: 'Hard',
167+
leetcode: 'https://leetcode.com/problems/chalkboard-xor-game/',
168+
},
169+
{
170+
id: 20,
171+
title: 'Trips and Users',
172+
description:
173+
"Given table `Trips` with columns `id`, `client_id`, `driver_id`, `city_id`, `status`, and `request_at`, where `id` is the primary key. The table holds all taxi trips. Each trip has a unique `id`, while `client_id` and `driver_id` are foreign keys to the `users_id` in the `Users` table.\n\nStatus is an `ENUM` (category) type of (`'completed'`, `'cancelled_by_driver'`, `'cancelled_by_client'`).\n\nGiven table `Users` with columns `users_id`, `banned`, and `role`, `users_id` is the primary key (column with unique values) for this table. The table holds all users. Each user has a unique `users_id` and `role` is an `ENUM` type of (`'client'`, `'driver'`, `'partner'`). `banned` is an `ENUM` category of type (`'Yes'`, `'No'`). The cancellation rate is computed by dividing the number of canceled (by client or driver) requests with unbanned users by the total number of requests with unbanned users on that day.\n\nWrite a solution to find the cancellation rate of requests with unbanned users (both client and driver must not be banned) each day between `\"2013-10-01\"` and `\"2013-10-03\"`. Round the cancellation rate to two decimal points.",
174+
topics: ['Databases'],
175+
difficulty: 'Hard',
176+
leetcode: 'https://leetcode.com/problems/trips-and-users/',
177+
},
178+
];
179+
180+
interface Question {
181+
title: string;
182+
difficulty: string;
183+
topic: string[];
184+
description: string;
185+
}
186+
187+
export const questionData: Question[] = questionDetails.map((question) => ({
188+
title: question.title,
189+
description: question.description,
190+
difficulty: question.difficulty as 'Easy' | 'Medium' | 'Hard',
191+
topic: question.topics,
192+
}));
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { sql } from 'drizzle-orm';
2+
3+
import { db, questions } from '@/lib/db';
4+
import { questionData } from './sample-data/questions';
5+
6+
const seedQuestions = async () => {
7+
try {
8+
await db.transaction(async (trx) => {
9+
// Delete all questions (not table)
10+
await trx.delete(questions);
11+
12+
// Reset Serial to start index 1
13+
await trx.execute(sql`
14+
SELECT setval(
15+
pg_get_serial_sequence('questions', 'id'),
16+
COALESCE(max(id) + 1, 1),
17+
false
18+
)
19+
FROM questions;
20+
`);
21+
22+
for (const question of questionData) {
23+
await trx
24+
.insert(questions)
25+
.values({ ...question, id: undefined }) // Let DB set ID
26+
.onConflictDoNothing();
27+
}
28+
});
29+
} catch (error) {
30+
console.log('[Questions]: Error seeding question data', error);
31+
process.exit(1);
32+
}
33+
};
34+
35+
void seedQuestions()
36+
.then(() => {
37+
console.log('[Questions]: Seeding completed successfully.');
38+
process.exit(0);
39+
})
40+
.catch((error) => {
41+
console.error('[Questions]: Error during seeding:', error);
42+
process.exit(1);
43+
});

backend/question/src/routes/question-routes.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
import { Router } from 'express';
2+
23
import {
34
searchQuestionsByTitle,
45
getQuestions,
56
getQuestionDetails,
67
getRandomQuestion,
7-
} from '../controller/question-controller';
8+
} from '@/controller/question-controller';
89

910
const router = Router();
1011

backend/question/src/services/get/index.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
1-
import { db } from '../../lib/db/index';
21
import { and, arrayOverlaps, eq, ilike, notInArray, sql } from 'drizzle-orm';
3-
import { questions } from '../../lib/db/schema';
4-
import {
2+
3+
import { db } from '@/lib/db/index';
4+
import { questions } from '@/lib/db/schema';
5+
6+
import type {
57
IGetQuestionsPayload,
68
IGetQuestionsResponse,
79
IGetQuestionPayload,
810
IGetQuestionResponse,
911
IGetRandomQuestionPayload,
1012
IGetRandomQuestionResponse,
11-
} from '../get/types';
13+
} from './types';
1214

1315
export const getQuestionsService = async (
1416
payload: IGetQuestionsPayload

0 commit comments

Comments
 (0)