@prisma/adapter-d1 7.2.0 → 7.3.0-integration-prisma6-fix-cloudflare-engine.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,729 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name2 in all)
10
- __defProp(target, name2, { get: all[name2], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index-node.ts
31
- var index_node_exports = {};
32
- __export(index_node_exports, {
33
- PrismaD1: () => PrismaD1,
34
- PrismaD1Http: () => PrismaD1HttpAdapterFactory,
35
- listLocalDatabases: () => listLocalDatabases
36
- });
37
- module.exports = __toCommonJS(index_node_exports);
38
-
39
- // package.json
40
- var name = "@prisma/adapter-d1";
41
-
42
- // src/d1-http.ts
43
- var import_driver_adapter_utils2 = require("@prisma/driver-adapter-utils");
44
-
45
- // ../../node_modules/.pnpm/kleur@4.1.5/node_modules/kleur/colors.mjs
46
- var FORCE_COLOR;
47
- var NODE_DISABLE_COLORS;
48
- var NO_COLOR;
49
- var TERM;
50
- var isTTY = true;
51
- if (typeof process !== "undefined") {
52
- ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {});
53
- isTTY = process.stdout && process.stdout.isTTY;
54
- }
55
- var $ = {
56
- enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== "dumb" && (FORCE_COLOR != null && FORCE_COLOR !== "0" || isTTY)
57
- };
58
- function init(x, y) {
59
- let rgx = new RegExp(`\\x1b\\[${y}m`, "g");
60
- let open = `\x1B[${x}m`, close = `\x1B[${y}m`;
61
- return function(txt) {
62
- if (!$.enabled || txt == null) return txt;
63
- return open + (!!~("" + txt).indexOf(close) ? txt.replace(rgx, close + open) : txt) + close;
64
- };
65
- }
66
- var reset = init(0, 0);
67
- var bold = init(1, 22);
68
- var dim = init(2, 22);
69
- var italic = init(3, 23);
70
- var underline = init(4, 24);
71
- var inverse = init(7, 27);
72
- var hidden = init(8, 28);
73
- var strikethrough = init(9, 29);
74
- var black = init(30, 39);
75
- var red = init(31, 39);
76
- var green = init(32, 39);
77
- var yellow = init(33, 39);
78
- var blue = init(34, 39);
79
- var magenta = init(35, 39);
80
- var cyan = init(36, 39);
81
- var white = init(37, 39);
82
- var gray = init(90, 39);
83
- var grey = init(90, 39);
84
- var bgBlack = init(40, 49);
85
- var bgRed = init(41, 49);
86
- var bgGreen = init(42, 49);
87
- var bgYellow = init(43, 49);
88
- var bgBlue = init(44, 49);
89
- var bgMagenta = init(45, 49);
90
- var bgCyan = init(46, 49);
91
- var bgWhite = init(47, 49);
92
-
93
- // src/d1-http.ts
94
- var import_ky = __toESM(require("ky"));
95
-
96
- // src/constants.ts
97
- var MAX_BIND_VALUES = 98;
98
- var GENERIC_SQLITE_ERROR = 1;
99
-
100
- // src/conversion.ts
101
- var import_driver_adapter_utils = require("@prisma/driver-adapter-utils");
102
- function getColumnTypes(columnNames, rows) {
103
- const columnTypes = [];
104
- columnLoop: for (let columnIndex = 0; columnIndex < columnNames.length; columnIndex++) {
105
- for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) {
106
- const candidateValue = rows[rowIndex][columnIndex];
107
- if (candidateValue !== null) {
108
- const inferred = inferColumnType(candidateValue);
109
- if (columnTypes[columnIndex] === void 0 || inferred === import_driver_adapter_utils.ColumnTypeEnum.Text) {
110
- columnTypes[columnIndex] = inferred;
111
- }
112
- if (inferred !== import_driver_adapter_utils.ColumnTypeEnum.UnknownNumber) {
113
- continue columnLoop;
114
- }
115
- }
116
- }
117
- if (columnTypes[columnIndex] === void 0) {
118
- columnTypes[columnIndex] = import_driver_adapter_utils.ColumnTypeEnum.Int32;
119
- }
120
- }
121
- return columnTypes;
122
- }
123
- function inferColumnType(value) {
124
- switch (typeof value) {
125
- case "string":
126
- return inferStringType(value);
127
- case "number":
128
- return inferNumberType(value);
129
- case "object":
130
- return inferObjectType(value);
131
- default:
132
- throw new UnexpectedTypeError(value);
133
- }
134
- }
135
- var isoDateRegex = new RegExp(
136
- /^(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))$|^(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))$|^(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))$/
137
- );
138
- var sqliteDateRegex = /^\d{4}-[0-1]\d-[0-3]\d [0-2]\d:[0-5]\d:[0-5]\d$/;
139
- function isISODate(str) {
140
- return isoDateRegex.test(str) || sqliteDateRegex.test(str);
141
- }
142
- function inferStringType(value) {
143
- if (isISODate(value)) {
144
- return import_driver_adapter_utils.ColumnTypeEnum.DateTime;
145
- }
146
- return import_driver_adapter_utils.ColumnTypeEnum.Text;
147
- }
148
- function inferNumberType(_) {
149
- return import_driver_adapter_utils.ColumnTypeEnum.UnknownNumber;
150
- }
151
- function inferObjectType(value) {
152
- if (value instanceof Array) {
153
- return import_driver_adapter_utils.ColumnTypeEnum.Bytes;
154
- }
155
- throw new UnexpectedTypeError(value);
156
- }
157
- var UnexpectedTypeError = class extends Error {
158
- name = "UnexpectedTypeError";
159
- constructor(value) {
160
- const type = typeof value;
161
- const repr = type === "object" ? JSON.stringify(value) : String(value);
162
- super(`unexpected value of type ${type}: ${repr}`);
163
- }
164
- };
165
- function mapRow(result, columnTypes) {
166
- for (let i = 0; i < result.length; i++) {
167
- const value = result[i];
168
- if (value instanceof ArrayBuffer) {
169
- result[i] = new Uint8Array(value);
170
- continue;
171
- }
172
- if (typeof value === "number" && (columnTypes[i] === import_driver_adapter_utils.ColumnTypeEnum.Int32 || columnTypes[i] === import_driver_adapter_utils.ColumnTypeEnum.Int64) && !Number.isInteger(value)) {
173
- result[i] = Math.trunc(value);
174
- continue;
175
- }
176
- if (typeof value === "number" && columnTypes[i] === import_driver_adapter_utils.ColumnTypeEnum.Text) {
177
- result[i] = value.toString();
178
- continue;
179
- }
180
- if (typeof value === "bigint") {
181
- result[i] = value.toString();
182
- continue;
183
- }
184
- if (columnTypes[i] === import_driver_adapter_utils.ColumnTypeEnum.Boolean) {
185
- result[i] = JSON.parse(value);
186
- }
187
- }
188
- return result;
189
- }
190
- function mapArg(arg, argType) {
191
- if (arg === null) {
192
- return null;
193
- }
194
- if (typeof arg === "bigint" || argType.scalarType === "bigint") {
195
- const asInt56 = Number.parseInt(`${arg}`);
196
- if (!Number.isSafeInteger(asInt56)) {
197
- throw new Error(`Invalid Int64-encoded value received: ${arg}`);
198
- }
199
- return asInt56;
200
- }
201
- if (typeof arg === "string" && argType.scalarType === "int") {
202
- return Number.parseInt(arg);
203
- }
204
- if (typeof arg === "string" && argType.scalarType === "float") {
205
- return Number.parseFloat(arg);
206
- }
207
- if (typeof arg === "string" && argType.scalarType === "decimal") {
208
- return Number.parseFloat(arg);
209
- }
210
- if (arg === true) {
211
- return 1;
212
- }
213
- if (arg === false) {
214
- return 0;
215
- }
216
- if (typeof arg === "string" && argType.scalarType === "datetime") {
217
- arg = new Date(arg);
218
- }
219
- if (arg instanceof Date) {
220
- return arg.toISOString().replace("Z", "+00:00");
221
- }
222
- if (typeof arg === "string" && argType.scalarType === "bytes") {
223
- return Array.from(Buffer.from(arg, "base64"));
224
- }
225
- if (arg instanceof Uint8Array) {
226
- return Array.from(arg);
227
- }
228
- return arg;
229
- }
230
-
231
- // src/errors.ts
232
- function convertDriverError(error) {
233
- if (isDriverError(error)) {
234
- return {
235
- originalMessage: error.message,
236
- ...mapDriverError(error)
237
- };
238
- }
239
- throw error;
240
- }
241
- function mapDriverError(error) {
242
- let stripped = error.message.split("D1_ERROR: ").at(1) ?? error.message;
243
- stripped = stripped.split("SqliteError: ").at(1) ?? stripped;
244
- if (stripped.startsWith("UNIQUE constraint failed") || stripped.startsWith("PRIMARY KEY constraint failed")) {
245
- const fields = stripped.split(": ").at(1)?.split(", ").map((field) => field.split(".").pop());
246
- return {
247
- kind: "UniqueConstraintViolation",
248
- constraint: fields !== void 0 ? { fields } : void 0
249
- };
250
- } else if (stripped.startsWith("NOT NULL constraint failed")) {
251
- const fields = stripped.split(": ").at(1)?.split(", ").map((field) => field.split(".").pop());
252
- return {
253
- kind: "NullConstraintViolation",
254
- constraint: fields !== void 0 ? { fields } : void 0
255
- };
256
- } else if (stripped.startsWith("FOREIGN KEY constraint failed") || stripped.startsWith("CHECK constraint failed")) {
257
- return {
258
- kind: "ForeignKeyConstraintViolation",
259
- constraint: { foreignKey: {} }
260
- };
261
- } else if (stripped.startsWith("no such table")) {
262
- return {
263
- kind: "TableDoesNotExist",
264
- table: stripped.split(": ").at(1)
265
- };
266
- } else if (stripped.startsWith("no such column")) {
267
- return {
268
- kind: "ColumnNotFound",
269
- column: stripped.split(": ").at(1)
270
- };
271
- } else if (stripped.includes("has no column named ")) {
272
- return {
273
- kind: "ColumnNotFound",
274
- column: stripped.split("has no column named ").at(1)
275
- };
276
- }
277
- return {
278
- kind: "sqlite",
279
- extendedCode: error["code"] ?? error["cause"]?.["code"] ?? 1,
280
- message: error.message
281
- };
282
- }
283
- function isDriverError(error) {
284
- return typeof error["message"] === "string";
285
- }
286
-
287
- // src/d1-http.ts
288
- var debug = (0, import_driver_adapter_utils2.Debug)("prisma:driver-adapter:d1-http");
289
- function onUnsuccessfulD1HttpResponse({ errors }) {
290
- debug("D1 HTTP Errors: %O", errors);
291
- const error = errors.at(0) ?? { message: "Unknown error", code: GENERIC_SQLITE_ERROR };
292
- throw new import_driver_adapter_utils2.DriverAdapterError(convertDriverError(error));
293
- }
294
- function onGenericD1HttpError(error) {
295
- debug("HTTP Error: %O", error);
296
- throw new import_driver_adapter_utils2.DriverAdapterError(convertDriverError(error));
297
- }
298
- function onError(error) {
299
- console.error("Error in performIO: %O", error);
300
- throw new import_driver_adapter_utils2.DriverAdapterError(convertDriverError(error));
301
- }
302
- async function performRawQuery(client, options) {
303
- try {
304
- const response = await client.post("raw", options).json();
305
- const tag = "[js::performRawQuery]";
306
- debug(`${tag} %O`, {
307
- success: response.success,
308
- errors: response.errors,
309
- messages: response.messages,
310
- result: response.result
311
- });
312
- if (!response.success) {
313
- onUnsuccessfulD1HttpResponse(response);
314
- }
315
- return response.result;
316
- } catch (e) {
317
- onGenericD1HttpError(e);
318
- }
319
- }
320
- function isD1HttpParams(params) {
321
- return typeof params === "object" && params !== null && "CLOUDFLARE_D1_TOKEN" in params && "CLOUDFLARE_ACCOUNT_ID" in params && "CLOUDFLARE_DATABASE_ID" in params;
322
- }
323
- var D1HttpQueryable = class {
324
- constructor(client) {
325
- this.client = client;
326
- }
327
- provider = "sqlite";
328
- adapterName = `${name}-http`;
329
- /**
330
- * Execute a query given as SQL, interpolating the given parameters.
331
- */
332
- async queryRaw(query) {
333
- const tag = "[js::query_raw]";
334
- debug(`${tag} %O`, query);
335
- const data = await this.performIO(query);
336
- const convertedData = this.convertData(data);
337
- return convertedData;
338
- }
339
- convertData({ columnNames, rows: results }) {
340
- if (results.length === 0) {
341
- return {
342
- columnNames: [],
343
- columnTypes: [],
344
- rows: []
345
- };
346
- }
347
- const columnTypes = getColumnTypes(columnNames, results);
348
- const rows = results.map((value) => mapRow(value, columnTypes));
349
- return {
350
- columnNames,
351
- columnTypes,
352
- rows
353
- };
354
- }
355
- /**
356
- * Execute a query given as SQL, interpolating the given parameters and
357
- * returning the number of affected rows.
358
- * Note: Queryable expects a u64, but napi.rs only supports u32.
359
- */
360
- async executeRaw(query) {
361
- const tag = "[js::execute_raw]";
362
- debug(`${tag} %O`, query);
363
- const result = await this.performIO(query);
364
- return result.affectedRows ?? 0;
365
- }
366
- async performIO(query) {
367
- try {
368
- const body = {
369
- json: {
370
- sql: query.sql,
371
- params: query.args.map((arg, i) => mapArg(arg, query.argTypes[i]))
372
- }
373
- };
374
- const tag = "[js::perform_io]";
375
- debug(`${tag} %O`, body);
376
- const results = await performRawQuery(this.client, body);
377
- if (results.length !== 1) {
378
- throw new Error("Expected exactly one result");
379
- }
380
- const result = results[0];
381
- const { columns: columnNames = [], rows = [] } = result.results ?? {};
382
- const affectedRows = result.meta?.changes;
383
- return { rows, columnNames, affectedRows };
384
- } catch (e) {
385
- onError(e);
386
- }
387
- }
388
- };
389
- var D1HttpTransaction = class extends D1HttpQueryable {
390
- constructor(client, options) {
391
- super(client);
392
- this.options = options;
393
- }
394
- async commit() {
395
- debug(`[js::commit]`);
396
- }
397
- async rollback() {
398
- debug(`[js::rollback]`);
399
- }
400
- };
401
- var PrismaD1HttpAdapter = class extends D1HttpQueryable {
402
- constructor(params, release) {
403
- const D1_API_BASE_URL = `https://api.cloudflare.com/client/v4/accounts/${params.CLOUDFLARE_ACCOUNT_ID}/d1/database/${params.CLOUDFLARE_DATABASE_ID}`;
404
- const client = import_ky.default.create({
405
- prefixUrl: D1_API_BASE_URL,
406
- headers: {
407
- Authorization: `Bearer ${params.CLOUDFLARE_D1_TOKEN}`
408
- },
409
- // Don't automatically throw on non-2xx status codes
410
- throwHttpErrors: false
411
- });
412
- super(client);
413
- this.release = release;
414
- }
415
- tags = {
416
- error: red("prisma:error"),
417
- warn: yellow("prisma:warn"),
418
- info: cyan("prisma:info"),
419
- query: blue("prisma:query")
420
- };
421
- alreadyWarned = /* @__PURE__ */ new Set();
422
- /**
423
- * This will warn once per transaction
424
- * e.g. the following two explicit transactions
425
- * will only trigger _two_ warnings
426
- *
427
- * ```ts
428
- * await prisma.$transaction([ ...queries ])
429
- * await prisma.$transaction([ ...moreQueries ])
430
- * ```
431
- */
432
- warnOnce = (key, message, ...args) => {
433
- if (!this.alreadyWarned.has(key)) {
434
- this.alreadyWarned.add(key);
435
- console.info(`${this.tags.warn} ${message}`, ...args);
436
- }
437
- };
438
- async executeScript(script) {
439
- try {
440
- await performRawQuery(this.client, {
441
- json: {
442
- sql: script
443
- }
444
- });
445
- } catch (error) {
446
- onError(error);
447
- }
448
- }
449
- getConnectionInfo() {
450
- return {
451
- maxBindValues: MAX_BIND_VALUES,
452
- supportsRelationJoins: false
453
- };
454
- }
455
- async startTransaction(isolationLevel) {
456
- if (isolationLevel && isolationLevel !== "SERIALIZABLE") {
457
- throw new import_driver_adapter_utils2.DriverAdapterError({
458
- kind: "InvalidIsolationLevel",
459
- level: isolationLevel
460
- });
461
- }
462
- this.warnOnce(
463
- "D1 Transaction",
464
- "Cloudflare D1 does not support transactions yet. When using Prisma's D1 adapter, implicit & explicit transactions will be ignored and run as individual queries, which breaks the guarantees of the ACID properties of transactions. For more details see https://pris.ly/d/d1-transactions"
465
- );
466
- const options = {
467
- usePhantomQuery: true
468
- };
469
- const tag = "[js::startTransaction]";
470
- debug("%s options: %O", tag, options);
471
- return new D1HttpTransaction(this.client, options);
472
- }
473
- async dispose() {
474
- await this.release?.();
475
- }
476
- };
477
- var PrismaD1HttpAdapterFactory = class {
478
- constructor(params) {
479
- this.params = params;
480
- }
481
- provider = "sqlite";
482
- adapterName = `${name}-http`;
483
- async connect() {
484
- return new PrismaD1HttpAdapter(this.params, async () => {
485
- });
486
- }
487
- async connectToShadowDb() {
488
- const D1_API_BASE_URL = `https://api.cloudflare.com/client/v4/accounts/${this.params.CLOUDFLARE_ACCOUNT_ID}/d1/database`;
489
- const client = import_ky.default.create({
490
- headers: {
491
- Authorization: `Bearer ${this.params.CLOUDFLARE_D1_TOKEN}`
492
- },
493
- // Don't throw on non-2xx status codes
494
- throwHttpErrors: false
495
- });
496
- const createShadowDatabase = async () => {
497
- const tag = "[js::connectToShadowDb::createShadowDatabase]";
498
- const SHADOW_DATABASE_PREFIX = "_prisma_shadow_";
499
- const CLOUDFLARE_SHADOW_DATABASE_NAME = `${SHADOW_DATABASE_PREFIX}${globalThis.crypto.randomUUID()}`;
500
- debug(`${tag} creating database %s`, CLOUDFLARE_SHADOW_DATABASE_NAME);
501
- try {
502
- const response = await client.post(D1_API_BASE_URL, {
503
- json: {
504
- name: CLOUDFLARE_SHADOW_DATABASE_NAME
505
- }
506
- }).json();
507
- debug(`${tag} %O`, response);
508
- if (!response.success) {
509
- onUnsuccessfulD1HttpResponse(response);
510
- }
511
- const { uuid: CLOUDFLARE_SHADOW_DATABASE_ID2 } = response.result;
512
- debug(`${tag} created database %s with ID %s`, CLOUDFLARE_SHADOW_DATABASE_NAME, CLOUDFLARE_SHADOW_DATABASE_ID2);
513
- return CLOUDFLARE_SHADOW_DATABASE_ID2;
514
- } catch (e) {
515
- onGenericD1HttpError(e);
516
- }
517
- };
518
- const CLOUDFLARE_SHADOW_DATABASE_ID = this.params.CLOUDFLARE_SHADOW_DATABASE_ID ?? await createShadowDatabase();
519
- const dispose = async () => {
520
- const tag = "[js::connectToShadowDb::dispose]";
521
- try {
522
- debug(`${tag} deleting database %s`, CLOUDFLARE_SHADOW_DATABASE_ID);
523
- const response = await client.delete(`${D1_API_BASE_URL}/${CLOUDFLARE_SHADOW_DATABASE_ID}`).json();
524
- debug(`${tag} %O`, response);
525
- if (!response.success) {
526
- onUnsuccessfulD1HttpResponse(response);
527
- }
528
- } catch (e) {
529
- onGenericD1HttpError(e);
530
- }
531
- };
532
- return new PrismaD1HttpAdapter(this.params, dispose);
533
- }
534
- };
535
-
536
- // src/d1-worker.ts
537
- var import_driver_adapter_utils3 = require("@prisma/driver-adapter-utils");
538
- var debug2 = (0, import_driver_adapter_utils3.Debug)("prisma:driver-adapter:d1");
539
- var D1WorkerQueryable = class {
540
- constructor(client) {
541
- this.client = client;
542
- }
543
- provider = "sqlite";
544
- adapterName = name;
545
- /**
546
- * Execute a query given as SQL, interpolating the given parameters.
547
- */
548
- async queryRaw(query) {
549
- const tag = "[js::query_raw]";
550
- debug2(`${tag} %O`, query);
551
- const data = await this.performIO(query);
552
- const convertedData = this.convertData(data);
553
- return convertedData;
554
- }
555
- convertData(ioResult) {
556
- const columnNames = ioResult[0];
557
- const results = ioResult[1];
558
- if (results.length === 0) {
559
- return {
560
- columnNames: [],
561
- columnTypes: [],
562
- rows: []
563
- };
564
- }
565
- const columnTypes = Object.values(getColumnTypes(columnNames, results));
566
- const rows = results.map((value) => mapRow(value, columnTypes));
567
- return {
568
- columnNames,
569
- // * Note: without Object.values the array looks like
570
- // * columnTypes: [ id: 128 ],
571
- // * and errors with:
572
- // * ✘ [ERROR] A hanging Promise was canceled. This happens when the worker runtime is waiting for a Promise from JavaScript to resolve, but has detected that the Promise cannot possibly ever resolve because all code and events related to the Promise's I/O context have already finished.
573
- columnTypes,
574
- rows
575
- };
576
- }
577
- /**
578
- * Execute a query given as SQL, interpolating the given parameters and
579
- * returning the number of affected rows.
580
- * Note: Queryable expects a u64, but napi.rs only supports u32.
581
- */
582
- async executeRaw(query) {
583
- const tag = "[js::execute_raw]";
584
- debug2(`${tag} %O`, query);
585
- const result = await this.performIO(query, true);
586
- return result.meta.changes ?? 0;
587
- }
588
- async performIO(query, executeRaw = false) {
589
- try {
590
- const args = query.args.map((arg, i) => mapArg(arg, query.argTypes[i]));
591
- const stmt = this.client.prepare(query.sql).bind(...args);
592
- if (executeRaw) {
593
- return await stmt.run();
594
- } else {
595
- const [columnNames, ...rows] = await stmt.raw({ columnNames: true });
596
- return [columnNames, rows];
597
- }
598
- } catch (e) {
599
- onError2(e);
600
- }
601
- }
602
- };
603
- var D1WorkerTransaction = class extends D1WorkerQueryable {
604
- constructor(client, options) {
605
- super(client);
606
- this.options = options;
607
- }
608
- async commit() {
609
- debug2(`[js::commit]`);
610
- }
611
- async rollback() {
612
- debug2(`[js::rollback]`);
613
- }
614
- };
615
- var PrismaD1WorkerAdapter = class extends D1WorkerQueryable {
616
- constructor(client, release) {
617
- super(client);
618
- this.release = release;
619
- }
620
- tags = {
621
- error: red("prisma:error"),
622
- warn: yellow("prisma:warn"),
623
- info: cyan("prisma:info"),
624
- query: blue("prisma:query")
625
- };
626
- alreadyWarned = /* @__PURE__ */ new Set();
627
- /**
628
- * This will warn once per transaction
629
- * e.g. the following two explicit transactions
630
- * will only trigger _two_ warnings
631
- *
632
- * ```ts
633
- * await prisma.$transaction([ ...queries ])
634
- * await prisma.$transaction([ ...moreQueries ])
635
- * ```
636
- */
637
- warnOnce = (key, message, ...args) => {
638
- if (!this.alreadyWarned.has(key)) {
639
- this.alreadyWarned.add(key);
640
- console.info(`${this.tags.warn} ${message}`, ...args);
641
- }
642
- };
643
- async executeScript(script) {
644
- try {
645
- await this.client.exec(script);
646
- } catch (error) {
647
- onError2(error);
648
- }
649
- }
650
- getConnectionInfo() {
651
- return {
652
- maxBindValues: MAX_BIND_VALUES,
653
- supportsRelationJoins: false
654
- };
655
- }
656
- async startTransaction(isolationLevel) {
657
- if (isolationLevel && isolationLevel !== "SERIALIZABLE") {
658
- throw new import_driver_adapter_utils3.DriverAdapterError({
659
- kind: "InvalidIsolationLevel",
660
- level: isolationLevel
661
- });
662
- }
663
- this.warnOnce(
664
- "D1 Transaction",
665
- "Cloudflare D1 does not support transactions yet. When using Prisma's D1 adapter, implicit & explicit transactions will be ignored and run as individual queries, which breaks the guarantees of the ACID properties of transactions. For more details see https://pris.ly/d/d1-transactions"
666
- );
667
- const options = {
668
- usePhantomQuery: true
669
- };
670
- const tag = "[js::startTransaction]";
671
- debug2("%s options: %O", tag, options);
672
- return new D1WorkerTransaction(this.client, options);
673
- }
674
- async dispose() {
675
- await this.release?.();
676
- }
677
- };
678
- var PrismaD1WorkerAdapterFactory = class {
679
- constructor(client) {
680
- this.client = client;
681
- }
682
- provider = "sqlite";
683
- adapterName = name;
684
- async connect() {
685
- return new PrismaD1WorkerAdapter(this.client, async () => {
686
- });
687
- }
688
- };
689
- function onError2(error) {
690
- console.error("Error in performIO: %O", error);
691
- throw new import_driver_adapter_utils3.DriverAdapterError(convertDriverError(error));
692
- }
693
-
694
- // src/d1.ts
695
- var PrismaD1 = class {
696
- provider = "sqlite";
697
- adapterName = name;
698
- connect;
699
- connectToShadowDb;
700
- constructor(params) {
701
- if (isD1HttpParams(params)) {
702
- const factory = new PrismaD1HttpAdapterFactory(params);
703
- const self = this;
704
- self.connect = factory.connect.bind(factory);
705
- self.connectToShadowDb = factory.connectToShadowDb.bind(factory);
706
- } else {
707
- const factory = new PrismaD1WorkerAdapterFactory(params);
708
- const self = this;
709
- self.connect = factory.connect.bind(factory);
710
- }
711
- }
712
- };
713
-
714
- // src/node/list-local-databases.ts
715
- var import_node_fs = __toESM(require("node:fs"));
716
- var import_node_path = __toESM(require("node:path"));
717
- var localD1DatabasePath = import_node_path.default.join(".wrangler", "state", "v3", "d1", "miniflare-D1DatabaseObject");
718
- function listLocalDatabases() {
719
- const cwd = process.cwd();
720
- const d1DirPath = import_node_path.default.join(cwd, localD1DatabasePath);
721
- const files = import_node_fs.default.readdirSync(d1DirPath);
722
- return files.filter((file) => file.endsWith(".sqlite")).map((file) => import_node_path.default.join(d1DirPath, file));
723
- }
724
- // Annotate the CommonJS export names for ESM import in node:
725
- 0 && (module.exports = {
726
- PrismaD1,
727
- PrismaD1Http,
728
- listLocalDatabases
729
- });