uql-orm 0.91.1 → 0.92.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.
Files changed (156) hide show
  1. package/dist/browser/http/bus.js +3 -4
  2. package/dist/browser/http/http.d.ts +1 -2
  3. package/dist/browser/http/http.js +8 -7
  4. package/dist/browser/index.d.ts +0 -1
  5. package/dist/browser/index.js +0 -1
  6. package/dist/browser/querier/httpQuerier.d.ts +18 -20
  7. package/dist/browser/querier/httpQuerier.js +20 -56
  8. package/dist/browser/type/index.d.ts +0 -1
  9. package/dist/browser/type/index.js +0 -1
  10. package/dist/browser/uql-browser.min.js +2 -2
  11. package/dist/browser/uql-browser.min.js.map +11 -12
  12. package/dist/cockroachdb/cockroachDialect.d.ts +4 -1
  13. package/dist/cockroachdb/cockroachDialect.js +5 -1
  14. package/dist/dialect/abstractDialect.d.ts +1 -1
  15. package/dist/dialect/abstractDialect.js +4 -1
  16. package/dist/dialect/abstractSqlDialect.d.ts +24 -28
  17. package/dist/dialect/abstractSqlDialect.js +47 -45
  18. package/dist/dialect/aliases.d.ts +4 -1
  19. package/dist/dialect/aliases.js +5 -2
  20. package/dist/dialect/hydrateColumn.js +3 -10
  21. package/dist/dialect/jsonSql.d.ts +4 -1
  22. package/dist/dialect/jsonSql.js +4 -1
  23. package/dist/dialect/mergeSqlDialect.d.ts +4 -3
  24. package/dist/dialect/mergeSqlDialect.js +5 -4
  25. package/dist/dialect/mysqlLikeSqlDialect.d.ts +7 -21
  26. package/dist/dialect/mysqlLikeSqlDialect.js +9 -36
  27. package/dist/dialect/pgLikeSqlDialect.d.ts +3 -7
  28. package/dist/dialect/pgLikeSqlDialect.js +11 -21
  29. package/dist/http/contract.d.ts +4 -0
  30. package/dist/http/contract.js +1 -0
  31. package/dist/http/handler.d.ts +2 -2
  32. package/dist/http/handler.js +17 -19
  33. package/dist/http/query.d.ts +5 -3
  34. package/dist/http/query.js +42 -42
  35. package/dist/index.d.ts +1 -1
  36. package/dist/index.js +1 -1
  37. package/dist/maria/mariaDialect.d.ts +2 -3
  38. package/dist/maria/mariaDialect.js +1 -5
  39. package/dist/migrate/builder/columnBuilder.d.ts +5 -15
  40. package/dist/migrate/builder/columnBuilder.js +50 -86
  41. package/dist/migrate/builder/expressions.d.ts +12 -18
  42. package/dist/migrate/builder/expressions.js +39 -42
  43. package/dist/migrate/builder/migrationBuilder.d.ts +3 -11
  44. package/dist/migrate/builder/migrationBuilder.js +41 -81
  45. package/dist/migrate/builder/tableBuilder.d.ts +0 -7
  46. package/dist/migrate/builder/tableBuilder.js +17 -28
  47. package/dist/migrate/builder/types.d.ts +2 -2
  48. package/dist/migrate/codegen/entityCodeGenerator.js +3 -3
  49. package/dist/migrate/codegen/entityTypes.js +2 -2
  50. package/dist/migrate/codegen/fieldOptionsSource.d.ts +2 -2
  51. package/dist/migrate/codegen/fieldOptionsSource.js +27 -12
  52. package/dist/migrate/codegen/indexDecoratorSource.js +64 -41
  53. package/dist/migrate/ddl/index.d.ts +2 -4
  54. package/dist/migrate/ddl/index.js +14 -5
  55. package/dist/migrate/ddl/mssqlTableDdl.d.ts +1 -0
  56. package/dist/migrate/ddl/mssqlTableDdl.js +4 -1
  57. package/dist/migrate/ddl/mysqlTableDdl.d.ts +17 -0
  58. package/dist/migrate/ddl/mysqlTableDdl.js +33 -0
  59. package/dist/migrate/ddl/pgTableDdl.d.ts +7 -0
  60. package/dist/migrate/ddl/pgTableDdl.js +17 -0
  61. package/dist/migrate/ddl/tableDdl.d.ts +15 -10
  62. package/dist/migrate/ddl/tableDdl.js +31 -32
  63. package/dist/migrate/drift/driftDetector.js +46 -59
  64. package/dist/migrate/generator/definitionToNode.d.ts +11 -7
  65. package/dist/migrate/generator/definitionToNode.js +27 -34
  66. package/dist/migrate/generator/indexNodeToSchema.d.ts +3 -3
  67. package/dist/migrate/generator/indexNodeToSchema.js +5 -4
  68. package/dist/migrate/index.js +1 -1
  69. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +10 -5
  70. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +10 -0
  71. package/dist/migrate/introspection/baseSqlIntrospector.d.ts +0 -1
  72. package/dist/migrate/introspection/baseSqlIntrospector.js +6 -8
  73. package/dist/migrate/introspection/mssqlIntrospector.js +3 -8
  74. package/dist/migrate/introspection/mysqlIntrospector.d.ts +11 -4
  75. package/dist/migrate/introspection/mysqlIntrospector.js +25 -11
  76. package/dist/migrate/introspection/postgresIntrospector.d.ts +2 -2
  77. package/dist/migrate/introspection/postgresIntrospector.js +3 -3
  78. package/dist/migrate/introspection/sqliteIntrospector.d.ts +1 -1
  79. package/dist/migrate/introspection/sqliteIntrospector.js +7 -10
  80. package/dist/migrate/migrationTarget.js +3 -3
  81. package/dist/migrate/schemaGenerator.d.ts +8 -12
  82. package/dist/migrate/schemaGenerator.js +35 -61
  83. package/dist/migrate/triggerSql.d.ts +1 -1
  84. package/dist/migrate/triggerSql.js +8 -6
  85. package/dist/mongo/mongoDialect.d.ts +4 -3
  86. package/dist/mongo/mongoDialect.js +52 -38
  87. package/dist/mongo/mongoIntrospector.js +1 -1
  88. package/dist/mongo/mongoSchemaGenerator.d.ts +7 -4
  89. package/dist/mongo/mongoSchemaGenerator.js +18 -21
  90. package/dist/mongo/mongodbQuerier.d.ts +2 -3
  91. package/dist/mongo/mongodbQuerier.js +9 -28
  92. package/dist/mssql/mssqlDialect.d.ts +4 -5
  93. package/dist/mssql/mssqlDialect.js +9 -7
  94. package/dist/postgres/postgresDialect.js +2 -2
  95. package/dist/querier/abstractQuerier.d.ts +16 -11
  96. package/dist/querier/abstractQuerier.js +74 -26
  97. package/dist/querier/abstractQuerierPool.d.ts +26 -24
  98. package/dist/querier/abstractQuerierPool.js +26 -64
  99. package/dist/querier/abstractSqlQuerier.d.ts +2 -3
  100. package/dist/querier/abstractSqlQuerier.js +8 -26
  101. package/dist/querier/cursor.d.ts +10 -0
  102. package/dist/querier/cursor.js +81 -0
  103. package/dist/querier/keyset.d.ts +19 -0
  104. package/dist/querier/keyset.js +198 -0
  105. package/dist/schema/canonicalType.d.ts +3 -3
  106. package/dist/schema/canonicalType.js +13 -12
  107. package/dist/schema/indexDifferences.d.ts +14 -7
  108. package/dist/schema/indexDifferences.js +7 -5
  109. package/dist/schema/schemaAST.d.ts +0 -1
  110. package/dist/schema/schemaAST.js +0 -2
  111. package/dist/schema/schemaASTBuilder.js +28 -20
  112. package/dist/schema/schemaASTDiffer.d.ts +7 -9
  113. package/dist/schema/schemaASTDiffer.js +54 -107
  114. package/dist/schema/sqlExpression.d.ts +22 -0
  115. package/dist/schema/sqlExpression.js +28 -0
  116. package/dist/schema/types.d.ts +48 -105
  117. package/dist/sqlite/sqliteDialect.d.ts +9 -13
  118. package/dist/sqlite/sqliteDialect.js +10 -29
  119. package/dist/type/dialect.d.ts +20 -3
  120. package/dist/type/entity.d.ts +3 -3
  121. package/dist/type/migration.d.ts +7 -7
  122. package/dist/type/querier.d.ts +19 -26
  123. package/dist/type/query.d.ts +104 -24
  124. package/dist/type/query.js +21 -28
  125. package/dist/type/universalQuerier.d.ts +31 -5
  126. package/dist/type/utility.d.ts +10 -0
  127. package/dist/util/bytes.d.ts +7 -0
  128. package/dist/util/bytes.js +22 -0
  129. package/dist/util/date.d.ts +5 -0
  130. package/dist/util/date.js +5 -0
  131. package/dist/util/dialect.util.d.ts +1 -25
  132. package/dist/util/dialect.util.js +4 -50
  133. package/dist/util/field.util.d.ts +9 -0
  134. package/dist/util/field.util.js +15 -0
  135. package/dist/util/fieldOption.util.js +2 -2
  136. package/dist/util/index.d.ts +1 -0
  137. package/dist/util/index.js +1 -0
  138. package/dist/util/object.util.d.ts +0 -2
  139. package/dist/util/object.util.js +0 -7
  140. package/dist/util/query.util.d.ts +40 -0
  141. package/dist/util/query.util.js +76 -0
  142. package/dist/util/raw.d.ts +5 -0
  143. package/dist/util/raw.js +5 -0
  144. package/dist/util/relationQuery.util.js +18 -16
  145. package/dist/util/rowKey.util.js +2 -3
  146. package/dist/util/sql.util.d.ts +8 -2
  147. package/dist/util/sql.util.js +16 -17
  148. package/dist/util/sqlLiteral.js +2 -12
  149. package/dist/util/string.util.d.ts +5 -0
  150. package/dist/util/string.util.js +12 -0
  151. package/package.json +1 -1
  152. package/skills/uql-orm/SKILL.md +21 -10
  153. package/dist/browser/options.d.ts +0 -4
  154. package/dist/browser/options.js +0 -13
  155. package/dist/browser/type/clientQuerierPool.d.ts +0 -4
  156. package/dist/browser/type/clientQuerierPool.js +0 -1
