@n8io/baseline-postgres 5.2.0 → 5.3.0

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/README.md CHANGED
@@ -16,7 +16,7 @@ pnpm add @n8io/baseline-postgres
16
16
  - `postgresIdColumnCreate(prefix)`: a Drizzle `uuid` column that reads and writes `Id<prefix>`.
17
17
  - `postgresUniqueViolationIs(error, constraint)`: true when a unique violation on that constraint is anywhere in the `cause` chain.
18
18
  - `postgresUniqueViolationRead(error)`: the first unique violation in the `cause` chain as `{ constraint, columns, values }`, or `undefined`. `columns` and `values` come from Postgres's detail (`Key (league_id, name)=(7, Eagles)`), so a value is text as Postgres printed it. Postgres quotes nothing there, so when a key of two or more columns holds a value with `", "` in it, both lists are empty rather than misaligned; an expression key such as `lower(name)` comes back as Postgres printed it, and one with `", "` inside may not split cleanly. Read `constraint` when you need certainty.
19
- - `postgresKeysetCreate({ after?, descending, idColumn, kind, sortColumn })`: keyset paging on `(sortColumn, idColumn)`. Returns `{ where, orderBy }` for a Drizzle `select`; `where` is `undefined` on the first page. `after` is the last row of the previous page, `{ id, value }`, with `id` written through `idColumn` (a prefixed id works). `kind` says how the sort compares: `text` by byte order (`COLLATE "C"`, the same in every locale, so give the column a `COLLATE "C"` index); `number` as the column's own type, so its index is used (for `integer`, `real` and `double precision` columns; a `numeric` or `bigint` column reads as a string or a bigint and is not supported); `date` as an instant, with `value` an ISO string with an offset (`toISOString()`). The sort column must be `NOT NULL`, because a NULL never compares, and a `date` column must hold no more than milliseconds (`timestamp({ precision: 3, withTimezone: true })`, or written only from a JS `Date`): a cursor made from a `Date` drops the microseconds a `now()` default stores, and pages would repeat or skip rows. A `value` of the wrong type for `kind`, or a date that is not an ISO instant, throws a `TypeError`: decode and check a cursor before you pass it.
19
+ - `postgresKeysetCreate({ after?, descending, idColumn, kind, sortColumn })`: keyset paging on `(sortColumn, idColumn)`. Returns `{ where, orderBy }` for a Drizzle `select`; `where` is `undefined` on the first page. `after` is the last row of the previous page, `{ id, value }`, with `id` written through `idColumn` (a prefixed id works). `kind` says how the sort compares: `text` by byte order (`COLLATE "C"`, the same in every locale, so give the column a `COLLATE "C"` index); `number` as the column's own type, so its index is used (for `integer`, `real` and `double precision` columns; a `numeric` or `bigint` column reads as a string or a bigint and is not supported); `integer` the same, for an `integer` or `serial` column only (any other column throws), taking only a whole number from -2147483648 to 2147483647; `date` as an instant, with `value` an ISO string with an offset (`toISOString()`). The sort column must be `NOT NULL`, because a NULL never compares, and a `date` column must hold no more than milliseconds (`timestamp({ precision: 3, withTimezone: true })`, or written only from a JS `Date`): a cursor made from a `Date` drops the microseconds a `now()` default stores, and pages would repeat or skip rows. A `value` of the wrong type for `kind`, a date that is not an ISO instant, or a number an `integer` or `smallint` sort column cannot hold (a fraction, or past its range), throws a `TypeError`: decode and check a cursor before you pass it.
20
20
  - `postgresAdvisoryLockTake(db, key)`: waits for and takes a transaction-scoped advisory lock on the string `key`; Postgres drops it at COMMIT or ROLLBACK. Use it to serialize work that has no row to lock, such as counting a League's Teams before inserting one. `db` is anything with Drizzle's `execute` (`PostgresExecutor`). Call it inside `postgresTransactionRun`: outside a transaction the lock ends with the statement.
21
21
 
22
22
  ## Example
package/dist/index.d.ts CHANGED
@@ -14,8 +14,11 @@ type PostgresIdColumnBuilder<P extends string> = PgCustomColumnBuilder<{
14
14
  driverParam: string;
15
15
  }>;
