@prisma/adapter-pg 7.10.1 → 7.11.0-dev.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.
package/dist/index.d.mts CHANGED
@@ -29,7 +29,7 @@ declare class PgQueryable<ClientT extends StdClient | TransactionClient> impleme
29
29
  * Should the query fail due to a connection error, the connection is
30
30
  * marked as unhealthy.
31
31
  */
32
- private performIO;
32
+ protected performIO(query: SqlQuery): Promise<pg.QueryArrayResult<any>>;
33
33
  protected onError(error: unknown): never;
34
34
  }
35
35
 
@@ -56,7 +56,13 @@ declare class PrismaPgAdapter extends PgQueryable<StdClient> implements SqlDrive
56
56
  }
57
57
 
58
58
  declare type PrismaPgOptions = {
59
- /** The name of the schema to use in generated queries */
59
+ /**
60
+ * The name of the schema to use in generated queries. When the adapter creates the pool itself
61
+ * (i.e. it is given a config object or a connection string), it also sets the `search_path` of
62
+ * every connection to this schema, so that raw queries resolve unqualified table names in this
63
+ * schema, unless the config's `options` already set a `search_path`. Externally provided pools are left untouched; configure the search path on the pool
64
+ * itself in that case, e.g. via `options: '-c search_path="mySchema"'`.
65
+ */
60
66
  schema?: string;
61
67
  /**
62
68
  * Whether to call `pool.end()` on an externally provided pool when the adapter is disposed.
package/dist/index.d.ts CHANGED
@@ -29,7 +29,7 @@ declare class PgQueryable<ClientT extends StdClient | TransactionClient> impleme
29
29
  * Should the query fail due to a connection error, the connection is
30
30
  * marked as unhealthy.
31
31
  */
32
- private performIO;
32
+ protected performIO(query: SqlQuery): Promise<pg.QueryArrayResult<any>>;
33
33
  protected onError(error: unknown): never;
34
34
  }
35
35
 
@@ -56,7 +56,13 @@ declare class PrismaPgAdapter extends PgQueryable<StdClient> implements SqlDrive
56
56
  }
57
57
 
