remult 3.4.2 → 3.5.0-next.2

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 (72) 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 +69 -14
  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 +14 -6
  8. package/esm/src/buildRestDataProvider.js +8 -6
  9. package/esm/src/context.js +1 -1
  10. package/esm/src/data-api.js +2 -2
  11. package/esm/src/data-interfaces.js +2 -1
  12. package/esm/src/data-providers/array-entity-data-provider.js +9 -4
  13. package/esm/src/data-providers/rest-data-provider-using-fetch.js +13 -6
  14. package/esm/src/data-providers/retry.js +11 -6
  15. package/esm/src/data-providers/sql-database.js +40 -30
  16. package/esm/src/filter/filter-consumer-bridge-to-sql-request.js +35 -4
  17. package/esm/src/filter/filter-interfaces.js +18 -4
  18. package/esm/src/live-query/SubscriptionChannel.js +13 -8
  19. package/esm/src/remult-proxy.js +12 -0
  20. package/esm/src/remult-static.js +2 -0
  21. package/esm/src/remult3/Fields.js +14 -14
  22. package/esm/src/remult3/RepositoryImplementation.js +69 -32
  23. package/esm/src/remult3/remult3.js +2 -0
  24. package/esm/src/server-action.js +43 -14
  25. package/esm/src/sort.js +18 -0
  26. package/index.d.ts +4 -3
  27. package/internals.d.ts +1 -0
  28. package/internals.js +3 -1
  29. package/package.json +41 -1
  30. package/postgres/postgres-data-provider.d.ts +2 -3
  31. package/postgres/postgres-data-provider.js +4 -4
  32. package/remult-duckdb.d.ts +2 -0
  33. package/remult-duckdb.js +4 -0
  34. package/remult-knex/index.d.ts +2 -0
  35. package/remult-knex/index.js +153 -83
  36. package/remult-mongo.js +28 -7
  37. package/remult-sqlite-core.d.ts +2 -1
  38. package/remult-sqlite-core.js +4 -0
  39. package/server/remult-api-server.d.ts +28 -1
  40. package/server/remult-api-server.js +19 -12
  41. package/src/buildRestDataProvider.d.ts +1 -1
  42. package/src/buildRestDataProvider.js +8 -6
  43. package/src/column-interfaces.d.ts +5 -1
  44. package/src/context.js +1 -1
  45. package/src/data-api.js +2 -2
  46. package/src/data-interfaces.d.ts +0 -1
  47. package/src/data-interfaces.js +3 -0
  48. package/src/data-providers/array-entity-data-provider.js +9 -4
  49. package/src/data-providers/rest-data-provider-using-fetch.d.ts +1 -1
  50. package/src/data-providers/rest-data-provider-using-fetch.js +11 -4
  51. package/src/data-providers/retry.d.ts +4 -1
  52. package/src/data-providers/retry.js +26 -16
  53. package/src/data-providers/sql-database.d.ts +7 -3
  54. package/src/data-providers/sql-database.js +99 -81
  55. package/src/filter/filter-consumer-bridge-to-sql-request.d.ts +8 -0
  56. package/src/filter/filter-consumer-bridge-to-sql-request.js +58 -19
  57. package/src/filter/filter-interfaces.js +19 -2
  58. package/src/live-query/SubscriptionChannel.js +16 -10
  59. package/src/remult-proxy.js +28 -0
  60. package/src/remult-static.d.ts +4 -0
  61. package/src/remult-static.js +2 -0
  62. package/src/remult3/Fields.d.ts +5 -3
  63. package/src/remult3/Fields.js +24 -13
  64. package/src/remult3/RepositoryImplementation.d.ts +7 -0
  65. package/src/remult3/RepositoryImplementation.js +325 -264
  66. package/src/remult3/remult3.d.ts +68 -5
  67. package/src/remult3/remult3.js +2 -0
  68. package/src/server-action.d.ts +34 -2
  69. package/src/server-action.js +195 -115
  70. package/src/sort.d.ts +19 -0
  71. package/src/sort.js +20 -1
  72. package/src/sql-command.d.ts +2 -1
