-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathprisma.ts
More file actions
274 lines (216 loc) · 8.67 KB
/
prisma.ts
File metadata and controls
274 lines (216 loc) · 8.67 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
import { BuildManifest, BuildTarget } from "@trigger.dev/core/v3";
import { binaryForRuntime, BuildContext, BuildExtension } from "@trigger.dev/core/v3/build";
import assert from "node:assert";
import { existsSync } from "node:fs";
import { cp, readdir } from "node:fs/promises";
import { dirname, join, resolve } from "node:path";
export type PrismaExtensionOptions = {
schema: string;
migrate?: boolean;
version?: string;
/**
* Adds the `--sql` flag to the `prisma generate` command. This will generate the SQL files for the Prisma schema. Requires the `typedSql preview feature and prisma 5.19.0 or later.
*/
typedSql?: boolean;
/**
* The client generator to use. Set this param to prevent all generators in the prisma schema from being generated.
*
* @example
*
* ### Prisma schema
*
* ```prisma
* generator client {
* provider = "prisma-client-js"
* }
*
* generator typegraphql {
* provider = "typegraphql-prisma"
* output = "./generated/type-graphql"
* }
* ```
*
* ### PrismaExtension
*
* ```ts
* prismaExtension({
* schema: "./prisma/schema.prisma",
* clientGenerator: "client"
* });
* ```
*/
clientGenerator?: string;
directUrlEnvVarName?: string;
};
const BINARY_TARGET = "linux-arm64-openssl-3.0.x";
export function prismaExtension(options: PrismaExtensionOptions): PrismaExtension {
return new PrismaExtension(options);
}
export class PrismaExtension implements BuildExtension {
moduleExternals: string[];
public readonly name = "PrismaExtension";
private _resolvedSchemaPath?: string;
constructor(private options: PrismaExtensionOptions) {
this.moduleExternals = ["@prisma/client", "@prisma/engines"];
}
externalsForTarget(target: BuildTarget) {
if (target === "dev") {
return [];
}
return this.moduleExternals;
}
async onBuildStart(context: BuildContext) {
if (context.target === "dev") {
return;
}
// Resolve the path to the prisma schema, relative to the config.directory
this._resolvedSchemaPath = resolve(context.workingDir, this.options.schema);
context.logger.debug(`Resolved the prisma schema to: ${this._resolvedSchemaPath}`);
// Check that the prisma schema exists
if (!existsSync(this._resolvedSchemaPath)) {
throw new Error(
`PrismaExtension could not find the prisma schema at ${this._resolvedSchemaPath}. Make sure the path is correct: ${this.options.schema}, relative to the working dir ${context.workingDir}`
);
}
}
async onBuildComplete(context: BuildContext, manifest: BuildManifest) {
if (context.target === "dev") {
return;
}
assert(this._resolvedSchemaPath, "Resolved schema path is not set");
context.logger.debug("Looking for @prisma/client in the externals", {
externals: manifest.externals,
});
const prismaExternal = manifest.externals?.find(
(external) => external.name === "@prisma/client"
);
const version = prismaExternal?.version ?? this.options.version;
if (!version) {
throw new Error(
`PrismaExtension could not determine the version of @prisma/client. It's possible that the @prisma/client was not used in the project. If this isn't the case, please provide a version in the PrismaExtension options.`
);
}
context.logger.debug(`PrismaExtension is generating the Prisma client for version ${version}`);
const usingSchemaFolder = dirname(this._resolvedSchemaPath).endsWith("schema");
const commands: string[] = [];
let prismaDir: string | undefined;
const generatorFlags: string[] = [];
if (this.options.clientGenerator) {
generatorFlags.push(`--generator=${this.options.clientGenerator}`);
}
if (this.options.typedSql) {
generatorFlags.push(`--sql`);
const prismaDir = usingSchemaFolder
? dirname(dirname(this._resolvedSchemaPath))
: dirname(this._resolvedSchemaPath);
context.logger.debug(`Using typedSql`);
// Find all the files prisma/sql/*.sql
const sqlFiles = await readdir(join(prismaDir, "sql")).then((files) =>
files.filter((file) => file.endsWith(".sql"))
);
context.logger.debug(`Found sql files`, {
sqlFiles,
});
const sqlDestinationPath = join(manifest.outputPath, "prisma", "sql");
for (const file of sqlFiles) {
const destination = join(sqlDestinationPath, file);
const source = join(prismaDir, "sql", file);
context.logger.debug(`Copying the sql from ${source} to ${destination}`);
await cp(source, destination);
}
}
if (usingSchemaFolder) {
const schemaDir = dirname(this._resolvedSchemaPath);
prismaDir = dirname(schemaDir);
context.logger.debug(`Using the schema folder: ${schemaDir}`);
// Find all the files in schemaDir that end with .prisma (excluding the schema.prisma file)
const prismaFiles = await readdir(schemaDir).then((files) =>
files.filter((file) => file.endsWith(".prisma"))
);
context.logger.debug(`Found prisma files in the schema folder`, {
prismaFiles,
});
const schemaDestinationPath = join(manifest.outputPath, "prisma", "schema");
const allPrismaFiles = [...prismaFiles];
for (const file of allPrismaFiles) {
const destination = join(schemaDestinationPath, file);
const source = join(schemaDir, file);
context.logger.debug(`Copying the prisma schema from ${source} to ${destination}`);
await cp(source, destination);
}
commands.push(
`${binaryForRuntime(
manifest.runtime
)} node_modules/prisma/build/index.js generate --schema=./prisma/schema ${generatorFlags.join(" ")}` // Add the --schema flag for prisma@^6.6.0 compatibility
);
} else {
prismaDir = dirname(this._resolvedSchemaPath);
// Now we need to add a layer that:
// Copies the prisma schema to the build outputPath
// Adds the `prisma` CLI dependency to the dependencies
// Adds the `prisma generate` command, which generates the Prisma client
const schemaDestinationPath = join(manifest.outputPath, "prisma", "schema.prisma");
// Copy the prisma schema to the build output path
context.logger.debug(
`Copying the prisma schema from ${this._resolvedSchemaPath} to ${schemaDestinationPath}`
);
await cp(this._resolvedSchemaPath, schemaDestinationPath);
commands.push(
`${binaryForRuntime(
manifest.runtime
)} node_modules/prisma/build/index.js generate --schema=./prisma/schema.prisma ${generatorFlags.join(
" "
)}`
);
}
const env: Record<string, string | undefined> = {};
if (this.options.migrate) {
// Copy the migrations directory to the build output path
const migrationsDir = join(prismaDir, "migrations");
const migrationsDestinationPath = join(manifest.outputPath, "prisma", "migrations");
context.logger.debug(
`Copying the prisma migrations from ${migrationsDir} to ${migrationsDestinationPath}`
);
await cp(migrationsDir, migrationsDestinationPath, { recursive: true });
commands.push(
`${binaryForRuntime(manifest.runtime)} node_modules/prisma/build/index.js migrate deploy`
);
}
env.DATABASE_URL = manifest.deploy.env?.DATABASE_URL;
if (this.options.directUrlEnvVarName) {
env[this.options.directUrlEnvVarName] =
manifest.deploy.env?.[this.options.directUrlEnvVarName] ??
process.env[this.options.directUrlEnvVarName];
if (!env[this.options.directUrlEnvVarName]) {
context.logger.warn(
`prismaExtension could not resolve the ${this.options.directUrlEnvVarName} environment variable. Make sure you add it to your environment variables or provide it as an environment variable to the deploy CLI command. See our docs for more info: https://trigger.dev/docs/deploy-environment-variables`
);
}
} else {
env.DIRECT_URL = manifest.deploy.env?.DIRECT_URL;
env.DIRECT_DATABASE_URL = manifest.deploy.env?.DIRECT_DATABASE_URL;
}
if (!env.DATABASE_URL) {
context.logger.warn(
`prismaExtension could not resolve the DATABASE_URL environment variable. Make sure you add it to your environment variables. See our docs for more info: https://trigger.dev/docs/deploy-environment-variables`
);
}
context.logger.debug(`Adding the prisma layer with the following commands`, {
commands,
env,
dependencies: {
prisma: version,
},
});
context.addLayer({
id: "prisma",
commands,
dependencies: {
prisma: version,
},
build: {
env,
},
});
}
}