@atscript/db-postgres 0.1.174 → 0.1.175

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.cjs CHANGED
@@ -600,6 +600,43 @@ const PG_CONTENTION_CODES = {
600
600
  "55P03": "LOCK_TIMEOUT",
601
601
  "40001": "SERIALIZATION_FAILURE"
602
602
  };
603
+ /** Connections whose COMMIT failed: the transaction is over, no ROLLBACK may follow. */
604
+ const endedTx = /* @__PURE__ */ new WeakSet();
605
+ /**
606
+ * `error` as the retryable `DbError` of its contention SQLSTATE (deadlock,
607
+ * lock timeout, serialization failure), else `error` as is; the driver error
608
+ * is kept as `cause`. Applied to every statement and to COMMIT — a
609
+ * serialization failure can surface at either.
610
+ */
611
+ function mapContention(error) {
612
+ const code = error && typeof error === "object" ? error.code : void 0;
613
+ const mapped = typeof code === "string" ? PG_CONTENTION_CODES[code] : void 0;
614
+ if (!mapped) return error;
615
+ return new _atscript_db.DbError(mapped, [{
616
+ path: "",
617
+ message: error.message
618
+ }], void 0, { cause: error });
619
+ }
620
+ /**
621
+ * Whether the server reported `error` (a 5-character SQLSTATE `code`), as
622
+ * opposed to a client-side failure — a timeout, a lost socket (`EPIPE`) —
623
+ * after which the server's transaction state is unknown.
624
+ */
625
+ function isServerError(error) {
626
+ const code = error && typeof error === "object" ? error.code : void 0;
627
+ return typeof code === "string" && /^[0-9A-DF-Z][0-9A-Z]{4}$/.test(code);
628
+ }
629
+ /** Closes `conn` — or, for a driver without `destroy()`, rolls it back (best effort) and releases it. */
630
+ async function discardConnection(conn) {
631
+ if (conn.destroy) {
632
+ conn.destroy();
633
+ return;
634
+ }
635
+ try {
636
+ await conn.exec("ROLLBACK");
637
+ } catch {}
638
+ conn.release();
639
+ }
603
640
  const PG_CONSTRAINT_LABELS = {
604
641
  p: "pkey",
605
642
  u: "key",
@@ -701,9 +738,13 @@ var PostgresAdapter = class PostgresAdapter extends _atscript_db.BaseDbAdapter {
701
738
  get _schema() {
702
739
  return this._table?.schema ?? null;
703
740
  }
704
- constructor(driver) {
741
+ /** `textSearchConfigs` — the text search configuration per fulltext language (since 0.1.175). */
742
+ _textSearchConfigs;
743
+ constructor(driver, options) {
705
744
  super();
706
745
  this.driver = driver;
746
+ validateTextSearchConfigs(options?.textSearchConfigs);
747
+ this._textSearchConfigs = options?.textSearchConfigs;
707
748
  }
708
749
  /** Every adapter over this pool shares one transaction (since 0.1.128). */
709
750
  _transactionOwner() {
@@ -730,12 +771,17 @@ var PostgresAdapter = class PostgresAdapter extends _atscript_db.BaseDbAdapter {
730
771
  try {
731
772
  this._log("COMMIT");
732
773
  await conn.exec("COMMIT");
733
- } finally {
734
- conn.release();
774
+ } catch (error) {
775
+ endedTx.add(conn);
776
+ if (isServerError(error)) conn.release();
777
+ else await discardConnection(conn);
778
+ throw mapContention(error);
735
779
  }
780
+ conn.release();
736
781
  }
737
782
  async _rollbackTransaction(state) {
738
783
  const conn = state;
784
+ if (endedTx.delete(conn)) return;
739
785
  try {
740
786
  this._log("ROLLBACK");
741
787
  await conn.exec("ROLLBACK");
@@ -768,11 +814,14 @@ var PostgresAdapter = class PostgresAdapter extends _atscript_db.BaseDbAdapter {
768
814
  const at = firstPendingGeo(params);
769
815
  return at < 0 ? run(params) : resolvePendingGeo(params, at, exec).then(run);
770
816
  };
817
+ const contention = (error) => {
818
+ throw mapContention(error);
819
+ };
771
820
  return {
772
- run: (sql, params) => prep(sql, params, (p) => exec.run(sql, p)),
773
- all: (sql, params) => prep(sql, params, (p) => exec.all(sql, p)),
774
- get: (sql, params) => prep(sql, params, (p) => exec.get(sql, p)),
775
- exec: (sql) => exec.exec(sql).finally(() => this._geoSchemaChanged())
821
+ run: (sql, params) => prep(sql, params, (p) => exec.run(sql, p)).catch(contention),
822
+ all: (sql, params) => prep(sql, params, (p) => exec.all(sql, p)).catch(contention),
823
+ get: (sql, params) => prep(sql, params, (p) => exec.get(sql, p)).catch(contention),
824
+ exec: (sql) => exec.exec(sql).catch(contention).finally(() => this._geoSchemaChanged())
776
825
  };
777
826
  }
778
827
  /**
@@ -958,11 +1007,6 @@ var PostgresAdapter = class PostgresAdapter extends _atscript_db.BaseDbAdapter {
958
1007
  columns: keyColumns(detail)
959
1008
  }, detail);
960
1009
  }
961
- const contention = PG_CONTENTION_CODES[err.code];
962
- if (contention) throw new _atscript_db.DbError(contention, [{
963
- path: "",
964
- message: err.message
965
- }]);
966
1010
  }
967
1011
  throw error;
968
1012
  }
@@ -1835,13 +1879,13 @@ var PostgresAdapter = class PostgresAdapter extends _atscript_db.BaseDbAdapter {
1835
1879
  definition: tsConfigOfIndexDef(r.def)
1836
1880
  }));
1837
1881
  },
1838
- renderDesiredDefinition: (index) => index.type === "fulltext" ? pgTextSearchConfig(index) : void 0,
1882
+ renderDesiredDefinition: (index) => index.type === "fulltext" ? this._textSearchConfig(index) : void 0,
1839
1883
  createIndex: async (index) => {
1840
1884
  if (index.type === "fulltext") {
1841
1885
  const textFields = (0, _atscript_db.splitFulltextFields)(index).text;
1842
1886
  if (textFields.length === 0) return;
1843
1887
  const tsvectorExpr = this._buildTsvectorExpr(textFields);
1844
- const sql = `CREATE INDEX IF NOT EXISTS ${qi(index.key)} ON ${quoteTableName(this.resolveTableName())} USING gin(to_tsvector('${pgTextSearchConfig(index)}', ${tsvectorExpr}))`;
1888
+ const sql = `CREATE INDEX IF NOT EXISTS ${qi(index.key)} ON ${quoteTableName(this.resolveTableName())} USING gin(to_tsvector('${this._textSearchConfig(index)}', ${tsvectorExpr}))`;
1845
1889
  this._log(sql);
1846
1890
  await this._exec().exec(sql);
1847
1891
  return;
@@ -2001,8 +2045,9 @@ var PostgresAdapter = class PostgresAdapter extends _atscript_db.BaseDbAdapter {
2001
2045
  * The search predicate (AND the request filter) and its relevance order
2002
2046
  * (`rank`, since 0.1.165) — used as the ORDER BY when the read has no
2003
2047
  * `$sort`: exact-number hits first, then `ts_rank` over the text members
2004
- * (per-field weights through `setweight` buckets), then the primary key.
2005
- * Grouped searches use only the predicate.
2048
+ * (per-field weights through `setweight` buckets), then the primary key;
2049
+ * the primary key alone under `$rank: false`. Grouped searches use only
2050
+ * the predicate.
2006
2051
  */
2007
2052
  _buildSearchWhere(text, query, indexName) {
2008
2053
  const fulltextIndex = this._getFulltextIndex(indexName);
@@ -2015,13 +2060,13 @@ var PostgresAdapter = class PostgresAdapter extends _atscript_db.BaseDbAdapter {
2015
2060
  const equalities = n === void 0 ? [] : integerFields.map((f) => `${qi(f.name)} = CAST(? AS BIGINT)`);
2016
2061
  let textRank;
2017
2062
  if (textFields.length > 0) {
2018
- const config = pgTextSearchConfig(fulltextIndex);
2063
+ const config = this._textSearchConfig(fulltextIndex);
2019
2064
  const tsvector = `to_tsvector('${config}', ${this._buildTsvectorExpr(textFields)})`;
2020
2065
  const { fn, term } = pgTsQuery(fulltextIndex, text);
2021
2066
  const tsquery = `${fn}('${config}', ?)`;
2022
2067
  parts.push(`${tsvector} @@ ${tsquery}`);
2023
2068
  params.push(term);
2024
- textRank = {
2069
+ if (query.controls?.$rank !== false) textRank = {
2025
2070
  sql: `${this._buildTsRankExpr(textFields, tsvector, config, tsquery)} DESC`,
2026
2071
  params: [term]
2027
2072
  };
@@ -2043,6 +2088,21 @@ var PostgresAdapter = class PostgresAdapter extends _atscript_db.BaseDbAdapter {
2043
2088
  };
2044
2089
  }
2045
2090
  /**
2091
+ * The text search configuration of a fulltext index: the one
2092
+ * `textSearchConfigs` gives its language (since 0.1.175), else
2093
+ * {@link pgTextSearchConfig}.
2094
+ */
2095
+ _textSearchConfig(index) {
2096
+ return this.fulltextEngineConfig(index) ?? pgTextSearchConfig(index);
2097
+ }
2098
+ /**
2099
+ * The `textSearchConfigs` entry of the index's language — an index without
2100
+ * one is `english` here — or `undefined`. Part of the schema hash (since 0.1.175).
2101
+ */
2102
+ fulltextEngineConfig(index) {
2103
+ return this._textSearchConfigs?.[index.language ?? "english"];
2104
+ }
2105
+ /**
2046
2106
  * `ts_rank(…)` over the text members (one `?` — the search text). Without
2047
2107
  * per-field weights it ranks `tsvector` — the indexed expression — itself; with them each
2048
2108
  * member's vector is put in a `setweight` bucket (the distinct weights,
@@ -2446,9 +2506,33 @@ function pgTextSearchConfig(index) {
2446
2506
  if (!_atscript_db.DB_FULLTEXT_LANGUAGES.includes(language)) throw new Error(`Unsupported fulltext language "${language}" on index "${index.name}"`);
2447
2507
  return language === "none" ? "simple" : language;
2448
2508
  }
2449
- /** The configuration of a `to_tsvector('<config>'::regconfig, …)` index definition, else `undefined`. */
2509
+ /**
2510
+ * The configuration of a `to_tsvector('<config>'::regconfig, …)` index
2511
+ * definition, else `undefined`. PostgreSQL prints a keyword name (`select`)
2512
+ * — and every name under `quote_all_identifiers` — quoted (`'"select"'`);
2513
+ * the quotes are removed so it compares with the configured name.
2514
+ */
2450
2515
  function tsConfigOfIndexDef(def) {
2451
- return def ? /to_tsvector\('([a-z_]+)'::regconfig/i.exec(def)?.[1] : void 0;
2516
+ const m = def ? /to_tsvector\('(?:"((?:[^"]|"")+)"|([a-z_][a-z0-9_]*))'::regconfig/i.exec(def) : null;
2517
+ return m ? m[1]?.replaceAll("\"\"", "\"") ?? m[2] : void 0;
2518
+ }
2519
+ /**
2520
+ * An unquoted lowercase identifier — what `pg_get_indexdef` prints back
2521
+ * unchanged (no quotes, no schema for a configuration on the `search_path`).
2522
+ */
2523
+ const PG_CONFIG_NAME = /^[a-z_][a-z0-9_]{0,62}$/;
2524
+ /**
2525
+ * Checks `textSearchConfigs` (since 0.1.175): every key a
2526
+ * `@db.index.fulltext.language` value, every configuration an unquoted
2527
+ * lowercase identifier (it is inlined into DDL and queries). Throws on the
2528
+ * first bad entry.
2529
+ */
2530
+ function validateTextSearchConfigs(configs) {
2531
+ for (const [language, config] of Object.entries(configs ?? {})) {
2532
+ if (config === void 0) continue;
2533
+ if (!_atscript_db.DB_FULLTEXT_LANGUAGES.includes(language)) throw new Error(`[postgres] textSearchConfigs: "${language}" is not a @db.index.fulltext.language value`);
2534
+ if (typeof config !== "string" || !PG_CONFIG_NAME.test(config)) throw new Error(`[postgres] textSearchConfigs.${language}: ${JSON.stringify(config)} is not a text search configuration name — use an unquoted lowercase identifier (letters, digits, "_") on the search_path`);
2535
+ }
2452
2536
  }
2453
2537
  /**
2454
2538
  * The tsquery function and its text for a search: `plainto_tsquery` (every
@@ -2658,6 +2742,10 @@ var PgDriver = class {
2658
2742
  release() {
2659
2743
  client.removeListener("error", onError);
2660
2744
  client.release(lost);
2745
+ },
2746
+ destroy() {
2747
+ client.removeListener("error", onError);
2748
+ client.release(lost ?? true);
2661
2749
  }
2662
2750
  };
2663
2751
  }
@@ -2673,15 +2761,19 @@ var PgDriver = class {
2673
2761
  * Creates a {@link DbSpace} backed by a PostgreSQL connection pool.
2674
2762
  *
2675
2763
  * @param uri - PostgreSQL connection URI (e.g., `postgresql://user@localhost:5432/mydb`)
2676
- * @param options - Additional pool options passed to pg.
2764
+ * @param options - Additional pool options passed to pg. `textSearchConfigs`
2765
+ * (not a pool option, since 0.1.175) maps a fulltext language to a text
2766
+ * search configuration ({@link TPostgresAdapterOptions}).
2677
2767
  * @returns A `DbSpace` that creates `PostgresAdapter` instances per table.
2678
2768
  */
2679
2769
  function createAdapter(uri, options) {
2770
+ const { textSearchConfigs, ...pool } = options ?? {};
2680
2771
  const driver = new PgDriver({
2681
2772
  connectionString: uri,
2682
- ...options
2773
+ ...pool
2683
2774
  });
2684
- return new _atscript_db.DbSpace(() => new PostgresAdapter(driver), { onClose: () => driver.close() });
2775
+ const adapterOptions = { textSearchConfigs };
2776
+ return new _atscript_db.DbSpace(() => new PostgresAdapter(driver, adapterOptions), { onClose: () => driver.close() });
2685
2777
  }
2686
2778
  //#endregion
2687
2779
  exports.PgDriver = PgDriver;
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { AggregateFn, BaseDbAdapter, BucketUnit, DbQuery, DbSpace, FilterExpr, TColumnDiff, TDbDefaultFn, TDbDeleteManyOptions, TDbDeleteResult, TDbFieldMeta, TDbInsertIgnoreOptions, TDbInsertIgnoreSlot, TDbInsertManyResult, TDbInsertResult, TDbIsolationLevel, TDbObjectKind, TDbUpdateOptions, TDbUpdateResult, TEnsureTableOptions, TExistingColumn, TFieldOps, TForeignKeyChange, TGenericLogger, TIndexChange, TJsonCopyTarget, TPrimaryKeyChange, TReferencingForeignKey, TSearchIndexInfo, TSyncColumnResult, TTransactionOptions, TValueFormatterPair, TViewCapability } from "@atscript/db";
1
+ import { AggregateFn, BaseDbAdapter, BucketUnit, DbQuery, DbSpace, FilterExpr, TColumnDiff, TDbDefaultFn, TDbDeleteManyOptions, TDbDeleteResult, TDbFieldMeta, TDbFulltextLanguage, TDbIndex, TDbInsertIgnoreOptions, TDbInsertIgnoreSlot, TDbInsertManyResult, TDbInsertResult, TDbIsolationLevel, TDbObjectKind, TDbUpdateOptions, TDbUpdateResult, TEnsureTableOptions, TExistingColumn, TFieldOps, TForeignKeyChange, TGenericLogger, TIndexChange, TJsonCopyTarget, TPrimaryKeyChange, TReferencingForeignKey, TSearchIndexInfo, TSyncColumnResult, TTransactionOptions, TValueFormatterPair, TViewCapability } from "@atscript/db";
2
2
  import { TMetadataMap } from "@atscript/typescript/utils";
3
3
  import { TFilterVisitorOptions, TSqlFragment } from "@atscript/db-sql-tools";
4
4
 
@@ -66,6 +66,29 @@ interface TPgConnection {
66
66
  exec(sql: string): Promise<void>;
67
67
  /** Release this connection back to the pool. */
68
68
  release(): void;
69
+ /**
70
+ * Close this connection instead of returning it to the pool (since
71
+ * 0.1.175) — used when its transaction state cannot be trusted, e.g. a
72
+ * COMMIT that failed on the client (a timeout) and may have left the
73
+ * transaction open. Optional: a driver without it gets a best-effort
74
+ * `ROLLBACK`, then `release()`.
75
+ */
76
+ destroy?(): void;
77
+ }
78
+ /**
79
+ * `PostgresAdapter` options.
80
+ * @since 0.1.175
81
+ */
82
+ interface TPostgresAdapterOptions {
83
+ /**
84
+ * The text search configuration per `@db.index.fulltext.language` — e.g.
85
+ * `{ russian: "ru_en" }` for a configuration the app created with
86
+ * `CREATE TEXT SEARCH CONFIGURATION`. Replaces the language's built-in
87
+ * configuration in the index and in every query. An unquoted lowercase
88
+ * name (letters, digits, `_`), found through the connection's
89
+ * `search_path`. Changing it rebuilds the index on the next schema sync.
90
+ */
91
+ textSearchConfigs?: Partial<Record<TDbFulltextLanguage, string>>;
69
92
  }
70
93
  //#endregion
71
94
  //#region src/postgres-adapter.d.ts
@@ -129,7 +152,9 @@ declare class PostgresAdapter extends BaseDbAdapter {
129
152
  * an adapter).
130
153
  */
131
154
  private get _schema();
132
- constructor(driver: TPgDriver);
155
+ /** `textSearchConfigs` — the text search configuration per fulltext language (since 0.1.175). */
156
+ private readonly _textSearchConfigs;
157
+ constructor(driver: TPgDriver, options?: TPostgresAdapterOptions);
133
158
  /** Every adapter over this pool shares one transaction (since 0.1.128). */
134
159
  protected _transactionOwner(): unknown;
135
160
  /** The dedicated connection of this pool's open transaction, if any. */
@@ -398,10 +423,22 @@ declare class PostgresAdapter extends BaseDbAdapter {
398
423
  * The search predicate (AND the request filter) and its relevance order
399
424
  * (`rank`, since 0.1.165) — used as the ORDER BY when the read has no
400
425
  * `$sort`: exact-number hits first, then `ts_rank` over the text members
401
- * (per-field weights through `setweight` buckets), then the primary key.
402
- * Grouped searches use only the predicate.
426
+ * (per-field weights through `setweight` buckets), then the primary key;
427
+ * the primary key alone under `$rank: false`. Grouped searches use only
428
+ * the predicate.
403
429
  */
404
430
  private _buildSearchWhere;
431
+ /**
432
+ * The text search configuration of a fulltext index: the one
433
+ * `textSearchConfigs` gives its language (since 0.1.175), else
434
+ * {@link pgTextSearchConfig}.
435
+ */
436
+ private _textSearchConfig;
437
+ /**
438
+ * The `textSearchConfigs` entry of the index's language — an index without
439
+ * one is `english` here — or `undefined`. Part of the schema hash (since 0.1.175).
440
+ */
441
+ fulltextEngineConfig(index: TDbIndex): string | undefined;
405
442
  /**
406
443
  * `ts_rank(…)` over the text members (one `?` — the search text). Without
407
444
  * per-field weights it ranks `tsvector` — the indexed expression — itself; with them each
@@ -574,9 +611,11 @@ declare function buildWhere(filter: FilterExpr, opts?: TFilterVisitorOptions): T
574
611
  * Creates a {@link DbSpace} backed by a PostgreSQL connection pool.
575
612
  *
576
613
  * @param uri - PostgreSQL connection URI (e.g., `postgresql://user@localhost:5432/mydb`)
577
- * @param options - Additional pool options passed to pg.
614
+ * @param options - Additional pool options passed to pg. `textSearchConfigs`
615
+ * (not a pool option, since 0.1.175) maps a fulltext language to a text
616
+ * search configuration ({@link TPostgresAdapterOptions}).
578
617
  * @returns A `DbSpace` that creates `PostgresAdapter` instances per table.
579
618
  */
580
- declare function createAdapter(uri: string, options?: Record<string, unknown>): DbSpace;
619
+ declare function createAdapter(uri: string, options?: Record<string, unknown> & TPostgresAdapterOptions): DbSpace;
581
620
  //#endregion
582
- export { PgDriver, PostgresAdapter, type TPgConnection, type TPgDriver, type TPgDriverOptions, type TPgRunResult, type TSqlFragment, buildWhere, createAdapter };
621
+ export { PgDriver, PostgresAdapter, type TPgConnection, type TPgDriver, type TPgDriverOptions, type TPgRunResult, type TPostgresAdapterOptions, type TSqlFragment, buildWhere, createAdapter };
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { AggregateFn, BaseDbAdapter, BucketUnit, DbQuery, DbSpace, FilterExpr, TColumnDiff, TDbDefaultFn, TDbDeleteManyOptions, TDbDeleteResult, TDbFieldMeta, TDbInsertIgnoreOptions, TDbInsertIgnoreSlot, TDbInsertManyResult, TDbInsertResult, TDbIsolationLevel, TDbObjectKind, TDbUpdateOptions, TDbUpdateResult, TEnsureTableOptions, TExistingColumn, TFieldOps, TForeignKeyChange, TGenericLogger, TIndexChange, TJsonCopyTarget, TPrimaryKeyChange, TReferencingForeignKey, TSearchIndexInfo, TSyncColumnResult, TTransactionOptions, TValueFormatterPair, TViewCapability } from "@atscript/db";
1
+ import { AggregateFn, BaseDbAdapter, BucketUnit, DbQuery, DbSpace, FilterExpr, TColumnDiff, TDbDefaultFn, TDbDeleteManyOptions, TDbDeleteResult, TDbFieldMeta, TDbFulltextLanguage, TDbIndex, TDbInsertIgnoreOptions, TDbInsertIgnoreSlot, TDbInsertManyResult, TDbInsertResult, TDbIsolationLevel, TDbObjectKind, TDbUpdateOptions, TDbUpdateResult, TEnsureTableOptions, TExistingColumn, TFieldOps, TForeignKeyChange, TGenericLogger, TIndexChange, TJsonCopyTarget, TPrimaryKeyChange, TReferencingForeignKey, TSearchIndexInfo, TSyncColumnResult, TTransactionOptions, TValueFormatterPair, TViewCapability } from "@atscript/db";
2
2
  import { TFilterVisitorOptions, TSqlFragment } from "@atscript/db-sql-tools";
3
3
  import { TMetadataMap } from "@atscript/typescript/utils";
4
4
 
@@ -66,6 +66,29 @@ interface TPgConnection {
66
66
  exec(sql: string): Promise<void>;
67
67
  /** Release this connection back to the pool. */
68
68
  release(): void;
69
+ /**
70
+ * Close this connection instead of returning it to the pool (since
71
+ * 0.1.175) — used when its transaction state cannot be trusted, e.g. a
72
+ * COMMIT that failed on the client (a timeout) and may have left the
73
+ * transaction open. Optional: a driver without it gets a best-effort
74
+ * `ROLLBACK`, then `release()`.
75
+ */
76
+ destroy?(): void;
77
+ }
78
+ /**
79
+ * `PostgresAdapter` options.
80
+ * @since 0.1.175
81
+ */
82
+ interface TPostgresAdapterOptions {
83
+ /**
84
+ * The text search configuration per `@db.index.fulltext.language` — e.g.
85
+ * `{ russian: "ru_en" }` for a configuration the app created with
86
+ * `CREATE TEXT SEARCH CONFIGURATION`. Replaces the language's built-in
87
+ * configuration in the index and in every query. An unquoted lowercase
88
+ * name (letters, digits, `_`), found through the connection's
89
+ * `search_path`. Changing it rebuilds the index on the next schema sync.
90
+ */
91
+ textSearchConfigs?: Partial<Record<TDbFulltextLanguage, string>>;
69
92
  }
70
93
  //#endregion
71
94
  //#region src/postgres-adapter.d.ts
@@ -129,7 +152,9 @@ declare class PostgresAdapter extends BaseDbAdapter {
129
152
  * an adapter).
130
153
  */
131
154
  private get _schema();
132
- constructor(driver: TPgDriver);
155
+ /** `textSearchConfigs` — the text search configuration per fulltext language (since 0.1.175). */
156
+ private readonly _textSearchConfigs;
157
+ constructor(driver: TPgDriver, options?: TPostgresAdapterOptions);
133
158
  /** Every adapter over this pool shares one transaction (since 0.1.128). */
134
159
  protected _transactionOwner(): unknown;
135
160
  /** The dedicated connection of this pool's open transaction, if any. */
@@ -398,10 +423,22 @@ declare class PostgresAdapter extends BaseDbAdapter {
398
423
  * The search predicate (AND the request filter) and its relevance order
399
424
  * (`rank`, since 0.1.165) — used as the ORDER BY when the read has no
400
425
  * `$sort`: exact-number hits first, then `ts_rank` over the text members
401
- * (per-field weights through `setweight` buckets), then the primary key.
402
- * Grouped searches use only the predicate.
426
+ * (per-field weights through `setweight` buckets), then the primary key;
427
+ * the primary key alone under `$rank: false`. Grouped searches use only
428
+ * the predicate.
403
429
  */
404
430
  private _buildSearchWhere;
431
+ /**
432
+ * The text search configuration of a fulltext index: the one
433
+ * `textSearchConfigs` gives its language (since 0.1.175), else
434
+ * {@link pgTextSearchConfig}.
435
+ */
436
+ private _textSearchConfig;
437
+ /**
438
+ * The `textSearchConfigs` entry of the index's language — an index without
439
+ * one is `english` here — or `undefined`. Part of the schema hash (since 0.1.175).
440
+ */
441
+ fulltextEngineConfig(index: TDbIndex): string | undefined;
405
442
  /**
406
443
  * `ts_rank(…)` over the text members (one `?` — the search text). Without
407
444
  * per-field weights it ranks `tsvector` — the indexed expression — itself; with them each
@@ -574,9 +611,11 @@ declare function buildWhere(filter: FilterExpr, opts?: TFilterVisitorOptions): T
574
611
  * Creates a {@link DbSpace} backed by a PostgreSQL connection pool.
575
612
  *
576
613
  * @param uri - PostgreSQL connection URI (e.g., `postgresql://user@localhost:5432/mydb`)
577
- * @param options - Additional pool options passed to pg.
614
+ * @param options - Additional pool options passed to pg. `textSearchConfigs`
615
+ * (not a pool option, since 0.1.175) maps a fulltext language to a text
616
+ * search configuration ({@link TPostgresAdapterOptions}).
578
617
  * @returns A `DbSpace` that creates `PostgresAdapter` instances per table.
579
618
  */
580
- declare function createAdapter(uri: string, options?: Record<string, unknown>): DbSpace;
619
+ declare function createAdapter(uri: string, options?: Record<string, unknown> & TPostgresAdapterOptions): DbSpace;
581
620
  //#endregion
582
- export { PgDriver, PostgresAdapter, type TPgConnection, type TPgDriver, type TPgDriverOptions, type TPgRunResult, type TSqlFragment, buildWhere, createAdapter };
621
+ export { PgDriver, PostgresAdapter, type TPgConnection, type TPgDriver, type TPgDriverOptions, type TPgRunResult, type TPostgresAdapterOptions, type TSqlFragment, buildWhere, createAdapter };
package/dist/index.mjs CHANGED
@@ -599,6 +599,43 @@ const PG_CONTENTION_CODES = {
599
599
  "55P03": "LOCK_TIMEOUT",
600
600
  "40001": "SERIALIZATION_FAILURE"
601
601
  };
602
+ /** Connections whose COMMIT failed: the transaction is over, no ROLLBACK may follow. */
603
+ const endedTx = /* @__PURE__ */ new WeakSet();
604
+ /**
605
+ * `error` as the retryable `DbError` of its contention SQLSTATE (deadlock,
606
+ * lock timeout, serialization failure), else `error` as is; the driver error
607
+ * is kept as `cause`. Applied to every statement and to COMMIT — a
608
+ * serialization failure can surface at either.
609
+ */
610
+ function mapContention(error) {
611
+ const code = error && typeof error === "object" ? error.code : void 0;
612
+ const mapped = typeof code === "string" ? PG_CONTENTION_CODES[code] : void 0;
613
+ if (!mapped) return error;
614
+ return new DbError(mapped, [{
615
+ path: "",
616
+ message: error.message
617
+ }], void 0, { cause: error });
618
+ }
619
+ /**
620
+ * Whether the server reported `error` (a 5-character SQLSTATE `code`), as
621
+ * opposed to a client-side failure — a timeout, a lost socket (`EPIPE`) —
622
+ * after which the server's transaction state is unknown.
623
+ */
624
+ function isServerError(error) {
625
+ const code = error && typeof error === "object" ? error.code : void 0;
626
+ return typeof code === "string" && /^[0-9A-DF-Z][0-9A-Z]{4}$/.test(code);
627
+ }
628
+ /** Closes `conn` — or, for a driver without `destroy()`, rolls it back (best effort) and releases it. */
629
+ async function discardConnection(conn) {
630
+ if (conn.destroy) {
631
+ conn.destroy();
632
+ return;
633
+ }
634
+ try {
635
+ await conn.exec("ROLLBACK");
636
+ } catch {}
637
+ conn.release();
638
+ }
602
639
  const PG_CONSTRAINT_LABELS = {
603
640
  p: "pkey",
604
641
  u: "key",
@@ -700,9 +737,13 @@ var PostgresAdapter = class PostgresAdapter extends BaseDbAdapter {
700
737
  get _schema() {
701
738
  return this._table?.schema ?? null;
702
739
  }
703
- constructor(driver) {
740
+ /** `textSearchConfigs` — the text search configuration per fulltext language (since 0.1.175). */
741
+ _textSearchConfigs;
742
+ constructor(driver, options) {
704
743
  super();
705
744
  this.driver = driver;
745
+ validateTextSearchConfigs(options?.textSearchConfigs);
746
+ this._textSearchConfigs = options?.textSearchConfigs;
706
747
  }
707
748
  /** Every adapter over this pool shares one transaction (since 0.1.128). */
708
749
  _transactionOwner() {
@@ -729,12 +770,17 @@ var PostgresAdapter = class PostgresAdapter extends BaseDbAdapter {
729
770
  try {
730
771
  this._log("COMMIT");
731
772
  await conn.exec("COMMIT");
732
- } finally {
733
- conn.release();
773
+ } catch (error) {
774
+ endedTx.add(conn);
775
+ if (isServerError(error)) conn.release();
776
+ else await discardConnection(conn);
777
+ throw mapContention(error);
734
778
  }
779
+ conn.release();
735
780
  }
736
781
  async _rollbackTransaction(state) {
737
782
  const conn = state;
783
+ if (endedTx.delete(conn)) return;
738
784
  try {
739
785
  this._log("ROLLBACK");
740
786
  await conn.exec("ROLLBACK");
@@ -767,11 +813,14 @@ var PostgresAdapter = class PostgresAdapter extends BaseDbAdapter {
767
813
  const at = firstPendingGeo(params);
768
814
  return at < 0 ? run(params) : resolvePendingGeo(params, at, exec).then(run);
769
815
  };
816
+ const contention = (error) => {
817
+ throw mapContention(error);
818
+ };
770
819
  return {
771
- run: (sql, params) => prep(sql, params, (p) => exec.run(sql, p)),
772
- all: (sql, params) => prep(sql, params, (p) => exec.all(sql, p)),
773
- get: (sql, params) => prep(sql, params, (p) => exec.get(sql, p)),
774
- exec: (sql) => exec.exec(sql).finally(() => this._geoSchemaChanged())
820
+ run: (sql, params) => prep(sql, params, (p) => exec.run(sql, p)).catch(contention),
821
+ all: (sql, params) => prep(sql, params, (p) => exec.all(sql, p)).catch(contention),
822
+ get: (sql, params) => prep(sql, params, (p) => exec.get(sql, p)).catch(contention),
823
+ exec: (sql) => exec.exec(sql).catch(contention).finally(() => this._geoSchemaChanged())
775
824
  };
776
825
  }
777
826
  /**
@@ -957,11 +1006,6 @@ var PostgresAdapter = class PostgresAdapter extends BaseDbAdapter {
957
1006
  columns: keyColumns(detail)
958
1007
  }, detail);
959
1008
  }
960
- const contention = PG_CONTENTION_CODES[err.code];
961
- if (contention) throw new DbError(contention, [{
962
- path: "",
963
- message: err.message
964
- }]);
965
1009
  }
966
1010
  throw error;
967
1011
  }
@@ -1834,13 +1878,13 @@ var PostgresAdapter = class PostgresAdapter extends BaseDbAdapter {
1834
1878
  definition: tsConfigOfIndexDef(r.def)
1835
1879
  }));
1836
1880
  },
1837
- renderDesiredDefinition: (index) => index.type === "fulltext" ? pgTextSearchConfig(index) : void 0,
1881
+ renderDesiredDefinition: (index) => index.type === "fulltext" ? this._textSearchConfig(index) : void 0,
1838
1882
  createIndex: async (index) => {
1839
1883
  if (index.type === "fulltext") {
1840
1884
  const textFields = splitFulltextFields(index).text;
1841
1885
  if (textFields.length === 0) return;
1842
1886
  const tsvectorExpr = this._buildTsvectorExpr(textFields);
1843
- const sql = `CREATE INDEX IF NOT EXISTS ${qi(index.key)} ON ${quoteTableName(this.resolveTableName())} USING gin(to_tsvector('${pgTextSearchConfig(index)}', ${tsvectorExpr}))`;
1887
+ const sql = `CREATE INDEX IF NOT EXISTS ${qi(index.key)} ON ${quoteTableName(this.resolveTableName())} USING gin(to_tsvector('${this._textSearchConfig(index)}', ${tsvectorExpr}))`;
1844
1888
  this._log(sql);
1845
1889
  await this._exec().exec(sql);
1846
1890
  return;
@@ -2000,8 +2044,9 @@ var PostgresAdapter = class PostgresAdapter extends BaseDbAdapter {
2000
2044
  * The search predicate (AND the request filter) and its relevance order
2001
2045
  * (`rank`, since 0.1.165) — used as the ORDER BY when the read has no
2002
2046
  * `$sort`: exact-number hits first, then `ts_rank` over the text members
2003
- * (per-field weights through `setweight` buckets), then the primary key.
2004
- * Grouped searches use only the predicate.
2047
+ * (per-field weights through `setweight` buckets), then the primary key;
2048
+ * the primary key alone under `$rank: false`. Grouped searches use only
2049
+ * the predicate.
2005
2050
  */
2006
2051
  _buildSearchWhere(text, query, indexName) {
2007
2052
  const fulltextIndex = this._getFulltextIndex(indexName);
@@ -2014,13 +2059,13 @@ var PostgresAdapter = class PostgresAdapter extends BaseDbAdapter {
2014
2059
  const equalities = n === void 0 ? [] : integerFields.map((f) => `${qi(f.name)} = CAST(? AS BIGINT)`);
2015
2060
  let textRank;
2016
2061
  if (textFields.length > 0) {
2017
- const config = pgTextSearchConfig(fulltextIndex);
2062
+ const config = this._textSearchConfig(fulltextIndex);
2018
2063
  const tsvector = `to_tsvector('${config}', ${this._buildTsvectorExpr(textFields)})`;
2019
2064
  const { fn, term } = pgTsQuery(fulltextIndex, text);
2020
2065
  const tsquery = `${fn}('${config}', ?)`;
2021
2066
  parts.push(`${tsvector} @@ ${tsquery}`);
2022
2067
  params.push(term);
2023
- textRank = {
2068
+ if (query.controls?.$rank !== false) textRank = {
2024
2069
  sql: `${this._buildTsRankExpr(textFields, tsvector, config, tsquery)} DESC`,
2025
2070
  params: [term]
2026
2071
  };
@@ -2042,6 +2087,21 @@ var PostgresAdapter = class PostgresAdapter extends BaseDbAdapter {
2042
2087
  };
2043
2088
  }
2044
2089
  /**
2090
+ * The text search configuration of a fulltext index: the one
2091
+ * `textSearchConfigs` gives its language (since 0.1.175), else
2092
+ * {@link pgTextSearchConfig}.
2093
+ */
2094
+ _textSearchConfig(index) {
2095
+ return this.fulltextEngineConfig(index) ?? pgTextSearchConfig(index);
2096
+ }
2097
+ /**
2098
+ * The `textSearchConfigs` entry of the index's language — an index without
2099
+ * one is `english` here — or `undefined`. Part of the schema hash (since 0.1.175).
2100
+ */
2101
+ fulltextEngineConfig(index) {
2102
+ return this._textSearchConfigs?.[index.language ?? "english"];
2103
+ }
2104
+ /**
2045
2105
  * `ts_rank(…)` over the text members (one `?` — the search text). Without
2046
2106
  * per-field weights it ranks `tsvector` — the indexed expression — itself; with them each
2047
2107
  * member's vector is put in a `setweight` bucket (the distinct weights,
@@ -2445,9 +2505,33 @@ function pgTextSearchConfig(index) {
2445
2505
  if (!DB_FULLTEXT_LANGUAGES.includes(language)) throw new Error(`Unsupported fulltext language "${language}" on index "${index.name}"`);
2446
2506
  return language === "none" ? "simple" : language;
2447
2507
  }
2448
- /** The configuration of a `to_tsvector('<config>'::regconfig, …)` index definition, else `undefined`. */
2508
+ /**
2509
+ * The configuration of a `to_tsvector('<config>'::regconfig, …)` index
2510
+ * definition, else `undefined`. PostgreSQL prints a keyword name (`select`)
2511
+ * — and every name under `quote_all_identifiers` — quoted (`'"select"'`);
2512
+ * the quotes are removed so it compares with the configured name.
2513
+ */
2449
2514
  function tsConfigOfIndexDef(def) {
2450
- return def ? /to_tsvector\('([a-z_]+)'::regconfig/i.exec(def)?.[1] : void 0;
2515
+ const m = def ? /to_tsvector\('(?:"((?:[^"]|"")+)"|([a-z_][a-z0-9_]*))'::regconfig/i.exec(def) : null;
2516
+ return m ? m[1]?.replaceAll("\"\"", "\"") ?? m[2] : void 0;
2517
+ }
2518
+ /**
2519
+ * An unquoted lowercase identifier — what `pg_get_indexdef` prints back
2520
+ * unchanged (no quotes, no schema for a configuration on the `search_path`).
2521
+ */
2522
+ const PG_CONFIG_NAME = /^[a-z_][a-z0-9_]{0,62}$/;
2523
+ /**
2524
+ * Checks `textSearchConfigs` (since 0.1.175): every key a
2525
+ * `@db.index.fulltext.language` value, every configuration an unquoted
2526
+ * lowercase identifier (it is inlined into DDL and queries). Throws on the
2527
+ * first bad entry.
2528
+ */
2529
+ function validateTextSearchConfigs(configs) {
2530
+ for (const [language, config] of Object.entries(configs ?? {})) {
2531
+ if (config === void 0) continue;
2532
+ if (!DB_FULLTEXT_LANGUAGES.includes(language)) throw new Error(`[postgres] textSearchConfigs: "${language}" is not a @db.index.fulltext.language value`);
2533
+ if (typeof config !== "string" || !PG_CONFIG_NAME.test(config)) throw new Error(`[postgres] textSearchConfigs.${language}: ${JSON.stringify(config)} is not a text search configuration name — use an unquoted lowercase identifier (letters, digits, "_") on the search_path`);
2534
+ }
2451
2535
  }
2452
2536
  /**
2453
2537
  * The tsquery function and its text for a search: `plainto_tsquery` (every
@@ -2657,6 +2741,10 @@ var PgDriver = class {
2657
2741
  release() {
2658
2742
  client.removeListener("error", onError);
2659
2743
  client.release(lost);
2744
+ },
2745
+ destroy() {
2746
+ client.removeListener("error", onError);
2747
+ client.release(lost ?? true);
2660
2748
  }
2661
2749
  };
2662
2750
  }
@@ -2672,15 +2760,19 @@ var PgDriver = class {
2672
2760
  * Creates a {@link DbSpace} backed by a PostgreSQL connection pool.
2673
2761
  *
2674
2762
  * @param uri - PostgreSQL connection URI (e.g., `postgresql://user@localhost:5432/mydb`)
2675
- * @param options - Additional pool options passed to pg.
2763
+ * @param options - Additional pool options passed to pg. `textSearchConfigs`
2764
+ * (not a pool option, since 0.1.175) maps a fulltext language to a text
2765
+ * search configuration ({@link TPostgresAdapterOptions}).
2676
2766
  * @returns A `DbSpace` that creates `PostgresAdapter` instances per table.
2677
2767
  */
2678
2768
  function createAdapter(uri, options) {
2769
+ const { textSearchConfigs, ...pool } = options ?? {};
2679
2770
  const driver = new PgDriver({
2680
2771
  connectionString: uri,
2681
- ...options
2772
+ ...pool
2682
2773
  });
2683
- return new DbSpace(() => new PostgresAdapter(driver), { onClose: () => driver.close() });
2774
+ const adapterOptions = { textSearchConfigs };
2775
+ return new DbSpace(() => new PostgresAdapter(driver, adapterOptions), { onClose: () => driver.close() });
2684
2776
  }
2685
2777
  //#endregion
2686
2778
  export { PgDriver, PostgresAdapter, buildWhere, createAdapter };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atscript/db-postgres",
3
- "version": "0.1.174",
3
+ "version": "0.1.175",
4
4
  "description": "PostgreSQL adapter for @atscript/db with pg (node-postgres) driver support.",
5
5
  "keywords": [
6
6
  "atscript",
@@ -43,22 +43,22 @@
43
43
  "access": "public"
44
44
  },
45
45
  "dependencies": {
46
- "@atscript/db-sql-tools": "^0.1.174"
46
+ "@atscript/db-sql-tools": "^0.1.175"
47
47
  },
48
48
  "devDependencies": {
49
- "@atscript/core": "^0.2.9",
50
- "@atscript/typescript": "^0.2.9",
49
+ "@atscript/core": "^0.2.11",
50
+ "@atscript/typescript": "^0.2.11",
51
51
  "@types/pg": "^8.11.0",
52
- "@uniqu/core": "^0.2.1",
52
+ "@uniqu/core": "^0.2.2",
53
53
  "pg": "^8.13.0",
54
- "unplugin-atscript": "^0.2.9"
54
+ "unplugin-atscript": "^0.2.11"
55
55
  },
56
56
  "peerDependencies": {
57
- "@atscript/core": "^0.2.9",
58
- "@atscript/typescript": "^0.2.9",
59
- "@uniqu/core": "^0.2.1",
57
+ "@atscript/core": "^0.2.11",
58
+ "@atscript/typescript": "^0.2.11",
59
+ "@uniqu/core": "^0.2.2",
60
60
  "pg": ">=8.0.0",
61
- "@atscript/db": "^0.1.174"
61
+ "@atscript/db": "^0.1.175"
62
62
  },
63
63
  "peerDependenciesMeta": {
64
64
  "pg": {