-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.ts
More file actions
330 lines (297 loc) · 11.2 KB
/
Copy pathdatabase.ts
File metadata and controls
330 lines (297 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
import dedent from 'dedent';
import { join } from 'path';
import { writeFile } from '../../utils/writeFile.js';
import type { GeneratorOptions } from '../interface.js';
export async function generateDatabase(outputDir: string, options: GeneratorOptions): Promise<void> {
await generateSchema(outputDir, options);
await generateDbClient(outputDir, options);
await generateMigrate(outputDir, options);
await generateMigrationSql(outputDir, options);
await generateMigrationJournal(outputDir, options);
await generateDrizzleConfig(outputDir, options);
if (options.database === 'postgres' || options.database === 'mysql') {
await generateDockerCompose(outputDir, options);
}
}
async function generateSchema(outputDir: string, options: GeneratorOptions): Promise<void> {
const content = schemaContent(options.database);
await writeFile(join(outputDir, 'src/database/schema.ts'), content);
}
function schemaContent(database: GeneratorOptions['database']): string {
if (database === 'postgres') {
return dedent`
import { integer, pgTable, primaryKey, text, timestamp, varchar } from 'drizzle-orm/pg-core';
export const pipedriveTokens = pgTable(
'pipedrive_tokens',
{
pipedriveCompanyId: integer('pipedrive_company_id').notNull(),
pipedriveUserId: integer('pipedrive_user_id').notNull(),
accessToken: varchar('access_token', { length: 768 }).notNull(),
refreshToken: varchar('refresh_token', { length: 768 }).notNull(),
tokenType: varchar('token_type', { length: 50 }).notNull().default('bearer'),
accessTokenExpiresAt: timestamp('access_token_expires_at').notNull(),
refreshTokenExpiresAt: timestamp('refresh_token_expires_at').notNull(),
scope: text('scope'),
apiDomain: varchar('api_domain', { length: 255 }).notNull(),
createdAt: timestamp('created_at').notNull().defaultNow(),
updatedAt: timestamp('updated_at').notNull().defaultNow(),
},
(table) => ({
pk: primaryKey({ columns: [table.pipedriveCompanyId, table.pipedriveUserId] }),
}),
);
`;
}
if (database === 'mysql') {
return dedent`
import { int, mysqlTable, primaryKey, text, timestamp, varchar } from 'drizzle-orm/mysql-core';
export const pipedriveTokens = mysqlTable(
'pipedrive_tokens',
{
pipedriveCompanyId: int('pipedrive_company_id').notNull(),
pipedriveUserId: int('pipedrive_user_id').notNull(),
accessToken: varchar('access_token', { length: 768 }).notNull(),
refreshToken: varchar('refresh_token', { length: 768 }).notNull(),
tokenType: varchar('token_type', { length: 50 }).notNull().default('bearer'),
accessTokenExpiresAt: timestamp('access_token_expires_at').notNull(),
refreshTokenExpiresAt: timestamp('refresh_token_expires_at').notNull(),
scope: text('scope'),
apiDomain: varchar('api_domain', { length: 255 }).notNull(),
createdAt: timestamp('created_at').notNull().defaultNow(),
updatedAt: timestamp('updated_at').notNull().defaultNow(),
},
(table) => ({
pk: primaryKey({ columns: [table.pipedriveCompanyId, table.pipedriveUserId] }),
}),
);
`;
}
return dedent`
import { integer, primaryKey, sqliteTable, text } from 'drizzle-orm/sqlite-core';
export const pipedriveTokens = sqliteTable(
'pipedrive_tokens',
{
pipedriveCompanyId: integer('pipedrive_company_id').notNull(),
pipedriveUserId: integer('pipedrive_user_id').notNull(),
accessToken: text('access_token').notNull(),
refreshToken: text('refresh_token').notNull(),
tokenType: text('token_type').notNull().default('bearer'),
accessTokenExpiresAt: integer('access_token_expires_at', { mode: 'timestamp' }).notNull(),
refreshTokenExpiresAt: integer('refresh_token_expires_at', { mode: 'timestamp' }).notNull(),
scope: text('scope'),
apiDomain: text('api_domain').notNull(),
createdAt: integer('created_at', { mode: 'timestamp' }).notNull().$defaultFn(() => new Date()),
updatedAt: integer('updated_at', { mode: 'timestamp' }).notNull().$defaultFn(() => new Date()),
},
(table) => ({
pk: primaryKey({ columns: [table.pipedriveCompanyId, table.pipedriveUserId] }),
}),
);
`;
}
async function generateDbClient(outputDir: string, options: GeneratorOptions): Promise<void> {
const content = dbClientContent(options.database);
await writeFile(join(outputDir, 'src/database/index.ts'), content);
}
function dbClientContent(database: GeneratorOptions['database']): string {
if (database === 'postgres') {
return dedent`
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import * as schema from './schema.js';
const client = postgres(process.env.DATABASE_URL!, {
onnotice: (notice) => {
if (notice.code === '42P06' || notice.code === '42P07') return;
console.warn(notice);
},
});
export const db = drizzle(client, { schema });
`;
}
if (database === 'mysql') {
return dedent`
import { drizzle } from 'drizzle-orm/mysql2';
import mysql from 'mysql2/promise';
import * as schema from './schema.js';
const pool = mysql.createPool(process.env.DATABASE_URL!);
export const db = drizzle(pool, { schema, mode: 'default' });
`;
}
return dedent`
import { drizzle } from 'drizzle-orm/libsql';
import { createClient } from '@libsql/client';
import * as schema from './schema.js';
const client = createClient({ url: process.env.DATABASE_URL ?? 'file:./data.db' });
export const db = drizzle(client, { schema });
`;
}
async function generateMigrate(outputDir: string, options: GeneratorOptions): Promise<void> {
const content = migrateContent(options.database);
await writeFile(join(outputDir, 'src/database/migrate.ts'), content);
}
function migrateContent(database: GeneratorOptions['database']): string {
if (database === 'postgres') {
return dedent`
import { migrate } from 'drizzle-orm/postgres-js/migrator';
import { db } from './index.js';
export async function runMigrations(): Promise<void> {
await migrate(db, { migrationsFolder: 'src/database/migrations' });
}
`;
}
if (database === 'mysql') {
return dedent`
import { migrate } from 'drizzle-orm/mysql2/migrator';
import { db } from './index.js';
export async function runMigrations(): Promise<void> {
await migrate(db, { migrationsFolder: 'src/database/migrations' });
}
`;
}
return dedent`
import { migrate } from 'drizzle-orm/libsql/migrator';
import { db } from './index.js';
export async function runMigrations(): Promise<void> {
await migrate(db, { migrationsFolder: 'src/database/migrations' });
}
`;
}
async function generateMigrationSql(outputDir: string, options: GeneratorOptions): Promise<void> {
const content = migrationSqlContent(options.database);
await writeFile(join(outputDir, 'src/database/migrations/0000_init.sql'), content);
}
function migrationSqlContent(database: GeneratorOptions['database']): string {
if (database === 'postgres') {
return dedent`
CREATE TABLE IF NOT EXISTS "pipedrive_tokens" (
"pipedrive_company_id" INTEGER NOT NULL,
"pipedrive_user_id" INTEGER NOT NULL,
"access_token" VARCHAR(768) NOT NULL,
"refresh_token" VARCHAR(768) NOT NULL,
"token_type" VARCHAR(50) NOT NULL DEFAULT 'bearer',
"access_token_expires_at" TIMESTAMP NOT NULL,
"refresh_token_expires_at" TIMESTAMP NOT NULL,
"scope" TEXT,
"api_domain" VARCHAR(255) NOT NULL,
"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),
"updated_at" TIMESTAMP NOT NULL DEFAULT NOW(),
PRIMARY KEY ("pipedrive_company_id", "pipedrive_user_id")
);
`;
}
if (database === 'mysql') {
return dedent`
CREATE TABLE IF NOT EXISTS \`pipedrive_tokens\` (
\`pipedrive_company_id\` INT NOT NULL,
\`pipedrive_user_id\` INT NOT NULL,
\`access_token\` VARCHAR(768) NOT NULL,
\`refresh_token\` VARCHAR(768) NOT NULL,
\`token_type\` VARCHAR(50) NOT NULL DEFAULT 'bearer',
\`access_token_expires_at\` TIMESTAMP NOT NULL,
\`refresh_token_expires_at\` TIMESTAMP NOT NULL,
\`scope\` TEXT,
\`api_domain\` VARCHAR(255) NOT NULL,
\`created_at\` TIMESTAMP NOT NULL DEFAULT NOW(),
\`updated_at\` TIMESTAMP NOT NULL DEFAULT NOW(),
PRIMARY KEY (\`pipedrive_company_id\`, \`pipedrive_user_id\`)
);
`;
}
return dedent`
CREATE TABLE IF NOT EXISTS "pipedrive_tokens" (
"pipedrive_company_id" INTEGER NOT NULL,
"pipedrive_user_id" INTEGER NOT NULL,
"access_token" TEXT NOT NULL,
"refresh_token" TEXT NOT NULL,
"token_type" TEXT NOT NULL DEFAULT 'bearer',
"access_token_expires_at" INTEGER NOT NULL,
"refresh_token_expires_at" INTEGER NOT NULL,
"scope" TEXT,
"api_domain" TEXT NOT NULL,
"created_at" INTEGER NOT NULL DEFAULT (unixepoch()),
"updated_at" INTEGER NOT NULL DEFAULT (unixepoch()),
PRIMARY KEY ("pipedrive_company_id", "pipedrive_user_id")
);
`;
}
async function generateMigrationJournal(outputDir: string, options: GeneratorOptions): Promise<void> {
const dialectMap: Record<GeneratorOptions['database'], string> = {
postgres: 'postgresql',
mysql: 'mysql',
sqlite: 'sqlite',
};
const journal = {
version: '6',
dialect: dialectMap[options.database],
entries: [{ idx: 0, version: '6', when: 0, tag: '0000_init', breakpoints: true }],
};
await writeFile(join(outputDir, 'src/database/migrations/meta/_journal.json'), JSON.stringify(journal, null, 2));
}
async function generateDockerCompose(outputDir: string, options: GeneratorOptions): Promise<void> {
const content =
options.database === 'postgres'
? dedent`
services:
db:
image: postgres:16
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: app
POSTGRES_DB: ${options.projectName}
ports:
- '5432:5432'
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ['CMD', 'pg_isready', '-U', 'app']
interval: 5s
timeout: 5s
retries: 5
volumes:
postgres_data:
`
: dedent`
services:
db:
image: mysql:8
environment:
MYSQL_ROOT_PASSWORD: app
MYSQL_DATABASE: ${options.projectName}
MYSQL_USER: app
MYSQL_PASSWORD: app
ports:
- '127.0.0.1:3307:3306'
volumes:
- mysql_data:/var/lib/mysql
healthcheck:
test: ['CMD', 'mysqladmin', 'ping', '-h', 'localhost', '-u', 'app', '--password=app']
interval: 5s
timeout: 5s
retries: 5
volumes:
mysql_data:
`;
await writeFile(join(outputDir, 'docker-compose.yml'), content);
}
async function generateDrizzleConfig(outputDir: string, options: GeneratorOptions): Promise<void> {
const dialectMap: Record<GeneratorOptions['database'], string> = {
postgres: 'postgresql',
mysql: 'mysql',
sqlite: 'sqlite',
};
const dialect = dialectMap[options.database];
const url =
options.database === 'sqlite' ? `process.env.DATABASE_URL ?? 'file:./data.db'` : `process.env.DATABASE_URL!`;
const content = dedent`
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
dialect: '${dialect}',
schema: './src/database/schema.ts',
out: './src/database/migrations',
dbCredentials: {
url: ${url},
},
});
`;
await writeFile(join(outputDir, 'drizzle.config.ts'), content);
}