16
16
  export declare const postgresIdColumnCreate: <P extends string>(prefix: P) => ((name?: string) => PostgresIdColumnBuilder<P>);
17
- /** How the sort column compares: `text` by byte order (`COLLATE "C"`), `date` as an instant. */
18
- type PostgresKeysetKind = "date" | "number" | "text";
17
+ /**
18
+ * How the sort column compares: `text` by byte order (`COLLATE "C"`), `date` as an instant,
19
+ * `integer` and `number` as numbers (`integer` takes only a whole number).
20
+ */
21
+ type PostgresKeysetKind = "date" | "integer" | "number" | "text";
19
22
  type PostgresKeysetOptions = {
20
23
  /** The last row of the previous page; none for the first page. */
21
24
  after?: {
package/dist/index.js CHANGED
@@ -29,10 +29,25 @@ const isoInstantIs = (value) => {
29
29
  const [year = 0, month = 0, day = 0] = value.slice(0, 10).split("-").map(Number);
30
30
  return new Date(Date.UTC(year, month - 1, day)).getUTCDate() === day;
31
31
  };
32
- const afterValueAssert = (kind, value) => {
33
- if (!(kind === "number" ? typeof value === "number" && Number.isFinite(value) : typeof value === "string" && (kind === "text" || isoInstantIs(value)))) throw new TypeError(`A ${kind} keyset needs ${kind === "number" ? "a finite number" : kind === "date" ? "an ISO instant such as 2026-01-01T00:00:00.000Z" : "a string"}, got ${JSON.stringify(value)}`);
32
+ const INT4 = [-(2 ** 31), 2 ** 31 - 1];
33
+ const INT2 = [-(2 ** 15), 2 ** 15 - 1];
34
+ const integerRanges = {
35
+ integer: INT4,
36
+ serial: INT4,
37
+ smallint: INT2,
38
+ smallserial: INT2
39
+ };
40
+ const integerKindAssert = (sortColumn) => {
41
+ const type = sortColumn.getSQLType();
42
+ if (integerRanges[type] !== INT4) throw new TypeError(`An integer keyset needs an integer or serial column, got ${type}`);
43
+ };
44
+ const afterValueAssert = ({ kind, sortColumn, value }) => {
45
+ const numeric = kind === "integer" || kind === "number";
46
+ const range = numeric ? integerRanges[sortColumn.getSQLType()] : void 0;
47
+ if (!(numeric ? typeof value === "number" && (range ? Number.isInteger(value) && value >= range[0] && value <= range[1] : Number.isFinite(value)) : typeof value === "string" && (kind === "text" || isoInstantIs(value)))) throw new TypeError(`${kind === "integer" ? "An" : "A"} ${kind} keyset needs ${range ? `an integer from ${range[0]} to ${range[1]}` : kind === "number" ? "a finite number" : kind === "date" ? "an ISO instant such as 2026-01-01T00:00:00.000Z" : "a string"}, got ${JSON.stringify(value)}`);
34
48
  };
35
49
  const postgresKeysetCreate = ({ after, descending, idColumn, kind, sortColumn }) => {
50
+ if (kind === "integer") integerKindAssert(sortColumn);
36
51
  const sortBy = kind === "text" ? sql`${sortColumn} COLLATE "C"` : sql`${sortColumn}`;
37
52
  const direction = descending ? sql`DESC` : sql`ASC`;
38
53
  const orderBy = [sql`${sortBy} ${direction}`, sql`${idColumn} ${direction}`];
@@ -40,7 +55,11 @@ const postgresKeysetCreate = ({ after, descending, idColumn, kind, sortColumn })
40
55
  orderBy,
41
56
  where: void 0
42
57
  };
43
- afterValueAssert(kind, after.value);
58
+ afterValueAssert({
59
+ kind,
60
+ sortColumn,
61
+ value: after.value
62
+ });
44
63
  const value = kind === "date" ? sql`${after.value}::timestamptz` : sql`${after.value}`;
45
64
  return {
46
65
  orderBy,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@n8io/baseline-postgres",
3
- "version": "5.2.0",
3
+ "version": "5.3.0",
4
4
  "description": "Postgres pool, Result-aware transactions, migrations and prefixed-id columns on pg and Drizzle.",
5
5
  "type": "module",
6
6
  "license": "MIT",