remult 3.5.0-next.1 → 3.5.0-next.3

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 (45) hide show
  1. package/esm/remult-knex/index.js +29 -6
  2. package/esm/server/remult-admin-html.js +6 -4
  3. package/esm/server/remult-admin.js +101 -7
  4. package/esm/server/remult-api-server.js +19 -8
  5. package/esm/src/buildRestDataProvider.js +4 -4
  6. package/esm/src/context.js +1 -1
  7. package/esm/src/data-providers/array-entity-data-provider.js +7 -7
  8. package/esm/src/data-providers/rest-data-provider-using-fetch.js +11 -4
  9. package/esm/src/data-providers/sql-database.js +2 -1
  10. package/esm/src/filter/filter-consumer-bridge-to-sql-request.js +35 -4
  11. package/esm/src/filter/filter-interfaces.js +18 -4
  12. package/esm/src/remult-proxy.js +12 -0
  13. package/esm/src/remult-static.js +1 -0
  14. package/esm/src/remult3/RepositoryImplementation.js +25 -1
  15. package/esm/src/remult3/remult3.js +2 -0
  16. package/esm/src/server-action.js +43 -14
  17. package/index.d.ts +3 -2
  18. package/package.json +1 -1
  19. package/remult-knex/index.js +29 -6
  20. package/server/get-remult-admin-html.js +1 -1
  21. package/server/index.d.ts +2 -1
  22. package/server/remult-admin-html.js +6 -4
  23. package/server/remult-admin.d.ts +31 -2
  24. package/server/remult-admin.js +168 -19
  25. package/server/remult-api-server.d.ts +30 -0
  26. package/server/remult-api-server.js +46 -33
  27. package/src/buildRestDataProvider.d.ts +1 -1
  28. package/src/buildRestDataProvider.js +5 -5
  29. package/src/context.js +1 -1
  30. package/src/data-providers/array-entity-data-provider.js +7 -7
  31. package/src/data-providers/rest-data-provider-using-fetch.d.ts +1 -1
  32. package/src/data-providers/rest-data-provider-using-fetch.js +10 -3
  33. package/src/data-providers/sql-database.js +2 -1
  34. package/src/filter/filter-consumer-bridge-to-sql-request.d.ts +8 -0
  35. package/src/filter/filter-consumer-bridge-to-sql-request.js +58 -19
  36. package/src/filter/filter-interfaces.js +19 -2
  37. package/src/remult-proxy.js +28 -0
  38. package/src/remult-static.d.ts +2 -0
  39. package/src/remult-static.js +1 -0
  40. package/src/remult3/RepositoryImplementation.d.ts +7 -0
  41. package/src/remult3/RepositoryImplementation.js +52 -1
  42. package/src/remult3/remult3.d.ts +65 -7
  43. package/src/remult3/remult3.js +2 -0
  44. package/src/server-action.d.ts +34 -2
  45. package/src/server-action.js +195 -115
@@ -1,4 +1,4 @@
1
- import { CustomSqlFilterBuilder, dbNamesOfWithForceSqlExpression, escapeLike, LIKE_ESCAPE_SQL, } from '../src/filter/filter-consumer-bridge-to-sql-request.js';
1
+ import { CustomSqlFilterBuilder, dbNamesOfWithForceSqlExpression, escapeLike, HandleNull, LIKE_ESCAPE_SQL, } from '../src/filter/filter-consumer-bridge-to-sql-request.js';
2
2
  import { dbNamesOf, isDbReadonly, shouldCreateEntity, shouldNotCreateField, } from '../src/filter/filter-consumer-bridge-to-sql-request.js';
3
3
  import { customDatabaseFilterToken, Filter, } from '../src/filter/filter-interfaces.js';
4
4
  import { remult as remultContext } from '../src/remult-proxy.js';
