@appweaver/data 2.5.0 → 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 (60) hide show
  1. package/README.md +4 -2
  2. package/config.d.ts +1 -0
  3. package/config.js +1 -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 +16 -5
  9. package/database/setup-database.d.ts +23 -0
  10. package/database/setup-database.js +59 -0
  11. package/database/sqlserver-extension.js +21 -107
  12. package/database/telemetry-extension.d.ts +10 -0
  13. package/database/telemetry-extension.js +52 -0
  14. package/export/export-service.js +4 -0
  15. package/factory/create-model.d.ts +1 -1
  16. package/factory/create-model.js +75 -4
  17. package/factory/create-service.js +8 -0
  18. package/index.d.ts +2 -0
  19. package/index.js +5 -0
  20. package/internal.d.ts +2 -0
  21. package/internal.js +3 -1
  22. package/module.js +6 -3
  23. package/package.json +3 -3
  24. package/resource/resource-service.d.ts +32 -7
  25. package/resource/resource-service.js +244 -35
  26. package/resource/schemas/resource-filter-schema.d.ts +8 -0
  27. package/resource/schemas/resource-filter-schema.js +40 -1
  28. package/resource/schemas/resource-sort-schema.js +10 -0
  29. package/resource/utils/cursor-util.d.ts +13 -0
  30. package/resource/utils/cursor-util.js +21 -0
  31. package/resource/utils/filter-util.d.ts +9 -0
  32. package/resource/utils/filter-util.js +17 -0
  33. package/resource/utils/sort-util.d.ts +14 -0
  34. package/resource/utils/sort-util.js +1 -0
  35. package/resource/utils/where-util.d.ts +20 -0
  36. package/resource/utils/where-util.js +210 -0
  37. package/seeder/create-seeder.d.ts +3 -0
  38. package/seeder/create-seeder.js +1 -1
  39. package/seeder/seeder.d.ts +4 -2
  40. package/seeder/seeder.js +56 -23
  41. package/spatial/geo-schema.d.ts +22 -0
  42. package/spatial/geo-schema.js +60 -0
  43. package/spatial/spatial-config.d.ts +21 -0
  44. package/spatial/spatial-config.js +52 -0
  45. package/spatial/spatial-engine.d.ts +78 -0
  46. package/spatial/spatial-engine.js +232 -0
  47. package/spatial/spatial-extension.d.ts +10 -0
  48. package/spatial/spatial-extension.js +100 -0
  49. package/spatial/spatial-service.d.ts +54 -0
  50. package/spatial/spatial-service.js +213 -0
  51. package/spatial/utils/box-util.d.ts +31 -0
  52. package/spatial/utils/box-util.js +62 -0
  53. package/timeseries/database-time-series.js +2 -13
  54. package/timeseries/timescale-config.d.ts +1 -1
  55. package/timeseries/timescale-time-series.d.ts +6 -4
  56. package/timeseries/timescale-time-series.js +46 -19
  57. package/utils/schema-util.d.ts +8 -0
  58. package/utils/schema-util.js +22 -0
  59. package/utils/write-data-util.d.ts +22 -0
  60. package/utils/write-data-util.js +144 -0
package/README.md CHANGED
@@ -20,12 +20,14 @@
20
20
  - **Resources** – `createModel`, `createService` and `createPolicy`, the resource services with filtering, sorting,
21
21
  cursor pagination, aggregation and CSV export, and the transactions.
22
22
  - **Auth data model** – `createAuthModel`, `createAuthService`, roles, permissions, API keys, one-time tokens,
23
- connected accounts and password hashing.
23
+ connected accounts, the two-factor methods and recovery codes, and password hashing.
24
24
  - **Files** – `FileService` with the File model, storing the files in any `Storage` provider.
25
25
  - **Seeders** – `createSeeder` and the database security store.
26
+ - **Time series** – the `database` and `timescale` (TimescaleDB hypertables) stores of the `series` fields of the
27
+ models, written to `<Model>Series` tables with their retention.
26
28
 