@@ -1,9 +1,8 @@
1
1
  import { AbstractSqlDialect, } from '../dialect/abstractSqlDialect.js';
2
2
  import { BYTES_PREFIX } from '../dialect/hydrateColumn.js';
3
- import { chainedCall, groupsPerCall, jsonSetCall, jsonPath, jsonArraySlotArgs, jsonSlotArgs, jsonRemoveCall, jsonSetTarget, } from '../dialect/jsonSql.js';
3
+ import { chainedCall, groupsPerCall, jsonSetCall, jsonPath, jsonArraySlotArgs, jsonSlotArgs, } from '../dialect/jsonSql.js';
4
4
  import { QueryRaw, } from '../type/index.js';
5
5
  import { indexDistance, isVectorIndexType } from '../type/vector.js';
6
- import { utcTimestamp } from '../util/date.js';
7
6
  import { declaredIndexName } from '../util/ddlExpression.util.js';
8
7
  import { findVectorIndex, findVectorSort, textSearchFields, vectorCandidates } from '../util/dialect.util.js';
9
8
  import { isIntegerColumn } from '../util/field.util.js';
@@ -32,6 +31,7 @@ export const SQLITE_FEATURES = {
32
31
  serverSideCursors: false,
33
32
  correlatedWrites: true,
34
33
  rowLocks: false,
34
+ nullsSortLowest: true,
35
35
  nullsOrdering: 'clause',
36
36
  textScoreIndexes: false,
37
37
  orderedUpsertReturning: true,
@@ -40,7 +40,6 @@ export const SQLITE_FEATURES = {
40
40
  vectorTuningNeedsTransaction: false,
41
41
  serialDeclaresPrimaryKey: true,
42
42
  triggers: {
43
- preamble: '',
44
43
  assignsRow: false,
45
44
  body: 'inline',
46
45
  fires: 'eachRowWhen',
@@ -54,16 +53,16 @@ export class SqliteDialect extends AbstractSqlDialect {
54
53
  dialectName = 'sqlite';
55
54
  escapeIdChar = '`';
56
55
  autoIncrementSuffix = 'PRIMARY KEY AUTOINCREMENT';
57
- tableOptions = '';
58
56
  beginTransactionCommand = 'BEGIN TRANSACTION';
59
- commitTransactionCommand = 'COMMIT';
60
- rollbackTransactionCommand = 'ROLLBACK';
61
57
  isolationLevelStrategy = 'none';
62
58
  booleanLiteral = 'integer';
59
+ /**
60
+ * Writes the same text as a bound `Date`. `CURRENT_TIMESTAMP` writes whole seconds with no fraction, so the
61
+ * two would not compare correctly. The parentheses also let SQLite take it as a column default.
62
+ */
63
+ currentTimestamp = "(strftime('%Y-%m-%d %H:%M:%f', 'now'))";
63
64
  /** SQLite's own cap on a function call before 3.48, which libSQL and `bun:sqlite`'s build still have. */
64
65
  maxFunctionArgs = 127;
65
- // SQLite supports `RETURNING` (including on `INSERT ... ON CONFLICT`), so IDs are exact per row.
66
- insertIdSource = 'returning';
67
66
  /**
68
67
  * The [sqlite-vec](https://github.com/asg017/sqlite-vec) functions, which need that extension
69
68
  * loaded on the connection (see `Sqlite3QuerierPool`'s `extensions` option). libSQL and Turso ship
@@ -123,21 +122,9 @@ export class SqliteDialect extends AbstractSqlDialect {
123
122
  neExpr(field, ph) {
124
123
  return `${field} IS NOT ${ph}`;
125
124
  }
126
- normalizeValue(value) {
127
- if (value instanceof Date)
128
- return utcTimestamp(value);
129
- return super.normalizeValue(value);
130
- }
131
- /**
132
- * `OFFSET` is only legal after a `LIMIT` here too, so a bare `$skip` needs one - `-1` being
133
- * SQLite's own spelling of "no limit", where the MySQL family uses its largest `BIGINT`.
134
- */
135
- pager(ctx, opts) {
136
- if (opts.$limit === undefined && opts.$skip !== undefined) {
137
- ctx.append(' LIMIT -1');
138
- }
139
- super.pager(ctx, opts);
140
- }
125
+ dateZone = '';
126
+ /** SQLite's own spelling of no limit. */
127
+ unboundedLimit = '-1';
141
128
  /** `json_group_array` of each row's object, ordered by the sort terms carried out beside them. */
142
129
  appendRelationArray(ctx, rows) {
143
130
  const { from, pairs, order } = this.derivedRelation(ctx, rows);
@@ -222,14 +209,8 @@ export class SqliteDialect extends AbstractSqlDialect {
222
209
  jsonArrayOf(elem) {
223
210
  return `JSON_GROUP_ARRAY(JSON(${elem}))`;
224
211
  }
225
- jsonSet(ctx, expr, set, field) {
226
- return jsonSetCall((value) => this.jsonScalarParam(ctx, value), jsonSetTarget(expr, field, `'{}'`), set, this.maxFunctionArgs);
227
- }
228
212
  /** `[#]` appends, creating the array where it is absent: `JSON_SET`, since Turso's `JSON_INSERT` will not touch an existing array. */
229
213
  jsonPush(ctx, expr, push) {
230
214
  return jsonSetCall((value) => this.jsonScalarParam(ctx, value), expr, push, this.maxFunctionArgs, '[#]');
231
215
  }
232
- jsonUnset(_ctx, expr, unset) {
233
- return jsonRemoveCall(expr, unset, this.maxFunctionArgs);
234
- }
235
216
  }
@@ -135,6 +135,12 @@ export interface DialectFeatures {
135
135
  * value rather than a flag each, since the details mean nothing without a lock.
136
136
  */
137
137
  readonly rowLocks: RowLockFeatures | false;
138
+ /**
139
+ * Whether a sort without `NULLS FIRST/LAST` treats nulls as lower than every value, putting them first on
140
+ * `asc`. True everywhere but Postgres, which treats them as higher. Cursor pagination reads it to know which
141
+ * side of a value the nulls fall on.
142
+ */
143
+ readonly nullsSortLowest: boolean;
138
144
  }
139
145
  /** How a dialect spells a row lock, once {@link DialectFeatures.rowLocks} says it has one. */
140
146
  export interface RowLockFeatures {
@@ -204,11 +210,17 @@ export interface TriggerFeatures {
204
210
  */
205
211
  readonly layout: 'timingFirst' | 'tableFirst';
206
212
  /**
207
- * What every body opens with, or `''`. T-SQL wants `SET NOCOUNT ON`: a trigger running its own DML
213
+ * SQL that every trigger body starts with, if any. T-SQL wants `SET NOCOUNT ON`: a trigger running its own DML
208
214
  * otherwise sends a rowcount of its own back, and the client reads that as what the original statement
209
- * affected. Nothing else here needs a preamble.
215
+ * affected.
216
+ */
217
+ readonly preamble?: string;
218
+ /**
219
+ * SQL a stamp that restates its row runs first, to return early when its own write fired it; unset where not
220
+ * needed. SQL Server fires a trigger once per statement, even for no rows, and reads its clock anew each time,
221
+ * so two stamps on one table would otherwise keep firing each other up to the nesting limit.
210
222
  */
211
- readonly preamble: string;
223
+ readonly reentryGuard?: string;
212
224
  /**
213
225
  * Whether a body may assign to the row it was handed, `NEW."col" := ...`. SQLite forbids writing `NEW`
214
226
  * at all, and SQL Server is handed a set rather than a row, so on both a trigger that fills a column
@@ -270,6 +282,11 @@ export interface SqlQueryDialect {
270
282
  readonly escapeIdChar: '"' | '`';
271
283
  /** What the engine can do. */
272
284
  readonly features: SqlDialectFeatures;
285
+ /**
286
+ * SQL for the database's current time the way uql stores a timestamp: UTC, to the millisecond, in the same
287
+ * form as a bound `Date`. A bare `CURRENT_TIMESTAMP` falls short of this on SQLite, MySQL and SQL Server.
288
+ */
289
+ readonly currentTimestamp: string;
273
290
  /** A read; with `totalAlias`, every row also carries the unpaged match count under that alias. */
274
291
  find<E>(ctx: QueryContext, entity: Type<E>, q: Query<E>, opts?: QueryRenderOptions, totalAlias?: string): void;
275
292
  /** A count of the records matching the filter, or of those a page of it takes. */
@@ -280,7 +280,7 @@ export type FieldOptions<V = TsTypeOf<FieldType>, E = unknown> = {
280
280
  /**
281
281
  * Where {@link FieldOptions.computed} lives instead of being spliced into each read. `true` makes it a
282
282
  * generated column, which takes only an immutable expression; a list of events makes it a stamp a trigger
283
- * writes on each, whoever writes the row - how `CURRENT_TIMESTAMP` is kept, where `onUpdate` sees only uql's writes.
283
+ * writes on each, whoever writes the row. It keeps a `currentTimestamp` current; `onUpdate` sees only uql's writes.
284
284
  */
285
285
  readonly stored?: boolean | readonly StampEvent[];
286
286
  readonly updatable?: boolean;
@@ -312,8 +312,8 @@ export type FieldOptions<V = TsTypeOf<FieldType>, E = unknown> = {
312
312
  readonly scale?: number;
313
313
  readonly nullable?: boolean;
314
314
  readonly unique?: boolean;
315
- /** The column's DDL default. */
316
- readonly defaultValue?: DdlDefault<V>;
315
+ /** The column's DDL default: a literal, or SQL the database evaluates per inserted row (`currentTimestamp`, `raw`). */
316
+ readonly defaultValue?: DdlDefault<V> | QueryRaw;
317
317
  /** Whether the database generates the value; a numeric sole key does unless something else fills it. */
318
318
  readonly autoIncrement?: boolean;
319
319
  /**
@@ -3,7 +3,7 @@ import type { IndexFacet } from '../schema/indexDifferences.js';
3
3
  import type { SchemaAST } from '../schema/schemaAST.js';
4
4
  import type { DiffOptions } from '../schema/schemaASTDiffer.js';
5
5
  import type { ColumnNode, ForeignKeyAction, IndexType, TableNode } from '../schema/types.js';
6
- import type { EntityMeta, EntityWhereMeta, FieldOptions, IndexColumnSchema, IndexedVectorField, LoggingOptions, Querier, SqlQuerier, Type, VectorIndexOptions } from './index.js';
6
+ import type { EntityMeta, EntityWhereMeta, Except, FieldOptions, IndexColumnSchema, IndexedVectorField, LoggingOptions, Querier, SqlQuerier, Type, VectorIndexOptions } from './index.js';
7
7
  /**
8
8
  * Defines a migration using a simple object literal. `Q` is `MongoQuerier` for a MongoDB migration.
9
9
  */
@@ -102,7 +102,7 @@ export interface MigrationResult {
102
102
  readonly error?: Error;
103
103
  }
104
104
  /** A column as a statement renders one: a {@link ColumnNode} with the engine's type spelling and no graph links. */
105
- export interface ColumnSchema extends Omit<ColumnNode, 'type' | 'table' | 'referencedBy' | 'references'> {
105
+ export interface ColumnSchema extends Except<ColumnNode, 'type' | 'table' | 'referencedBy' | 'references'> {
106
106
  /**
107
107
  * The engine's own type spelling, `TINYINT(1)`, compared as stored: canonical types would differ where
108
108
  * the engine stores them alike. `sqlToCanonical` reads it.
@@ -182,11 +182,6 @@ export interface ForeignKeySchema {
182
182
  readonly onDelete?: ForeignKeyAction;
183
183
  readonly onUpdate?: ForeignKeyAction;
184
184
  }
185
- /**
186
- * One object's change: added (`to` alone), dropped (`from` alone), or altered (both), each whole so the
187
- * change is undone by swapping its ends. No engine alters an index, a key or a foreign key in place, so
188
- * an alter of one is its drop and its add, which safe mode holds back together.
189
- */
190
185
  /** A column's change, and whether it can lose what the column holds: a drop, or a retype that narrows it. */
191
186
  export type ColumnChange = Change<ColumnSchema> & {
192
187
  readonly isBreaking?: boolean;
@@ -198,6 +193,11 @@ export type Rename = {
198
193
  };
199
194
  /** Renamed columns by qualified table name. */
200
195
  export type ColumnRenames = ReadonlyMap<string, readonly Rename[]>;
196
+ /**
197
+ * One object's change: added (`to` alone), dropped (`from` alone), or altered (both). Each side is the whole
198
+ * object, so swapping them undoes the change. No engine alters an index, a key or a foreign key in place, so
199
+ * altering one is a drop plus an add, which safe mode holds back together.
200
+ */
201
201
  export interface Change<T> {
202
202
  readonly from?: T;
203
203
  readonly to?: T;
@@ -3,9 +3,10 @@ import type { SqlDialectName } from './dialect.js';
3
3
  import type { FieldKey, HookEvent, RelationKey } from './entity.js';
4
4
  import type { LoggingOptions } from './logger.js';
5
5
  import type { NamingStrategy } from './namingStrategy.js';
6
- import type { QueryFilter, QueryFindResult, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, QueryUpdateResult } from './query.js';
7
- import type { UniversalQuerier } from './universalQuerier.js';
6
+ import type { QueryFilter, QueryFindResult, QueryOptions, QueryPage, QuerySearch, QueryUpdateResult } from './query.js';
7
+ import type { ProjectedQuery, ProjectedRead, ProjectedResult, UniversalQuerier } from './universalQuerier.js';
8
8
  import type { Type } from './utility.js';
9
+ import type { QuerierRaw } from './wire.js';
9
10
  /**
10
11
  * Isolation levels for transactions.
11
12
  */
@@ -22,32 +23,23 @@ export type TransactionOptions = {
22
23
  };
23
24
  export type DialectName = SqlDialectName | 'mongodb';
24
25
  /**
25
- * The read and delete methods below take the entity as an argument or as the query's `$entity` key.
26
- * In each pair the `$entity` overload comes **first** on purpose: when no overload matches,
27
- * TypeScript reports the error from the *last* one, so keeping the entity-argument form last is
28
- * what makes a typo'd query key report as itself rather than as a missing `$entity`.
26
+ * A projected read that takes the entity first or as the query's `$entity`. The `$entity` form comes
27
+ * **first** on purpose: when no signature matches, TypeScript reports the error of the *last* one, so a
28
+ * typo'd query key is reported as itself rather than as a missing `$entity`.
29
29
  */
30
+ type DualRead<Q extends keyof ProjectedQuery<object, never, never, never, never, never, never>, R extends keyof ProjectedResult<'server', unknown>> = (<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(q: ProjectedQuery<E, S, V, X, P, C, QuerierRaw<'server'>>[Q] & {
31
+ $entity: Type<E>;
32
+ }, opts?: QueryOptions) => ProjectedResult<'server', QueryFindResult<E, S, V, X, P, C>>[R]) & ProjectedRead<Q, R, 'server', QueryOptions>;
33
+ /** The reads, counts and deletes below take the entity first or as the query's `$entity`, as {@link DualRead} does. */
30
34
  export interface Querier extends UniversalQuerier {
31
- /** Find one record, the entity passed first or as the query's `$entity`. */
32
- findOne<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(q: QueryOneProjected<E, S, V, X, P, C> & {
33
- $entity: Type<E>;
34
- }, opts?: QueryOptions): Promise<QueryFindResult<E, S, V, X, P, C> | undefined>;
35
- findOne<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(entity: Type<E>, q: QueryOneProjected<E, S, V, X, P, C>, opts?: QueryOptions): Promise<QueryFindResult<E, S, V, X, P, C> | undefined>;
36
- /** Find many records, the entity passed first or as the query's `$entity`. */
37
- findMany<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(q: QueryProjected<E, S, V, X, P, C> & {
38
- $entity: Type<E>;
39
- }, opts?: QueryOptions): Promise<QueryFindResult<E, S, V, X, P, C>[]>;
40
- findMany<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(entity: Type<E>, q: QueryProjected<E, S, V, X, P, C>, opts?: QueryOptions): Promise<QueryFindResult<E, S, V, X, P, C>[]>;
41
- /** Stream records with the relations and counts `findMany` reads, the entity passed first or as `$entity`. No hooks fire. */
42
- findManyStream<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(q: QueryProjected<E, S, V, X, P, C> & {
43
- $entity: Type<E>;
44
- }, opts?: QueryOptions): AsyncIterable<QueryFindResult<E, S, V, X, P, C>>;
45
- findManyStream<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(entity: Type<E>, q: QueryProjected<E, S, V, X, P, C>, opts?: QueryOptions): AsyncIterable<QueryFindResult<E, S, V, X, P, C>>;
46
- /** Find many records and count every match, the entity passed first or as the query's `$entity`. */
47
- findManyAndCount<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(q: QueryProjected<E, S, V, X, P, C> & {
48
- $entity: Type<E>;
49
- }, opts?: QueryOptions): Promise<[QueryFindResult<E, S, V, X, P, C>[], number]>;
50
- findManyAndCount<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(entity: Type<E>, q: QueryProjected<E, S, V, X, P, C>, opts?: QueryOptions): Promise<[QueryFindResult<E, S, V, X, P, C>[], number]>;
35
+ findOne: DualRead<'one', 'one'>;
36
+ findMany: DualRead<'many', 'many'>;
37
+ /** Stream records with the relations and counts `findMany` reads. No hooks fire. */
38
+ findManyStream: DualRead<'many', 'stream'>;
39
+ /** Find many records and count every match. */
40
+ findManyAndCount: DualRead<'many', 'counted'>;
41
+ /** Read a page of records from a cursor. */
42
+ findManyPage: DualRead<'page', 'page'>;
51
43
  /** Count records, the entity passed first or as the query's `$entity`. */
52
44
  count<E extends object>(q: QueryPage<E> & {
53
45
  $entity: Type<E>;
@@ -149,3 +141,4 @@ export type ExtraOptions = {
149
141
  readonly schema?: string;
150
142
  readonly listeners?: readonly QuerierListener[];
151
143
  };
144
+ export {};
@@ -126,8 +126,8 @@ export type FilterOptions<E = unknown> = {
126
126
  /**
127
127
  * direction for the sort, and where nulls land in it.
128
128
  *
129
- * Unqualified, each engine has its own answer - Postgres and CockroachDB sort nulls last on `asc`, the
130
- * rest sort them first - so a placement is the only portable one. Engines with no `NULLS FIRST/LAST`
129
+ * Without a placement, engines disagree: Postgres sorts nulls last on `asc` and the rest sort them first,
130
+ * so only an explicit placement is portable. Engines with no `NULLS FIRST/LAST`
131
131
  * emulate it with a leading term, which no index can serve, which is why it is asked for and never
132
132
  * applied by default.
133
133
  */
@@ -280,31 +280,83 @@ export type Query<E, Raw = QueryRaw> = {
280
280
  */
281
281
  export type WireQuery<E> = Query<E, never>;
282
282
  /**
283
- * `Query`'s clauses grouped by the shape of their value, for the wire parser and the relation query
284
- * check alike; `satisfies` keeps them in step with `Query`.
283
+ * The type of a clause's value, and where the clause may appear: a `relation` clause is also allowed in a
284
+ * populated relation's own query, a `statement` clause only in the statement itself.
285
285
  */
286
- export declare const QUERY_OBJECT_CLAUSES: readonly ["$select", "$populate", "$exclude", "$where", "$sort"];
287
- /**
288
- * Object clauses only the statement itself takes: a populated relation's rows keep their declared type,
289
- * so a `$count` inside one would have no `_count` to land in.
290
- */
291
- export declare const QUERY_ROOT_OBJECT_CLAUSES: readonly ["$count"];
292
- export declare const QUERY_NUMBER_CLAUSES: readonly ["$skip", "$limit"];
293
- /**
294
- * Number clauses only the statement itself takes - the numeric mirror of {@link QUERY_ROOT_OBJECT_CLAUSES}.
295
- * `$candidates` tunes the index behind a vector search, and a vector search only ever ranks the rows
296
- * the statement returns, so a relation's own query has nothing to tune.
297
- */
298
- export declare const QUERY_ROOT_NUMBER_CLAUSES: readonly ["$candidates"];
299
- export declare const QUERY_BOOLEAN_CLAUSES: readonly ["$distinct"];
300
- /** The clauses that describe the statement, which a populated relation's own query refuses by name. */
301
- export declare const QUERY_STATEMENT_CLAUSES: readonly ["$lock", "$count", "$candidates"];
302
- type RelationClause = (typeof QUERY_OBJECT_CLAUSES | typeof QUERY_NUMBER_CLAUSES | typeof QUERY_BOOLEAN_CLAUSES)[number];
286
+ export type QueryClause = {
287
+ readonly value: 'object' | 'number' | 'boolean' | 'string';
288
+ readonly scope: 'relation' | 'statement';
289
+ };
303
290
  /**
304
- * A populated relation's own query: the clause groups its runtime check accepts, so the two cannot
305
- * drift, and a clause added to {@link Query} stays off it until it joins one of them.
291
+ * Every clause of `Query` and `QueryKeyset`, read by both the wire parser and the relation query check. It
292
+ * must cover both types, so a clause added to either fails to compile until it is declared here.
306
293
  */
307
- export type RelationQuery<E = object, Raw = QueryRaw> = Pick<Query<E, Raw>, RelationClause> & {
294
+ export declare const QUERY_CLAUSES: {
295
+ readonly $select: {
296
+ readonly value: 'object';
297
+ readonly scope: 'relation';
298
+ };
299
+ readonly $populate: {
300
+ readonly value: 'object';
301
+ readonly scope: 'relation';
302
+ };
303
+ readonly $exclude: {
304
+ readonly value: 'object';
305
+ readonly scope: 'relation';
306
+ };
307
+ readonly $where: {
308
+ readonly value: 'object';
309
+ readonly scope: 'relation';
310
+ };
311
+ readonly $sort: {
312
+ readonly value: 'object';
313
+ readonly scope: 'relation';
314
+ };
315
+ readonly $skip: {
316
+ readonly value: 'number';
317
+ readonly scope: 'relation';
318
+ };
319
+ readonly $limit: {
320
+ readonly value: 'number';
321
+ readonly scope: 'relation';
322
+ };
323
+ readonly $distinct: {
324
+ readonly value: 'boolean';
325
+ readonly scope: 'relation';
326
+ };
327
+ readonly $count: {
328
+ readonly value: 'object';
329
+ readonly scope: 'statement';
330
+ };
331
+ readonly $candidates: {
332
+ readonly value: 'number';
333
+ readonly scope: 'statement';
334
+ };
335
+ readonly $lock: {
336
+ readonly value: 'object';
337
+ readonly scope: 'statement';
338
+ };
339
+ readonly $after: {
340
+ readonly value: 'string';
341
+ readonly scope: 'statement';
342
+ };
343
+ readonly $before: {
344
+ readonly value: 'string';
345
+ readonly scope: 'statement';
346
+ };
347
+ };
348
+ type QueryClauseKey = keyof typeof QUERY_CLAUSES;
349
+ /** The keys of the `QUERY_CLAUSES` entries that match `Shape`, such as `{ scope: 'relation' }`. */
350
+ export type QueryClauseOf<Shape extends Partial<QueryClause>> = {
351
+ [K in QueryClauseKey]: (typeof QUERY_CLAUSES)[K] extends Shape ? K : never;
352
+ }[QueryClauseKey];
353
+ /**
354
+ * A populated relation's own query: the clauses {@link QUERY_CLAUSES} gives the `relation` scope. Its runtime
355
+ * check reads the same table, so the two cannot drift.
356
+ */
357
+ export type RelationQuery<E = object, Raw = QueryRaw> = Pick<Query<E, Raw>, QueryClauseOf<{
358
+ scope: 'relation';
359
+ }>> & {
308
360
  $required?: boolean;
309
361
  };
310
362
  /**
@@ -334,6 +386,34 @@ export type QueryProjected<E, S extends FieldKey<E>, V, X extends FieldKey<E>, P
334
386
  * A {@link QueryOne} whose projection is captured, so {@link QueryFindResult} can shape the row.
335
387
  */
336
388
  export type QueryOneProjected<E, S extends FieldKey<E>, V, X extends FieldKey<E>, P extends RelationKey<E>, C extends RelationKey<E> = never, Raw = QueryRaw> = QueryOne<E, Raw> & QueryProjection<E, S, V, X, P, C, Raw>;
389
+ /**
390
+ * The query `findManyPage` takes: a {@link Query} paged by cursor instead of offset, so it has no `$skip` and
391
+ * `$limit` is the page size. `$after` reads the page after a cursor, `$before` the page before it.
392
+ */
393
+ export type QueryKeyset<E, Raw = QueryRaw> = Except<Query<E, Raw>, '$skip'> & {
394
+ /** The page size, required here although `Query` leaves it optional. */
395
+ $limit: number;
396
+ /** A page's `endCursor`, to read the rows after it. */
397
+ $after?: string;
398
+ /** A page's `startCursor`, to read the rows before it. */
399
+ $before?: string;
400
+ };
401
+ /** A {@link QueryKeyset} with its projection captured, so {@link QueryFindResult} can narrow the row. */
402
+ export type QueryKeysetProjected<E, S extends FieldKey<E>, V, X extends FieldKey<E>, P extends RelationKey<E>, C extends RelationKey<E> = never, Raw = QueryRaw> = QueryKeyset<E, Raw> & QueryProjection<E, S, V, X, P, C, Raw>;
403
+ /**
404
+ * One page of `findManyPage`. Each cursor is opaque, and absent on an empty page. The flag in the reading
405
+ * direction is exact. The other one only says whether the page was read from a cursor (`hasPrevPage` forward,
406
+ * `hasNextPage` backward), since checking for rows on that side would cost another statement.
407
+ */
408
+ export type CursorPage<T> = {
409
+ readonly items: T[];
410
+ /** Pass as `$before` to read the page before this one. */
411
+ readonly startCursor?: string;
412
+ /** Pass as `$after` to read the page after this one. */
413
+ readonly endCursor?: string;
414
+ readonly hasNextPage: boolean;
415
+ readonly hasPrevPage: boolean;
416
+ };
337
417
  /**
338
418
  * The keys a query comes back with, as the runtime projects them: a positive `$select`'s, or every
339
419
  * field minus what `$select` or `$exclude` subtracts, plus the populated relations.
@@ -4,32 +4,25 @@
4
4
  */
5
5
  export const COUNT_RESULT_KEY = '_count';
6
6
  /**
7
- * `Query`'s clauses grouped by the shape of their value, for the wire parser and the relation query
8
- * check alike; `satisfies` keeps them in step with `Query`.
7
+ * Every clause of `Query` and `QueryKeyset`, read by both the wire parser and the relation query check. It
8
+ * must cover both types, so a clause added to either fails to compile until it is declared here.
9
9
  */
10
- export const QUERY_OBJECT_CLAUSES = [
11
- '$select',
12
- '$populate',
13
- '$exclude',
14
- '$where',
15
- '$sort',
16
- ];
17
- /**
18
- * Object clauses only the statement itself takes: a populated relation's rows keep their declared type,
19
- * so a `$count` inside one would have no `_count` to land in.
20
- */
21
- export const QUERY_ROOT_OBJECT_CLAUSES = ['$count'];
22
- export const QUERY_NUMBER_CLAUSES = ['$skip', '$limit'];
23
- /**
24
- * Number clauses only the statement itself takes - the numeric mirror of {@link QUERY_ROOT_OBJECT_CLAUSES}.
25
- * `$candidates` tunes the index behind a vector search, and a vector search only ever ranks the rows
26
- * the statement returns, so a relation's own query has nothing to tune.
27
- */
28
- export const QUERY_ROOT_NUMBER_CLAUSES = ['$candidates'];
29
- export const QUERY_BOOLEAN_CLAUSES = ['$distinct'];
30
- /** The clauses that describe the statement, which a populated relation's own query refuses by name. */
31
- export const QUERY_STATEMENT_CLAUSES = [
32
- '$lock',
33
- ...QUERY_ROOT_OBJECT_CLAUSES,
34
- ...QUERY_ROOT_NUMBER_CLAUSES,
35
- ];
10
+ export const QUERY_CLAUSES = {
11
+ $select: { value: 'object', scope: 'relation' },
12
+ $populate: { value: 'object', scope: 'relation' },
13
+ $exclude: { value: 'object', scope: 'relation' },
14
+ $where: { value: 'object', scope: 'relation' },
15
+ $sort: { value: 'object', scope: 'relation' },
16
+ $skip: { value: 'number', scope: 'relation' },
17
+ $limit: { value: 'number', scope: 'relation' },
18
+ $distinct: { value: 'boolean', scope: 'relation' },
19
+ // A populated relation's rows keep their declared type, so they have no `_count` for a `$count` to fill.
20
+ $count: { value: 'object', scope: 'statement' },
21
+ // A vector search ranks only the statement's rows, so a relation's own query has nothing for it to tune.
22
+ $candidates: { value: 'number', scope: 'statement' },
23
+ // Never decoded: HTTP refuses it, because a request cannot hold a lock past its response.
24
+ $lock: { value: 'object', scope: 'statement' },
25
+ // Statement only: keyset paging per parent of a populated relation is not supported.
26
+ $after: { value: 'string', scope: 'statement' },
27
+ $before: { value: 'string', scope: 'statement' },
28
+ };
@@ -1,8 +1,28 @@
1
1
  import type { EntityId, EntityWrite, FieldKey, RelationKey, UpdateWrite, WrittenId } from './entity.js';
2
- import type { QueryConflictPaths, QueryFilter, QueryFindResult, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, QueryUpsertOneResult, QueryUpsertManyResult } from './query.js';
2
+ import type { CursorPage, QueryConflictPaths, QueryFilter, QueryFindResult, QueryKeysetProjected, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, QueryUpsertOneResult, QueryUpsertManyResult } from './query.js';
3
3
  import type { QueryAggMap, QueryAggregate, QueryAggregateResult, QueryGroupMap } from './queryAggregate.js';
4
4
  import type { Type } from './utility.js';
5
5
  import type { QuerierCountedResult, QuerierRaw, QuerierResult, QuerierTransport } from './wire.js';
6
+ /** The query type each projected read takes, keyed by the kind of read. */
7
+ export type ProjectedQuery<E, S extends FieldKey<E>, V, X extends FieldKey<E>, P extends RelationKey<E>, C extends RelationKey<E>, Raw> = {
8
+ readonly one: QueryOneProjected<E, S, V, X, P, C, Raw>;
9
+ readonly many: QueryProjected<E, S, V, X, P, C, Raw>;
10
+ readonly page: QueryKeysetProjected<E, S, V, X, P, C, Raw>;
11
+ };
12
+ /** The result type of each projected read on transport `W`, keyed by the kind of read. */
13
+ export type ProjectedResult<W extends QuerierTransport, T> = {
14
+ readonly one: QuerierResult<W, T | undefined>;
15
+ readonly many: QuerierResult<W, T[]>;
16
+ readonly counted: QuerierCountedResult<W, T>;
17
+ readonly page: QuerierResult<W, CursorPage<T>>;
18
+ readonly stream: AsyncIterable<T>;
19
+ };
20
+ /**
21
+ * A read that takes an entity and a query, and returns rows narrowed to what the query projected. `Q` picks
22
+ * the query type, `R` the result type on transport `W`, and `O` the options. Declaring it once saves every
23
+ * such read from repeating the six type parameters.
24
+ */
25
+ export type ProjectedRead<Q extends keyof ProjectedQuery<object, never, never, never, never, never, never>, R extends keyof ProjectedResult<QuerierTransport, unknown>, W extends QuerierTransport, O> = <E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(entity: Type<E>, q: ProjectedQuery<E, S, V, X, P, C, QuerierRaw<W>>[Q], opts?: O) => ProjectedResult<W, QueryFindResult<E, S, V, X, P, C>>[R];
6
26
  /**
7
27
  * The operations the server and the browser client declare alike, per transport `W`, options `O`,
8
28
  * and delete options `DO`, which on the client also carry the {@link QueryOptions} it cannot pass otherwise.
@@ -16,16 +36,22 @@ export interface SharedQuerier<W extends QuerierTransport, O, DO = O> {
16
36
  * @param q the criteria options
17
37
  * @return the record
18
38
  */
19
- findOne<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(entity: Type<E>, q: QueryOneProjected<E, S, V, X, P, C, QuerierRaw<W>>, opts?: O): QuerierResult<W, QueryFindResult<E, S, V, X, P, C> | undefined>;
39
+ findOne: ProjectedRead<'one', 'one', W, O>;
20
40
  /**
21
41
  * obtains the records matching the given search parameters.
22
42
  * @param entity the target entity
23
43
  * @param q the criteria options
24
44
  * @return the records
25
45
  */
26
- findMany<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(entity: Type<E>, q: QueryProjected<E, S, V, X, P, C, QuerierRaw<W>>, opts?: O): QuerierResult<W, QueryFindResult<E, S, V, X, P, C>[]>;
46
+ findMany: ProjectedRead<'many', 'many', W, O>;
27
47
  /** Find the records matching the query, and count every match past its page. */
28
- findManyAndCount<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(entity: Type<E>, q: QueryProjected<E, S, V, X, P, C, QuerierRaw<W>>, opts?: O): QuerierCountedResult<W, QueryFindResult<E, S, V, X, P, C>>;
48
+ findManyAndCount: ProjectedRead<'many', 'counted', W, O>;
49
+ /**
50
+ * Read a page of the records matching the query, from a cursor instead of an offset, so every page costs
51
+ * the same as the first and rows written in between shift no page. The sort must be total: it must end in
52
+ * the key or a unique, non-null field. Counts nothing.
53
+ */
54
+ findManyPage: ProjectedRead<'page', 'page', W, O>;
29
55
  /** Count the records matching the filter, or those a page of them takes. */
30
56
  count<E extends object>(entity: Type<E>, q?: QueryPage<E, QuerierRaw<W>>, opts?: O): QuerierResult<W, number>;
31
57
  /** Whether any record matches: a count capped at one row, so the engine stops at the first match. */
@@ -57,7 +83,7 @@ export interface UniversalQuerier extends SharedQuerier<'server', QueryOptions>
57
83
  * Stream the records matching the query one at a time, each with the relations and counts `findMany`
58
84
  * reads, for bulk reads. Fires no lifecycle hooks.
59
85
  */
60
- findManyStream<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(entity: Type<E>, q: QueryProjected<E, S, V, X, P, C>, opts?: QueryOptions): AsyncIterable<QueryFindResult<E, S, V, X, P, C>>;
86
+ findManyStream: ProjectedRead<'many', 'stream', 'server', QueryOptions>;
61
87
  /** Insert a record and resolve to its id. See {@link UniversalQuerier.insertMany}. */
62
88
  insertOne<E extends object>(entity: Type<E>, payload: EntityWrite<E>): Promise<WrittenId<E> | undefined>;
63
89
  /**
@@ -47,6 +47,16 @@ export type Writable<T> = {
47
47
  /**
48
48
  * `Omit` whose key has to exist, which distributes over a union rather than flattening it, and removes
49
49
  * a key from a type with an index signature.
50
+ *
51
+ * `Omit<T, K>` is `Pick<T, Exclude<keyof T, K>>`; its `K extends keyof any` admits any string, so a typo
52
+ * (`Omit<Post, 'titl'>`) compiles and silently drops nothing. `Except` requires `K extends keyof T`, so a
53
+ * misspelled key is a compile error the instant it is written.
54
+ *
55
+ * Beyond the key check, the two differ structurally. `Omit` computes `keyof (A | B)` (the common keys),
56
+ * then `Pick`s from that flat set, so `Omit<A | B, 'x'>` loses every key unique to one arm. `Except` is a
57
+ * homomorphic mapped type over `T`, which TypeScript distributes over unions: `Except<A | B, 'x'>` is
58
+ * `Except<A, 'x'> | Except<B, 'x'>`, each arm keeping its own keys. It also preserves index signatures
59
+ * and property modifiers that `Pick` over a computed key set drops.
50
60
  */
51
61
  export type Except<T, K extends keyof T> = {
52
62
  [P in keyof T as P extends K ? never : P]: T[P];
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Encodes bytes as lowercase hex, two digits per byte. Uses `Buffer` when it exists (~130x faster on 4 KB),
3
+ * and a lookup table on the browser and edge runtimes, which lack it.
4
+ */
5
+ export declare function bytesToHex(bytes: Uint8Array): string;
6
+ /** Decodes the hex text {@link bytesToHex} writes back into bytes. */
7
+ export declare function hexToBytes(hex: string): Uint8Array;
@@ -0,0 +1,22 @@
1
+ const HEX_BYTES = Array.from({ length: 256 }, (_, byte) => byte.toString(16).padStart(2, '0'));
2
+ /**
3
+ * Encodes bytes as lowercase hex, two digits per byte. Uses `Buffer` when it exists (~130x faster on 4 KB),
4
+ * and a lookup table on the browser and edge runtimes, which lack it.
5
+ */
6
+ export function bytesToHex(bytes) {
7
+ if (typeof Buffer !== 'undefined') {
8
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('hex');
9
+ }
10
+ let hex = '';
11
+ for (let i = 0; i < bytes.length; i++)
12
+ hex += HEX_BYTES[bytes[i]];
13
+ return hex;
14
+ }
15
+ /** Decodes the hex text {@link bytesToHex} writes back into bytes. */
16
+ export function hexToBytes(hex) {
17
+ const bytes = new Uint8Array(hex.length / 2);
18
+ for (let at = 0; at < bytes.length; at++) {
19
+ bytes[at] = Number.parseInt(hex.slice(at * 2, at * 2 + 2), 16);
20
+ }
21
+ return bytes;
22
+ }
@@ -1,3 +1,8 @@
1
+ /**
2
+ * The fractional-second digits of a timestamp column uql declares when its field states no precision. It
3
+ * matches the milliseconds of a JS `Date` on every engine, so a value the database writes reads back exactly.
4
+ */
5
+ export declare const DATE_PRECISION = 3;
1
6
  /**
2
7
  * `YYYY-MM-DD HH:mm:ss.SSS` in UTC, then `zone`: how a date is written, whichever machine writes it. Not
3
8
  * `toISOString` as it is, whose `T` and `Z` MySQL rejects outright ("Invalid default value").
package/dist/util/date.js CHANGED
@@ -1,3 +1,8 @@
1
+ /**
2
+ * The fractional-second digits of a timestamp column uql declares when its field states no precision. It
3
+ * matches the milliseconds of a JS `Date` on every engine, so a value the database writes reads back exactly.
4
+ */
5
+ export const DATE_PRECISION = 3;
1
6
  /**
2
7
  * `YYYY-MM-DD HH:mm:ss.SSS` in UTC, then `zone`: how a date is written, whichever machine writes it. Not
3
8
  * `toISOString` as it is, whose `T` and `Z` MySQL rejects outright ("Invalid default value").