@@ -372,6 +372,7 @@ class FilterConsumerBridgeToKnexRequest {
372
372
  _addWhere = true;
373
373
  promises = [];
374
374
  result = [];
375
+ handleNull = new HandleNull();
375
376
  async resolveWhere() {
376
377
  while (this.promises.length > 0) {
377
378
  let p = this.promises;
@@ -393,12 +394,14 @@ class FilterConsumerBridgeToKnexRequest {
393
394
  or(orElements) {
394
395
  this.promises.push((async () => {
395
396
  const result = [];
397
+ const branches = new HandleNull();
396
398
  for (const element of orElements) {
397
399
  let f = new FilterConsumerBridgeToKnexRequest(this.innerNameProvider, this.rawSqlWrapIdentifier, this.jsonColumnStorage);
398
400
  f._addWhere = false;
399
401
  element.__applyToConsumer(f);
400
402
  let where = await f.resolveWhere();
401
403
  if (where.length > 0) {
404
+ branches.add(f.handleNull);
402
405
  result.push((b) => {
403
406
  b.orWhere((b) => {
404
407
  where.forEach((x) => x(b));
@@ -409,6 +412,7 @@ class FilterConsumerBridgeToKnexRequest {
409
412
  return; //empty or means all rows
410
413
  }
411
414
  if (result.length > 0) {
415
+ this.handleNull.add(branches);
412
416
  this.result.push((b) => b.where((x) => result.find((y) => y(x))));
413
417
  }
414
418
  })());
@@ -420,23 +424,38 @@ class FilterConsumerBridgeToKnexRequest {
420
424
  element.__applyToConsumer(f);
421
425
  let where = await f.resolveWhere();
422
426
  if (where.length > 0) {
423
- this.result.push((b) => {
424
- b.whereNot((b) => {
425
- where.forEach((x) => x(b));
427
+ if (f.handleNull.nullable) {
428
+ this.result.push((b) => {
429
+ const nested = b.client.queryBuilder();
430
+ where.forEach((x) => x(nested));
431
+ const compiled = nested.toSQL();
432
+ const pred = compiled.sql.replace(/^select \* where /i, '');
433
+ b.whereRaw(`case when (${pred}) then 0 else 1 end = 1`, compiled.bindings);
426
434
  });
427
- });
435
+ }
436
+ else {
437
+ this.result.push((b) => {
438
+ b.whereNot((x) => {
439
+ where.forEach((w) => w(x));
440
+ });
441
+ });
442
+ }
428
443
  }
429
444
  else
430
- return; //empty or means all rows
445
+ this.result.push((b) => b.whereRaw('1 = 0'));
431
446
  })());
432
447
  }
433
448
  isNull(col) {
449
+ this.handleNull.column(col);
434
450
  this.result.push((b) => b.whereNull(this.innerNameProvider.$dbNameOf(col)));
435
451
  }
436
452
  isNotNull(col) {
453
+ this.handleNull.column(col);
437
454
  this.result.push((b) => b.whereNotNull(this.innerNameProvider.$dbNameOf(col)));
438
455
  }
439
456
  isIn(col, val) {
457
+ if (val?.length)
458
+ this.handleNull.column(col);
440
459
  this.result.push((knex) => knex.whereIn(this.innerNameProvider.$dbNameOf(col), val.map((x) => translateValueAndHandleArrayAndHandleArray(col, x, this.jsonColumnStorage))));
441
460
  }
442
461
  isEqualTo(col, val) {
@@ -470,6 +489,7 @@ class FilterConsumerBridgeToKnexRequest {
470
489
  this.like(col, '%' + escapeLike(val));
471
490
  }
472
491
  like(col, pattern, not = '') {
492
+ this.handleNull.column(col);
473
493
  this.result.push((b) => b.whereRaw(not +
474
494
  'lower (' +
475
495
  b.client.ref(this.innerNameProvider.$dbNameOf(col)) +
@@ -478,12 +498,14 @@ class FilterConsumerBridgeToKnexRequest {
478
498
  this.promises.push((async () => { })());
479
499
  }
480
500
  add(col, val, operator) {
501
+ this.handleNull.column(col);
481
502
  this.result.push((b) => b.where(this.innerNameProvider.$dbNameOf(col), operator, translateValueAndHandleArrayAndHandleArray(col, val, this.jsonColumnStorage)));
482
503
  }
483
504
  databaseCustom(databaseCustom) {
484
505
  this.promises.push((async () => {
485
506
  if (databaseCustom?.buildKnex) {
486
507
  this.result.push(await databaseCustom.buildKnex());
508
+ this.handleNull.custom();
487
509
  }
488
510
  if (databaseCustom?.buildSql) {
489
511
  let r = new KnexCommandHelper();
@@ -492,6 +514,7 @@ class FilterConsumerBridgeToKnexRequest {
492
514
  if (typeof sql !== 'string')
493
515
  sql = item.sql;
494
516
  if (sql) {
517
+ this.handleNull.custom();
495
518
  this.result.push((b) => b.whereRaw(sql, r.values));
496
519
  }
497
520
  }
@@ -1,13 +1,15 @@
1
1
  import { getHtml } from './get-remult-admin-html.js';
2
2
  export default function remultAdminHtml(options) {
3
3
  const { head, rootPath, requireAuthToken, disableLiveQuery } = options;
4
- return getHtml()
5
- .replace('<!--PLACE_HERE_HEAD-->', head)
6
- .replace('<!--PLACE_HERE_BODY-->', `<script>
4
+ const body = `<script>
7
5
  window.optionsFromServer = ${JSON.stringify({
8
6
  rootPath,
9
7
  requireAuthToken,
10
8
  disableLiveQuery,
11
9
  })}
12
- </script>`);
10
+ </script>`;
11
+ // replacer functions: a string replacement would expand `$&` and friends
12
+ return getHtml()
13
+ .replace('<!--PLACE_HERE_HEAD-->', () => head)
14
+ .replace('<!--PLACE_HERE_BODY-->', () => body);
13
15
  }
@@ -63,7 +63,7 @@ export function buildEntityInfo(options) {
63
63
  }
64
64
  fields.push({
65
65
  key: x.key,
66
- readOnly: !x.apiUpdateAllowed(),
66
+ readOnly: readOnlyOf(x),
67
67
  values: getValueList(x),
68
68
  valFieldKey,
69
69
  caption: x.label,
@@ -87,13 +87,11 @@ export function buildEntityInfo(options) {
87
87
  }
88
88
  }
89
89
  if (metadata.apiReadAllowed) {
90
- let superKey = metadata.key;
91
- let caption = metadata.label;
92
90
  const nbOfEntities = entities.filter((e) => e.key === metadata.key).length;
93
- if (nbOfEntities > 0) {
94
- superKey = metadata.key + '_ext_' + nbOfEntities;
95
- caption = metadata.label + '*'.repeat(nbOfEntities);
96
- }
91
+ const superKey = adminSuperKey(metadata.key, nbOfEntities);
92
+ const caption = metadata.label + '*'.repeat(nbOfEntities);
93
+ const config = options.entityConfig?.(metadata, options.remult) ?? true;
94
+ const custom = typeof config === 'object' ? config : undefined;
97
95
  entities.push({
98
96
  superKey,
99
97
  key: metadata.key,
@@ -102,8 +100,104 @@ export function buildEntityInfo(options) {
102
100
  fields,
103
101
  relations,
104
102
  defaultOrderBy: metadata.options.defaultOrderBy ?? { id: 'asc' },
103
+ hidden: config === false,
104
+ editMode: custom?.editMode ?? 'inline',
105
+ editModeLocked: custom?.lockEditMode ?? false,
106
+ apiPrefilter: metadata.options.apiPrefilter !== undefined,
107
+ permissions: {
108
+ insert: resolveAdminPermission(options.remult, metadata.options.allowApiInsert),
109
+ update: resolveAdminPermission(options.remult, metadata.options.allowApiUpdate),
110
+ delete: resolveAdminPermission(options.remult, metadata.options.allowApiDelete),
111
+ },
112
+ rules: {
113
+ read: adminRule(metadata.options.allowApiRead),
114
+ insert: adminRule(metadata.options.allowApiInsert),
115
+ update: adminRule(metadata.options.allowApiUpdate),
116
+ delete: adminRule(metadata.options.allowApiDelete),
117
+ },
105
118
  });
106
119
  }
107
120
  }
108
121
  return entities;
109
122
  }
123
+ /** First occurrence of a key is the key itself, later ones get `_ext_n`. */
124
+ function adminSuperKey(key, nbOfPrevious) {
125
+ return nbOfPrevious > 0 ? key + '_ext_' + nbOfPrevious : key;
126
+ }
127
+ function findAdminEntity(entities, remult, superKey) {
128
+ const seen = {};
129
+ for (const entity of entities) {
130
+ const metadata = remult.repo(entity).metadata;
131
+ if (!metadata.apiReadAllowed)
132
+ continue;
133
+ const nb = seen[metadata.key] ?? 0;
134
+ seen[metadata.key] = nb + 1;
135
+ if (adminSuperKey(metadata.key, nb) === superKey)
136
+ return entity;
137
+ }
138
+ }
139
+ /** Keeps `apiPrefilter` only where it narrows rows for this user: an admin whose prefilter is `{}` sees everything. */
140
+ export async function resolveAdminPrefilters(info, entities, remult) {
141
+ for (const e of info) {
142
+ if (!e.apiPrefilter)
143
+ continue;
144
+ const entity = findAdminEntity(entities, remult, e.superKey);
145
+ if (!entity)
146
+ continue;
147
+ const metadata = remult.repo(entity).metadata;
148
+ const prefilter = metadata.options.apiPrefilter;
149
+ try {
150
+ const where = typeof prefilter === 'function' ? await prefilter() : prefilter;
151
+ e.apiPrefilter =
152
+ Object.keys(Filter.entityFilterToJson(metadata, where ?? {}) ?? {})
153
+ .length > 0;
154
+ }
155
+ catch {
156
+ // can't tell: say it may narrow
157
+ e.apiPrefilter = true;
158
+ }
159
+ }
160
+ return info;
161
+ }
162
+ const needsRow = () => {
163
+ throw new Error('needs the row');
164
+ };
165
+ // any look at this row throws: a rule that never reads it is decided now
166
+ const rowProbe = new Proxy({}, {
167
+ get: needsRow,
168
+ has: needsRow,
169
+ ownKeys: needsRow,
170
+ getOwnPropertyDescriptor: needsRow,
171
+ getPrototypeOf: needsRow,
172
+ });
173
+ function readOnlyOf(field) {
174
+ try {
175
+ return !field.apiUpdateAllowed();
176
+ }
177
+ catch {
178
+ // the rule needs the row; the server still enforces it per row
179
+ return true;
180
+ }
181
+ }
182
+ export function adminRule(rule) {
183
+ if (Array.isArray(rule)) {
184
+ const kinds = rule.map(adminRule);
185
+ if (kinds.includes('function'))
186
+ return 'function';
187
+ return kinds.includes('role') ? 'roles' : 'bool';
188
+ }
189
+ if (typeof rule === 'function')
190
+ return 'function';
191
+ return typeof rule === 'string' ? 'role' : 'bool';
192
+ }
193
+ export function resolveAdminPermission(remult, rule) {
194
+ if (rule === undefined)
195
+ return false;
196
+ try {
197
+ return remult.isAllowedForInstance(rowProbe, rule) === true;
198
+ }
199
+ catch {
200
+ // the rule reads the row (or fails without it): the server decides per row
201
+ return 'row';
202
+ }
203
+ }
@@ -2,6 +2,7 @@ import { __decorate, __metadata } from "tslib";
2
2
  import { SseSubscriptionServer } from '../SseSubscriptionServer.js';
3
3
  import { Remult, RemultAsyncLocalStorage, withRemult } from '../src/context.js';
4
4
  import { DataApi, serializeError } from '../src/data-api.js';
5
+ import { EntityError } from '../src/data-interfaces.js';
5
6
  import { liveQueryKeepAliveRoute } from '../src/live-query/SubscriptionChannel.js';
6
7
  import { InMemoryLiveQueryStorage, LiveQueryPublisher, } from '../src/live-query/SubscriptionServer.js';
7
8
  import { IdEntity } from '../src/remult3/IdEntity.js';
@@ -11,7 +12,7 @@ import { getEntityKey } from '../src/remult3/getEntityRef.js';
11
12
  import { Action, classBackendMethodsArray } from '../src/server-action.js';
12
13
  import { serverActionField } from '../src/server-action-info.js';
13
14
  import { remultStatic } from '../src/remult-static.js';
14
- import { buildEntityInfo } from './remult-admin.js';
15
+ import { buildEntityInfo, resolveAdminPrefilters, } from './remult-admin.js';
15
16
  import { isOfType } from '../src/isOfType.js';
16
17
  import { initDataProviderOrJson } from './initDataProviderOrJson.js';
17
18
  import { modulesFlatAndOrdered } from './module.js';
@@ -230,10 +231,13 @@ export class RemultServerImplementation {
230
231
  : this.options.admin;
231
232
  if (remult.isAllowed(allowed)) {
232
233
  if (orig?.params?.id === '__entities-metadata') {
233
- res.success(buildEntityInfo({
234
+ res.success(await resolveAdminPrefilters(buildEntityInfo({
234
235
  remult,
235
236
  entities: this.entities,
236
- }));
237
+ entityConfig: isOfType(this.options.admin, 'allow')
238
+ ? this.options.admin.entities
239
+ : undefined,
240
+ }), this.entities, remult));
237
241
  }
238
242
  else {
239
243
  let head = '<title>Admin</title>';
@@ -360,7 +364,7 @@ export class RemultServerImplementation {
360
364
  genReq.params = req['_tempParams'];
361
365
  }
362
366
  let myReq = new RequestBridgeToDataApiRequest(genReq);
363
- let myRes = new ResponseBridgeToDataApiResponse(origRes, req, genReq, this.options.error);
367
+ let myRes = new ResponseBridgeToDataApiResponse(origRes, req, genReq, this.options.error, this.options.defaultErrorStatus);
364
368
  try {
365
369
  if (remultStatic.asyncContext.isInInitRequest() &&
366
370
  !doNotReuseInitRequest)
@@ -847,17 +851,19 @@ class ResponseBridgeToDataApiResponse {
847
851
  req;
848
852
  genReq;
849
853
  handleError;
854
+ defaultErrorStatus;
850
855
  forbidden(message = 'Forbidden') {
851
856
  this.error({ message }, undefined, 403);
852
857
  }
853
858
  setStatus(status) {
854
859
  return this.r.status(status);
855
860
  }
856
- constructor(r, req, genReq, handleError) {
861
+ constructor(r, req, genReq, handleError, defaultErrorStatus = 400) {
857
862
  this.r = r;
858
863
  this.req = req;
859
864
  this.genReq = genReq;
860
865
  this.handleError = handleError;
866
+ this.defaultErrorStatus = defaultErrorStatus;
861
867
  }
862
868
  progress(progress) { }
863
869
  success(data) {
@@ -875,16 +881,21 @@ class ResponseBridgeToDataApiResponse {
875
881
  async error(exception, entity, httpStatusCode) {
876
882
  let data = serializeError(exception);
877
883
  if (!httpStatusCode) {
878
- if (data.httpStatusCode) {
879
- httpStatusCode = data.httpStatusCode;
884
+ // serializeError drops httpStatusCode from an Error.
885
+ const explicitStatus = exception.httpStatusCode ?? data.httpStatusCode;
886
+ if (explicitStatus) {
887
+ httpStatusCode = explicitStatus;
880
888
  }
881
889
  else if (isOfType(exception, 'isForbiddenError') &&
882
890
  exception.isForbiddenError) {
883
891
  httpStatusCode = 403;
884
892
  }
885
- else if (data.modelState) {
893
+ else if (data.modelState || exception instanceof EntityError) {
886
894
  httpStatusCode = 400;
887
895
  }
896
+ else if (exception instanceof Error) {
897
+ httpStatusCode = this.defaultErrorStatus;
898
+ }
888
899
  else {
889
900
  httpStatusCode = 400;
890
901
  }
@@ -1,5 +1,7 @@
1
+ import { EntityError, } from './data-interfaces.js';
1
2
  import { RestDataProviderHttpProviderUsingFetch } from './data-providers/rest-data-provider-using-fetch.js';
2
3
  import { isReadPost, retry } from './data-providers/retry.js';
4
+ import { flags } from './remult3/remult3.js';
3
5
  export function buildRestDataProvider(provider) {
4
6
  if (!provider)
5
7
  return new RestDataProviderHttpProviderUsingFetch();
@@ -93,8 +95,6 @@ export async function processHttpException(ex) {
93
95
  if (httpStatusCode !== undefined && httpStatusCode !== null) {
94
96
  error.httpStatusCode = httpStatusCode;
95
97
  }
96
- var result = Object.assign(error ?? {}, {
97
- // exception: ex disabled for now because JSON.stringify crashed with this
98
- });
99
- return result;
98
+ error ??= {};
99
+ return flags.clientErrorsAsEntityError ? new EntityError(error) : error;
100
100
  }
@@ -228,7 +228,7 @@ export class Remult {
228
228
  if (!z.doWork)
229
229
  throw Error('The method received is not a valid backend method');
230
230
  //@ts-ignore
231
- return z.doWork(args, classInstance, this.apiClient.url, buildRestDataProvider(this.apiClient.httpClient));
231
+ return z.doWork(args, classInstance, this);
232
232
  }
233
233
  /* @internal*/
234
234
  liveQuerySubscriber = new LiveQueryClient(() => this.apiClient, () => this.user?.id);
@@ -58,7 +58,7 @@ export class ArrayEntityDataProvider {
58
58
  finishGroup(result) {
59
59
  result[key] = {
60
60
  ...result[key],
61
- avg: sum / count,
61
+ avg: count ? sum / count : null,
62
62
  };
63
63
  sum = 0;
64
64
  count = 0;
@@ -76,7 +76,7 @@ export class ArrayEntityDataProvider {
76
76
  }
77
77
  },
78
78
  finishGroup(result) {
79
- result[key] = { ...result[key], min };
79
+ result[key] = { ...result[key], min: min ?? null };
80
80
  min = undefined;
81
81
  },
82
82
  };
@@ -92,7 +92,7 @@ export class ArrayEntityDataProvider {
92
92
  }
93
93
  },
94
94
  finishGroup(result) {
95
- result[key] = { ...result[key], max };
95
+ result[key] = { ...result[key], max: max ?? null };
96
96
  max = undefined;
97
97
  },
98
98
  };
@@ -468,7 +468,7 @@ class FilterConsumerBridgeToObject {
468
468
  }
469
469
  containsCaseInsensitive(col, val) {
470
470
  let v = this.row[this.dbNames.$dbNameOf(col)];
471
- if (!v) {
471
+ if (v === undefined || v === null) {
472
472
  this.ok = false;
473
473
  return;
474
474
  }
@@ -482,7 +482,7 @@ class FilterConsumerBridgeToObject {
482
482
  }
483
483
  notContainsCaseInsensitive(col, val) {
484
484
  let v = this.row[this.dbNames.$dbNameOf(col)];
485
- if (!v) {
485
+ if (v === undefined || v === null) {
486
486
  this.ok = false;
487
487
  return;
488
488
  }
@@ -496,7 +496,7 @@ class FilterConsumerBridgeToObject {
496
496
  }
497
497
  startsWithCaseInsensitive(col, val) {
498
498
  let v = this.row[this.dbNames.$dbNameOf(col)];
499
- if (!v) {
499
+ if (v === undefined || v === null) {
500
500
  this.ok = false;
501
501
  return;
502
502
  }
@@ -510,7 +510,7 @@ class FilterConsumerBridgeToObject {
510
510
  }
511
511
  endsWithCaseInsensitive(col, val) {
512
512
  let v = this.row[this.dbNames.$dbNameOf(col)];
513
- if (!v) {
513
+ if (v === undefined || v === null) {
514
514
  this.ok = false;
515
515
  return;
516
516
  }
@@ -1,3 +1,5 @@
1
+ import { EntityError, } from '../data-interfaces.js';
2
+ import { flags } from '../remult3/remult3.js';
1
3
  import { isReadPost, retry } from './retry.js';
2
4
  export class RestDataProviderHttpProviderUsingFetch {
3
5
  fetch;
@@ -60,19 +62,24 @@ function onSuccess(response) {
60
62
  throw response
61
63
  .json()
62
64
  .then((x) => {
63
- return {
65
+ return fetchError({
64
66
  ...x,
65
67
  message: x.message || response.statusText,
66
68
  url: response.url,
67
69
  status: response.status,
68
- };
70
+ });
69
71
  })
70
72
  .catch(() => {
71
- throw {
73
+ throw fetchError({
72
74
  message: response.statusText,
73
75
  url: response.url,
74
76
  status: response.status,
75
- };
77
+ });
76
78
  });
77
79
  }
78
80
  }
81
+ function fetchError(info) {
82
+ return flags.clientErrorsAsEntityError
83
+ ? new EntityError({ ...info, httpStatusCode: info.status })
84
+ : info;
85
+ }
@@ -724,7 +724,8 @@ export async function buildGroupBySql(options, e, r, nativeNullSort, limitSyntax
724
724
  }
725
725
  const turnToNumber = x.valueType === Number || operator == 'distinctCount';
726
726
  processResultRow.push((sqlResult, theResult) => {
727
- if (turnToNumber)
727
+ // AVG, MIN and MAX are NULL when there is no value; keep it instead of turning it into 0
728
+ if (turnToNumber && (sqlResult != null || operator === 'sum'))
728
729
  sqlResult = Number(sqlResult);
729
730
  if (operator === 'max' || operator === 'min')
730
731
  sqlResult = fromDbColumn(x, sqlResult, jsonColumnStorage);
@@ -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':
@@ -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()
@@ -23,6 +23,7 @@ let x = {
23
23
  nullSort: undefined,
24
24
  defaultIdFactory: undefined,
25
25
  defaultDataProvider: () => undefined,
26
+ backendMethodSerializer: undefined,
26
27
  };
27
28
  if ((typeof process !== 'undefined' &&
28
29
  process.env['IGNORE_GLOBAL_REMULT_IN_TESTS']) ||