27
29
  The framework models reach only the applications using them: the auth tables with an auth model, File with a model
28
- declaring `files`, Seeder with a seeders directory.
30
+ declaring `files`, Seeder with a seeders directory, and the series tables with a model declaring `series`.
29
31
 
30
32
  ## Installation
31
33
 
package/config.d.ts CHANGED
@@ -3,6 +3,7 @@ export * from './database/database-config';
3
3
  export * from './export/export-config';
4
4
  export * from './resource/resource-config';
5
5
  export * from './security/auth-config';
6
+ export * from './spatial/spatial-config';
6
7
  export * from './storage/image-config';
7
8
  export * from './timeseries/database-series-config';
8
9
  export * from './timeseries/timescale-config';
package/config.js CHANGED
@@ -19,6 +19,7 @@ __exportStar(require("./database/database-config"), exports);
19
19
  __exportStar(require("./export/export-config"), exports);
20
20
  __exportStar(require("./resource/resource-config"), exports);
21
21
  __exportStar(require("./security/auth-config"), exports);
22
+ __exportStar(require("./spatial/spatial-config"), exports);
22
23
  __exportStar(require("./storage/image-config"), exports);
23
24
  __exportStar(require("./timeseries/database-series-config"), exports);
24
25
  __exportStar(require("./timeseries/timescale-config"), exports);
