@appweaver/data 2.4.1 → 2.6.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 (105) hide show
  1. package/README.md +4 -2
  2. package/config.d.ts +3 -0
  3. package/config.js +3 -0
  4. package/database/database-config.d.ts +9 -0
  5. package/database/database-config.js +56 -1
  6. package/database/database-error.d.ts +8 -0
  7. package/database/database-error.js +18 -0
  8. package/database/prisma-database.js +18 -1
  9. package/database/setup-database.d.ts +23 -0
  10. package/database/setup-database.js +59 -0
  11. package/database/sqlserver-extension.d.ts +18 -0
  12. package/database/sqlserver-extension.js +183 -0
  13. package/database/telemetry-extension.d.ts +10 -0
  14. package/database/telemetry-extension.js +52 -0
  15. package/export/export-service.js +4 -0
  16. package/factory/create-model.d.ts +1 -1
  17. package/factory/create-model.js +135 -5
  18. package/factory/create-service.js +8 -0
  19. package/index.d.ts +3 -0
  20. package/index.js +6 -0
  21. package/internal.d.ts +2 -0
  22. package/internal.js +3 -1
  23. package/module.js +23 -3
  24. package/package.json +3 -3
  25. package/prisma/client/browser.d.ts +10 -0
  26. package/prisma/client/client.d.ts +10 -0
  27. package/prisma/client/commonInputTypes.d.ts +81 -0
  28. package/prisma/client/enums.d.ts +6 -1
  29. package/prisma/client/enums.js +6 -0
  30. package/prisma/client/internal/class.d.ts +22 -0
  31. package/prisma/client/internal/class.js +4 -4
  32. package/prisma/client/internal/prismaNamespace.d.ts +175 -1
  33. package/prisma/client/internal/prismaNamespace.js +19 -1
  34. package/prisma/client/internal/prismaNamespaceBrowser.d.ts +20 -0
  35. package/prisma/client/internal/prismaNamespaceBrowser.js +19 -1
  36. package/prisma/client/models/TwoFactorMethod.d.ts +1140 -0
  37. package/prisma/client/models/TwoFactorMethod.js +2 -0
  38. package/prisma/client/models/TwoFactorRecoveryCode.d.ts +1005 -0
  39. package/prisma/client/models/TwoFactorRecoveryCode.js +2 -0
  40. package/prisma/client/models.d.ts +2 -0
  41. package/resource/resource-service.d.ts +32 -7
  42. package/resource/resource-service.js +248 -35
  43. package/resource/schemas/resource-filter-schema.d.ts +8 -0
  44. package/resource/schemas/resource-filter-schema.js +40 -1
  45. package/resource/schemas/resource-sort-schema.js +10 -0
  46. package/resource/utils/cursor-util.d.ts +13 -0
  47. package/resource/utils/cursor-util.js +21 -0
  48. package/resource/utils/filter-util.d.ts +9 -0
  49. package/resource/utils/filter-util.js +17 -0
  50. package/resource/utils/prune-util.js +3 -1
  51. package/resource/utils/sort-util.d.ts +14 -0
  52. package/resource/utils/sort-util.js +1 -0
  53. package/resource/utils/where-util.d.ts +20 -0
  54. package/resource/utils/where-util.js +210 -0
  55. package/resources.d.ts +4 -0
  56. package/resources.js +17 -9
  57. package/security/auth-config.d.ts +3 -0
  58. package/security/auth-config.js +6 -1
  59. package/security/create-auth-resources.d.ts +3 -3
  60. package/security/create-auth-resources.js +44 -7
  61. package/security/helper.d.ts +6 -0
  62. package/security/helper.js +11 -0
  63. package/security/resources/two-factor-method/model.d.ts +2 -0
  64. package/security/resources/two-factor-method/model.js +64 -0
  65. package/security/resources/two-factor-method/service.d.ts +2 -0
  66. package/security/resources/two-factor-method/service.js +7 -0
  67. package/security/resources/two-factor-recovery-code/model.d.ts +2 -0
  68. package/security/resources/two-factor-recovery-code/model.js +49 -0
  69. package/security/resources/two-factor-recovery-code/service.d.ts +2 -0
  70. package/security/resources/two-factor-recovery-code/service.js +7 -0
  71. package/security/store/database-security-store.d.ts +2 -2
  72. package/security/store/database-security-store.js +11 -1
  73. package/seeder/create-seeder.d.ts +3 -0
  74. package/seeder/create-seeder.js +6 -2
  75. package/seeder/seeder.d.ts +4 -2
  76. package/seeder/seeder.js +56 -23
  77. package/spatial/geo-schema.d.ts +22 -0
  78. package/spatial/geo-schema.js +60 -0
  79. package/spatial/spatial-config.d.ts +21 -0
  80. package/spatial/spatial-config.js +52 -0
  81. package/spatial/spatial-engine.d.ts +78 -0
  82. package/spatial/spatial-engine.js +232 -0
  83. package/spatial/spatial-extension.d.ts +10 -0
  84. package/spatial/spatial-extension.js +100 -0
  85. package/spatial/spatial-service.d.ts +54 -0
  86. package/spatial/spatial-service.js +213 -0
  87. package/spatial/utils/box-util.d.ts +31 -0
  88. package/spatial/utils/box-util.js +62 -0
  89. package/timeseries/database-series-config.d.ts +5 -0
  90. package/timeseries/database-series-config.js +15 -0
  91. package/timeseries/database-time-series.d.ts +36 -0
  92. package/timeseries/database-time-series.js +147 -0
  93. package/timeseries/index.d.ts +2 -0
  94. package/timeseries/index.js +18 -0
  95. package/timeseries/timescale-config.d.ts +6 -0
  96. package/timeseries/timescale-config.js +19 -0
  97. package/timeseries/timescale-time-series.d.ts +21 -0
  98. package/timeseries/timescale-time-series.js +158 -0
  99. package/timeseries/utils/series-sql-util.d.ts +90 -0
  100. package/timeseries/utils/series-sql-util.js +313 -0
  101. package/types/generated.d.ts +92 -0
  102. package/utils/schema-util.d.ts +8 -0
  103. package/utils/schema-util.js +22 -0
  104. package/utils/write-data-util.d.ts +22 -0
  105. package/utils/write-data-util.js +144 -0
