remult 3.4.2 → 3.5.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/esm/internals.js +1 -0
  2. package/esm/postgres/postgres-data-provider.js +4 -5
  3. package/esm/remult-duckdb.js +4 -0
  4. package/esm/remult-knex/index.js +40 -8
  5. package/esm/remult-mongo.js +25 -7
  6. package/esm/remult-sqlite-core.js +4 -1
  7. package/esm/server/remult-api-server.js +1 -1
  8. package/esm/src/buildRestDataProvider.js +4 -2
  9. package/esm/src/data-api.js +2 -2
  10. package/esm/src/data-interfaces.js +2 -1
  11. package/esm/src/data-providers/array-entity-data-provider.js +5 -0
  12. package/esm/src/data-providers/rest-data-provider-using-fetch.js +2 -2
  13. package/esm/src/data-providers/retry.js +11 -6
  14. package/esm/src/data-providers/sql-database.js +40 -30
  15. package/esm/src/live-query/SubscriptionChannel.js +13 -8
  16. package/esm/src/remult-static.js +1 -0
  17. package/esm/src/remult3/Fields.js +14 -14
  18. package/esm/src/remult3/RepositoryImplementation.js +45 -32
  19. package/esm/src/sort.js +18 -0
  20. package/index.d.ts +1 -1
  21. package/internals.d.ts +1 -0
  22. package/internals.js +3 -1
  23. package/package.json +41 -1
  24. package/postgres/postgres-data-provider.d.ts +2 -3
  25. package/postgres/postgres-data-provider.js +4 -4
  26. package/remult-duckdb.d.ts +2 -0
  27. package/remult-duckdb.js +4 -0
  28. package/remult-knex/index.d.ts +2 -0
  29. package/remult-knex/index.js +125 -78
  30. package/remult-mongo.js +28 -7
  31. package/remult-sqlite-core.d.ts +2 -1
  32. package/remult-sqlite-core.js +4 -0
  33. package/server/remult-api-server.d.ts +12 -1
  34. package/server/remult-api-server.js +1 -1
  35. package/src/buildRestDataProvider.js +3 -1
  36. package/src/column-interfaces.d.ts +5 -1
  37. package/src/data-api.js +2 -2
  38. package/src/data-interfaces.d.ts +0 -1
  39. package/src/data-interfaces.js +3 -0
  40. package/src/data-providers/array-entity-data-provider.js +5 -0
  41. package/src/data-providers/rest-data-provider-using-fetch.js +1 -1
  42. package/src/data-providers/retry.d.ts +4 -1
  43. package/src/data-providers/retry.js +26 -16
  44. package/src/data-providers/sql-database.d.ts +7 -3
  45. package/src/data-providers/sql-database.js +99 -81
  46. package/src/live-query/SubscriptionChannel.js +16 -10
  47. package/src/remult-static.d.ts +2 -0
  48. package/src/remult-static.js +1 -0
  49. package/src/remult3/Fields.d.ts +5 -3
  50. package/src/remult3/Fields.js +24 -13
  51. package/src/remult3/RepositoryImplementation.js +274 -264
  52. package/src/remult3/remult3.d.ts +6 -1
  53. package/src/sort.d.ts +19 -0
  54. package/src/sort.js +20 -1
  55. package/src/sql-command.d.ts +2 -1
package/esm/internals.js CHANGED
@@ -8,6 +8,7 @@ export { omitFilterField, walkFilter } from './src/filter/walk-filter.js';
8
8
  export const actionInfo = remultStatic.actionInfo;
9
9
  export { isOfType } from './src/isOfType.js';
10
10
  export { flags } from './src/remult3/remult3.js';
11
+ export { NullSort } from './src/sort.js';
11
12
  export { SseSubscriptionClient } from './src/live-query/SseSubscriptionClient.js';
12
13
  export { DataProviderPromiseWrapper } from './src/data-interfaces.js';
13
14
  export { pagedQueryResult } from './src/remult3/pagedQueryResult.js';
