@zero-server/sdk 0.9.0 → 0.9.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 (126) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +460 -437
  3. package/index.js +414 -412
  4. package/lib/app.js +1172 -1172
  5. package/lib/auth/authorize.js +399 -399
  6. package/lib/auth/enrollment.js +367 -367
  7. package/lib/auth/index.js +57 -57
  8. package/lib/auth/jwt.js +731 -731
  9. package/lib/auth/oauth.js +362 -362
  10. package/lib/auth/session.js +588 -588
  11. package/lib/auth/trustedDevice.js +409 -409
  12. package/lib/auth/twoFactor.js +1150 -1150
  13. package/lib/auth/webauthn.js +946 -946
  14. package/lib/body/index.js +14 -14
  15. package/lib/body/json.js +109 -109
  16. package/lib/body/multipart.js +440 -440
  17. package/lib/body/raw.js +71 -71
  18. package/lib/body/rawBuffer.js +160 -160
  19. package/lib/body/sendError.js +25 -25
  20. package/lib/body/text.js +75 -75
  21. package/lib/body/typeMatch.js +41 -41
  22. package/lib/body/urlencoded.js +235 -235
  23. package/lib/cli.js +845 -845
  24. package/lib/cluster.js +666 -666
  25. package/lib/debug.js +372 -372
  26. package/lib/env/index.js +460 -460
  27. package/lib/errors.js +683 -683
  28. package/lib/fetch/index.js +256 -256
  29. package/lib/grpc/balancer.js +378 -378
  30. package/lib/grpc/call.js +708 -708
  31. package/lib/grpc/client.js +764 -764
  32. package/lib/grpc/codec.js +1221 -1221
  33. package/lib/grpc/credentials.js +398 -398
  34. package/lib/grpc/frame.js +262 -262
  35. package/lib/grpc/health.js +287 -287
  36. package/lib/grpc/index.js +121 -121
  37. package/lib/grpc/metadata.js +461 -461
  38. package/lib/grpc/proto.js +821 -821
  39. package/lib/grpc/reflection.js +590 -590
  40. package/lib/grpc/server.js +445 -445
  41. package/lib/grpc/status.js +118 -118
  42. package/lib/grpc/watch.js +173 -173
  43. package/lib/http/index.js +10 -10
  44. package/lib/http/request.js +727 -727
  45. package/lib/http/response.js +799 -799
  46. package/lib/lifecycle.js +557 -557
  47. package/lib/middleware/compress.js +230 -230
  48. package/lib/middleware/cookieParser.js +237 -237
  49. package/lib/middleware/cors.js +93 -93
  50. package/lib/middleware/csrf.js +136 -136
  51. package/lib/middleware/errorHandler.js +101 -101
  52. package/lib/middleware/helmet.js +175 -175
  53. package/lib/middleware/index.js +19 -17
  54. package/lib/middleware/logger.js +74 -74
  55. package/lib/middleware/rateLimit.js +88 -88
  56. package/lib/middleware/requestId.js +53 -53
  57. package/lib/middleware/static.js +326 -326
  58. package/lib/middleware/timeout.js +71 -71
  59. package/lib/middleware/validator.js +254 -254
  60. package/lib/observe/health.js +326 -326
  61. package/lib/observe/index.js +50 -50
  62. package/lib/observe/logger.js +359 -359
  63. package/lib/observe/metrics.js +805 -805
  64. package/lib/observe/tracing.js +592 -592
  65. package/lib/orm/adapters/json.js +290 -290
  66. package/lib/orm/adapters/memory.js +764 -764
  67. package/lib/orm/adapters/mongo.js +764 -764
  68. package/lib/orm/adapters/mysql.js +933 -933
  69. package/lib/orm/adapters/postgres.js +1144 -1144
  70. package/lib/orm/adapters/redis.js +1534 -1534
  71. package/lib/orm/adapters/sql-base.js +212 -212
  72. package/lib/orm/adapters/sqlite.js +858 -858
  73. package/lib/orm/audit.js +649 -649
  74. package/lib/orm/cache.js +394 -394
  75. package/lib/orm/geo.js +387 -387
  76. package/lib/orm/index.js +784 -784
  77. package/lib/orm/migrate.js +432 -432
  78. package/lib/orm/model.js +1706 -1706
  79. package/lib/orm/plugin.js +375 -375
  80. package/lib/orm/procedures.js +836 -836
  81. package/lib/orm/profiler.js +233 -233
  82. package/lib/orm/query.js +1772 -1772
  83. package/lib/orm/replicas.js +241 -241
  84. package/lib/orm/schema.js +307 -307
  85. package/lib/orm/search.js +380 -380
  86. package/lib/orm/seed/data/commerce.js +136 -136
  87. package/lib/orm/seed/data/internet.js +111 -111
  88. package/lib/orm/seed/data/locations.js +204 -204
  89. package/lib/orm/seed/data/names.js +338 -338
  90. package/lib/orm/seed/data/person.js +128 -128
  91. package/lib/orm/seed/data/phone.js +211 -211
  92. package/lib/orm/seed/data/words.js +134 -134
  93. package/lib/orm/seed/factory.js +178 -178
  94. package/lib/orm/seed/fake.js +1186 -1186
  95. package/lib/orm/seed/index.js +18 -18
  96. package/lib/orm/seed/rng.js +70 -70
  97. package/lib/orm/seed/seeder.js +124 -124
  98. package/lib/orm/seed/unique.js +68 -68
  99. package/lib/orm/snapshot.js +366 -366
  100. package/lib/orm/tenancy.js +605 -605
  101. package/lib/orm/views.js +350 -350
  102. package/lib/router/index.js +436 -436
  103. package/lib/sse/index.js +8 -8
  104. package/lib/sse/stream.js +349 -349
  105. package/lib/ws/connection.js +451 -451
  106. package/lib/ws/handshake.js +125 -125
  107. package/lib/ws/index.js +14 -14
  108. package/lib/ws/room.js +223 -223
  109. package/package.json +73 -73
  110. package/types/app.d.ts +223 -223
  111. package/types/auth.d.ts +520 -520
  112. package/types/cluster.d.ts +75 -75
  113. package/types/env.d.ts +80 -80
  114. package/types/errors.d.ts +316 -316
  115. package/types/fetch.d.ts +43 -43
  116. package/types/grpc.d.ts +432 -432
  117. package/types/index.d.ts +384 -384
  118. package/types/lifecycle.d.ts +60 -60
  119. package/types/middleware.d.ts +320 -320
  120. package/types/observe.d.ts +304 -304
  121. package/types/orm.d.ts +1887 -1887
  122. package/types/request.d.ts +109 -109
  123. package/types/response.d.ts +157 -157
  124. package/types/router.d.ts +78 -78
  125. package/types/sse.d.ts +78 -78
  126. package/types/websocket.d.ts +126 -126