@@ -0,0 +1,313 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.mssqlDialect = exports.mysqlDialect = exports.sqliteDialect = exports.postgresDialect = void 0;
4
+ exports.seriesDialect = seriesDialect;
5
+ exports.upsertStatements = upsertStatements;
6
+ exports.selectStatement = selectStatement;
7
+ exports.deleteStatement = deleteStatement;
8
+ exports.expiredStatement = expiredStatement;
9
+ exports.toSeriesPoints = toSeriesPoints;
10
+ exports.toDate = toDate;
11
+ const client_1 = require("@prisma/client/runtime/client");
12
+ const common_1 = require("@appweaver/common");
13
+ const ansiQuote = (name) => `"${name.replace(/"/g, '""')}"`;
14
+ // The integer division truncates toward zero, which would round up before the epoch
15
+ const floorSeconds = (seconds, width) => `(${seconds} - ((${seconds} % ${width}) + ${width}) % ${width})`;
16
+ const toInteger = (column, field) => field.type === 'boolean' ? `CAST(${column} AS INTEGER)` : column;
17
+ const conflictUpsert = (table, columns, fields, rows) => (0, client_1.sqltag) `INSERT INTO ${(0, client_1.raw)(table)} (${(0, client_1.raw)(columns.map(ansiQuote).join(', '))}) VALUES ${rows} ON CONFLICT (${(0, client_1.raw)(`${ansiQuote('resourceId')}, ${ansiQuote('time')}`)}) ${(0, client_1.raw)(fields.length
18
+ ? `DO UPDATE SET ${fields
19
+ .map((field) => `${ansiQuote(field)} = COALESCE(excluded.${ansiQuote(field)}, ${table}.${ansiQuote(field)})`)
20
+ .join(', ')}`
21
+ : 'DO NOTHING')}`;
22
+ exports.postgresDialect = {
23
+ maxParams: 30_000,
24
+ quote: ansiQuote,
25
+ table: ansiQuote,
26
+ bucket: (column, width) => `date_bin(INTERVAL '${width} seconds', ${column}, TIMESTAMP '1970-01-01 00:00:00')`,
27
+ numeric: toInteger,
28
+ average: (column) => column,
29
+ sum: (column) => column,
30
+ limit: (count) => `LIMIT ${count}`,
31
+ upsert: conflictUpsert
32
+ };
33
+ exports.sqliteDialect = {
34
+ maxParams: 9_999,
35
+ quote: ansiQuote,
36
+ table: ansiQuote,
37
+ // The times are stored as ISO 8601 text with a `+00:00` offset, the bucket written back the same way
38
+ bucket: (column, width) => `strftime('%Y-%m-%dT%H:%M:%S.000+00:00', ${floorSeconds(`CAST(strftime('%s', ${column}) AS INTEGER)`, width)}, 'unixepoch')`,
39
+ numeric: (column) => column,
40
+ average: (column) => column,
41
+ sum: (column) => column,
42
+ limit: (count) => `LIMIT ${count}`,
43
+ upsert: conflictUpsert
44
+ };
45
+ const mysqlQuote = (name) => `\`${name.replace(/`/g, '``')}\``;
46
+ exports.mysqlDialect = {
47
+ maxParams: 30_000,
48
+ quote: mysqlQuote,
49
+ table: mysqlQuote,
50
+ // Computed apart from the time zone of the session, unlike UNIX_TIMESTAMP
51
+ bucket: (column, width) => `TIMESTAMPADD(SECOND, FLOOR(TIMESTAMPDIFF(SECOND, '1970-01-01 00:00:00', ${column}) / ${width}) * ${width}, '1970-01-01 00:00:00')`,
52
+ numeric: (column, field) => field.type === 'boolean' ? `CAST(${column} AS SIGNED)` : column,
53
+ average: (column) => column,
54
+ sum: (column) => column,
55
+ limit: (count) => `LIMIT ${count}`,
56
+ upsert: (table, columns, fields, rows) => (0, client_1.sqltag) `INSERT INTO ${(0, client_1.raw)(table)} (${(0, client_1.raw)(columns.map(mysqlQuote).join(', '))}) VALUES ${rows} ON DUPLICATE KEY UPDATE ${(0, client_1.raw)((fields.length ? fields : ['time'])
57
+ .map((field) => field === 'time'
58
+ ? `${mysqlQuote(field)} = ${mysqlQuote(field)}`
59
+ : `${mysqlQuote(field)} = COALESCE(VALUES(${mysqlQuote(field)}), ${mysqlQuote(field)})`)
60
+ .join(', '))}`
61
+ };
62
+ const mssqlQuote = (name) => `[${name.replace(/]/g, ']]')}]`;
63
+ exports.mssqlDialect = {
64
+ maxParams: 2_000,
65
+ quote: mssqlQuote,
66
+ table: mssqlQuote,
67
+ bucket: (column, width) => {
68
+ const start = floorSeconds(`DATEDIFF_BIG(SECOND, CAST('1970-01-01' AS DATETIME2), ${column})`, width);
69
+ return `DATEADD(SECOND, CAST(${start} % 86400 AS INT), DATEADD(DAY, CAST(${start} / 86400 AS INT), CAST('1970-01-01' AS DATETIME2)))`;
70
+ },
71
+ numeric: (column, field) => field.type === 'boolean' ? `CAST(${column} AS INT)` : column,
72
+ average: (column) => `CAST(${column} AS FLOAT)`,
73
+ // SUM of an INT is an INT, overflowing past 2^31
74
+ sum: (column, field) => field.type === 'int' ? `CAST(${column} AS BIGINT)` : column,
75
+ limit: (count) => `OFFSET 0 ROWS FETCH NEXT ${count} ROWS ONLY`,
76
+ upsert: (table, columns, fields, rows) => {
77
+ const quoted = columns.map(mssqlQuote);
78
+ const update = fields.length
79
+ ? `WHEN MATCHED THEN UPDATE SET ${fields
80
+ .map((field) => `t.${mssqlQuote(field)} = COALESCE(s.${mssqlQuote(field)}, t.${mssqlQuote(field)})`)
81
+ .join(', ')} `
82
+ : '';
83
+ // A MERGE without the lock fails on a key two of them insert at once
84
+ return (0, client_1.sqltag) `MERGE INTO ${(0, client_1.raw)(table)} WITH (HOLDLOCK) AS t USING (VALUES ${rows}) AS s (${(0, client_1.raw)(quoted.join(', '))}) ON ${(0, client_1.raw)(`t.${mssqlQuote('resourceId')} = s.${mssqlQuote('resourceId')} AND t.${mssqlQuote('time')} = s.${mssqlQuote('time')}`)} ${(0, client_1.raw)(update)}WHEN NOT MATCHED THEN INSERT (${(0, client_1.raw)(quoted.join(', '))}) VALUES (${(0, client_1.raw)(quoted.map((column) => `s.${column}`).join(', '))});`;
85
+ }
86
+ };
87
+ /**
88
+ * Returns the SQL dialect of the time series of a database, its tables qualified by the PostgreSQL schema of the
89
+ * connection, since the raw queries are not qualified by the Prisma client.
90
+ *
91
+ * @param {DatabaseType} type - The database type.
92
+ * @param {string} [schema] - The PostgreSQL schema of the connection (the `schema` parameter of its URL).
93
+ * @return {SeriesDialect} The dialect.
94
+ */
95
+ function seriesDialect(type, schema) {
96
+ switch (type) {
97
+ case common_1.DatabaseType.PostgreSQL:
98
+ return schema
99
+ ? {
100
+ ...exports.postgresDialect,
101
+ table: (name) => `${ansiQuote(schema)}.${ansiQuote(name)}`
102
+ }
103
+ : exports.postgresDialect;
104
+ case common_1.DatabaseType.MySQL:
105
+ return exports.mysqlDialect;
106
+ case common_1.DatabaseType.SQLServer:
107
+ return exports.mssqlDialect;
108
+ default:
109
+ return exports.sqliteDialect;
110
+ }
111
+ }
112
+ /**
113
+ * Builds the statements writing the points of a model, each binding up to the parameters the database allows.
114
+ *
115
+ * @param {SeriesDialect} dialect - The SQL dialect.
116
+ * @param {SeriesModel} model - The series model.
117
+ * @param {SeriesPoint[]} points - The points, at most one per resource and time.
118
+ * @return {Sql[]} The statements.
119
+ */
120
+ function upsertStatements(dialect, model, points) {
121
+ const fields = Object.keys(model.fields);
122
+ const columns = ['resourceId', 'time', ...fields];
123
+ const rowsPerStatement = Math.max(1, Math.floor(dialect.maxParams / columns.length));
124
+ const statements = [];
125
+ for (let i = 0; i < points.length; i += rowsPerStatement) {
126
+ const rows = points
127
+ .slice(i, i + rowsPerStatement)
128
+ .map((point) => (0, client_1.sqltag) `(${(0, client_1.join)([
129
+ point.resourceId,
130
+ point.time,
131
+ ...fields.map((field) => point.values[field] ?? null)
132
+ ])})`);
133
+ statements.push(dialect.upsert(dialect.table(model.table), columns, fields, (0, client_1.join)(rows)));
134
+ }
135
+ return statements;
136
+ }
137
+ /** The conditions of the resources and the time range of a query. */
138
+ function rangeConditions(dialect, query) {
139
+ const q = dialect.quote;
140
+ return [
141
+ (0, client_1.sqltag) `${(0, client_1.raw)(q('resourceId'))} IN (${(0, client_1.join)(query.resourceIds)})`,
142
+ query.from ? (0, client_1.sqltag) `${(0, client_1.raw)(q('time'))} >= ${query.from}` : client_1.empty,
143
+ query.to ? (0, client_1.sqltag) `${(0, client_1.raw)(q('time'))} < ${query.to}` : client_1.empty
144
+ ].filter((condition) => condition !== client_1.empty);
145
+ }
146
+ /**
147
+ * Builds the query of the points of a model: the stored points, or the points aggregated by bucket, or over the whole
148
+ * range of each resource without one. The points without a value of the selected fields are skipped.
149
+ *
150
+ * @param {SeriesDialect} dialect - The SQL dialect.
151
+ * @param {SeriesModel} model - The series model.
152
+ * @param {SeriesQuery} query - The normalized query, its fields selected.
153
+ * @param {Function} [bucket] - Builds the bucket start of a time column, the one of the dialect by default.
154
+ * @return {Sql} The query, its columns `rid`, `t` and the fields.
155
+ */
156
+ function selectStatement(dialect, model, query, bucket = dialect.bucket) {
157
+ const q = dialect.quote;
158
+ const fields = query.fields?.length
159
+ ? query.fields
160
+ : Object.keys(model.fields);
161
+ const where = (0, client_1.join)([
162
+ ...rangeConditions(dialect, query),
163
+ (0, client_1.raw)(`(${fields.map((field) => `${q(field)} IS NOT NULL`).join(' OR ')})`)
164
+ ], ' AND ');
165
+ const direction = query.order === 'desc' ? 'DESC' : 'ASC';
166
+ const limit = query.limit !== undefined ? dialect.limit(query.limit) : '';
167
+ const orderBy = (time, rid) => `ORDER BY ${time} ${direction}, ${rid} ASC ${limit}`;
168
+ const order = orderBy(q('t'), q('rid'));
169
+ const table = (0, client_1.raw)(dialect.table(model.table));
170
+ if (!query.bucket && !query.aggregate) {
171
+ const columns = [
172
+ `${q('resourceId')} AS ${q('rid')}`,
173
+ `${q('time')} AS ${q('t')}`,
174
+ ...fields.map(q)
175
+ ];
176
+ return (0, client_1.sqltag) `SELECT ${(0, client_1.raw)(columns.join(', '))} FROM ${table} WHERE ${where} ${(0, client_1.raw)(order)}`;
177
+ }
178
+ const aggregate = query.aggregate ?? 'avg';
179
+ const bucketColumn = query.bucket
180
+ ? bucket(q('time'), query.bucket)
181
+ : undefined;
182
+ if (aggregate === 'first' || aggregate === 'last') {
183
+ // Ordered by the expressions, since SQL Server does not order a join by an alias
184
+ const k = (column) => `${q('k')}.${q(column)}`;
185
+ return firstOrLastStatement(dialect, fields, aggregate, where, table, bucketColumn, orderBy(k(bucketColumn ? 'b' : 'mt'), k('rid')));
186
+ }
187
+ const columns = [
188
+ `${q('resourceId')} AS ${q('rid')}`,
189
+ `${bucketColumn ?? `MIN(${q('time')})`} AS ${q('t')}`,
190
+ ...fields.map((field) => `${aggregateExpression(dialect, aggregate, q(field), model.fields[field])} AS ${q(field)}`)
191
+ ];
192
+ const groupBy = [
193
+ q('resourceId'),
194
+ ...(bucketColumn ? [bucketColumn] : [])
195
+ ].join(', ');
196
+ return (0, client_1.sqltag) `SELECT ${(0, client_1.raw)(columns.join(', '))} FROM ${table} WHERE ${where} ${(0, client_1.raw)(`GROUP BY ${groupBy} ${order}`)}`;
197
+ }
198
+ /**
199
+ * The first or last value of each field in a bucket, ignoring the points without one, with a window function per
200
+ * field, which every supported database has.
201
+ */
202
+ function firstOrLastStatement(dialect, fields, aggregate, where, table, bucketColumn, order) {
203
+ const q = dialect.quote;
204
+ const direction = aggregate === 'first' ? 'ASC' : 'DESC';
205
+ const source = [
206
+ `${q('resourceId')} AS ${q('rid')}`,
207
+ `${bucketColumn ?? '0'} AS ${q('b')}`,
208
+ `${q('time')} AS ${q('time')}`,
209
+ ...fields.map(q)
210
+ ].join(', ');
211
+ const joins = fields.map((field, i) => {
212
+ const alias = q(`j${i}`);
213
+ return (`LEFT JOIN (SELECT ${q('rid')}, ${q('b')}, ${q(field)} AS ${q('v')}, ROW_NUMBER() OVER (PARTITION BY ${q('rid')}, ${q('b')} ORDER BY ${q('time')} ${direction}) AS ${q('rn')} ` +
214
+ `FROM ${q('src')} WHERE ${q(field)} IS NOT NULL) ${alias} ` +
215
+ `ON ${alias}.${q('rid')} = ${q('k')}.${q('rid')} AND ${alias}.${q('b')} = ${q('k')}.${q('b')} AND ${alias}.${q('rn')} = 1`);
216
+ });
217
+ const columns = [
218
+ `${q('k')}.${q('rid')} AS ${q('rid')}`,
219
+ `${q('k')}.${bucketColumn ? q('b') : q('mt')} AS ${q('t')}`,
220
+ ...fields.map((field, i) => `${q(`j${i}`)}.${q('v')} AS ${q(field)}`)
221
+ ].join(', ');
222
+ return (0, client_1.sqltag) `WITH ${(0, client_1.raw)(q('src'))} AS (SELECT ${(0, client_1.raw)(source)} FROM ${table} WHERE ${where}) ${(0, client_1.raw)(`SELECT ${columns} FROM (SELECT ${q('rid')}, ${q('b')}, MIN(${q('time')}) AS ${q('mt')} FROM ${q('src')} GROUP BY ${q('rid')}, ${q('b')}) ${q('k')} ${joins.join(' ')} ${order}`)}`;
223
+ }
224
+ function aggregateExpression(dialect, aggregate, column, field) {
225
+ if (aggregate === 'count') {
226
+ return `COUNT(${column})`;
227
+ }
228
+ const value = dialect.numeric(column, field);
229
+ switch (aggregate) {
230
+ case 'avg':
231
+ return `AVG(${dialect.average(value)})`;
232
+ case 'sum':
233
+ return `SUM(${dialect.sum(value, field)})`;
234
+ default:
235
+ return `${aggregate.toUpperCase()}(${value})`;
236
+ }
237
+ }
238
+ /**
239
+ * Builds the statement deleting the points of a model within a time range.
240
+ *
241
+ * @param {SeriesDialect} dialect - The SQL dialect.
242
+ * @param {SeriesModel} model - The series model.
243
+ * @param {Object} query - The resources and the time range.
244
+ * @return {Sql} The statement.
245
+ */
246
+ function deleteStatement(dialect, model, query) {
247
+ return (0, client_1.sqltag) `DELETE FROM ${(0, client_1.raw)(dialect.table(model.table))} WHERE ${(0, client_1.join)(rangeConditions(dialect, query), ' AND ')}`;
248
+ }
249
+ /**
250
+ * Builds the statement deleting the points of a model older than a time, of every resource.
251
+ *
252
+ * @param {SeriesDialect} dialect - The SQL dialect.
253
+ * @param {SeriesModel} model - The series model.
254
+ * @param {Date} before - The time the points are older than.
255
+ * @return {Sql} The statement.
256
+ */
257
+ function expiredStatement(dialect, model, before) {
258
+ return (0, client_1.sqltag) `DELETE FROM ${(0, client_1.raw)(dialect.table(model.table))} WHERE ${(0, client_1.raw)(dialect.quote('time'))} < ${before}`;
259
+ }
260
+ /**
261
+ * Converts the rows of a time series query to points, the values to the types of their fields: the numbers of a
262
+ * database returning them as text, decimals or big integers, the booleans of one storing them as numbers, and the
263
+ * times of one returning them as text in UTC.
264
+ *
265
+ * @param {SeriesModel} model - The series model.
266
+ * @param {SeriesQuery} query - The query.
267
+ * @param {SeriesRow[]} rows - The rows.
268
+ * @return {SeriesPoint[]} The points.
269
+ */
270
+ function toSeriesPoints(model, query, rows) {
271
+ const fields = query.fields?.length
272
+ ? query.fields
273
+ : Object.keys(model.fields);
274
+ const aggregate = query.bucket || query.aggregate ? (query.aggregate ?? 'avg') : undefined;
275
+ const keepsType = !aggregate || aggregate === 'first' || aggregate === 'last';
276
+ return rows.map((row) => ({
277
+ resourceId: toId(model, row.rid),
278
+ time: toDate(row.t),
279
+ values: Object.fromEntries(fields.map((field) => [
280
+ field,
281
+ toValue(row[field], keepsType && model.fields[field].type === 'boolean')
282
+ ]))
283
+ }));
284
+ }
285
+ function toId(model, value) {
286
+ return model.idType === 'string' ? String(value) : Number(value);
287
+ }
288
+ /** Converts a time read from a database, a text without an offset being in UTC. */
289
+ function toDate(value) {
290
+ if (value instanceof Date) {
291
+ return value;
292
+ }
293
+ if (typeof value === 'string' && !/(Z|[+-]\d\d:?\d\d)$/.test(value)) {
294
+ return new Date(`${value.replace(' ', 'T')}Z`);
295
+ }
296
+ return new Date(value);
297
+ }
298
+ function toValue(value, boolean) {
299
+ if (value === null || value === undefined) {
300
+ return null;
301
+ }
302
+ if (boolean) {
303
+ return value === true || Number(value) === 1;
304
+ }
305
+ if (typeof value === 'number') {
306
+ return value;
307
+ }
308
+ if (typeof value === 'object' &&
309
+ typeof value.toNumber === 'function') {
310
+ return value.toNumber();
311
+ }
312
+ return Number(value);
313
+ }
@@ -268,6 +268,98 @@ export type RoleQuery = QueryFilter<Role>;
268
268
  export type RoleSort = QuerySort<RoleMultiple>;