58
58
  declare type PrismaPgOptions = {
59
- /** The name of the schema to use in generated queries */
59
+ /**
60
+ * The name of the schema to use in generated queries. When the adapter creates the pool itself
61
+ * (i.e. it is given a config object or a connection string), it also sets the `search_path` of
62
+ * every connection to this schema, so that raw queries resolve unqualified table names in this
63
+ * schema, unless the config's `options` already set a `search_path`. Externally provided pools are left untouched; configure the search path on the pool
64
+ * itself in that case, e.g. via `options: '-c search_path="mySchema"'`.
65
+ */
60
66
  schema?: string;
61
67
  /**
62
68
  * Whether to call `pool.end()` on an externally provided pool when the adapter is disposed.
package/dist/index.js CHANGED
@@ -75,6 +75,7 @@ var ArrayColumnType = {
75
75
  TEXT_ARRAY: 1009,
76
76
  TIMESTAMP_ARRAY: 1115,
77
77
  TIMESTAMPTZ_ARRAY: 1185,
78
+ TIMETZ_ARRAY: 1270,
78
79
  TIME_ARRAY: 1183,
79
80
  UUID_ARRAY: 2951,
80
81
  VARBIT_ARRAY: 1563,
@@ -273,6 +274,7 @@ function fieldToColumnType(fieldTypeId) {
273
274
  case ArrayColumnType.DATE_ARRAY:
274
275
  return import_driver_adapter_utils.ColumnTypeEnum.DateArray;
275
276
  case ArrayColumnType.TIME_ARRAY:
277
+ case ArrayColumnType.TIMETZ_ARRAY:
276
278
  return import_driver_adapter_utils.ColumnTypeEnum.TimeArray;
277
279
  case ArrayColumnType.TIMESTAMP_ARRAY:
278
280
  return import_driver_adapter_utils.ColumnTypeEnum.DateTimeArray;
@@ -314,10 +316,22 @@ function normalize_time(time) {
314
316
  return time;
315
317
  }
316
318
  function normalize_timez(time) {
317
- return time.replace(/[+-]\d{2}(:\d{2})?$/, "");
319
+ const match = time.match(/^(\d{2}):(\d{2}):(\d{2})(\.\d+)?([+-])(\d{2})(?::(\d{2}))?(?::(\d{2}))?$/);
320
+ if (!match) return time;
321
+ const [, h, m, s, fraction = "", sign, oh, om = "0", os = "0"] = match;
322
+ const offset = (sign === "+" ? 1 : -1) * (Number(oh) * 3600 + Number(om) * 60 + Number(os));
323
+ if (offset === 0) return `${h}:${m}:${s}${fraction}`;
324
+ const seconds = ((Number(h) * 3600 + Number(m) * 60 + Number(s) - offset) % 86400 + 86400) % 86400;
325
+ const pad = (n) => String(n).padStart(2, "0");
326
+ return `${pad(Math.floor(seconds / 3600))}:${pad(Math.floor(seconds / 60) % 60)}:${pad(seconds % 60)}${fraction}`;
318
327
  }
319
328
  function normalize_money(money) {
320
- return money.slice(1);
329
+ if (!/^-?\$\d{1,3}(,\d{3})*\.\d{2}$/.test(money)) {
330
+ throw new Error(
331
+ `Unsupported money format "${money}": only the default lc_monetary format, such as -$1,234.50, is supported`
332
+ );
333
+ }
334
+ return money.replace(/[^\d.-]/g, "");
321
335
  }
322
336
  function normalize_xml(xml) {
323
337
  return xml;
@@ -339,6 +353,7 @@ var customParsers = {
339
353
  [ScalarColumnType.TIME]: normalize_time,
340
354
  [ArrayColumnType.TIME_ARRAY]: normalize_array(normalize_time),
341
355
  [ScalarColumnType.TIMETZ]: normalize_timez,
356
+ [ArrayColumnType.TIMETZ_ARRAY]: normalize_array(normalize_timez),
342
357
  [ScalarColumnType.DATE]: normalize_date,
343
358
  [ArrayColumnType.DATE_ARRAY]: normalize_array(normalize_date),
344
359
  [ScalarColumnType.TIMESTAMP]: normalize_timestamp,
@@ -370,8 +385,9 @@ function mapArg(arg, argType) {
370
385
  if (arg instanceof Date) {
371
386
  switch (argType.dbType) {
372
387
  case "TIME":
373
- case "TIMETZ":
374
388
  return formatTime(arg);
389
+ case "TIMETZ":
390
+ return formatTime(arg) + "+00";
375
391
  case "DATE":
376
392
  return formatDate(arg);
377
393
  default:
@@ -709,15 +725,50 @@ var PgTransaction = class extends PgQueryable {
709
725
  this.pgOptions = pgOptions;
710
726
  this.cleanup = cleanup;
711
727
  }
728
+ closed = false;
729
+ runningStatements = 0;
730
+ async performIO(query) {
731
+ if (this.closed) {
732
+ throw new import_driver_adapter_utils2.DriverAdapterError({
733
+ kind: "TransactionAlreadyClosed",
734
+ cause: "The transaction has already been committed or rolled back"
735
+ });
736
+ }
737
+ this.runningStatements++;
738
+ try {
739
+ return await super.performIO(query);
740
+ } finally {
741
+ this.runningStatements--;
742
+ }
743
+ }
744
+ /**
745
+ * Closes the transaction at most once. Once the pool has lent the client to
746
+ * a new owner, a second `release()` would corrupt the pool's bookkeeping, so
747
+ * it is skipped. A client with a statement still running is released with an
748
+ * error so the pool destroys it instead of lending out a busy connection.
749
+ */
750
+ close() {
751
+ if (this.closed) {
752
+ return;
753
+ }
754
+ this.closed = true;
755
+ try {
756
+ this.cleanup?.();
757
+ } finally {
758
+ if (this.runningStatements > 0) {
759
+ this.client.release(new Error("Transaction closed with a statement still running"));
760
+ } else {
761
+ this.client.release();
762
+ }
763
+ }
764
+ }
712
765
  async commit() {
713
766
  debug(`[js::commit]`);
714
- this.cleanup?.();
715
- this.client.release();
767
+ this.close();
716
768
  }
717
769
  async rollback() {
718
770
  debug(`[js::rollback]`);
719
- this.cleanup?.();
720
- this.client.release();
771
+ this.close();
721
772
  }
722
773
  async createSavepoint(name2) {
723
774
  await this.executeRaw({ sql: `SAVEPOINT ${name2}`, args: [], argTypes: [] });
@@ -809,7 +860,12 @@ var PrismaPgAdapterFactory = class {
809
860
  config;
810
861
  externalPool;
811
862
  async connect() {
812
- const client = this.externalPool ?? new import_pg2.default.Pool(this.config);
863
+ const client = this.externalPool ?? new import_pg2.default.Pool(withSearchPath(this.config, this.options?.schema));
864
+ if (this.externalPool !== null && this.options?.schema !== void 0) {
865
+ debug(
866
+ `The search path is not set on externally provided pools, schema "${this.options.schema}" is only used for generated queries. Set the search path on the pool itself if raw queries need it.`
867
+ );
868
+ }
813
869
  const onIdleClientError = (err) => {
814
870
  debug(`Error from idle pool client: ${err.message} %O`, err);
815
871
  this.options?.onPoolError?.(err);
@@ -839,6 +895,28 @@ var PrismaPgAdapterFactory = class {
839
895
  });
840
896
  }
841
897
  };
898
+ function withSearchPath(config, schema) {
899
+ if (schema === void 0 || setsSearchPath(config.options)) {
900
+ return config;
901
+ }
902
+ const searchPath = `-c search_path=${escapeOptionValue(quoteIdentifierIfNeeded(schema))},public`;
903
+ return {
904
+ ...config,
905
+ options: config.options ? `${config.options} ${searchPath}` : searchPath
906
+ };
907
+ }
908
+ function setsSearchPath(options) {
909
+ return options !== void 0 && /(?:^|\s)(?:-c\s*|--)search[_-]path=/i.test(options);
910
+ }
911
+ function quoteIdentifierIfNeeded(name2) {
912
+ if (/^[a-z_][a-z0-9_$]*$/.test(name2)) {
913
+ return name2;
914
+ }
915
+ return `"${name2.replaceAll('"', '""')}"`;
916
+ }
917
+ function escapeOptionValue(value) {
918
+ return value.replace(/[\\\s]/g, (char) => `\\${char}`);
919
+ }
842
920
  // Annotate the CommonJS export names for ESM import in node:
843
921
  0 && (module.exports = {
844
922
  PrismaPg
package/dist/index.mjs CHANGED
@@ -39,6 +39,7 @@ var ArrayColumnType = {
39
39
  TEXT_ARRAY: 1009,
40
40
  TIMESTAMP_ARRAY: 1115,
41
41
  TIMESTAMPTZ_ARRAY: 1185,
42
+ TIMETZ_ARRAY: 1270,
42
43
  TIME_ARRAY: 1183,
43
44
  UUID_ARRAY: 2951,
44
45
  VARBIT_ARRAY: 1563,
@@ -237,6 +238,7 @@ function fieldToColumnType(fieldTypeId) {
237
238
  case ArrayColumnType.DATE_ARRAY:
238
239
  return ColumnTypeEnum.DateArray;
239
240
  case ArrayColumnType.TIME_ARRAY:
241
+ case ArrayColumnType.TIMETZ_ARRAY:
240
242
  return ColumnTypeEnum.TimeArray;
241
243
  case ArrayColumnType.TIMESTAMP_ARRAY:
242
244
  return ColumnTypeEnum.DateTimeArray;
@@ -278,10 +280,22 @@ function normalize_time(time) {
278
280
  return time;
279
281
  }
280
282
  function normalize_timez(time) {
281
- return time.replace(/[+-]\d{2}(:\d{2})?$/, "");
283
+ const match = time.match(/^(\d{2}):(\d{2}):(\d{2})(\.\d+)?([+-])(\d{2})(?::(\d{2}))?(?::(\d{2}))?$/);
284
+ if (!match) return time;
285
+ const [, h, m, s, fraction = "", sign, oh, om = "0", os = "0"] = match;
286
+ const offset = (sign === "+" ? 1 : -1) * (Number(oh) * 3600 + Number(om) * 60 + Number(os));
287
+ if (offset === 0) return `${h}:${m}:${s}${fraction}`;
288
+ const seconds = ((Number(h) * 3600 + Number(m) * 60 + Number(s) - offset) % 86400 + 86400) % 86400;
289
+ const pad = (n) => String(n).padStart(2, "0");
290
+ return `${pad(Math.floor(seconds / 3600))}:${pad(Math.floor(seconds / 60) % 60)}:${pad(seconds % 60)}${fraction}`;
282
291
  }
283
292
  function normalize_money(money) {
284
- return money.slice(1);
293
+ if (!/^-?\$\d{1,3}(,\d{3})*\.\d{2}$/.test(money)) {
294
+ throw new Error(
295
+ `Unsupported money format "${money}": only the default lc_monetary format, such as -$1,234.50, is supported`
296
+ );
297
+ }
298
+ return money.replace(/[^\d.-]/g, "");
285
299
  }
286
300
  function normalize_xml(xml) {
287
301
  return xml;
@@ -303,6 +317,7 @@ var customParsers = {
303
317
  [ScalarColumnType.TIME]: normalize_time,
304
318
  [ArrayColumnType.TIME_ARRAY]: normalize_array(normalize_time),
305
319
  [ScalarColumnType.TIMETZ]: normalize_timez,
320
+ [ArrayColumnType.TIMETZ_ARRAY]: normalize_array(normalize_timez),
306
321
  [ScalarColumnType.DATE]: normalize_date,
307
322
  [ArrayColumnType.DATE_ARRAY]: normalize_array(normalize_date),
308
323
  [ScalarColumnType.TIMESTAMP]: normalize_timestamp,
@@ -334,8 +349,9 @@ function mapArg(arg, argType) {
334
349
  if (arg instanceof Date) {
335
350
  switch (argType.dbType) {
336
351
  case "TIME":
337
- case "TIMETZ":
338
352
  return formatTime(arg);
353
+ case "TIMETZ":
354
+ return formatTime(arg) + "+00";
339
355
  case "DATE":
340
356
  return formatDate(arg);
341
357
  default:
@@ -673,15 +689,50 @@ var PgTransaction = class extends PgQueryable {
673
689
  this.pgOptions = pgOptions;
674
690
  this.cleanup = cleanup;
675
691
  }
692
+ closed = false;
693
+ runningStatements = 0;
694
+ async performIO(query) {
695
+ if (this.closed) {
696
+ throw new DriverAdapterError({
697
+ kind: "TransactionAlreadyClosed",
698
+ cause: "The transaction has already been committed or rolled back"
699
+ });
700
+ }
701
+ this.runningStatements++;
702
+ try {
703
+ return await super.performIO(query);
704
+ } finally {
705
+ this.runningStatements--;
706
+ }
707
+ }
708
+ /**
709
+ * Closes the transaction at most once. Once the pool has lent the client to
710
+ * a new owner, a second `release()` would corrupt the pool's bookkeeping, so
711
+ * it is skipped. A client with a statement still running is released with an
712
+ * error so the pool destroys it instead of lending out a busy connection.
713
+ */
714
+ close() {
715
+ if (this.closed) {
716
+ return;
717
+ }
718
+ this.closed = true;
719
+ try {
720
+ this.cleanup?.();
721
+ } finally {
722
+ if (this.runningStatements > 0) {
723
+ this.client.release(new Error("Transaction closed with a statement still running"));
724
+ } else {
725
+ this.client.release();
726
+ }
727
+ }
728
+ }
676
729
  async commit() {
677
730
  debug(`[js::commit]`);
678
- this.cleanup?.();
679
- this.client.release();
731
+ this.close();
680
732
  }
681
733
  async rollback() {
682
734
  debug(`[js::rollback]`);
683
- this.cleanup?.();
684
- this.client.release();
735
+ this.close();
685
736
  }
686
737
  async createSavepoint(name2) {
687
738
  await this.executeRaw({ sql: `SAVEPOINT ${name2}`, args: [], argTypes: [] });
@@ -773,7 +824,12 @@ var PrismaPgAdapterFactory = class {
773
824
  config;
774
825
  externalPool;
775
826
  async connect() {
776
- const client = this.externalPool ?? new pg2.Pool(this.config);
827
+ const client = this.externalPool ?? new pg2.Pool(withSearchPath(this.config, this.options?.schema));
828
+ if (this.externalPool !== null && this.options?.schema !== void 0) {
829
+ debug(
830
+ `The search path is not set on externally provided pools, schema "${this.options.schema}" is only used for generated queries. Set the search path on the pool itself if raw queries need it.`
831
+ );
832
+ }
777
833
  const onIdleClientError = (err) => {
778
834
  debug(`Error from idle pool client: ${err.message} %O`, err);
779
835
  this.options?.onPoolError?.(err);
@@ -803,6 +859,28 @@ var PrismaPgAdapterFactory = class {
803
859
  });
804
860
  }
805
861
  };
862
+ function withSearchPath(config, schema) {
863
+ if (schema === void 0 || setsSearchPath(config.options)) {
864
+ return config;
865
+ }
866
+ const searchPath = `-c search_path=${escapeOptionValue(quoteIdentifierIfNeeded(schema))},public`;
867
+ return {
868
+ ...config,
869
+ options: config.options ? `${config.options} ${searchPath}` : searchPath
870
+ };
871
+ }
872
+ function setsSearchPath(options) {
873
+ return options !== void 0 && /(?:^|\s)(?:-c\s*|--)search[_-]path=/i.test(options);
874
+ }
875
+ function quoteIdentifierIfNeeded(name2) {
876
+ if (/^[a-z_][a-z0-9_$]*$/.test(name2)) {
877
+ return name2;
878
+ }
879
+ return `"${name2.replaceAll('"', '""')}"`;
880
+ }
881
+ function escapeOptionValue(value) {
882
+ return value.replace(/[\\\s]/g, (char) => `\\${char}`);
883
+ }
806
884
  export {
807
885
  PrismaPgAdapterFactory as PrismaPg
808
886
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma/adapter-pg",
3
- "version": "7.10.1",
3
+ "version": "7.11.0-dev.1",
4
4
  "description": "Prisma's driver adapter for \"pg\"",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -34,14 +34,13 @@
34
34
  "pg": "^8.16.3",
35
35
  "postgres-array": "3.0.4",
36
36
  "@types/pg": "^8.16.0",
37
- "@prisma/driver-adapter-utils": "7.10.1"
37
+ "@prisma/driver-adapter-utils": "7.11.0-dev.1"
38
38
  },
39
39
  "devDependencies": {
40
- "@prisma/debug": "7.10.1"
40
+ "@prisma/debug": "7.11.0-dev.1"
41
41
  },
42
42
  "scripts": {
43
43
  "dev": "DEV=true tsx helpers/build.ts",
44
- "build": "tsx helpers/build.ts",
45
- "test": "vitest run"
44
+ "build": "tsx helpers/build.ts"
46
45
  }
47
46
  }