|
1 | 1 | import { type ChildProcess } from 'node:child_process' |
2 | | -import path from 'node:path' |
| 2 | +import { toSchemasContainer } from '@prisma/internals' |
3 | 3 |
|
4 | | -import chalk from 'chalk' |
5 | | -import { createDatabase, uriToCredentials, type DatabaseCredentials } from '@prisma/internals' |
| 4 | +// @ts-expect-error |
6 | 5 | import { Migrate } from '@prisma/migrate' |
7 | 6 |
|
8 | 7 | import { type System } from './createSystem' |
9 | 8 |
|
10 | | -import { ExitError } from '../scripts/utils' |
11 | | -import { confirmPrompt } from './prompts' |
12 | | - |
13 | | -// we don't want to pollute process.env.DATABASE_URL so we're |
14 | | -// setting the env variable _just_ long enough for Migrate to |
15 | | -// read it and then we reset it immediately after. |
16 | | -// Migrate reads the env variables a single time when it starts the child process that it talks to |
17 | | - |
18 | | -// note that we could only run this once per Migrate instance but we're going to do it consistently for all migrate calls |
19 | | -// so that calls can moved around freely without implictly relying on some other migrate command being called before it |
| 9 | +function setOrRemoveEnvVariable (name: string, value: string | undefined) { |
| 10 | + if (value === undefined) { |
| 11 | + delete process.env[name] |
| 12 | + return |
| 13 | + } |
| 14 | + process.env[name] = value |
| 15 | +} |
20 | 16 |
|
21 | | -// We also want to silence messages from Prisma about available updates, since the developer is |
22 | | -// not in control of their Prisma version. |
23 | | -// https://www.prisma.io/docs/reference/api-reference/environment-variables-reference#prisma_hide_update_message |
24 | | -function runMigrateWithDbUrl<T> ( |
| 17 | +export async function withMigrate<T> ( |
| 18 | + prismaSchemaPath: string, |
25 | 19 | system: { |
26 | 20 | config: { |
27 | 21 | db: Pick<System['config']['db'], 'url' | 'shadowDatabaseUrl'> |
28 | 22 | } |
29 | 23 | }, |
30 | | - cb: () => T |
31 | | -): T { |
32 | | - const prevDBURLFromEnv = process.env.DATABASE_URL |
33 | | - const prevShadowDBURLFromEnv = process.env.SHADOW_DATABASE_URL |
34 | | - const prevHiddenUpdateMessage = process.env.PRISMA_HIDE_UPDATE_MESSAGE |
35 | | - try { |
36 | | - process.env.DATABASE_URL = system.config.db.url |
37 | | - setOrRemoveEnvVariable('SHADOW_DATABASE_URL', system.config.db.shadowDatabaseUrl) |
38 | | - process.env.PRISMA_HIDE_UPDATE_MESSAGE = '1' |
39 | | - return cb() |
40 | | - } finally { |
41 | | - setOrRemoveEnvVariable('DATABASE_URL', prevDBURLFromEnv) |
42 | | - setOrRemoveEnvVariable('SHADOW_DATABASE_URL', prevShadowDBURLFromEnv) |
43 | | - setOrRemoveEnvVariable('PRISMA_HIDE_UPDATE_MESSAGE', prevHiddenUpdateMessage) |
44 | | - } |
45 | | -} |
46 | | - |
47 | | -function setOrRemoveEnvVariable (name: string, value: string | undefined) { |
48 | | - if (value === undefined) { |
49 | | - delete process.env[name] |
50 | | - } else { |
51 | | - process.env[name] = value |
| 24 | + cb: (operations: { |
| 25 | + apply: () => Promise<any> |
| 26 | + diagnostic: () => Promise<any> |
| 27 | + push: (force: boolean) => Promise<any> |
| 28 | + reset: () => Promise<any> |
| 29 | + schema: (_: string, force: boolean) => Promise<any> |
| 30 | + }) => Promise<T> |
| 31 | +) { |
| 32 | + const migrate = new Migrate(prismaSchemaPath) |
| 33 | + function run <T> (f: () => T): T { |
| 34 | + // only required once - on child process start - but easiest to do this always |
| 35 | + const prevDBURLFromEnv = process.env.DATABASE_URL |
| 36 | + const prevShadowDBURLFromEnv = process.env.SHADOW_DATABASE_URL |
| 37 | + const prevHiddenUpdateMessage = process.env.PRISMA_HIDE_UPDATE_MESSAGE |
| 38 | + try { |
| 39 | + process.env.DATABASE_URL = system.config.db.url |
| 40 | + setOrRemoveEnvVariable('SHADOW_DATABASE_URL', system.config.db.shadowDatabaseUrl) |
| 41 | + process.env.PRISMA_HIDE_UPDATE_MESSAGE = '1' // temporarily silence |
| 42 | + return f() |
| 43 | + } finally { |
| 44 | + setOrRemoveEnvVariable('DATABASE_URL', prevDBURLFromEnv) |
| 45 | + setOrRemoveEnvVariable('SHADOW_DATABASE_URL', prevShadowDBURLFromEnv) |
| 46 | + setOrRemoveEnvVariable('PRISMA_HIDE_UPDATE_MESSAGE', prevHiddenUpdateMessage) |
| 47 | + } |
52 | 48 | } |
53 | | -} |
54 | 49 |
|
55 | | -async function withMigrate<T> (schemaPath: string, cb: (migrate: Migrate) => Promise<T>) { |
56 | | - const migrate = new Migrate(schemaPath) |
57 | 50 | try { |
58 | | - return await cb(migrate) |
| 51 | + return await cb({ |
| 52 | + async apply () { return run(() => migrate.applyMigrations()) }, |
| 53 | + async diagnostic () { return run(() => migrate.devDiagnostic()) }, |
| 54 | + async push (force) { return run(() => migrate.push({ force })) }, |
| 55 | + async reset () { return run(() => migrate.reset()) }, |
| 56 | + async schema (schema, force) { |
| 57 | + const schemaContainer = toSchemasContainer([ |
| 58 | + [prismaSchemaPath, schema] |
| 59 | + ]) |
| 60 | + |
| 61 | + return run(() => migrate.engine.schemaPush({ force, schema: schemaContainer })) |
| 62 | + } |
| 63 | + }) |
59 | 64 | } finally { |
60 | 65 | const closePromise = new Promise<void>(resolve => { |
61 | | - const child = (migrate.engine as any).child as ChildProcess |
| 66 | + const { child } = migrate.engine as { child: ChildProcess } |
62 | 67 | child.once('exit', () => resolve()) |
63 | 68 | }) |
64 | 69 | migrate.stop() |
65 | 70 | await closePromise |
66 | 71 | } |
67 | 72 | } |
68 | | - |
69 | | -export async function runMigrationsOnDatabase (cwd: string, system: System) { |
70 | | - const paths = system.getPaths(cwd) |
71 | | - return await withMigrate(paths.schema.prisma, async (migrate) => { |
72 | | - const { appliedMigrationNames } = await runMigrateWithDbUrl(system, () => migrate.applyMigrations()) |
73 | | - return appliedMigrationNames |
74 | | - }) |
75 | | -} |
76 | | - |
77 | | -export async function runMigrationsOnDatabaseMaybeReset (cwd: string, system: System) { |
78 | | - const paths = system.getPaths(cwd) |
79 | | - |
80 | | - return await withMigrate(paths.schema.prisma, async (migrate) => { |
81 | | - const diagnostic = await runMigrateWithDbUrl(system, () => migrate.devDiagnostic()) |
82 | | - |
83 | | - if (diagnostic.action.tag === 'reset') { |
84 | | - console.log(diagnostic.action.reason) |
85 | | - const consent = await confirmPrompt(`Do you want to continue? ${chalk.red('All data will be lost')}`) |
86 | | - if (!consent) throw new ExitError(1) |
87 | | - |
88 | | - await runMigrateWithDbUrl(system, () => migrate.reset()) |
89 | | - } |
90 | | - |
91 | | - const { appliedMigrationNames } = await runMigrateWithDbUrl(system, () => migrate.applyMigrations()) |
92 | | - return appliedMigrationNames |
93 | | - }) |
94 | | -} |
95 | | - |
96 | | -export async function resetDatabase (dbUrl: string, prismaSchemaPath: string) { |
97 | | - await createDatabase(dbUrl, path.dirname(prismaSchemaPath)) |
98 | | - const config = { |
99 | | - db: { |
100 | | - url: dbUrl, |
101 | | - shadowDatabaseUrl: '' |
102 | | - } |
103 | | - } |
104 | | - |
105 | | - await withMigrate(prismaSchemaPath, async (migrate) => { |
106 | | - await runMigrateWithDbUrl({ config }, () => migrate.reset()) |
107 | | - await runMigrateWithDbUrl({ config }, () => migrate.push({ force: true })) |
108 | | - }) |
109 | | -} |
110 | | - |
111 | | -export async function pushPrismaSchemaToDatabase ( |
112 | | - cwd: string, |
113 | | - system: System, |
114 | | - prismaSchema: string, // already exists |
115 | | - interactive: boolean = false |
116 | | -) { |
117 | | - const paths = system.getPaths(cwd) |
118 | | - |
119 | | - const created = await createDatabase(system.config.db.url, path.dirname(paths.schema.prisma)) |
120 | | - if (interactive && created) { |
121 | | - const credentials = uriToCredentials(system.config.db.url) |
122 | | - console.log(`✨ ${credentials.type} database "${credentials.database}" created at ${getDbLocation(credentials)}`) |
123 | | - } |
124 | | - |
125 | | - const migration = await withMigrate(paths.schema.prisma, async migrate => { |
126 | | - // what does force on migrate.engine.schemaPush mean? |
127 | | - // - true: ignore warnings, but unexecutable steps will block |
128 | | - // - false: warnings or unexecutable steps will block |
129 | | - const migration = await runMigrateWithDbUrl(system, () => migrate.engine.schemaPush({ force: false, schema: prismaSchema })) |
130 | | - |
131 | | - // if there are unexecutable steps, we need to reset the database [or the user can use migrations] |
132 | | - if (migration.unexecutable.length) { |
133 | | - if (!interactive) throw new ExitError(1) |
134 | | - |
135 | | - logUnexecutableSteps(migration.unexecutable) |
136 | | - if (migration.warnings.length) logWarnings(migration.warnings) |
137 | | - |
138 | | - console.log('\nTo apply this migration, we need to reset the database') |
139 | | - if (!(await confirmPrompt(`Do you want to continue? ${chalk.red('All data will be lost')}`, false))) { |
140 | | - console.log('Reset cancelled') |
141 | | - throw new ExitError(0) |
142 | | - } |
143 | | - |
144 | | - await runMigrateWithDbUrl(system, () => migrate.reset()) |
145 | | - return runMigrateWithDbUrl(system, () => migrate.engine.schemaPush({ force: false, schema: prismaSchema })) |
146 | | - } |
147 | | - |
148 | | - if (migration.warnings.length) { |
149 | | - if (!interactive) throw new ExitError(1) |
150 | | - |
151 | | - logWarnings(migration.warnings) |
152 | | - if (!(await confirmPrompt(`Do you want to continue? ${chalk.red('Some data will be lost')}`, false))) { |
153 | | - console.log('Push cancelled') |
154 | | - throw new ExitError(0) |
155 | | - } |
156 | | - return runMigrateWithDbUrl(system, () => migrate.engine.schemaPush({ force: true, schema: prismaSchema })) |
157 | | - } |
158 | | - |
159 | | - return migration |
160 | | - }) |
161 | | - |
162 | | - if (!interactive) return |
163 | | - if (migration.warnings.length === 0 && migration.executedSteps === 0) { |
164 | | - console.log(`✨ Database unchanged`) |
165 | | - } else { |
166 | | - console.log(`✨ Database synchronized with Prisma schema`) |
167 | | - } |
168 | | -} |
169 | | - |
170 | | -function logUnexecutableSteps (unexecutableSteps: string[]) { |
171 | | - console.log(`${chalk.bold.red('\n⚠️ We found changes that cannot be executed:\n')}`) |
172 | | - for (const item of unexecutableSteps) { |
173 | | - console.log(` • ${item}`) |
174 | | - } |
175 | | -} |
176 | | - |
177 | | -function logWarnings (warnings: string[]) { |
178 | | - console.warn(chalk.bold(`\n⚠️ Warnings:\n`)) |
179 | | - for (const warning of warnings) { |
180 | | - console.warn(` • ${warning}`) |
181 | | - } |
182 | | -} |
183 | | - |
184 | | -function getDbLocation (credentials: DatabaseCredentials): string { |
185 | | - if (credentials.type === 'sqlite') { |
186 | | - return credentials.uri! |
187 | | - } |
188 | | - |
189 | | - return `${credentials.host}${credentials.port === undefined ? '' : `:${credentials.port}`}` |
190 | | -} |
0 commit comments