269
269
  export type RoleAggregate = AggregateSelect<Role>;
270
270
  export type RoleResourceService = IResourceService<Role, RoleMultiple, RoleCreate, RoleUpdate, RoleQuery, RoleReplace>;
271
+ export type TwoFactorMethod = {
272
+ id: number;
273
+ type: 'Email' | 'Sms' | 'Totp';
274
+ priority: number;
275
+ secret?: string | null;
276
+ confirmedAt?: Date | null;
277
+ lastUsedStep?: number | null;
278
+ updatedAt: Date;
279
+ createdAt: Date;
280
+ };
281
+ export type TwoFactorMethodSingle = {
282
+ id: number;
283
+ type: 'Email' | 'Sms' | 'Totp';
284
+ priority: number;
285
+ confirmedAt?: Date | null;
286
+ updatedAt: Date;
287
+ createdAt: Date;
288
+ };
289
+ export type TwoFactorMethodMultiple = {
290
+ id: number;
291
+ type: 'Email' | 'Sms' | 'Totp';
292
+ priority: number;
293
+ confirmedAt?: Date | null;
294
+ updatedAt: Date;
295
+ createdAt: Date;
296
+ };
297
+ export type TwoFactorMethodCreate = {
298
+ type: 'Email' | 'Sms' | 'Totp';
299
+ priority?: number;
300
+ confirmedAt?: Date | null;
301
+ };
302
+ export type TwoFactorMethodUpdate = {
303
+ type?: 'Email' | 'Sms' | 'Totp';
304
+ priority?: number;
305
+ confirmedAt?: Date | null;
306
+ };
307
+ export type TwoFactorMethodReplace = {
308
+ type: 'Email' | 'Sms' | 'Totp';
309
+ priority?: number;
310
+ confirmedAt?: Date | null;
311
+ };
312
+ export type TwoFactorMethodRelationCreate = {
313
+ type: 'Email' | 'Sms' | 'Totp';
314
+ priority?: number;
315
+ confirmedAt?: Date | null;
316
+ };
317
+ export type TwoFactorMethodRelationUpdate = {
318
+ id: number;
319
+ type?: 'Email' | 'Sms' | 'Totp';
320
+ priority?: number;
321
+ confirmedAt?: Date | null;
322
+ };
323
+ export type TwoFactorMethodQuery = QueryFilter<TwoFactorMethod>;
324
+ export type TwoFactorMethodSort = QuerySort<TwoFactorMethodMultiple>;
325
+ export type TwoFactorMethodAggregate = AggregateSelect<TwoFactorMethod>;
326
+ export type TwoFactorMethodResourceService = IResourceService<TwoFactorMethod, TwoFactorMethodMultiple, TwoFactorMethodCreate, TwoFactorMethodUpdate, TwoFactorMethodQuery, TwoFactorMethodReplace>;
327
+ export type TwoFactorRecoveryCode = {
328
+ id: number;
329
+ codeHash: string;
330
+ usedAt?: Date | null;
331
+ createdAt: Date;
332
+ };
333
+ export type TwoFactorRecoveryCodeSingle = {
334
+ id: number;
335
+ usedAt?: Date | null;
336
+ createdAt: Date;
337
+ };
338
+ export type TwoFactorRecoveryCodeMultiple = {
339
+ id: number;
340
+ usedAt?: Date | null;
341
+ createdAt: Date;
342
+ };
343
+ export type TwoFactorRecoveryCodeCreate = {
344
+ usedAt?: Date | null;
345
+ };
346
+ export type TwoFactorRecoveryCodeUpdate = {
347
+ usedAt?: Date | null;
348
+ };
349
+ export type TwoFactorRecoveryCodeReplace = {
350
+ usedAt?: Date | null;
351
+ };
352
+ export type TwoFactorRecoveryCodeRelationCreate = {
353
+ usedAt?: Date | null;
354
+ };
355
+ export type TwoFactorRecoveryCodeRelationUpdate = {
356
+ id: number;
357
+ usedAt?: Date | null;
358
+ };
359
+ export type TwoFactorRecoveryCodeQuery = QueryFilter<TwoFactorRecoveryCode>;
360
+ export type TwoFactorRecoveryCodeSort = QuerySort<TwoFactorRecoveryCodeMultiple>;
361
+ export type TwoFactorRecoveryCodeAggregate = AggregateSelect<TwoFactorRecoveryCode>;
362
+ export type TwoFactorRecoveryCodeResourceService = IResourceService<TwoFactorRecoveryCode, TwoFactorRecoveryCodeMultiple, TwoFactorRecoveryCodeCreate, TwoFactorRecoveryCodeUpdate, TwoFactorRecoveryCodeQuery, TwoFactorRecoveryCodeReplace>;
271
363
  export type File = {
272
364
  id: number;
273
365
  name: string;
@@ -0,0 +1,8 @@
1
+ import { DatabaseType } from '@appweaver/common';
2
+ /**
3
+ * The `schema` parameter of a PostgreSQL URL, which the Prisma client leaves out of the raw queries.
4
+ *
5
+ * @param {DatabaseType} type - The database type.
6
+ * @return {string | undefined} The schema, undefined for another database or a URL without one.
7
+ */
8
+ export declare function postgresSchema(type: DatabaseType): string | undefined;
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.postgresSchema = postgresSchema;
4
+ const common_1 = require("@appweaver/common");
5
+ const database_config_1 = require("../database/database-config");
6
+ /**
7
+ * The `schema` parameter of a PostgreSQL URL, which the Prisma client leaves out of the raw queries.
8
+ *
9
+ * @param {DatabaseType} type - The database type.
10
+ * @return {string | undefined} The schema, undefined for another database or a URL without one.
11
+ */
12
+ function postgresSchema(type) {
13
+ if (type !== common_1.DatabaseType.PostgreSQL) {
14
+ return undefined;
15
+ }
16
+ try {
17
+ return new URL(database_config_1.databaseConfig.URL).searchParams.get('schema') ?? undefined;
18
+ }
19
+ catch {
20
+ return undefined;
21
+ }
22
+ }
@@ -0,0 +1,22 @@
1
+ /** Maps the data of a record a write stores, the nested writes of its relations excluded. */
2
+ export type RecordMapper = (modelName: string, data: Record<string, any>) => Record<string, any>;
3
+ /**
4
+ * Maps the data of the records a write operation stores, and of the nested writes of their relations, i.e. to
5
+ * serialize the JSON fields of SQL Server.
6
+ *
7
+ * @param {string} modelName - The model the operation runs on.
8
+ * @param {string} operation - The Prisma operation, i.e. `create`.
9
+ * @param {any} args - The arguments of the operation.
10
+ * @param {RecordMapper} mapRecord - Maps the data of a record.
11
+ * @return {any} The mapped arguments.
12
+ */
13
+ export declare function mapWriteArgs(modelName: string, operation: string, args: any, mapRecord: RecordMapper): any;
14
+ /**
15
+ * Maps the records of a result, and of their included relations, i.e. to parse the JSON fields of SQL Server.
16
+ *
17
+ * @param {string} modelName - The model of the records.
18
+ * @param {any} result - The result, a record or a list of them.
19
+ * @param {RecordMapper} mapRecord - Maps a record.
20
+ * @return {any} The mapped result.
21
+ */
22
+ export declare function mapResultRecords(modelName: string, result: any, mapRecord: RecordMapper): any;
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.mapWriteArgs = mapWriteArgs;
4
+ exports.mapResultRecords = mapResultRecords;
5
+ const common_1 = require("@appweaver/common");
6
+ const internal_1 = require("@appweaver/core/internal");
7
+ let cached;
8
+ /**
9
+ * Maps the data of the records a write operation stores, and of the nested writes of their relations, i.e. to
10
+ * serialize the JSON fields of SQL Server.
11
+ *
12
+ * @param {string} modelName - The model the operation runs on.
13
+ * @param {string} operation - The Prisma operation, i.e. `create`.
14
+ * @param {any} args - The arguments of the operation.
15
+ * @param {RecordMapper} mapRecord - Maps the data of a record.
16
+ * @return {any} The mapped arguments.
17
+ */
18
+ function mapWriteArgs(modelName, operation, args, mapRecord) {
19
+ if (!(0, common_1.isPlainObject)(args)) {
20
+ return args;
21
+ }
22
+ const related = relatedModels();
23
+ const map = (data) => mapWriteData(modelName, data, mapRecord, related);
24
+ switch (operation) {
25
+ case 'create':
26
+ case 'createMany':
27
+ case 'createManyAndReturn':
28
+ case 'update':
29
+ case 'updateMany':
30
+ case 'updateManyAndReturn':
31
+ return { ...args, data: map(args.data) };
32
+ case 'upsert':
33
+ return { ...args, create: map(args.create), update: map(args.update) };
34
+ default:
35
+ return args;
36
+ }
37
+ }
38
+ /**
39
+ * Maps the records of a result, and of their included relations, i.e. to parse the JSON fields of SQL Server.
40
+ *
41
+ * @param {string} modelName - The model of the records.
42
+ * @param {any} result - The result, a record or a list of them.
43
+ * @param {RecordMapper} mapRecord - Maps a record.
44
+ * @return {any} The mapped result.
45
+ */
46
+ function mapResultRecords(modelName, result, mapRecord) {
47
+ return mapRecords(modelName, result, mapRecord, relatedModels());
48
+ }
49
+ function mapRecords(modelName, result, mapRecord, related) {
50
+ if ((0, common_1.isArray)(result)) {
51
+ return result.map((item) => mapRecords(modelName, item, mapRecord, related));
52
+ }
53
+ if (!(0, common_1.isPlainObject)(result)) {
54
+ return result;
55
+ }
56
+ const record = mapRecord(modelName, result);
57
+ const fields = related.get(modelName);
58
+ for (const [key, value] of Object.entries(record)) {
59
+ if (fields?.has(key) && value !== null) {
60
+ record[key] = mapRecords(fields.get(key), value, mapRecord, related);
61
+ }
62
+ }
63
+ return record;
64
+ }
65
+ /** The related models of the loaded models, recomputed when the models change. */
66
+ function relatedModels() {
67
+ const loaded = [
68
+ ...internal_1.context.resource.models.values()
69
+ ];
70
+ if (cached?.models.length === loaded.length &&
71
+ cached.models.every((model, i) => model === loaded[i])) {
72
+ return cached.related;
73
+ }
74
+ const authModel = loaded.find(common_1.isResourceAuthModel);
75
+ const related = new Map();
76
+ for (const model of loaded) {
77
+ const fields = new Map();
78
+ for (const [field, relation] of Object.entries(model.config.relations ?? {})) {
79
+ fields.set(field, (0, common_1.capitalize)(relation.model));
80
+ }
81
+ for (const field of Object.keys(model.config.files ?? {})) {
82
+ fields.set(field, 'File');
83
+ }
84
+ if (authModel) {
85
+ fields.set('createdBy', authModel.name);
86
+ fields.set('deletedBy', authModel.name);
87
+ }
88
+ related.set(model.name, fields);
89
+ }
90
+ cached = { models: loaded, related };
91
+ return related;
92
+ }
93
+ function mapWriteData(modelName, data, mapRecord, related) {
94
+ if ((0, common_1.isArray)(data)) {
95
+ return data.map((item) => mapWriteData(modelName, item, mapRecord, related));
96
+ }
97
+ if (!(0, common_1.isPlainObject)(data)) {
98
+ return data;
99
+ }
100
+ const mapped = mapRecord(modelName, data);
101
+ const fields = related.get(modelName);
102
+ for (const [key, value] of Object.entries(mapped)) {
103
+ if (fields?.has(key) && (0, common_1.isPlainObject)(value)) {
104
+ mapped[key] = mapNestedWrites(fields.get(key), value, mapRecord, related);
105
+ }
106
+ }
107
+ return mapped;
108
+ }
109
+ function mapNestedWrites(modelName, writes, mapRecord, related) {
110
+ const map = (data) => mapWriteData(modelName, data, mapRecord, related);
111
+ const each = (value, fn) => (0, common_1.isArray)(value) ? value.map(fn) : fn(value);
112
+ const withData = (item) => (0, common_1.isPlainObject)(item) && 'data' in item
113
+ ? { ...item, data: map(item.data) }
114
+ : map(item);
115
+ const mapped = { ...writes };
116
+ for (const [action, value] of Object.entries(writes)) {
117
+ switch (action) {
118
+ case 'create':
119
+ mapped[action] = map(value);
120
+ break;
121
+ case 'createMany':
122
+ mapped[action] = { ...value, data: map(value?.data) };
123
+ break;
124
+ case 'update':
125
+ case 'updateMany':
126
+ mapped[action] = each(value, withData);
127
+ break;
128
+ case 'upsert':
129
+ mapped[action] = each(value, (item) => ({
130
+ ...item,
131
+ create: map(item?.create),
132
+ update: map(item?.update)
133
+ }));
134
+ break;
135
+ case 'connectOrCreate':
136
+ mapped[action] = each(value, (item) => ({
137
+ ...item,
138
+ create: map(item?.create)
139
+ }));
140
+ break;
141
+ }
142
+ }
143
+ return mapped;
144
+ }