@zero-server/orm 0.9.1 → 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 (41) hide show
  1. package/LICENSE +21 -21
  2. package/index.js +35 -35
  3. package/lib/debug.js +372 -0
  4. package/lib/orm/adapters/json.js +290 -0
  5. package/lib/orm/adapters/memory.js +764 -0
  6. package/lib/orm/adapters/mongo.js +764 -0
  7. package/lib/orm/adapters/mysql.js +933 -0
  8. package/lib/orm/adapters/postgres.js +1144 -0
  9. package/lib/orm/adapters/redis.js +1534 -0
  10. package/lib/orm/adapters/sql-base.js +212 -0
  11. package/lib/orm/adapters/sqlite.js +858 -0
  12. package/lib/orm/audit.js +649 -0
  13. package/lib/orm/cache.js +394 -0
  14. package/lib/orm/geo.js +387 -0
  15. package/lib/orm/index.js +784 -0
  16. package/lib/orm/migrate.js +432 -0
  17. package/lib/orm/model.js +1706 -0
  18. package/lib/orm/plugin.js +375 -0
  19. package/lib/orm/procedures.js +836 -0
  20. package/lib/orm/profiler.js +233 -0
  21. package/lib/orm/query.js +1772 -0
  22. package/lib/orm/replicas.js +241 -0
  23. package/lib/orm/schema.js +307 -0
  24. package/lib/orm/search.js +380 -0
  25. package/lib/orm/seed/data/commerce.js +136 -0
  26. package/lib/orm/seed/data/internet.js +111 -0
  27. package/lib/orm/seed/data/locations.js +204 -0
  28. package/lib/orm/seed/data/names.js +338 -0
  29. package/lib/orm/seed/data/person.js +128 -0
  30. package/lib/orm/seed/data/phone.js +211 -0
  31. package/lib/orm/seed/data/words.js +134 -0
  32. package/lib/orm/seed/factory.js +178 -0
  33. package/lib/orm/seed/fake.js +1186 -0
  34. package/lib/orm/seed/index.js +18 -0
  35. package/lib/orm/seed/rng.js +71 -0
  36. package/lib/orm/seed/seeder.js +125 -0
  37. package/lib/orm/seed/unique.js +68 -0
  38. package/lib/orm/snapshot.js +366 -0
  39. package/lib/orm/tenancy.js +605 -0
  40. package/lib/orm/views.js +350 -0
  41. package/package.json +11 -2