@@ -32,8 +32,6 @@ export class PostgresDataProvider {
32
32
  this.wrapIdentifier = options.wrapIdentifier;
33
33
  if (!options?.wrapIdentifier && options?.caseInsensitiveIdentifiers)
34
34
  this.wrapIdentifier = (name) => name;
35
- if (options?.orderByNullsFirst)
36
- this.orderByNullsFirst = options.orderByNullsFirst;
37
35
  if (options?.schema) {
38
36
  this.pool = new PostgresSchemaWrapper(pool, options.schema);
39
37
  }
@@ -62,7 +60,10 @@ export class PostgresDataProvider {
62
60
  var sb = new PostgresSchemaBuilder(db, this.options?.schema);
63
61
  await sb.ensureSchema(entities);
64
62
  }
65
- orderByNullsFirst;
63
+ nativeNullSort = {
64
+ order: { asc: 'NULLS LAST', desc: 'NULLS FIRST' },
65
+ syntax: 'NULLS FIRST/LAST',
66
+ };
66
67
  async transaction(action) {
67
68
  let client = await this.pool.connect();
68
69
  try {
@@ -78,7 +79,6 @@ export class PostgresDataProvider {
78
79
  //@ts-ignore
79
80
  pool: client,
80
81
  wrapIdentifier: this.wrapIdentifier,
81
- orderByNullsFirst: this.orderByNullsFirst,
82
82
  });
83
83
  await client.query('COMMIT');
84
84
  }
@@ -154,7 +154,6 @@ export async function createPostgresDataProvider(options) {
154
154
  wrapIdentifier: options.wrapIdentifier,
155
155
  caseInsensitiveIdentifiers: options.caseInsensitiveIdentifiers,
156
156
  schema: options.schema,
157
- orderByNullsFirst: options.orderByNullsFirst,
158
157
  }));
159
158
  return db;
160
159
  }
@@ -9,6 +9,10 @@ export class DuckDBDataProvider extends SqliteCoreDataProvider {
9
9
  super(() => new DuckDBCommand(this.connection), async () => this.connection.disconnectSync(), false, true);
10
10
  this.connection = connection;
11
11
  }
12
+ nativeNullSort = {
13
+ order: { asc: 'NULLS LAST', desc: 'NULLS LAST' },
14
+ syntax: 'NULLS FIRST/LAST',
15
+ };
12
16
  wrapIdentifier(name) {
13
17
  return `"${name}"`;
14
18
  }
@@ -6,7 +6,7 @@ import { getRepository, isAutoIncrement, } from '../src/remult3/RepositoryImplem
6
6
  import { Sort } from '../src/sort.js';
7
7
  import { fromDbColumn, toDbColumn, ValueConverters, } from '../src/valueConverters.js';
8
8
  import { getRepositoryInternals } from '../src/remult3/repository-internals.js';