@@ -2,6 +2,7 @@ import { DatabaseEvent, DatabaseType } from '@appweaver/common';
2
2
  export declare const databaseConfig: Readonly<{
3
3
  TYPE?: DatabaseType | undefined;
4
4
  URL: string;
5
+ MIGRATION_URL: string;
5
6
  SCHEMA_PATH: string;
6
7
  MIGRATIONS_DIR_PATH: string;
7
8
  SEEDERS_DIR_PATH: string;
@@ -13,3 +14,11 @@ export declare const databaseConfig: Readonly<{
13
14
  SLOW_QUERY_THRESHOLD: number;
14
15
  PROVIDER: string;
15
16
  }>;
17
+ /**
18
+ * Returns the URL the migrations run with: `database.migrationUrl`, or `database.url` when it is not set.
19
+ *
20
+ * @return {string} The connection URL of the migrations.
21
+ * @throws {ConfigurationError} `CONFIGURATION_INVALID` when the migration URL points to another type of database, or
22
+ * another database name, than the URL of the application, i.e. an environment overriding one URL but not the other.
23
+ */
24
+ export declare function migrationUrl(): string;
@@ -1,13 +1,21 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.databaseConfig = void 0;
7
+ exports.migrationUrl = migrationUrl;
8
+ const node_path_1 = __importDefault(require("node:path"));
4
9
  const typebox_1 = require("@sinclair/typebox");
5
10
  const common_1 = require("@appweaver/common");
6
11
  exports.databaseConfig = (0, common_1.defineConfig)('database', {
7
12
  /** Database type. Values: `sqlite`, `postgresql`, `mysql`, `sqlserver`. */
8
13
  TYPE: typebox_1.Type.Optional(typebox_1.Type.Enum(common_1.DatabaseType)),
9
- /** Database connection URL/DSN. Default: `''`. */
14
+ /** Database connection URL/DSN the application queries the data with. Default: `''`. */
10
15
  URL: typebox_1.Type.String({ default: '' }),
16
+ /** Database connection URL/DSN of the migrations (`prisma.config.ts`) and of the database setup of `weaver migrate`,
17
+ * i.e. a user owning the tables, or a direct connection beside the pooled one of `URL`. Default: `''` (the `URL`). */
18
+ MIGRATION_URL: typebox_1.Type.String({ default: '' }),
11
19
  /** Path to a Prisma schema file. Default: `'./database/schema.prisma'`. */
12
20
  SCHEMA_PATH: typebox_1.Type.String({
13
21
  default: './database/schema.prisma'
@@ -41,3 +49,50 @@ exports.databaseConfig = (0, common_1.defineConfig)('database', {
41
49
  /** Database provider: `auto` or `prisma`, or `none` for an application without a database. Default: `'auto'`. */
42
50
  PROVIDER: typebox_1.Type.String({ default: 'auto' })
43
51
  });
52
+ /**
53
+ * Returns the URL the migrations run with: `database.migrationUrl`, or `database.url` when it is not set.
54
+ *
55
+ * @return {string} The connection URL of the migrations.
56
+ * @throws {ConfigurationError} `CONFIGURATION_INVALID` when the migration URL points to another type of database, or
57
+ * another database name, than the URL of the application, i.e. an environment overriding one URL but not the other.
58
+ */
59
+ function migrationUrl() {
60
+ const url = exports.databaseConfig.URL;
61
+ const migration = exports.databaseConfig.MIGRATION_URL;
62
+ if (!migration || !url) {
63
+ return migration || url;
64
+ }
65
+ // Compared by the URLs alone, since database.type names the type of both
66
+ const type = (0, common_1.resolveDatabaseType)(undefined, url);
67
+ const migrationType = (0, common_1.resolveDatabaseType)(undefined, migration);
68
+ const name = databaseName(url);
69
+ const migrationName = databaseName(migration);
70
+ if (type !== migrationType || name !== migrationName) {
71
+ const describe = (dbType, dbName) => `the ${dbType} database${dbName ? ` ${dbName}` : ''}`;
72
+ throw new common_1.ConfigurationError(common_1.ErrorCode.ConfigurationInvalid, `DATABASE_MIGRATION_URL (config.database.migrationUrl) points to ${describe(migrationType, migrationName)}, ` +
73
+ `while DATABASE_URL (config.database.url) points to ${describe(type, name)}`);
74
+ }
75
+ return migration;
76
+ }
77
+ /** The name of the database of a connection URL, or the path of a SQLite file. */
78
+ function databaseName(url) {
79
+ if (/^sqlserver:/i.test(url)) {
80
+ return /;\s*(?:database|initial catalog)\s*=\s*([^;]+)/i
81
+ .exec(url)?.[1]
82
+ ?.trim();
83
+ }
84
+ if (/^(postgres(ql)?|mysql|mariadb):/i.test(url)) {
85
+ try {
86
+ return decodeURIComponent(new URL(url).pathname.slice(1)) || undefined;
87
+ }
88
+ catch {
89
+ return undefined;
90
+ }
91
+ }
92
+ // With forward slashes on every platform, so a Windows path compares and reads the same
93
+ const file = url
94
+ .replace(/^file:/, '')
95
+ .split('?')[0]
96
+ .replace(/\\/g, '/');
97
+ return node_path_1.default.posix.normalize(file);
98
+ }
@@ -40,6 +40,14 @@ export declare function isPrismaError(error: unknown): error is PrismaError;
40
40
  * cause, or the error as it is.
41
41
  */
42
42
  export declare function toDatabaseError(error: unknown, model?: string): unknown;
43
+ /**
44
+ * Checks whether an error was raised because the user of the connection lacks a privilege, i.e. a PostgreSQL
45
+ * `insufficient_privilege` (`42501`) on a `CREATE` or on a table the user does not own.
46
+ *
47
+ * @param {unknown} error The error an operation failed with.
48
+ * @return {boolean} Whether the database refused the operation for a missing privilege.
49
+ */
50
+ export declare function isPrivilegeError(error: unknown): boolean;
43
51
  /**
44
52
  * Returns the explanation of a Prisma error, without the invocation and the
45
53
  * code frame its message starts with, i.e. "Unique constraint failed on the
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.isPrismaError = isPrismaError;
4
4
  exports.toDatabaseError = toDatabaseError;
5
+ exports.isPrivilegeError = isPrivilegeError;
5
6
  exports.prismaErrorMessage = prismaErrorMessage;
6
7
  const common_1 = require("@appweaver/common");
7
8
  const core_1 = require("@appweaver/core");
@@ -86,6 +87,23 @@ function toDatabaseError(error, model) {
86
87
  };
87
88
  return new common_1.DatabaseError(code, violationMessage(code, subject, fields), details, options);
88
89
  }
90
+ /**
91
+ * Checks whether an error was raised because the user of the connection lacks a privilege, i.e. a PostgreSQL
92
+ * `insufficient_privilege` (`42501`) on a `CREATE` or on a table the user does not own.
93
+ *
94
+ * @param {unknown} error The error an operation failed with.
95
+ * @return {boolean} Whether the database refused the operation for a missing privilege.
96
+ */
97
+ function isPrivilegeError(error) {
98
+ for (let current = error, depth = 0; current && depth < 5; current = current.cause, depth++) {
99
+ // A raw query error of the driver adapter, or the error of the driver itself
100
+ const cause = current.meta?.driverAdapterError?.cause ?? current;
101
+ if (cause.code === '42501') {
102
+ return true;
103
+ }
104
+ }
105
+ return false;
106
+ }
89
107
  /**
90
108
  * Returns the explanation of a Prisma error, without the invocation and the
91
109
  * code frame its message starts with, i.e. "Unique constraint failed on the
@@ -5,6 +5,8 @@ const common_1 = require("@appweaver/common");
5
5
  const database_config_1 = require("./database-config");
6
6
  const create_client_1 = require("./create-client");
7
7
  const sqlserver_extension_1 = require("./sqlserver-extension");
8
+ const spatial_extension_1 = require("../spatial/spatial-extension");
9
+ const telemetry_extension_1 = require("./telemetry-extension");
8
10
  const internal_1 = require("@appweaver/core/internal");
9
11
  const logger = (0, common_1.createLogger)('database');
10
12
  // Members that act on the connection itself, never on a transaction
@@ -126,12 +128,21 @@ class PrismaDatabase extends common_1.Database {
126
128
  /** @internal */
127
129
  clientInstance() {
128
130
  if (!this._client) {
129
- const client = (0, create_client_1.createClient)();
130
131
  const dbType = (0, common_1.resolveDatabaseType)(database_config_1.databaseConfig.TYPE, database_config_1.databaseConfig.URL);
131
- this._client =
132
- dbType === common_1.DatabaseType.SQLServer
133
- ? client.$extends((0, sqlserver_extension_1.sqlServerExtension)(this))
134
- : client;
132
+ // The outer extension runs first, so the geo values are normalized
133
+ // before SQL Server serializes the JSON fields, and the telemetry
134
+ // extension last, so the span of an operation covers only its query
135
+ let client = (0, create_client_1.createClient)();
136
+ if ((0, common_1.telemetryEnabled)('database')) {
137
+ client = client.$extends((0, telemetry_extension_1.telemetryExtension)(dbType));
138
+ }
139
+ if ([...internal_1.context.resource.models.values()].some((model) => (0, common_1.hasGeo)(model.config))) {
140
+ client = client.$extends((0, spatial_extension_1.spatialExtension)());
141
+ }
142
+ if (dbType === common_1.DatabaseType.SQLServer) {
143
+ client = client.$extends((0, sqlserver_extension_1.sqlServerExtension)(this));
144
+ }
145
+ this._client = client;
135
146
  }
136
147
  return this._client;
137
148
  }
@@ -0,0 +1,23 @@
1
+ export type SetupDatabaseParams = {
2
+ /** The directory of the application source code the models are loaded from. (default: ./dist/src) */
3
+ scanPath?: string;
4
+ };
5
+ export type SetupDatabaseResult = {
6
+ /** The directory the models were loaded from */
7
+ scanPath: string;
8
+ /** Whether the directory exists, the setup being skipped otherwise, i.e. before the build */
9
+ built: boolean;
10
+ /** The parts set up, empty when the models need none */
11
+ parts: string[];
12
+ };
13
+ /**
14
+ * Sets up the parts of the database the Prisma migrations do not hold, which the application otherwise sets up when
15
+ * it starts: the hypertables and the policies of the `timescale` time series provider, and the geometry triggers of
16
+ * the `postgis` spatial provider. Run by `weaver migrate` with the user of `database.migrationUrl`, so the user of the
17
+ * application needs no privilege to change the schema.
18
+ *
19
+ * @param {SetupDatabaseParams} [params={}] - The setup parameters.
20
+ * @return {Promise<SetupDatabaseResult>} The parts set up, and whether the models were built.
21
+ * @throws {ConfigurationError} `CONFIGURATION_INVALID` when a part cannot be set up, i.e. without the extension.
22
+ */
23
+ export declare function setupDatabase(params?: SetupDatabaseParams): Promise<SetupDatabaseResult>;
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.setupDatabase = setupDatabase;
7
+ const node_fs_1 = __importDefault(require("node:fs"));
8
+ const common_1 = require("@appweaver/common");
9
+ const core_1 = require("@appweaver/core");
10
+ const internal_1 = require("@appweaver/core/internal");
11
+ const resource_loader_1 = require("../resource/resource-loader");
12
+ const spatial_config_1 = require("../spatial/spatial-config");
13
+ const spatial_engine_1 = require("../spatial/spatial-engine");
14
+ const spatial_service_1 = require("../spatial/spatial-service");
15
+ const timescale_time_series_1 = require("../timeseries/timescale-time-series");
16
+ /**
17
+ * Sets up the parts of the database the Prisma migrations do not hold, which the application otherwise sets up when
18
+ * it starts: the hypertables and the policies of the `timescale` time series provider, and the geometry triggers of
19
+ * the `postgis` spatial provider. Run by `weaver migrate` with the user of `database.migrationUrl`, so the user of the
20
+ * application needs no privilege to change the schema.
21
+ *
22
+ * @param {SetupDatabaseParams} [params={}] - The setup parameters.
23
+ * @return {Promise<SetupDatabaseResult>} The parts set up, and whether the models were built.
24
+ * @throws {ConfigurationError} `CONFIGURATION_INVALID` when a part cannot be set up, i.e. without the extension.
25
+ */
26
+ async function setupDatabase(params = {}) {
27
+ const scanPath = (0, common_1.resolveSourcePath)(common_1.appConfig.BUILD_PATH, common_1.appConfig.SOURCE_PATH, params.scanPath, './dist/src');
28
+ if (!node_fs_1.default.existsSync(scanPath)) {
29
+ return { scanPath, built: false, parts: [] };
30
+ }
31
+ const modules = await (0, core_1.discoverModules)({ scanPath });
32
+ await (0, internal_1.loadProviders)(modules, scanPath);
33
+ await (0, resource_loader_1.loadResources)(scanPath, undefined, modules.flatMap(({ module }) => module.resources ? [module.resources] : []));
34
+ const store = (0, core_1.inject)(common_1.TimeSeries, false);
35
+ const seriesModels = store instanceof timescale_time_series_1.TimescaleTimeSeries
36
+ ? ((0, core_1.inject)(core_1.TimeSeriesService, false)?.models() ?? [])
37
+ : [];
38
+ const spatial = (0, core_1.inject)(spatial_service_1.SpatialService, false);
39
+ const geoModels = spatial && (0, spatial_config_1.spatialProvider)() === 'postgis' ? spatial.models() : [];
40
+ const parts = [];
41
+ if (seriesModels.length === 0 && geoModels.length === 0) {
42
+ return { scanPath, built: true, parts };
43
+ }
44
+ const db = (0, core_1.inject)(common_1.Database);
45
+ try {
46
+ if (seriesModels.length > 0) {
47
+ await store.register(seriesModels);
48
+ parts.push('time series hypertables');
49
+ }
50
+ if (geoModels.length > 0) {
51
+ await new spatial_engine_1.PostgisSpatialEngine(db).setup(geoModels);
52
+ parts.push('spatial geometry triggers');
53
+ }
54
+ }
55
+ finally {
56
+ await db.disconnect();
57
+ }
58
+ return { scanPath, built: true, parts };
59
+ }
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.sqlServerExtension = sqlServerExtension;
4
4
  const common_1 = require("@appweaver/common");
5
5
  const internal_1 = require("@appweaver/core/internal");
6
+ const write_data_util_1 = require("../utils/write-data-util");
6
7
  // The operations whose result holds no records
7
8
  const COUNT_OPERATIONS = new Set([
8
9
  'count',
@@ -93,85 +94,16 @@ async function applyDeleteActions(client, modelName, ids) {
93
94
  }
94
95
  /** Serializes the JSON fields of the data a write operation stores. */
95
96
  function serializeArgs(modelName, operation, args) {
96
- if (!(0, common_1.isPlainObject)(args)) {
97
- return args;
98
- }
99
- switch (operation) {
100
- case 'create':
101
- case 'createMany':
102
- case 'createManyAndReturn':
103
- case 'update':
104
- case 'updateMany':
105
- case 'updateManyAndReturn':
106
- return { ...args, data: serializeData(modelName, args.data) };
107
- case 'upsert':
108
- return {
109
- ...args,
110
- create: serializeData(modelName, args.create),
111
- update: serializeData(modelName, args.update)
112
- };
113
- default:
114
- return args;
115
- }
97
+ return (0, write_data_util_1.mapWriteArgs)(modelName, operation, args, serializeRecord);
116
98
  }
117
- /** Serializes the JSON fields of a record's data, and of the nested writes of its relations. */
118
- function serializeData(modelName, data) {
119
- if ((0, common_1.isArray)(data)) {
120
- return data.map((item) => serializeData(modelName, item));
121
- }
122
- if (!(0, common_1.isPlainObject)(data)) {
123
- return data;
124
- }
125
- const schema = sqlServerSchema();
126
- const jsonFields = schema.jsonFields.get(modelName);
127
- const relatedModels = schema.relatedModels.get(modelName);
99
+ /** Serializes the JSON fields of the data of a record. */
100
+ function serializeRecord(modelName, data) {
101
+ const jsonFields = sqlServerSchema().jsonFields.get(modelName);
128
102
  const serialized = { ...data };
129
103
  for (const [key, value] of Object.entries(data)) {
130
104
  if (jsonFields?.has(key) && value !== undefined) {
131
105
  serialized[key] = serializeJson(value);
132
106
  }
133
- else if (relatedModels?.has(key) && (0, common_1.isPlainObject)(value)) {
134
- serialized[key] = serializeNestedWrites(relatedModels.get(key), value);
135
- }
136
- }
137
- return serialized;
138
- }
139
- /** Serializes the JSON fields of the records a nested relation write stores. */
140
- function serializeNestedWrites(modelName, writes) {
141
- const each = (value, fn) => (0, common_1.isArray)(value) ? value.map(fn) : fn(value);
142
- const withData = (item) => (0, common_1.isPlainObject)(item) && 'data' in item
143
- ? { ...item, data: serializeData(modelName, item.data) }
144
- : serializeData(modelName, item);
145
- const serialized = { ...writes };
146
- for (const [action, value] of Object.entries(writes)) {
147
- switch (action) {
148
- case 'create':
149
- serialized[action] = serializeData(modelName, value);
150
- break;
151
- case 'createMany':
152
- serialized[action] = {
153
- ...value,
154
- data: serializeData(modelName, value?.data)
155
- };
156
- break;
157
- case 'update':
158
- case 'updateMany':
159
- serialized[action] = each(value, withData);
160
- break;
161
- case 'upsert':
162
- serialized[action] = each(value, (item) => ({
163
- ...item,
164
- create: serializeData(modelName, item?.create),
165
- update: serializeData(modelName, item?.update)
166
- }));
167
- break;
168
- case 'connectOrCreate':
169
- serialized[action] = each(value, (item) => ({
170
- ...item,
171
- create: serializeData(modelName, item?.create)
172
- }));
173
- break;
174
- }
175
107
  }
176
108
  return serialized;
177
109
  }
@@ -190,24 +122,17 @@ function isNullSentinel(value) {
190
122
  }
191
123
  /** Parses the JSON fields of the records of a result, and of their included relations. */
192
124
  function parseJsonFields(modelName, result) {
193
- if ((0, common_1.isArray)(result)) {
194
- return result.map((item) => parseJsonFields(modelName, item));
195
- }
196
- if (!(0, common_1.isPlainObject)(result)) {
197
- return result;
198
- }
199
- const schema = sqlServerSchema();
200
- const jsonFields = schema.jsonFields.get(modelName);
201
- const relatedModels = schema.relatedModels.get(modelName);
202
- for (const [key, value] of Object.entries(result)) {
125
+ return (0, write_data_util_1.mapResultRecords)(modelName, result, parseRecord);
126
+ }
127
+ /** Parses the JSON fields of a record. */
128
+ function parseRecord(modelName, record) {
129
+ const jsonFields = sqlServerSchema().jsonFields.get(modelName);
130
+ for (const [key, value] of Object.entries(record)) {
203
131
  if (jsonFields?.has(key) && typeof value === 'string') {
204
- result[key] = JSON.parse(value);
205
- }
206
- else if (relatedModels?.has(key) && value !== null) {
207
- result[key] = parseJsonFields(relatedModels.get(key), value);
132
+ record[key] = JSON.parse(value);
208
133
  }
209
134
  }
210
- return result;
135
+ return record;
211
136
  }
212
137
  /**
213
138
  * The models whose delete needs the actions of the data layer: the ones referenced through a foreign key whose action
@@ -237,32 +162,21 @@ function sqlServerSchema() {
237
162
  return cached.schema;
238
163
  }
239
164
  const models = Object.fromEntries(loaded.map((m) => [m.name, m]));
240
- const authModel = Object.values(models).find(common_1.isResourceAuthModel);
241
165
  const jsonFields = new Map();
242
- const relatedModels = new Map();
243
166
  for (const model of Object.values(models)) {
244
- jsonFields.set(model.name, new Set(Object.entries(model.config.scalars ?? {})
245
- .filter(([, scalar]) => scalar.type === 'json')
246
- .map(([field]) => field)));
247
- const related = new Map();
248
- for (const [field, relation] of Object.entries(model.config.relations ?? {})) {
249
- related.set(field, (0, common_1.capitalize)(relation.model));
250
- }
251
- for (const field of Object.keys(model.config.files ?? {})) {
252
- related.set(field, 'File');
253
- }
254
- if (authModel) {
255
- related.set('createdBy', authModel.name);
256
- related.set('deletedBy', authModel.name);
257
- }
258
- relatedModels.set(model.name, related);
167
+ jsonFields.set(model.name, new Set([
168
+ ...Object.entries(model.config.scalars ?? {})
169
+ .filter(([, scalar]) => scalar.type === 'json')
170
+ .map(([field]) => field),
171
+ // A geo field holds its GeoJSON geometry
172
+ ...Object.keys(model.config.geo ?? {})
173
+ ]));
259
174
  }
260
175
  const foreignKeys = (0, common_1.sqlServerForeignKeys)(models);
261
176
  const schema = {
262
177
  foreignKeys,
263
178
  deleteActions: deleteActionModels(foreignKeys),
264
- jsonFields,
265
- relatedModels
179
+ jsonFields
266
180
  };
267
181
  cached = { models: loaded, schema };
268
182
  return schema;
@@ -0,0 +1,10 @@
1
+ import { DatabaseType } from '@appweaver/common';
2
+ /**
3
+ * Creates the Prisma client extension tracing every operation of the client in a client span named after the
4
+ * operation and its model (`findMany User`, `$queryRaw`), and measuring its duration. Neither the query nor its
5
+ * arguments are recorded.
6
+ *
7
+ * @param {DatabaseType} dbType - The type of the database.
8
+ * @return {Object} The Prisma client extension.
9
+ */
10
+ export declare function telemetryExtension(dbType: DatabaseType): any;
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.telemetryExtension = telemetryExtension;
4
+ const common_1 = require("@appweaver/common");
5
+ // The names of the databases in the OpenTelemetry semantic conventions
6
+ const DB_SYSTEMS = {
7
+ [common_1.DatabaseType.Sqlite]: 'sqlite',
8
+ [common_1.DatabaseType.PostgreSQL]: 'postgresql',
9
+ [common_1.DatabaseType.MySQL]: 'mysql',
10
+ [common_1.DatabaseType.SQLServer]: 'microsoft.sql_server'
11
+ };
12
+ const operationDuration = (0, common_1.telemetryHistogram)('db.client.operation.duration', {
13
+ description: 'Duration of the database operations.',
14
+ unit: 's',
15
+ advice: { explicitBucketBoundaries: common_1.DURATION_BUCKETS }
16
+ });
17
+ /**
18
+ * Creates the Prisma client extension tracing every operation of the client in a client span named after the
19
+ * operation and its model (`findMany User`, `$queryRaw`), and measuring its duration. Neither the query nor its
20
+ * arguments are recorded.
21
+ *
22
+ * @param {DatabaseType} dbType - The type of the database.
23
+ * @return {Object} The Prisma client extension.
24
+ */
25
+ function telemetryExtension(dbType) {
26
+ const system = DB_SYSTEMS[dbType];
27
+ return {
28
+ name: 'appweaver-telemetry',
29
+ query: {
30
+ $allOperations({ model, operation, args, query }) {
31
+ const attributes = {
32
+ 'db.system.name': system,
33
+ 'db.operation.name': operation,
34
+ ...(model ? { 'db.collection.name': model } : {})
35
+ };
36
+ const start = performance.now();
37
+ // The query starts in the same tick, so it stays in the transaction
38
+ // of a batch
39
+ return (0, common_1.withSpan)(model ? `${operation} ${model}` : operation, { kind: common_1.SpanKind.CLIENT, attributes }, () => query(args)).then((result) => {
40
+ (0, common_1.recordDuration)(operationDuration(), start, attributes);
41
+ return result;
42
+ }, (error) => {
43
+ (0, common_1.recordDuration)(operationDuration(), start, {
44
+ ...attributes,
45
+ 'error.type': (0, common_1.spanErrorType)(error)
46
+ });
47
+ throw error;
48
+ });
49
+ }
50
+ }
51
+ };
52
+ }
@@ -155,6 +155,10 @@ class ExportService {
155
155
  }
156
156
  }
157
157
  }
158
+ // A geometry is written as its GeoJSON
159
+ if (resourceModel.config.geo?.[key] && (0, common_1.isPlainObject)(value)) {
160
+ value = JSON.stringify(value);
161
+ }
158
162
  // Recursively map relation and file fields if the value is an object.
159
163
  // Arrays of plain values are written as a single column below.
160
164
  if ((0, common_1.isPlainObject)(value) || (isArrayValue && (0, common_1.isPlainObject)(value[0]))) {
@@ -8,4 +8,4 @@ import { ResourceModel, ResourceModelConfig } from '@appweaver/common';
8
8
  * @param {boolean} [override=false] - Whether to replace a model already defined under the same name.
9
9
  * @return {ResourceModel} The created resource model.
10
10
  */
11
- export declare function createModel<S extends string, R extends string, F extends string, V extends string>(modelConfig: ResourceModelConfig<S, R, F, V>, override?: boolean): ResourceModel;
11
+ export declare function createModel<S extends string, R extends string, F extends string, V extends string, G extends string>(modelConfig: ResourceModelConfig<S, R, F, V, never, G>, override?: boolean): ResourceModel;