package/lib/orm/geo.js ADDED
@@ -0,0 +1,387 @@
1
+ /**
2
+ * @module orm/geo
3
+ * @description Geo-spatial query support for the ORM.
4
+ * Provides distance calculations, bounding box queries,
5
+ * radius searches, and GeoJSON support.
6
+ * Works with in-memory adapters using Haversine formula;
7
+ * SQL adapters can use native spatial extensions (PostGIS, MySQL spatial).
8
+ *
9
+ * @section Geo-Spatial Queries
10
+ *
11
+ * @example
12
+ * const { GeoQuery } = require('@zero-server/sdk');
13
+ *
14
+ * // Create a geo query helper for a model
15
+ * const geo = new GeoQuery(Store, {
16
+ * latField: 'latitude',
17
+ * lngField: 'longitude',
18
+ * });
19
+ *
20
+ * // Find stores within 10km of a point
21
+ * const nearby = await geo.near(40.7128, -74.0060, { radius: 10 });
22
+ *
23
+ * // Find stores within a bounding box
24
+ * const inBox = await geo.within({
25
+ * north: 40.8, south: 40.6,
26
+ * east: -73.9, west: -74.1,
27
+ * });
28
+ */
29
+
30
+ const log = require('../debug')('zero:orm:geo');
31
+
32
+ // -- Constants --------------------------------------------
33
+
34
+ /**
35
+ * Earth's radius in kilometres.
36
+ * @const {number}
37
+ */
38
+ const EARTH_RADIUS_KM = 6371;
39
+
40
+ /**
41
+ * Earth's radius in miles.
42
+ * @const {number}
43
+ */
44
+ const EARTH_RADIUS_MI = 3959;
45
+
46
+ // -- GeoQuery class ---------------------------------------
47
+
48
+ /**
49
+ * Geo-spatial query builder for ORM models.
50
+ * Provides distance-based searches, bounding box queries,
51
+ * and GeoJSON conversion utilities.
52
+ */
53
+ class GeoQuery
54
+ {
55
+ /**
56
+ * @constructor
57
+ * @param {typeof Model} ModelClass - Model class with location data.
58
+ * @param {object} options - Configuration options.
59
+ * @param {string} options.latField - Column name for latitude.
60
+ * @param {string} options.lngField - Column name for longitude.
61
+ * @param {string} [options.unit='km'] - Distance unit: 'km' or 'mi'.
62
+ */
63
+ constructor(ModelClass, options = {})
64
+ {
65
+ if (!ModelClass) throw new Error('GeoQuery requires a Model class');
66
+ if (!options.latField) throw new Error('GeoQuery requires latField option');
67
+ if (!options.lngField) throw new Error('GeoQuery requires lngField option');
68
+
69
+ /** @type {typeof Model} */
70
+ this._model = ModelClass;
71
+
72
+ /** @type {string} Latitude column name. */
73
+ this._latField = options.latField;
74
+
75
+ /** @type {string} Longitude column name. */
76
+ this._lngField = options.lngField;
77
+
78
+ /** @type {string} Distance unit. */
79
+ this._unit = options.unit || 'km';
80
+ }
81
+
82
+ /**
83
+ * Find records near a geographic point.
84
+ * Uses Haversine formula for distance calculation.
85
+ *
86
+ * @param {number} lat - Latitude of the center point.
87
+ * @param {number} lng - Longitude of the center point.
88
+ * @param {object} [options] - Search options.
89
+ * @param {number} [options.radius] - Maximum distance (in configured unit).
90
+ * @param {number} [options.limit] - Maximum number of results.
91
+ * @param {number} [options.offset] - Skip N results.
92
+ * @param {object} [options.where] - Additional WHERE conditions.
93
+ * @param {string} [options.unit] - Override distance unit ('km' or 'mi').
94
+ * @param {boolean} [options.includeDistance=true] - Add `_distance` property to results.
95
+ * @returns {Promise<Array<object>>} Records sorted by distance, with `_distance` property.
96
+ *
97
+ * @example
98
+ * // Find 5 nearest stores within 25km
99
+ * const stores = await geo.near(40.7128, -74.0060, {
100
+ * radius: 25,
101
+ * limit: 5,
102
+ * });
103
+ * stores[0]._distance // => 1.23 (km)
104
+ */
105
+ async near(lat, lng, options = {})
106
+ {
107
+ lat = Number(lat);
108
+ lng = Number(lng);
109
+ if (!Number.isFinite(lat) || !Number.isFinite(lng))
110
+ {
111
+ throw new Error('lat and lng must be finite numbers');
112
+ }
113
+
114
+ const {
115
+ radius,
116
+ limit,
117
+ offset = 0,
118
+ where = {},
119
+ unit = this._unit,
120
+ includeDistance = true,
121
+ } = options;
122
+
123
+ if (radius !== undefined && (!Number.isFinite(Number(radius)) || Number(radius) < 0))
124
+ {
125
+ throw new Error('radius must be a non-negative finite number');
126
+ }
127
+
128
+ const adapter = this._model._adapter;
129
+ if (!adapter) throw new Error('Model is not registered with a database');
130
+
131
+ // Use adapter-native geo search if available
132
+ if (typeof adapter.geoNear === 'function')
133
+ {
134
+ return adapter.geoNear(this._model.table, this._latField, this._lngField, lat, lng, {
135
+ radius, limit, offset, where, unit, model: this._model,
136
+ });
137
+ }
138
+
139
+ // Fallback: in-memory Haversine calculation
140
+ return this._memoryNear(lat, lng, { radius, limit, offset, where, unit, includeDistance });
141
+ }
142
+
143
+ /**
144
+ * Find records within a bounding box.
145
+ *
146
+ * @param {object} bounds - Bounding box coordinates.
147
+ * @param {number} bounds.north - Northern latitude boundary.
148
+ * @param {number} bounds.south - Southern latitude boundary.
149
+ * @param {number} bounds.east - Eastern longitude boundary.
150
+ * @param {number} bounds.west - Western longitude boundary.
151
+ * @param {object} [options] - Query options.
152
+ * @param {number} [options.limit] - Maximum results.
153
+ * @param {object} [options.where] - Additional WHERE conditions.
154
+ * @returns {Promise<Array<object>>} Records within the bounding box.
155
+ *
156
+ * @example
157
+ * const stores = await geo.within({
158
+ * north: 40.8, south: 40.6,
159
+ * east: -73.9, west: -74.1,
160
+ * });
161
+ */
162
+ async within(bounds, options = {})
163
+ {
164
+ if (!bounds || !Number.isFinite(bounds.north) || !Number.isFinite(bounds.south) ||
165
+ !Number.isFinite(bounds.east) || !Number.isFinite(bounds.west))
166
+ {
167
+ throw new Error('within() requires bounds with north, south, east, and west as finite numbers');
168
+ }
169
+
170
+ const { limit, where = {} } = options;
171
+
172
+ let q = this._model.query()
173
+ .where(this._latField, '>=', bounds.south)
174
+ .where(this._latField, '<=', bounds.north)
175
+ .where(this._lngField, '>=', bounds.west)
176
+ .where(this._lngField, '<=', bounds.east);
177
+
178
+ if (Object.keys(where).length) q = q.where(where);
179
+ if (limit) q = q.limit(limit);
180
+
181
+ return q.exec();
182
+ }
183
+
184
+ /**
185
+ * Calculate the distance between two geographic points.
186
+ * Uses the Haversine formula.
187
+ *
188
+ * @param {number} lat1 - Latitude of point 1.
189
+ * @param {number} lng1 - Longitude of point 1.
190
+ * @param {number} lat2 - Latitude of point 2.
191
+ * @param {number} lng2 - Longitude of point 2.
192
+ * @param {string} [unit] - Distance unit ('km' or 'mi'). Defaults to configured unit.
193
+ * @returns {number} Distance between the two points.
194
+ *
195
+ * @example
196
+ * const dist = geo.distance(40.7128, -74.0060, 34.0522, -118.2437);
197
+ * // => 3944.42 (km)
198
+ */
199
+ distance(lat1, lng1, lat2, lng2, unit)
200
+ {
201
+ return GeoQuery.haversine(lat1, lng1, lat2, lng2, unit || this._unit);
202
+ }
203
+
204
+ /**
205
+ * Calculate the Haversine distance between two points.
206
+ *
207
+ * @param {number} lat1 - Latitude of point 1 (degrees).
208
+ * @param {number} lng1 - Longitude of point 1 (degrees).
209
+ * @param {number} lat2 - Latitude of point 2 (degrees).
210
+ * @param {number} lng2 - Longitude of point 2 (degrees).
211
+ * @param {string} [unit='km'] - Distance unit: 'km' or 'mi'.
212
+ * @returns {number} Distance in the specified unit.
213
+ */
214
+ static haversine(lat1, lng1, lat2, lng2, unit = 'km')
215
+ {
216
+ const R = unit === 'mi' ? EARTH_RADIUS_MI : EARTH_RADIUS_KM;
217
+ const toRad = (deg) => deg * (Math.PI / 180);
218
+
219
+ const dLat = toRad(lat2 - lat1);
220
+ const dLng = toRad(lng2 - lng1);
221
+
222
+ const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
223
+ Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
224
+ Math.sin(dLng / 2) * Math.sin(dLng / 2);
225
+
226
+ const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
227
+ return R * c;
228
+ }
229
+
230
+ /**
231
+ * Convert a record to GeoJSON Point feature.
232
+ *
233
+ * @param {object} record - Model instance or plain object.
234
+ * @param {object} [options] - Configuration options.
235
+ * @param {string[]} [options.properties] - Fields to include in GeoJSON properties.
236
+ * @returns {object} GeoJSON Feature object.
237
+ *
238
+ * @example
239
+ * const feature = geo.toGeoJSON(store);
240
+ * // => { type: 'Feature', geometry: { type: 'Point', coordinates: [-74.006, 40.7128] }, properties: { ... } }
241
+ */
242
+ toGeoJSON(record, options = {})
243
+ {
244
+ const lat = record[this._latField];
245
+ const lng = record[this._lngField];
246
+
247
+ const properties = {};
248
+ const propFields = options.properties;
249
+ if (propFields)
250
+ {
251
+ for (const f of propFields)
252
+ {
253
+ if (record[f] !== undefined) properties[f] = record[f];
254
+ }
255
+ }
256
+ else
257
+ {
258
+ // Include all non-geo fields
259
+ const data = record.toJSON ? record.toJSON() : { ...record };
260
+ for (const [k, v] of Object.entries(data))
261
+ {
262
+ if (k !== this._latField && k !== this._lngField)
263
+ {
264
+ properties[k] = v;
265
+ }
266
+ }
267
+ }
268
+
269
+ return {
270
+ type: 'Feature',
271
+ geometry: {
272
+ type: 'Point',
273
+ coordinates: [lng, lat], // GeoJSON is [lng, lat]
274
+ },
275
+ properties,
276
+ };
277
+ }
278
+
279
+ /**
280
+ * Convert multiple records to a GeoJSON FeatureCollection.
281
+ *
282
+ * @param {Array<object>} records - Array of model instances or plain objects.
283
+ * @param {object} [options] - Configuration options.
284
+ * @param {string[]} [options.properties] - Fields to include in each feature's properties.
285
+ * @returns {object} GeoJSON FeatureCollection.
286
+ *
287
+ * @example
288
+ * const collection = geo.toGeoJSONCollection(stores);
289
+ * // => { type: 'FeatureCollection', features: [...] }
290
+ */
291
+ toGeoJSONCollection(records, options = {})
292
+ {
293
+ return {
294
+ type: 'FeatureCollection',
295
+ features: records.map(r => this.toGeoJSON(r, options)),
296
+ };
297
+ }
298
+
299
+ /**
300
+ * Create a model instance from a GeoJSON Feature.
301
+ *
302
+ * @param {object} feature - GeoJSON Feature with Point geometry.
303
+ * @returns {object} Plain data object ready for Model.create().
304
+ *
305
+ * @example
306
+ * const data = geo.fromGeoJSON(feature);
307
+ * const store = await Store.create(data);
308
+ */
309
+ fromGeoJSON(feature)
310
+ {
311
+ if (!feature || feature.type !== 'Feature' || !feature.geometry)
312
+ {
313
+ throw new Error('Invalid GeoJSON Feature');
314
+ }
315
+ if (feature.geometry.type !== 'Point')
316
+ {
317
+ throw new Error('Only Point geometry is supported');
318
+ }
319
+
320
+ const [lng, lat] = feature.geometry.coordinates;
321
+ const data = { ...feature.properties };
322
+ data[this._latField] = lat;
323
+ data[this._lngField] = lng;
324
+ return data;
325
+ }
326
+
327
+ /**
328
+ * Check if a point is within a given radius of a center point.
329
+ *
330
+ * @param {number} lat - Point latitude.
331
+ * @param {number} lng - Point longitude.
332
+ * @param {number} centerLat - Center latitude.
333
+ * @param {number} centerLng - Center longitude.
334
+ * @param {number} radius - Radius to check.
335
+ * @param {string} [unit] - Distance unit.
336
+ * @returns {boolean} True if the point is within the radius.
337
+ */
338
+ isWithinRadius(lat, lng, centerLat, centerLng, radius, unit)
339
+ {
340
+ const dist = this.distance(lat, lng, centerLat, centerLng, unit);
341
+ return dist <= radius;
342
+ }
343
+
344
+ /**
345
+ * In-memory near search with Haversine distance.
346
+ * @param {number} lat - Center latitude.
347
+ * @param {number} lng - Center longitude.
348
+ * @param {object} options - Search options.
349
+ * @returns {Promise<Array>} Sorted results with _distance.
350
+ * @private
351
+ */
352
+ async _memoryNear(lat, lng, options = {})
353
+ {
354
+ const { radius, limit, offset = 0, where = {}, unit = this._unit, includeDistance = true } = options;
355
+
356
+ let q = this._model.query();
357
+ if (Object.keys(where).length) q = q.where(where);
358
+ const allRows = await q.exec();
359
+
360
+ const scored = [];
361
+ for (const row of allRows)
362
+ {
363
+ const rowLat = row[this._latField];
364
+ const rowLng = row[this._lngField];
365
+ if (rowLat == null || rowLng == null) continue;
366
+
367
+ const dist = GeoQuery.haversine(lat, lng, rowLat, rowLng, unit);
368
+
369
+ if (radius !== undefined && dist > radius) continue;
370
+
371
+ const data = row.toJSON ? row.toJSON() : { ...row };
372
+ if (includeDistance) data._distance = Math.round(dist * 100) / 100;
373
+ scored.push({ data, dist });
374
+ }
375
+
376
+ // Sort by distance
377
+ scored.sort((a, b) => a.dist - b.dist);
378
+
379
+ let results = scored.map(s => s.data);
380
+ if (offset) results = results.slice(offset);
381
+ if (limit) results = results.slice(0, limit);
382
+
383
+ return results;
384
+ }
385
+ }
386
+
387
+ module.exports = { GeoQuery, EARTH_RADIUS_KM, EARTH_RADIUS_MI };