@@ -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;
@@ -13,6 +13,21 @@ export const LIKE_ESCAPE_SQL = " escape '!'";
13
13
  export function escapeLike(val) {
14
14
  return val.replace(REGEX_LIKE_SPECIAL, '!$&');
15
15
  }
16
+ /** `$not` uses `case when` once the predicate mentions a column that allows null. */
17
+ export class HandleNull {
18
+ nullable = false;
19
+ add(other) {
20
+ if (other.nullable)
21
+ this.nullable = true;
22
+ }
23
+ column(col) {
24
+ if (col.allowNull)
25
+ this.nullable = true;
26
+ }
27
+ custom() {
28
+ this.nullable = true;
29
+ }
30
+ }
16
31
  export class FilterConsumerBridgeToSqlRequest {
17
32
  r;
18
33
  nameProvider;
@@ -20,6 +35,7 @@ export class FilterConsumerBridgeToSqlRequest {
20
35
  where = '';
21
36
  _addWhere = true;
22
37
  promises = [];
38
+ handleNull = new HandleNull();
23
39
  async resolveWhere() {
24
40
  while (this.promises.length > 0) {
25
41
  let p = this.promises;
@@ -39,8 +55,9 @@ export class FilterConsumerBridgeToSqlRequest {
39
55
  throw new Error('Custom filter should be translated before it gets here');
40
56
  }
41
57
  or(orElements) {
42
- let statement = '';
43
58
  this.promises.push((async () => {
59
+ let statement = '';
60
+ const branches = new HandleNull();
44
61
  for (const element of orElements) {
45
62
  let f = new FilterConsumerBridgeToSqlRequest(this.r, this.nameProvider, this.jsonColumnStorage);
46
63
  f._addWhere = false;
@@ -49,6 +66,7 @@ export class FilterConsumerBridgeToSqlRequest {
49
66
  if (!where)
50
67
  return; //since if any member of or is empty, then the entire or is irrelevant
51
68
  if (where.length > 0) {
69
+ branches.add(f.handleNull);
52
70
  if (statement.length > 0) {
53
71
  statement += ' or ';
54
72
  }
@@ -59,6 +77,7 @@ export class FilterConsumerBridgeToSqlRequest {
59
77
  statement += where;
60
78
  }
61
79
  }
80
+ this.handleNull.add(branches);
62
81
  this.addToWhere('(' + statement + ')');
63
82
  })());
64
83
  }
@@ -68,18 +87,27 @@ export class FilterConsumerBridgeToSqlRequest {
68
87
  f._addWhere = false;
69
88
  element.__applyToConsumer(f);
70
89
  let where = await f.resolveWhere();
71
- if (!where)
72
- return; //since if any member of or is empty, then the entire or is irrelevant
73
- this.addToWhere('not (' + where + ')');
90
+ // An empty filter matches every row, so its not matches none.
91
+ if (!where) {
92
+ this.addToWhere('1 = 0');
93
+ return;
94
+ }
95
+ this.addToWhere(f.handleNull.nullable
96
+ ? 'case when (' + where + ') then 0 else 1 end = 1'
97
+ : 'not (' + where + ')');
74
98
  })());
75
99
  }
76
100
  isNull(col) {
101
+ this.handleNull.column(col);
77
102
  this.promises.push((async () => this.addToWhere(this.nameProvider.$dbNameOf(col) + ' is null'))());
78
103
  }
79
104
  isNotNull(col) {
105
+ this.handleNull.column(col);
80
106
  this.promises.push((async () => this.addToWhere(this.nameProvider.$dbNameOf(col) + ' is not null'))());
81
107
  }
82
108
  isIn(col, val) {
109
+ if (val?.length)
110
+ this.handleNull.column(col);
83
111
  this.promises.push((async () => {
84
112
  if (val && val.length > 0)
85
113
  this.addToWhere(this.nameProvider.$dbNameOf(col) +
@@ -123,6 +151,7 @@ export class FilterConsumerBridgeToSqlRequest {
123
151
  this.like(col, '%' + escapeLike(val));
124
152
  }
125
153
  like(col, pattern, not = '') {
154
+ this.handleNull.column(col);
126
155
  this.promises.push((async () => {
127
156
  this.addToWhere(not +
128
157
  'lower (' +
@@ -134,6 +163,7 @@ export class FilterConsumerBridgeToSqlRequest {
134
163
  })());
135
164
  }
136
165
  add(col, val, operator) {
166
+ this.handleNull.column(col);
137
167
  this.promises.push((async () => {
138
168
  let x = this.nameProvider.$dbNameOf(col) +
139
169
  ' ' +
@@ -160,6 +190,7 @@ export class FilterConsumerBridgeToSqlRequest {
160
190
  if (typeof sql !== 'string')
161
191
  sql = item.sql;
162
192
  if (sql) {
193
+ this.handleNull.custom();
163
194
  this.addToWhere('(' + sql + ')');
164
195
  }
165
196
  }
@@ -357,15 +357,20 @@ class filterHelper {
357
357
  }
358
358
  isNotIn(values) {
359
359
  return new Filter((add) => {
360
- for (const v of values) {
361
- add.isDifferentFrom(this.metadata, this.processVal(v));
362
- }
360
+ for (const v of values)
361
+ this.isDifferentFrom(v).__applyToConsumer(add);
363
362
  });
364
363
  }
365
364
  isDifferentFrom(val) {
366
365
  val = this.processVal(val);
367
366
  if ((val === null || val === undefined) && this.metadata.allowNull)
368
367
  return new Filter((add) => add.isNotNull(this.metadata));
368
+ // NULL is a value, so it differs from every other value. SQL `<>` does not.
369
+ if (this.metadata.allowNull)
370
+ return new Filter((add) => add.or([
371
+ new Filter((add) => add.isDifferentFrom(this.metadata, val)),
372
+ new Filter((add) => add.isNull(this.metadata)),
373
+ ]));
369
374
  return new Filter((add) => add.isDifferentFrom(this.metadata, val));
370
375
  }
371
376
  isLessOrEqualTo(val) {
@@ -384,6 +389,15 @@ class filterHelper {
384
389
  }
385
390
  isIn(val) {
386
391
  val = val.map((x) => this.processVal(x));
392
+ if (this.metadata.allowNull) {
393
+ const values = val.filter((x) => x !== null && x !== undefined);
394
+ if (values.length !== val.length) {
395
+ const isNull = new Filter((add) => add.isNull(this.metadata));
396
+ if (values.length === 0)
397
+ return isNull;
398
+ return new Filter((add) => add.or([this.isIn(values), isNull]));
399
+ }
400
+ }
387
401
  if (val?.length == 1 && val[0] != undefined && val[0] !== null)
388
402
  return new Filter((add) => add.isEqualTo(this.metadata, val[0]));
389
403
  return new Filter((add) => add.isIn(this.metadata, val));
@@ -660,7 +674,7 @@ export function buildFilterFromRequestParameters(entity, filterInfo) {
660
674
  addFilter('.ne', (val) => ({ $ne: val }));
661
675
  addFilter('.in', (val) => val, true);
662
676
  var nullFilter = filterInfo.get(col.key + '.null');
663
- if (nullFilter) {
677
+ if (nullFilter !== undefined) {
664
678
  nullFilter = nullFilter.toString().trim().toLowerCase();
665
679
  switch (nullFilter) {
666
680
  case 'y':
@@ -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);
@@ -150,6 +150,18 @@ export class RemultProxy {
150
150
  .remultFactory()
151
151
  .repo(...args)
152
152
  .findId(a, b),
153
+ findIdOrThrow: (a, b) => self
154
+ .remultFactory()
155
+ .repo(...args)
156
+ .findIdOrThrow(a, b),
157
+ findFirstOrThrow: (...args2) => self
158
+ .remultFactory()
159
+ .repo(...args)
160
+ .findFirstOrThrow(...args2),
161
+ findOneOrThrow: (...args2) => self
162
+ .remultFactory()
163
+ .repo(...args)
164
+ .findOneOrThrow(...args2),
153
165
  //@ts-ignore
154
166
  toJson: (json) => self
155
167
  .remultFactory()
@@ -20,8 +20,10 @@ let x = {
20
20
  },
21
21
  fieldOptionsEnricher: undefined,
22
22
  labelTransformer: undefined,
23
+ nullSort: undefined,
23
24
  defaultIdFactory: undefined,
24
25
  defaultDataProvider: () => undefined,
26
+ backendMethodSerializer: undefined,
25
27
  };
26
28
  if ((typeof process !== 'undefined' &&
27
29
  process.env['IGNORE_GLOBAL_REMULT_IN_TESTS']) ||
@@ -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
  /**
@@ -2,7 +2,7 @@ import { LookupColumn, makeTitle } from '../column.js';
2
2
  import { CompoundIdField } from '../CompoundIdField.js';
3
3
  import { Remult } from '../context.js';
4
4
  import { Filter } from '../filter/filter-interfaces.js';
5
- import { Sort } from '../sort.js';
5
+ import { Sort, isNullFirstSort } from '../sort.js';
6
6
  import { GroupByCountMember, GroupByForApiKey, } from './remult3.js';
7
7
  import { assign } from '../../assign.js';
8
8
  import { EntityError, } from '../data-interfaces.js';
@@ -53,41 +53,41 @@ export class RepositoryImplementation {
53
53
  httpStatusCode: 404,
54
54
  };
55
55
  }
56
+ _noMatchError() {
57
+ return {
58
+ message: `no row matches the filter in entity ${this.metadata.key}`,
59
+ httpStatusCode: 404,
60
+ };
61
+ }
56
62
  [getInternalKey]() {
57
63
  return this;
58
64
  }
59
65
  async _createAfterFilter(orderBy, lastRow) {
60
- let values = new Map();
61
- for (const s of Sort.translateOrderByToSort(this.metadata, orderBy)
62
- .Segments) {
63
- let existingVal = lastRow[s.field.key];
64
- // if (typeof existingVal !== "string" && typeof existingVal !== "number") {
65
- // }
66
- // else {
67
- // let ei = getEntitySettings(s.field.valueType, false);
68
- // if (ei) {
69
- // existingVal = await this.remult.repo(s.field.valueType).findId(existingVal);
70
- // }
71
- // }
72
- values.set(s.field.key, existingVal);
73
- }
74
- let r = { $or: [] };
75
- let equalToColumn = [];
76
- for (const s of Sort.translateOrderByToSort(this.metadata, orderBy)
77
- .Segments) {
78
- let f = {};
79
- for (const c of equalToColumn) {
80
- f[c.key] = values.get(c.key);
81
- }
82
- equalToColumn.push(s.field);
83
- if (s.isDescending) {
84
- f[s.field.key] = { $lt: values.get(s.field.key) };
66
+ const ref = this.getEntityRef(lastRow);
67
+ const filter = { $or: [] };
68
+ const or = filter.$or;
69
+ let equal = {};
70
+ for (const { field, isDescending } of Sort.translateOrderByToSort(this.metadata, orderBy).Segments) {
71
+ // A string key cannot name an entity member for TypeScript.
72
+ const keyIs = (condition) => ({ [field.key]: condition });
73
+ // An unloaded relation reads `undefined`, its id is there.
74
+ const value = ref.fields.find(field.key).getId() ?? null;
75
+ const nullFirst = isNullFirstSort(isDescending);
76
+ if (value === null) {
77
+ if (nullFirst)
78
+ or.push({ ...equal, $not: keyIs(null) });
85
79
  }
86
- else
87
- f[s.field.key] = { $gt: values.get(s.field.key) };
88
- r.$or.push(f);
80
+ else {
81
+ or.push({
82
+ ...equal,
83
+ ...keyIs(isDescending ? { $lt: value } : { $gt: value }),
84
+ });
85
+ if (field.allowNull && !nullFirst)
86
+ or.push({ ...equal, ...keyIs(null) });
87
+ }
88
+ equal = { ...equal, ...keyIs(value) };
89
89
  }
90
- return r;
90
+ return filter;
91
91
  }
92
92
  relations(item) {
93
93
  return new Proxy({}, {
@@ -760,7 +760,9 @@ export class RepositoryImplementation {
760
760
  }
761
761
  else {
762
762
  for (const row of result) {
763
- Reflect.deleteProperty(row, col.key);
763
+ // Deleting the relation's accessor would drop its change tracking, so only a plain value goes.
764
+ if (!Object.getOwnPropertyDescriptor(row, col.key)?.get)
765
+ Reflect.deleteProperty(row, col.key);
764
766
  }
765
767
  }
766
768
  }
@@ -1040,6 +1042,24 @@ export class RepositoryImplementation {
1040
1042
  where: this.metadata.idMetadata.getIdFilter(id),
1041
1043
  }, true);
1042
1044
  }
1045
+ async findIdOrThrow(id, options) {
1046
+ const row = await this.findId(id, options);
1047
+ if (!row)
1048
+ throw new EntityError(this._notFoundError(id));
1049
+ return row;
1050
+ }
1051
+ async findFirstOrThrow(where, options) {
1052
+ const row = await this.findFirst(where, options);
1053
+ if (!row)
1054
+ throw new EntityError(this._noMatchError());
1055
+ return row;
1056
+ }
1057
+ async findOneOrThrow(options) {
1058
+ const row = await this.findOne(options);
1059
+ if (!row)
1060
+ throw new EntityError(this._noMatchError());
1061
+ return row;
1062
+ }
1043
1063
  async _translateWhereToFilter(where) {
1044
1064
  let safeWhere = where ?? {};
1045
1065
  if (this._defaultFindOptions?.where) {
@@ -2118,6 +2138,19 @@ export function buildLabel(label, key, remult, metaData) {
2118
2138
  return makeTitle(key);
2119
2139
  return '';
2120
2140
  }
2141
+ /** Migrations give the column a default value (`''`, `0`, `false`), so it is `not null`. */
2142
+ function hasColumnDefault({ valueType, valueConverter, }) {
2143
+ if (valueType === Number || valueType === Boolean)
2144
+ return true;
2145
+ if (valueType === Date)
2146
+ return false;
2147
+ // A relation id is an integer or a string, and its fieldTypeInDb would load the related entity.
2148
+ if (getEntitySettings(valueType, false))
2149
+ return true;
2150
+ const type = valueConverter?.fieldTypeInDb;
2151
+ // None is a string column, default ''. `dbid` is a Mongo ObjectId marker, not a column type.
2152
+ return !type || type === 'dbid' || type === 'integer';
2153
+ }
2121
2154
  export class columnDefsImpl {
2122
2155
  settings;
2123
2156
  entityDefs;
@@ -2150,7 +2183,7 @@ export class columnDefsImpl {
2150
2183
  return result;
2151
2184
  },
2152
2185
  });
2153
- this.allowNull = !!this.settings.allowNull;
2186
+ this.allowNull = this.settings.allowNull ?? !hasColumnDefault(settings);
2154
2187
  this.valueType = this.settings.valueType;
2155
2188
  this.key = this.settings.key;
2156
2189
  this.inputType = this.settings.inputType;
@@ -2276,6 +2309,10 @@ class EntityFullInfo {
2276
2309
  else
2277
2310
  this.idMetadata.field = [...this.fields][0];
2278
2311
  }
2312
+ // The database rejects NULL in a primary key.
2313
+ for (const f of this.idMetadata.fields)
2314
+ if (f)
2315
+ f.allowNull = f.options.allowNull ?? false;
2279
2316
  }
2280
2317
  apiUpdateAllowed(item) {
2281
2318
  if (this.options.allowApiUpdate === undefined)
@@ -22,6 +22,8 @@ export const flags = {
22
22
  liveQueryKeepAliveMs: 30_000,
23
23
  /** Version poll while SSE is stale */
24
24
  liveQueryPollWhenStaleMs: 1_000,
25
+ /** Client calls reject with an `EntityError` instead of a plain object. On by default in the next major. */
26
+ clientErrorsAsEntityError: false,
25
27
  };
26
28
  /*p1 - issues in https://stackblitz.com/edit/demo-allow-delete-based-on-other-entity:
27
29
  - don't like the ensure schema