package/lib/orm/views.js CHANGED
@@ -1,350 +1,350 @@
1
- /**
2
- * @module orm/views
3
- * @description Database view management for the ORM.
4
- * Supports creating, dropping, and querying database views.
5
- * View-backed models are read-only by default.
6
- *
7
- * @section Views
8
- *
9
- * @example
10
- * const { DatabaseView } = require('@zero-server/sdk');
11
- *
12
- * // Define a view
13
- * const activeUsers = new DatabaseView('active_users', {
14
- * query: User.query().where('active', true).select('id', 'name', 'email'),
15
- * model: User,
16
- * });
17
- *
18
- * // Create the view in the database
19
- * await activeUsers.create(db);
20
- *
21
- * // Query the view
22
- * const users = await activeUsers.all();
23
- * const user = await activeUsers.findOne({ name: 'Alice' });
24
- */
25
-
26
- const Model = require('./model');
27
- const Query = require('./query');
28
- const log = require('../debug')('zero:orm:views');
29
-
30
- // -- DatabaseView class -----------------------------------
31
-
32
- /**
33
- * Represents a database view.
34
- * Wraps a query definition and provides read-only access through a model-like API.
35
- */
36
- class DatabaseView
37
- {
38
- /**
39
- * @constructor
40
- * @param {string} name - View name.
41
- * @param {object} options - View configuration.
42
- * @param {Query} [options.query] - Query builder instance defining the view's SELECT.
43
- * @param {string} [options.sql] - Raw SQL for the view definition (SQL adapters only).
44
- * @param {typeof Model} [options.model] - Model class the view is based on.
45
- * @param {object} [options.schema] - Column schema for the view (optional; inferred from model if omitted).
46
- * @param {boolean} [options.materialized=false] - Whether to create a materialized view (PostgreSQL only).
47
- */
48
- constructor(name, options = {})
49
- {
50
- if (!name || typeof name !== 'string')
51
- {
52
- throw new Error('DatabaseView requires a non-empty string name');
53
- }
54
- if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name))
55
- {
56
- throw new Error(`Invalid view name: "${name}"`);
57
- }
58
-
59
- /** @type {string} View name. */
60
- this.name = name;
61
-
62
- /** @type {Query|null} Query builder defining the view. */
63
- this._query = options.query || null;
64
-
65
- /** @type {string|null} Raw SQL for view definition. */
66
- this._sql = options.sql || null;
67
-
68
- /** @type {typeof Model|null} Base model class. */
69
- this._model = options.model || null;
70
-
71
- /** @type {object|null} Column schema for the view. */
72
- this._schema = options.schema || null;
73
-
74
- /** @type {boolean} Whether this is a materialized view. */
75
- this._materialized = options.materialized === true;
76
-
77
- /** @type {object|null} The database adapter. */
78
- this._adapter = null;
79
-
80
- /** @type {typeof Model|null} The generated view model. */
81
- this._viewModel = null;
82
-
83
- if (!this._query && !this._sql)
84
- {
85
- throw new Error('DatabaseView requires either a query or sql option');
86
- }
87
- }
88
-
89
- /**
90
- * Create the view in the database.
91
- * For SQL adapters, issues CREATE VIEW (or CREATE MATERIALIZED VIEW).
92
- * For memory/JSON adapters, stores the query definition for execution.
93
- *
94
- * @param {object} db - Database instance.
95
- * @returns {Promise<DatabaseView>} `this` for chaining.
96
- *
97
- * @example
98
- * await activeUsers.create(db);
99
- */
100
- async create(db)
101
- {
102
- this._adapter = db.adapter;
103
-
104
- if (typeof this._adapter.createView === 'function')
105
- {
106
- const sql = this._sql || this._buildSQL();
107
- await this._adapter.createView(this.name, sql, { materialized: this._materialized });
108
- }
109
-
110
- // Create the view-backed model
111
- this._viewModel = this._createViewModel(db);
112
-
113
- log.debug('view %s created', this.name);
114
- return this;
115
- }
116
-
117
- /**
118
- * Drop the view from the database.
119
- *
120
- * @param {object} db - Database instance.
121
- * @returns {Promise<void>}
122
- */
123
- async drop(db)
124
- {
125
- const adapter = db ? db.adapter : this._adapter;
126
- if (!adapter) throw new Error('No database adapter available');
127
-
128
- if (typeof adapter.dropView === 'function')
129
- {
130
- await adapter.dropView(this.name, { materialized: this._materialized });
131
- }
132
-
133
- this._viewModel = null;
134
- log.debug('view %s dropped', this.name);
135
- }
136
-
137
- /**
138
- * Refresh a materialized view (PostgreSQL only).
139
- *
140
- * @param {object} [db] - Database instance.
141
- * @returns {Promise<void>}
142
- */
143
- async refresh(db)
144
- {
145
- const adapter = db ? db.adapter : this._adapter;
146
- if (!adapter) throw new Error('No database adapter available');
147
-
148
- if (!this._materialized)
149
- {
150
- throw new Error('Only materialized views can be refreshed');
151
- }
152
-
153
- if (typeof adapter.refreshView === 'function')
154
- {
155
- await adapter.refreshView(this.name);
156
- }
157
-
158
- log.debug('view %s refreshed', this.name);
159
- }
160
-
161
- /**
162
- * Check whether the view exists.
163
- *
164
- * @param {object} [db] - Database instance.
165
- * @returns {Promise<boolean>} True if the view exists.
166
- */
167
- async exists(db)
168
- {
169
- const adapter = db ? db.adapter : this._adapter;
170
- if (!adapter) throw new Error('No database adapter available');
171
-
172
- if (typeof adapter.hasTable === 'function')
173
- {
174
- return adapter.hasTable(this.name);
175
- }
176
- return false;
177
- }
178
-
179
- /**
180
- * Query all records from the view.
181
- *
182
- * @returns {Promise<Array>} All rows from the view.
183
- */
184
- async all()
185
- {
186
- return this._executeQuery();
187
- }
188
-
189
- /**
190
- * Find records from the view matching conditions.
191
- *
192
- * @param {object} conditions - WHERE conditions.
193
- * @returns {Promise<Array>} Matching rows.
194
- */
195
- async find(conditions = {})
196
- {
197
- return this._executeQuery(conditions);
198
- }
199
-
200
- /**
201
- * Find a single record from the view.
202
- *
203
- * @param {object} conditions - WHERE conditions.
204
- * @returns {Promise<object|null>} First matching row or null.
205
- */
206
- async findOne(conditions = {})
207
- {
208
- const results = await this._executeQuery(conditions, 1);
209
- return results[0] || null;
210
- }
211
-
212
- /**
213
- * Count records in the view.
214
- *
215
- * @param {object} [conditions={}] - Optional WHERE conditions.
216
- * @returns {Promise<number>} Number of matching records.
217
- */
218
- async count(conditions = {})
219
- {
220
- if (this._viewModel)
221
- {
222
- return this._viewModel.count(conditions);
223
- }
224
- const results = await this._executeQuery(conditions);
225
- return results.length;
226
- }
227
-
228
- /**
229
- * Start a fluent query against the view.
230
- *
231
- * @returns {Query} Query builder targeting the view.
232
- */
233
- query()
234
- {
235
- if (this._viewModel)
236
- {
237
- return this._viewModel.query();
238
- }
239
- throw new Error('View model not created. Call create() first.');
240
- }
241
-
242
- /**
243
- * Execute the view query with optional conditions.
244
- * @param {object} [conditions={}] - WHERE conditions.
245
- * @param {number} [limit] - Optional limit.
246
- * @returns {Promise<Array>} Results.
247
- * @private
248
- */
249
- async _executeQuery(conditions = {}, limit)
250
- {
251
- if (this._viewModel)
252
- {
253
- let q = this._viewModel.query().where(conditions);
254
- if (limit) q = q.limit(limit);
255
- return q.exec();
256
- }
257
-
258
- // Fallback: re-execute the source query with additional filters
259
- if (this._query)
260
- {
261
- // Clone the query state
262
- const src = this._query;
263
- const model = src._model;
264
- const q = model.query();
265
- q._fields = src._fields;
266
- q._where = [...src._where];
267
- q._orderBy = [...src._orderBy];
268
- q._limitVal = limit || src._limitVal;
269
- q._offsetVal = src._offsetVal;
270
-
271
- // Add additional conditions
272
- if (Object.keys(conditions).length)
273
- {
274
- q.where(conditions);
275
- }
276
-
277
- return q.exec();
278
- }
279
-
280
- return [];
281
- }
282
-
283
- /**
284
- * Build SQL from a Query descriptor.
285
- * @returns {string} SQL SELECT statement.
286
- * @private
287
- */
288
- _buildSQL()
289
- {
290
- if (this._sql) return this._sql;
291
- if (!this._query) throw new Error('No query or SQL defined for view');
292
-
293
- const descriptor = this._query.build();
294
- const table = descriptor.table;
295
-
296
- // Validate field names and table — identifier-safe only
297
- const idRe = /^[a-zA-Z_][a-zA-Z0-9_.*]*$/;
298
- const fields = descriptor.fields
299
- ? descriptor.fields.filter(f => idRe.test(f)).join(', ') || '*'
300
- : '*';
301
- if (!idRe.test(table)) throw new Error(`Invalid table name in view query: "${table}"`);
302
-
303
- let sql = `SELECT ${fields} FROM ${table}`;
304
-
305
- if (descriptor.where && descriptor.where.length)
306
- {
307
- const clauses = descriptor.where.map(w =>
308
- {
309
- if (w.raw) return w.raw;
310
- if (w.op === 'IS NULL') return `${w.field} IS NULL`;
311
- if (w.op === 'IS NOT NULL') return `${w.field} IS NOT NULL`;
312
- if (w.op === 'IN') return `${w.field} IN (${w.value.map(() => '?').join(',')})`;
313
- // Escape single quotes in values for DDL safety
314
- const escaped = String(w.value).replace(/'/g, "''");
315
- return `${w.field} ${w.op} '${escaped}'`;
316
- });
317
- sql += ` WHERE ${clauses.join(' AND ')}`;
318
- }
319
-
320
- if (descriptor.orderBy && descriptor.orderBy.length)
321
- {
322
- const orders = descriptor.orderBy.map(o => `${o.field} ${o.dir}`);
323
- sql += ` ORDER BY ${orders.join(', ')}`;
324
- }
325
-
326
- return sql;
327
- }
328
-
329
- /**
330
- * Create an internal view-backed Model class.
331
- * @param {object} db - Database instance.
332
- * @returns {typeof Model} View model class.
333
- * @private
334
- */
335
- _createViewModel(db)
336
- {
337
- const viewName = this.name;
338
- const schema = this._schema || (this._model ? this._model.schema : {});
339
- const ViewM = class extends Model
340
- {
341
- static table = viewName;
342
- static schema = { ...schema };
343
- };
344
- Object.defineProperty(ViewM, 'name', { value: `${viewName}_view` });
345
- db.register(ViewM);
346
- return ViewM;
347
- }
348
- }
349
-
350
- module.exports = { DatabaseView };
1
+ /**
2
+ * @module orm/views
3
+ * @description Database view management for the ORM.
4
+ * Supports creating, dropping, and querying database views.
5
+ * View-backed models are read-only by default.
6
+ *
7
+ * @section Views
8
+ *
9
+ * @example
10
+ * const { DatabaseView } = require('@zero-server/sdk');
11
+ *
12
+ * // Define a view
13
+ * const activeUsers = new DatabaseView('active_users', {
14
+ * query: User.query().where('active', true).select('id', 'name', 'email'),
15
+ * model: User,
16
+ * });
17
+ *
18
+ * // Create the view in the database
19
+ * await activeUsers.create(db);
20
+ *
21
+ * // Query the view
22
+ * const users = await activeUsers.all();
23
+ * const user = await activeUsers.findOne({ name: 'Alice' });
24
+ */
25
+
26
+ const Model = require('./model');
27
+ const Query = require('./query');
28
+ const log = require('../debug')('zero:orm:views');
29
+
30
+ // -- DatabaseView class -----------------------------------
31
+
32
+ /**
33
+ * Represents a database view.
34
+ * Wraps a query definition and provides read-only access through a model-like API.
35
+ */
36
+ class DatabaseView
37
+ {
38
+ /**
39
+ * @constructor
40
+ * @param {string} name - View name.
41
+ * @param {object} options - View configuration.
42
+ * @param {Query} [options.query] - Query builder instance defining the view's SELECT.
43
+ * @param {string} [options.sql] - Raw SQL for the view definition (SQL adapters only).
44
+ * @param {typeof Model} [options.model] - Model class the view is based on.
45
+ * @param {object} [options.schema] - Column schema for the view (optional; inferred from model if omitted).
46
+ * @param {boolean} [options.materialized=false] - Whether to create a materialized view (PostgreSQL only).
47
+ */
48
+ constructor(name, options = {})
49
+ {
50
+ if (!name || typeof name !== 'string')
51
+ {
52
+ throw new Error('DatabaseView requires a non-empty string name');
53
+ }
54
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name))
55
+ {
56
+ throw new Error(`Invalid view name: "${name}"`);
57
+ }
58
+
59
+ /** @type {string} View name. */
60
+ this.name = name;
61
+
62
+ /** @type {Query|null} Query builder defining the view. */
63
+ this._query = options.query || null;
64
+
65
+ /** @type {string|null} Raw SQL for view definition. */
66
+ this._sql = options.sql || null;
67
+
68
+ /** @type {typeof Model|null} Base model class. */
69
+ this._model = options.model || null;
70
+
71
+ /** @type {object|null} Column schema for the view. */
72
+ this._schema = options.schema || null;
73
+
74
+ /** @type {boolean} Whether this is a materialized view. */
75
+ this._materialized = options.materialized === true;
76
+
77
+ /** @type {object|null} The database adapter. */
78
+ this._adapter = null;
79
+
80
+ /** @type {typeof Model|null} The generated view model. */
81
+ this._viewModel = null;
82
+
83
+ if (!this._query && !this._sql)
84
+ {
85
+ throw new Error('DatabaseView requires either a query or sql option');
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Create the view in the database.
91
+ * For SQL adapters, issues CREATE VIEW (or CREATE MATERIALIZED VIEW).
92
+ * For memory/JSON adapters, stores the query definition for execution.
93
+ *
94
+ * @param {object} db - Database instance.
95
+ * @returns {Promise<DatabaseView>} `this` for chaining.
96
+ *
97
+ * @example
98
+ * await activeUsers.create(db);
99
+ */
100
+ async create(db)
101
+ {
102
+ this._adapter = db.adapter;
103
+
104
+ if (typeof this._adapter.createView === 'function')
105
+ {
106
+ const sql = this._sql || this._buildSQL();
107
+ await this._adapter.createView(this.name, sql, { materialized: this._materialized });
108
+ }
109
+
110
+ // Create the view-backed model
111
+ this._viewModel = this._createViewModel(db);
112
+
113
+ log.debug('view %s created', this.name);
114
+ return this;
115
+ }
116
+
117
+ /**
118
+ * Drop the view from the database.
119
+ *
120
+ * @param {object} db - Database instance.
121
+ * @returns {Promise<void>}
122
+ */
123
+ async drop(db)
124
+ {
125
+ const adapter = db ? db.adapter : this._adapter;
126
+ if (!adapter) throw new Error('No database adapter available');
127
+
128
+ if (typeof adapter.dropView === 'function')
129
+ {
130
+ await adapter.dropView(this.name, { materialized: this._materialized });
131
+ }
132
+
133
+ this._viewModel = null;
134
+ log.debug('view %s dropped', this.name);
135
+ }
136
+
137
+ /**
138
+ * Refresh a materialized view (PostgreSQL only).
139
+ *
140
+ * @param {object} [db] - Database instance.
141
+ * @returns {Promise<void>}
142
+ */
143
+ async refresh(db)
144
+ {
145
+ const adapter = db ? db.adapter : this._adapter;
146
+ if (!adapter) throw new Error('No database adapter available');
147
+
148
+ if (!this._materialized)
149
+ {
150
+ throw new Error('Only materialized views can be refreshed');
151
+ }
152
+
153
+ if (typeof adapter.refreshView === 'function')
154
+ {
155
+ await adapter.refreshView(this.name);
156
+ }
157
+
158
+ log.debug('view %s refreshed', this.name);
159
+ }
160
+
161
+ /**
162
+ * Check whether the view exists.
163
+ *
164
+ * @param {object} [db] - Database instance.
165
+ * @returns {Promise<boolean>} True if the view exists.
166
+ */
167
+ async exists(db)
168
+ {
169
+ const adapter = db ? db.adapter : this._adapter;
170
+ if (!adapter) throw new Error('No database adapter available');
171
+
172
+ if (typeof adapter.hasTable === 'function')
173
+ {
174
+ return adapter.hasTable(this.name);
175
+ }
176
+ return false;
177
+ }
178
+
179
+ /**
180
+ * Query all records from the view.
181
+ *
182
+ * @returns {Promise<Array>} All rows from the view.
183
+ */
184
+ async all()
185
+ {
186
+ return this._executeQuery();
187
+ }
188
+
189
+ /**
190
+ * Find records from the view matching conditions.
191
+ *
192
+ * @param {object} conditions - WHERE conditions.
193
+ * @returns {Promise<Array>} Matching rows.
194
+ */
195
+ async find(conditions = {})
196
+ {
197
+ return this._executeQuery(conditions);
198
+ }
199
+
200
+ /**
201
+ * Find a single record from the view.
202
+ *
203
+ * @param {object} conditions - WHERE conditions.
204
+ * @returns {Promise<object|null>} First matching row or null.
205
+ */
206
+ async findOne(conditions = {})
207
+ {
208
+ const results = await this._executeQuery(conditions, 1);
209
+ return results[0] || null;
210
+ }
211
+
212
+ /**
213
+ * Count records in the view.
214
+ *
215
+ * @param {object} [conditions={}] - Optional WHERE conditions.
216
+ * @returns {Promise<number>} Number of matching records.
217
+ */
218
+ async count(conditions = {})
219
+ {
220
+ if (this._viewModel)
221
+ {
222
+ return this._viewModel.count(conditions);
223
+ }
224
+ const results = await this._executeQuery(conditions);
225
+ return results.length;
226
+ }
227
+
228
+ /**
229
+ * Start a fluent query against the view.
230
+ *
231
+ * @returns {Query} Query builder targeting the view.
232
+ */
233
+ query()
234
+ {
235
+ if (this._viewModel)
236
+ {
237
+ return this._viewModel.query();
238
+ }
239
+ throw new Error('View model not created. Call create() first.');
240
+ }
241
+
242
+ /**
243
+ * Execute the view query with optional conditions.
244
+ * @param {object} [conditions={}] - WHERE conditions.
245
+ * @param {number} [limit] - Optional limit.
246
+ * @returns {Promise<Array>} Results.
247
+ * @private
248
+ */
249
+ async _executeQuery(conditions = {}, limit)
250
+ {
251
+ if (this._viewModel)
252
+ {
253
+ let q = this._viewModel.query().where(conditions);
254
+ if (limit) q = q.limit(limit);
255
+ return q.exec();
256
+ }
257
+
258
+ // Fallback: re-execute the source query with additional filters
259
+ if (this._query)
260
+ {
261
+ // Clone the query state
262
+ const src = this._query;
263
+ const model = src._model;
264
+ const q = model.query();
265
+ q._fields = src._fields;
266
+ q._where = [...src._where];
267
+ q._orderBy = [...src._orderBy];
268
+ q._limitVal = limit || src._limitVal;
269
+ q._offsetVal = src._offsetVal;
270
+
271
+ // Add additional conditions
272
+ if (Object.keys(conditions).length)
273
+ {
274
+ q.where(conditions);
275
+ }
276
+
277
+ return q.exec();
278
+ }
279
+
280
+ return [];
281
+ }
282
+
283
+ /**
284
+ * Build SQL from a Query descriptor.
285
+ * @returns {string} SQL SELECT statement.
286
+ * @private
287
+ */
288
+ _buildSQL()
289
+ {
290
+ if (this._sql) return this._sql;
291
+ if (!this._query) throw new Error('No query or SQL defined for view');
292
+
293
+ const descriptor = this._query.build();
294
+ const table = descriptor.table;
295
+
296
+ // Validate field names and table — identifier-safe only
297
+ const idRe = /^[a-zA-Z_][a-zA-Z0-9_.*]*$/;
298
+ const fields = descriptor.fields
299
+ ? descriptor.fields.filter(f => idRe.test(f)).join(', ') || '*'
300
+ : '*';
301
+ if (!idRe.test(table)) throw new Error(`Invalid table name in view query: "${table}"`);
302
+
303
+ let sql = `SELECT ${fields} FROM ${table}`;
304
+
305
+ if (descriptor.where && descriptor.where.length)
306
+ {
307
+ const clauses = descriptor.where.map(w =>
308
+ {
309
+ if (w.raw) return w.raw;
310
+ if (w.op === 'IS NULL') return `${w.field} IS NULL`;
311
+ if (w.op === 'IS NOT NULL') return `${w.field} IS NOT NULL`;
312
+ if (w.op === 'IN') return `${w.field} IN (${w.value.map(() => '?').join(',')})`;
313
+ // Escape single quotes in values for DDL safety
314
+ const escaped = String(w.value).replace(/'/g, "''");
315
+ return `${w.field} ${w.op} '${escaped}'`;
316
+ });
317
+ sql += ` WHERE ${clauses.join(' AND ')}`;
318
+ }
319
+
320
+ if (descriptor.orderBy && descriptor.orderBy.length)
321
+ {
322
+ const orders = descriptor.orderBy.map(o => `${o.field} ${o.dir}`);
323
+ sql += ` ORDER BY ${orders.join(', ')}`;
324
+ }
325
+
326
+ return sql;
327
+ }
328
+
329
+ /**
330
+ * Create an internal view-backed Model class.
331
+ * @param {object} db - Database instance.
332
+ * @returns {typeof Model} View model class.
333
+ * @private
334
+ */
335
+ _createViewModel(db)
336
+ {
337
+ const viewName = this.name;
338
+ const schema = this._schema || (this._model ? this._model.schema : {});
339
+ const ViewM = class extends Model
340
+ {
341
+ static table = viewName;
342
+ static schema = { ...schema };
343
+ };
344
+ Object.defineProperty(ViewM, 'name', { value: `${viewName}_view` });
345
+ db.register(ViewM);
346
+ return ViewM;
347
+ }
348
+ }
349
+
350
+ module.exports = { DatabaseView };