9
- import { groupByImpl, getRowAfterUpdate, jsonColumnStorageOf, } from '../src/data-providers/sql-database.js';
9
+ import { groupByImpl, getRowAfterUpdate, jsonColumnStorageOf, orderBySql, } from '../src/data-providers/sql-database.js';
10
10
  export class KnexDataProvider {
11
11
  knex;
12
12
  constructor(knex) {
@@ -46,6 +46,35 @@ export class KnexDataProvider {
46
46
  return r.knex;
47
47
  }
48
48
  wrapIdentifier = (x) => this.knex.ref(x) + '';
49
+ // By `driverName`, as CockroachDB shares the `postgresql` dialect.
50
+ get nativeNullSort() {
51
+ switch (this.knex.client.driverName) {
52
+ case 'pg':
53
+ case 'pgnative':
54
+ case 'pg-redshift':
55
+ case 'oracledb':
56
+ return {
57
+ order: { asc: 'NULLS LAST', desc: 'NULLS FIRST' },
58
+ syntax: 'NULLS FIRST/LAST',
59
+ };
60
+ case 'mysql':
61
+ case 'mysql2':
62
+ case 'mssql':
63
+ return {
64
+ order: { asc: 'NULLS FIRST', desc: 'NULLS LAST' },
65
+ syntax: 'CASE WHEN',
66
+ };
67
+ case 'sqlite3':
68
+ case 'better-sqlite3':
69
+ case 'cockroachdb':
70
+ return {
71
+ order: { asc: 'NULLS FIRST', desc: 'NULLS LAST' },
72
+ syntax: 'NULLS FIRST/LAST',
73
+ };
74
+ }
75
+ // `case when` runs on any SQL database.
76
+ return { order: 'unknown', syntax: 'CASE WHEN' };
77
+ }
49
78
  get jsonColumnStorage() {
50
79
  if (!supportsJsonLoadingAndSaving(this.knex))
51
80
  return 'text';
@@ -102,7 +131,7 @@ class KnexEntityDataProvider {
102
131
  this.dp = dp;
103
132
  }
104
133
  async groupBy(options) {
105
- return groupByImpl(options, await dbNamesOfWithForceSqlExpression(this.entity, this.dp.wrapIdentifier, true), this.dp.createCommand(), false, (limit, offset) => this.knex.client.config.client?.includes('mssql')
134
+ return groupByImpl(options, await dbNamesOfWithForceSqlExpression(this.entity, this.dp.wrapIdentifier, true), this.dp.createCommand(), this.dp.nativeNullSort, (limit, offset) => this.knex.client.config.client?.includes('mssql')
106
135
  ? ' offset ' + offset + ' rows fetch next ' + limit + ' rows only'
107
136
  : ' limit ' + limit + ' offset ' + offset, this.dp.jsonColumnStorage);
108
137
  }
@@ -156,10 +185,10 @@ class KnexEntityDataProvider {
156
185
  options.orderBy = Sort.createUniqueSort(this.entity, new Sort());
157
186
  }
158
187
  if (options.orderBy) {
159
- query = query.orderBy(options.orderBy.Segments.map((s) => ({
160
- column: e.$dbNameOf(s.field),
161
- order: s.isDescending ? 'desc' : 'asc',
162
- })));
188
+ const native = this.dp.nativeNullSort;
189
+ // Not Knex's own `nulls` option: outside Postgres it sorts on `(x is null)` alone.
190
+ for (const s of options.orderBy.Segments)
191
+ query = query.orderByRaw(orderBySql(':column:', s.isDescending, s.field.allowNull, native), { column: e.$dbNameOf(s.field) });
163
192
  }
164
193
  if (options.limit) {
165
194
  query = query.limit(options.limit);
@@ -576,8 +605,11 @@ export function buildColumn(x, dbName, b, supportsJson = true) {
576
605
  c.defaultTo(0).notNullable();
577
606
  }
578
607
  }
579
- else
580
- b.specificType(dbName, x.valueConverter.fieldTypeInDb);
608
+ else {
609
+ let c = b.specificType(dbName, x.valueConverter.fieldTypeInDb);
610
+ if (!x.allowNull)
611
+ c.defaultTo(0).notNullable();
612
+ }
581
613
  }
582
614
  else if (x.valueType == Date) {
583
615
  if (!x.valueConverter.fieldTypeInDb)
@@ -6,6 +6,18 @@ import { getRepository } from './src/remult3/RepositoryImplementation.js';
6
6
  import { getRepositoryInternals } from './src/remult3/repository-internals.js';
7
7
  import { getRowAfterUpdate } from './src/data-providers/sql-database.js';
8
8
  import { GroupByCountMember, GroupByOperators, } from './src/remult3/remult3.js';
9
+ import { NullSort } from './src/sort.js';
10
+ let nullSortWarned = false;
11
+ // `$sort` has no NULL option, so Mongo sorts NULL lowest whatever NullSort says.
12
+ function warnIfNullSortIgnored() {
13
+ const order = NullSort.order;
14
+ if (nullSortWarned || order === 'native')
15
+ return;
16
+ if (order.asc === 'NULLS FIRST' && order.desc === 'NULLS LAST')
17
+ return;
18
+ nullSortWarned = true;
19
+ console.warn('[remult] NullSort is ignored on Mongo, which sorts NULL lowest: paginator() can skip or repeat rows');
20
+ }
9
21
  export class MongoDataProvider {
10
22
  db;
11
23
  client;
@@ -64,7 +76,12 @@ export class MongoDataProvider {
64
76
  return r;
65
77
  }
66
78
  }
79
+ // Older versions wrote NULL as this marker, which sorts above numbers and strings.
67
80
  const NULL = { $null: '$null' };
81
+ // `$in: [null, NULL]` fails: Mongo cannot nest `$` under `$in`.
82
+ function nullFilter(name) {
83
+ return { $or: [{ [name]: null }, { [name]: { $eq: NULL } }] };
84
+ }
68
85
  function isNull(x) {
69
86
  return x?.$null === NULL.$null;
70
87
  }
@@ -121,10 +138,7 @@ class MongoEntityDataProvider {
121
138
  for (const col of this.entity.fields) {
122
139
  if (col.dbReadOnly || col.isServerExpression)
123
140
  continue;
124
- let val = toDb(col, row[col.key]);
125
- if (val === null)
126
- val = NULL;
127
- result[nameProvider.$dbNameOf(col)] = val;
141
+ result[nameProvider.$dbNameOf(col)] = toDb(col, row[col.key]);
128
142
  }
129
143
  return result;
130
144
  }
@@ -187,6 +201,7 @@ class MongoEntityDataProvider {
187
201
  }
188
202
  }
189
203
  if (options?.orderBy) {
204
+ warnIfNullSortIgnored();
190
205
  let sort = {};
191
206
  for (const x of options.orderBy) {
192
207
  const direction = x.isDescending ? -1 : 1;
@@ -238,6 +253,7 @@ class MongoEntityDataProvider {
238
253
  }
239
254
  }
240
255
  if (options.orderBy) {
256
+ warnIfNullSortIgnored();
241
257
  op.sort = {};
242
258
  for (const s of options.orderBy.Segments) {
243
259
  op.sort[e.$dbNameOf(s.field)] = s.isDescending ? -1 : 1;
@@ -357,10 +373,12 @@ class FilterConsumerBridgeToMongo {
357
373
  })());
358
374
  }
359
375
  isNull(col) {
360
- this.add(col, NULL, '$eq');
376
+ this.result.push(() => nullFilter(this.nameProvider.$dbNameOf(col)));
361
377
  }
362
378
  isNotNull(col) {
363
- this.add(col, NULL, '$ne');
379
+ this.result.push(() => ({
380
+ $nor: [nullFilter(this.nameProvider.$dbNameOf(col))],
381
+ }));
364
382
  }
365
383
  isIn(col, val) {
366
384
  this.result.push(() => ({
@@ -413,7 +431,7 @@ class FilterConsumerBridgeToMongo {
413
431
  add(col, val, operator, moreOptions) {
414
432
  this.result.push(() => ({
415
433
  [this.nameProvider.$dbNameOf(col)]: {
416
- [operator]: isNull(val) ? val : toDb(col, val),
434
+ [operator]: toDb(col, val),
417
435
  ...moreOptions,
418
436
  },
419
437
  }));
@@ -12,7 +12,10 @@ export class SqliteCoreDataProvider {
12
12
  this.doesNotSupportReturningSyntax = doesNotSupportReturningSyntax;
13
13
  this.doesNotSupportReturningSyntaxOnlyForUpdate = doesNotSupportReturningSyntaxOnlyForUpdate;
14
14
  }
15
- orderByNullsFirst;
15
+ nativeNullSort = {
16
+ order: { asc: 'NULLS FIRST', desc: 'NULLS LAST' },
17
+ syntax: 'NULLS FIRST/LAST',
18
+ };
16
19
  maxParametersInOneSqlStatement = 999;
17
20
  getLimitSqlSyntax(limit, offset) {
18
21
  return ' limit ' + limit + ' offset ' + offset;
@@ -898,7 +898,7 @@ class ResponseBridgeToDataApiResponse {
898
898
  console.error({
899
899
  message: body.message,
900
900
  httpStatusCode,
901
- stack: data.stack?.split('\n'),
901
+ stack: exception?.stack?.split('\n'),
902
902
  url: this.genReq?.url,
903
903
  method: this.genReq?.method,
904
904
  });
@@ -1,5 +1,5 @@
1
1
  import { RestDataProviderHttpProviderUsingFetch } from './data-providers/rest-data-provider-using-fetch.js';
2
- import { retry } from './data-providers/retry.js';
2
+ import { isReadPost, retry } from './data-providers/retry.js';
3
3
  export function buildRestDataProvider(provider) {
4
4
  if (!provider)
5
5
  return new RestDataProviderHttpProviderUsingFetch();
@@ -28,7 +28,9 @@ export class HttpProviderBridgeToRestDataProviderHttpProvider {
28
28
  this.http = http;
29
29
  }
30
30
  async post(url, data) {
31
- return await retry(() => toPromise(this.http.post(url, data)));
31
+ return await retry(() => toPromise(this.http.post(url, data)), {
32
+ read: isReadPost(url),
33
+ });
32
34
  }
33
35
  delete(url) {
34
36
  return toPromise(this.http.delete(url));
@@ -566,11 +566,11 @@ export function serializeError(data) {
566
566
  data = { message: data.message, modelState: data.modelState };
567
567
  }
568
568
  else if (data instanceof Error) {
569
- data = { message: data.message, stack: data.stack };
569
+ data = { message: data.message };
570
570
  }
571
571
  let x = JSON.parse(JSON.stringify(data));
572
572
  if (!x.message && !x.modelState)
573
- data = { message: data.message, stack: data.stack };
573
+ data = { message: data.message };
574
574
  if (typeof x === 'string')
575
575
  data = { message: x };
576
576
  return data;
@@ -12,10 +12,11 @@ export function extractSort(sort) {
12
12
  export class EntityError extends Error {
13
13
  constructor(errorInfo) {
14
14
  super(errorInfo.message);
15
+ // The ES5 build gets a plain Error back from super(), so instanceof EntityError would be false.
16
+ Object.setPrototypeOf(this, new.target.prototype);
15
17
  Object.assign(this, errorInfo);
16
18
  }
17
19
  modelState;
18
- stack;
19
20
  exception;
20
21
  httpStatusCode;
21
22
  }
@@ -445,19 +445,24 @@ class FilterConsumerBridgeToObject {
445
445
  if (this.row[this.dbNames.$dbNameOf(col)] == col.valueConverter.toJson(val))
446
446
  this.ok = false;
447
447
  }
448
+ // As in SQL, NULL never matches an ordering comparison.
448
449
  isGreaterOrEqualTo(col, val) {
450
+ this.isNotNull(col);
449
451
  if (this.row[this.dbNames.$dbNameOf(col)] < col.valueConverter.toJson(val))
450
452
  this.ok = false;
451
453
  }
452
454
  isGreaterThan(col, val) {
455
+ this.isNotNull(col);
453
456
  if (this.row[this.dbNames.$dbNameOf(col)] <= col.valueConverter.toJson(val))
454
457
  this.ok = false;
455
458
  }
456
459
  isLessOrEqualTo(col, val) {
460
+ this.isNotNull(col);
457
461
  if (this.row[this.dbNames.$dbNameOf(col)] > col.valueConverter.toJson(val))
458
462
  this.ok = false;
459
463
  }
460
464
  isLessThan(col, val) {
465
+ this.isNotNull(col);
461
466
  if (this.row[this.dbNames.$dbNameOf(col)] >= col.valueConverter.toJson(val))
462
467
  this.ok = false;
463
468
  }
@@ -1,4 +1,4 @@
1
- import { retry } from './retry.js';
1
+ import { isReadPost, retry } from './retry.js';
2
2
  export class RestDataProviderHttpProviderUsingFetch {
3
3
  fetch;
4
4
  constructor(fetch) {
@@ -22,7 +22,7 @@ export class RestDataProviderHttpProviderUsingFetch {
22
22
  return await retry(() => this.myFetch(url, {
23
23
  method: 'post',
24
24
  body: JSON.stringify(data),
25
- }));
25
+ }), { read: isReadPost(url) });
26
26
  }
27
27
  myFetch(url, options) {
28
28
  const headers = {};
@@ -1,16 +1,18 @@
1
1
  import { flags } from '../remult3/remult3.js';
2
- export async function retry(what) {
2
+ // These mean the proxy never reached the server, so any request is safe to send again.
3
+ const isUnreachable = (err) => err.message?.startsWith('Error occurred while trying to proxy') ||
4
+ err.message?.startsWith('Error occured while trying to proxy') ||
5
+ err.message?.includes('http proxy error');
6
+ // The server may have run the request before failing, so only reads are safe to send again.
7
+ const isServerFailure = (err) => err.message?.startsWith('Gateway Timeout') || err.status == 500;
8
+ export async function retry(what, options = { read: true }) {
3
9
  let i = 0;
4
10
  while (true) {
5
11
  try {
6
12
  return await what();
7
13
  }
8
14
  catch (err) {
9
- if ((err.message?.startsWith('Error occurred while trying to proxy') ||
10
- err.message?.startsWith('Error occured while trying to proxy') ||
11
- err.message?.includes('http proxy error') ||
12
- err.message?.startsWith('Gateway Timeout') ||
13
- err.status == 500) &&
15
+ if ((isUnreachable(err) || (options.read && isServerFailure(err))) &&
14
16
  i++ < flags.error500RetryCount) {
15
17
  await new Promise((res, req) => {
16
18
  setTimeout(() => {
@@ -23,3 +25,6 @@ export async function retry(what) {
23
25
  }
24
26
  }
25
27
  }
28
+ // Finds with a long filter, counts and aggregates are POSTs too, but they only read.
29
+ const readActions = /[?&]__action=(?:(?:get|query|groupBy|count)(?:&|$)|liveQuery-)/;
30
+ export const isReadPost = (url) => readActions.test(url);
@@ -3,7 +3,7 @@ import { Filter, customDatabaseFilterToken, } from '../filter/filter-interfaces.
3
3
  import { remult as defaultRemult } from '../remult-proxy.js';
4
4
  import { GroupByCountMember, GroupByOperators, } from '../remult3/remult3.js';
5
5
  import { getRepository, isAutoIncrement, } from '../remult3/RepositoryImplementation.js';
6
- import { Sort } from '../sort.js';
6
+ import { NullSort, Sort } from '../sort.js';
7
7
  import { fromDbColumn, toDbColumn } from '../valueConverters.js';
8
8
  import { getRepositoryInternals } from '../remult3/repository-internals.js';
9
9
  import { isOfType } from '../isOfType.js';
@@ -54,6 +54,9 @@ export class SqlDatabase {
54
54
  get jsonColumnStorage() {
55
55
  return this.sql.supportsJsonColumnType ? 'native' : 'text';
56
56
  }
57
+ get nativeNullSort() {
58
+ return this.sql.nativeNullSort;
59
+ }
57
60
  /* @internal*/
58
61
  _getSourceSql() {
59
62
  return this.sql;
@@ -107,7 +110,7 @@ export class SqlDatabase {
107
110
  end: this.end,
108
111
  doesNotSupportReturningSyntax: this.sql.doesNotSupportReturningSyntax,
109
112
  doesNotSupportReturningSyntaxOnlyForUpdate: this.sql.doesNotSupportReturningSyntaxOnlyForUpdate,
110
- orderByNullsFirst: this.sql.orderByNullsFirst,
113
+ nativeNullSort: this.sql.nativeNullSort,
111
114
  afterMutation: this.sql.afterMutation,
112
115
  maxParametersInOneSqlStatement: this.sql.maxParametersInOneSqlStatement,
113
116
  }));
@@ -158,7 +161,7 @@ export class SqlDatabase {
158
161
  static async groupByToRaw(repo, options, sql) {
159
162
  const r = getRepository(repo);
160
163
  const built = await buildGroupBySql(await getRepositoryInternals(r).__buildGroupByOptions(options), sql?.dbNames ??
161
- (await dbNamesOfWithForceSqlExpression(r.metadata, sql?.wrapIdentifier ?? wrapIdentifierOf(r))), sql?.sqlCommand ?? new myDummySQLCommand(), false, sql?.limitSyntax ?? limitSyntaxRequired, jsonColumnStorageForRaw(r, sql?.jsonAsString));
164
+ (await dbNamesOfWithForceSqlExpression(r.metadata, sql?.wrapIdentifier ?? wrapIdentifierOf(r))), sql?.sqlCommand ?? new myDummySQLCommand(), nativeNullSortOf(r), sql?.limitSyntax ?? limitSyntaxRequired, jsonColumnStorageForRaw(r, sql?.jsonAsString));
162
165
  return {
163
166
  sql: built.select,
164
167
  toResult: (row) => built.toResult((_, alias) => row[alias]),
@@ -172,7 +175,7 @@ export class SqlDatabase {
172
175
  static async selectToRaw(repo, options, sql) {
173
176
  const r = getRepository(repo);
174
177
  const built = await buildFindSql(r.metadata, await getRepositoryInternals(r)._buildEntityDataProviderFindOptions(options ?? {}), sql?.dbNames ??
175
- (await dbNamesOfWithForceSqlExpression(r.metadata, sql?.wrapIdentifier ?? wrapIdentifierOf(r))), sql?.sqlCommand ?? new myDummySQLCommand(), false, sql?.limitSyntax ?? limitSyntaxRequired, {
178
+ (await dbNamesOfWithForceSqlExpression(r.metadata, sql?.wrapIdentifier ?? wrapIdentifierOf(r))), sql?.sqlCommand ?? new myDummySQLCommand(), nativeNullSortOf(r), sql?.limitSyntax ?? limitSyntaxRequired, {
176
179
  aliasColumns: true,
177
180
  jsonColumnStorage: jsonColumnStorageForRaw(r, sql?.jsonAsString),
178
181
  });
@@ -342,14 +345,14 @@ class ActualSQLEntityDataProvider {
342
345
  });
343
346
  }
344
347
  async groupBy(options) {
345
- return await groupByImpl(options, await this.init(), this.sql.createCommand(), this.sql._getSourceSql().orderByNullsFirst, this.sql._getSourceSql().getLimitSqlSyntax, this.sql.jsonColumnStorage);
348
+ return await groupByImpl(options, await this.init(), this.sql.createCommand(), this.sql.nativeNullSort, this.sql._getSourceSql().getLimitSqlSyntax, this.sql.jsonColumnStorage);
346
349
  }
347
350
  async find(options) {
348
351
  const e = await this.init();
349
352
  const r = this.sql.createCommand();
350
353
  if (options && !options.orderBy)
351
354
  options.orderBy = Sort.createUniqueSort(this.entity, new Sort());
352
- const { select, toResult } = await buildFindSql(this.entity, options, e, r, this.sql._getSourceSql().orderByNullsFirst, (limit, offset) => this.strategy.getLimitSqlSyntax(limit, offset), { jsonColumnStorage: this.sql.jsonColumnStorage });
355
+ const { select, toResult } = await buildFindSql(this.entity, options, e, r, this.sql.nativeNullSort, (limit, offset) => this.strategy.getLimitSqlSyntax(limit, offset), { jsonColumnStorage: this.sql.jsonColumnStorage });
353
356
  const result = await r.execute(select);
354
357
  return result.rows.map((y) => toResult((i) => y[result.getColumnKeyInResultForIndexInSelect(i)]));
355
358
  }
@@ -516,6 +519,13 @@ function wrapIdentifierOf(r) {
516
519
  return dp.wrapIdentifier?.bind(dp);
517
520
  return undefined;
518
521
  }
522
+ function nativeNullSortOf(r) {
523
+ const dp = getRepositoryInternals(r)._dataProvider;
524
+ if (isOfType(dp, 'nativeNullSort'))
525
+ return dp.nativeNullSort;
526
+ // Not a SQL repo, so the raw select's database is unknown.
527
+ return { order: 'unknown', syntax: 'CASE WHEN' };
528
+ }
519
529
  export function jsonColumnStorageOf(r) {
520
530
  const dp = getRepositoryInternals(r)._dataProvider;
521
531
  if (isOfType(dp, 'jsonColumnStorage'))
@@ -566,8 +576,22 @@ export function getRowAfterUpdate(meta, dataProvider, data, id, operation) {
566
576
  return r[0];
567
577
  });
568
578
  }
579
+ /** Writes the NULL order only on a nullable column, where NullSort differs from the database's own. */
580
+ export function orderBySql(expr, isDescending, nullable, native) {
581
+ const sql = isDescending ? expr + ' desc' : expr;
582
+ if (!nullable || NullSort.order === 'native')
583
+ return sql;
584
+ const dir = isDescending ? 'desc' : 'asc';
585
+ const nullSort = NullSort.order[dir];
586
+ if (native.order !== 'unknown' && native.order[dir] === nullSort)
587
+ return sql;
588
+ if (native.syntax === 'NULLS FIRST/LAST')
589
+ return sql + ' ' + nullSort.toLowerCase();
590
+ const [ifNull, otherwise] = nullSort === 'NULLS FIRST' ? [0, 1] : [1, 0];
591
+ return `case when ${expr} is null then ${ifNull} else ${otherwise} end, ${sql}`;
592
+ }
569
593
  /** The select that `find` runs, and the mapping of one result row to field values. With `aliasColumns`, every column is aliased through `wrapIdentifier`, so a row can be read by alias as well as by position. */
570
- export async function buildFindSql(entity, options, e, r, orderByNullsFirst, limitSyntax, { aliasColumns = false, jsonColumnStorage = 'native', } = {}) {
594
+ export async function buildFindSql(entity, options, e, r, nativeNullSort, limitSyntax, { aliasColumns = false, jsonColumnStorage = 'native', } = {}) {
571
595
  const { colKeys, select: columns } = await selectColumns(entity, e, r, options?.select, options?.args, aliasColumns);
572
596
  let select = 'select ' + columns + '\n from ' + e.$entityName;
573
597
  if (options) {
@@ -588,17 +612,9 @@ export async function buildFindSql(entity, options, e, r, orderByNullsFirst, lim
588
612
  }
589
613
  else
590
614
  select += ', ';
591
- select += c.field.options.sqlExpression
592
- ? c.field.options.key
593
- : await e.$dbNameOf(c.field);
594
- if (c.isDescending)
595
- select += ' desc';
596
- if (orderByNullsFirst) {
597
- if (c.isDescending)
598
- select += ' nulls last';
599
- else
600
- select += ' nulls first';
601
- }
615
+ select += orderBySql(c.field.options.sqlExpression
616
+ ? c.field.key
617
+ : await e.$dbNameOf(c.field), c.isDescending, c.field.allowNull, nativeNullSort);
602
618
  }
603
619
  }
604
620
  if (options.limit) {
@@ -660,13 +676,13 @@ function resultRow(colKeys, valueAt, storage) {
660
676
  });
661
677
  return result;
662
678
  }
663
- export async function groupByImpl(options, e, r, orderByNullFirst, limitSyntax, jsonColumnStorage = 'native') {
664
- const { select, toResult } = await buildGroupBySql(options, e, r, orderByNullFirst, limitSyntax, jsonColumnStorage);
679
+ export async function groupByImpl(options, e, r, nativeNullSort, limitSyntax, jsonColumnStorage = 'native') {
680
+ const { select, toResult } = await buildGroupBySql(options, e, r, nativeNullSort, limitSyntax, jsonColumnStorage);
665
681
  const result = await r.execute(select);
666
682
  return result.rows.map((sql) => toResult((i) => sql[result.getColumnKeyInResultForIndexInSelect(i)]));
667
683
  }
668
684
  /** The select that `groupBy` runs, and the mapping of one result row back to a `GroupByResult`. Every column is aliased through `wrapIdentifier`, so a row can be read by alias as well as by position. */
669
- export async function buildGroupBySql(options, e, r, orderByNullFirst, limitSyntax, jsonColumnStorage = 'native') {
685
+ export async function buildGroupBySql(options, e, r, nativeNullSort, limitSyntax, jsonColumnStorage = 'native') {
670
686
  const aliases = [];
671
687
  function alias(name) {
672
688
  aliases.push(name);
@@ -741,15 +757,9 @@ export async function buildGroupBySql(options, e, r, orderByNullFirst, limitSynt
741
757
  default:
742
758
  field = aggregateSqlSyntax(x.operation, field);
743
759
  }
744
- orderBy += field;
745
- if (x.isDescending)
746
- orderBy += ' desc';
747
- if (orderByNullFirst) {
748
- if (x.isDescending)
749
- orderBy += ' nulls last';
750
- else
751
- orderBy += ' nulls first';
752
- }
760
+ // A distinct count is never NULL; other aggregates are NULL only over NULL values.
761
+ const nullable = !!x.field?.allowNull && x.operation !== 'distinctCount';
762
+ orderBy += orderBySql(field, x.isDescending, nullable, nativeNullSort);
753
763
  }
754
764
  if (orderBy)
755
765
  select += orderBy;
@@ -39,12 +39,6 @@ export class LiveQuerySubscriber {
39
39
  forListeners(what, changes) {
40
40
  what((reducer) => {
41
41
  this.defaultQueryState = reducer(this.defaultQueryState);
42
- if (changes.find((c) => c.type === 'add' || c.type === 'replace')) {
43
- if (this.query.options.orderBy) {
44
- const o = Sort.translateOrderByToSort(this.repo.metadata, this.query.options.orderBy);
45
- this.defaultQueryState.sort((a, b) => o.compare(a, b));
46
- }
47
- }
48
42
  });
49
43
  for (const l of this.listeners) {
50
44
  what((reducer) => {
@@ -88,7 +82,7 @@ export class LiveQuerySubscriber {
88
82
  }
89
83
  }
90
84
  this.forListeners((listener) => {
91
- listener((items) => {
85
+ listener((items, { pos = 'auto' } = {}) => {
92
86
  if (!items)
93
87
  items = [];
94
88
  for (const message of data) {
@@ -105,13 +99,24 @@ export class LiveQuerySubscriber {
105
99
  case 'add':
106
100
  items = items.filter((x) => this.repo.metadata.idMetadata.getId(x) !==
107
101
  this.repo.metadata.idMetadata.getId(message.data.item));
108
- items.push(message.data.item);
102
+ if (pos === 'first')
103
+ items.unshift(message.data.item);
104
+ else
105
+ items.push(message.data.item);
109
106
  break;
110
107
  case 'remove':
111
108
  items = items.filter((x) => this.repo.metadata.idMetadata.getId(x) !== message.data.id);
112
109
  break;
113
110
  }
114
111
  }
112
+ const orderBy = this.query.options.orderBy ??
113
+ this.repo.metadata.options.defaultOrderBy;
114
+ if (pos === 'auto' &&
115
+ orderBy &&
116
+ data.some((m) => m.type === 'add' || m.type === 'replace')) {
117
+ const o = Sort.translateOrderByToSort(this.repo.metadata, orderBy);
118
+ items.sort((a, b) => o.compare(a, b));
119
+ }
115
120
  return items;
116
121
  });
117
122
  }, data);
@@ -20,6 +20,7 @@ let x = {
20
20
  },
21
21
  fieldOptionsEnricher: undefined,
22
22
  labelTransformer: undefined,
23
+ nullSort: undefined,
23
24
  defaultIdFactory: undefined,
24
25
  defaultDataProvider: () => undefined,
25
26
  };
@@ -63,6 +63,8 @@ export class Fields {
63
63
  static createdAt(...options) {
64
64
  return Field(() => Date, {
65
65
  allowApiUpdate: false,
66
+ // Set on every insert, so never NULL.
67
+ allowNull: false,
66
68
  saving: (_, ref, { isNew }) => {
67
69
  if (isNew)
68
70
  ref.value = new Date();
@@ -72,6 +74,8 @@ export class Fields {
72
74
  static updatedAt(...options) {
73
75
  return Field(() => Date, {
74
76
  allowApiUpdate: false,
77
+ // Set on every save, so never NULL.
78
+ allowNull: false,
75
79
  saving: (_, ref) => {
76
80
  ref.value = new Date();
77
81
  },
@@ -79,10 +83,7 @@ export class Fields {
79
83
  }
80
84
  /** @deprecated use `@Fields.id()` instead */
81
85
  static uuid(...options) {
82
- return Fields.id({
83
- idFactory: () => crypto.randomUUID(),
84
- ...options,
85
- });
86
+ return Fields.id({ idFactory: () => crypto.randomUUID() }, ...options);
86
87
  }
87
88
  /**
88
89
  * ### cuid
@@ -143,20 +144,19 @@ export class Fields {
143
144
  * }
144
145
  * ```
145
146
  */
146
- static id(options) {
147
+ static id(...options) {
148
+ // Read once the options are merged, so a later option or a function option can set it.
149
+ let idFactory;
150
+ const newId = () => (idFactory ?? Fields.defaultIdFactory)();
147
151
  return Field(() => String, {
148
152
  allowApiUpdate: false,
149
- defaultValue: () => {
150
- let idFactory = options?.idFactory ?? Fields.defaultIdFactory;
151
- return idFactory();
152
- },
153
+ defaultValue: newId,
153
154
  saving: (_, r) => {
154
- if (!r.value) {
155
- let idFactory = options?.idFactory ?? Fields.defaultIdFactory;
156
- r.value = idFactory();
157
- }
155
+ if (!r.value)
156
+ r.value = newId();
158
157
  },
159
- ...options,
158
+ }, ...options, (o) => {
159
+ idFactory = o.idFactory;
160
160
  });
161
161
  }
162
162
  /**