@stonyx/orm 0.2.7-alpha.0 → 0.3.1

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 (166) hide show
  1. package/README.md +482 -15
  2. package/config/environment.js +63 -6
  3. package/dist/aggregates.d.ts +21 -0
  4. package/dist/aggregates.js +93 -0
  5. package/dist/attr.d.ts +2 -0
  6. package/dist/attr.js +22 -0
  7. package/dist/belongs-to.d.ts +11 -0
  8. package/dist/belongs-to.js +59 -0
  9. package/dist/cli.d.ts +22 -0
  10. package/dist/cli.js +148 -0
  11. package/dist/commands.d.ts +7 -0
  12. package/dist/commands.js +146 -0
  13. package/dist/db.d.ts +21 -0
  14. package/dist/db.js +180 -0
  15. package/dist/exports/db.d.ts +7 -0
  16. package/{src → dist}/exports/db.js +2 -4
  17. package/dist/has-many.d.ts +11 -0
  18. package/dist/has-many.js +58 -0
  19. package/dist/hooks.d.ts +75 -0
  20. package/dist/hooks.js +110 -0
  21. package/dist/index.d.ts +14 -0
  22. package/dist/index.js +34 -0
  23. package/dist/main.d.ts +46 -0
  24. package/dist/main.js +181 -0
  25. package/dist/manage-record.d.ts +13 -0
  26. package/dist/manage-record.js +123 -0
  27. package/dist/meta-request.d.ts +6 -0
  28. package/dist/meta-request.js +52 -0
  29. package/dist/migrate.d.ts +2 -0
  30. package/dist/migrate.js +57 -0
  31. package/dist/model-property.d.ts +9 -0
  32. package/dist/model-property.js +29 -0
  33. package/dist/model.d.ts +15 -0
  34. package/dist/model.js +18 -0
  35. package/dist/mysql/connection.d.ts +14 -0
  36. package/dist/mysql/connection.js +24 -0
  37. package/dist/mysql/migration-generator.d.ts +45 -0
  38. package/dist/mysql/migration-generator.js +254 -0
  39. package/dist/mysql/migration-runner.d.ts +12 -0
  40. package/dist/mysql/migration-runner.js +88 -0
  41. package/dist/mysql/mysql-db.d.ts +100 -0
  42. package/dist/mysql/mysql-db.js +425 -0
  43. package/dist/mysql/query-builder.d.ts +10 -0
  44. package/dist/mysql/query-builder.js +44 -0
  45. package/dist/mysql/schema-introspector.d.ts +19 -0
  46. package/dist/mysql/schema-introspector.js +257 -0
  47. package/dist/mysql/type-map.d.ts +21 -0
  48. package/dist/mysql/type-map.js +36 -0
  49. package/dist/orm-request.d.ts +38 -0
  50. package/dist/orm-request.js +475 -0
  51. package/dist/plural-registry.d.ts +4 -0
  52. package/dist/plural-registry.js +9 -0
  53. package/dist/postgres/connection.d.ts +15 -0
  54. package/dist/postgres/connection.js +32 -0
  55. package/dist/postgres/migration-generator.d.ts +45 -0
  56. package/dist/postgres/migration-generator.js +280 -0
  57. package/dist/postgres/migration-runner.d.ts +10 -0
  58. package/dist/postgres/migration-runner.js +87 -0
  59. package/dist/postgres/postgres-db.d.ts +119 -0
  60. package/dist/postgres/postgres-db.js +477 -0
  61. package/dist/postgres/query-builder.d.ts +27 -0
  62. package/dist/postgres/query-builder.js +98 -0
  63. package/dist/postgres/schema-introspector.d.ts +29 -0
  64. package/dist/postgres/schema-introspector.js +296 -0
  65. package/dist/postgres/type-map.d.ts +23 -0
  66. package/dist/postgres/type-map.js +56 -0
  67. package/dist/record.d.ts +75 -0
  68. package/dist/record.js +129 -0
  69. package/dist/relationships.d.ts +10 -0
  70. package/dist/relationships.js +41 -0
  71. package/dist/schema-helpers.d.ts +20 -0
  72. package/dist/schema-helpers.js +48 -0
  73. package/dist/serializer.d.ts +17 -0
  74. package/dist/serializer.js +136 -0
  75. package/dist/setup-rest-server.d.ts +1 -0
  76. package/dist/setup-rest-server.js +52 -0
  77. package/dist/standalone-db.d.ts +58 -0
  78. package/dist/standalone-db.js +142 -0
  79. package/dist/store.d.ts +62 -0
  80. package/dist/store.js +286 -0
  81. package/dist/timescale/query-builder.d.ts +43 -0
  82. package/dist/timescale/query-builder.js +115 -0
  83. package/dist/timescale/timescale-db.d.ts +45 -0
  84. package/dist/timescale/timescale-db.js +84 -0
  85. package/dist/transforms.d.ts +2 -0
  86. package/dist/transforms.js +17 -0
  87. package/dist/types/orm-types.d.ts +153 -0
  88. package/dist/types/orm-types.js +1 -0
  89. package/dist/utils.d.ts +7 -0
  90. package/dist/utils.js +17 -0
  91. package/dist/view-resolver.d.ts +8 -0
  92. package/dist/view-resolver.js +171 -0
  93. package/dist/view.d.ts +11 -0
  94. package/dist/view.js +18 -0
  95. package/package.json +64 -11
  96. package/src/aggregates.ts +109 -0
  97. package/src/{attr.js → attr.ts} +2 -2
  98. package/src/belongs-to.ts +90 -0
  99. package/src/cli.ts +183 -0
  100. package/src/commands.ts +179 -0
  101. package/src/db.ts +232 -0
  102. package/src/exports/db.ts +7 -0
  103. package/src/has-many.ts +92 -0
  104. package/src/hooks.ts +151 -0
  105. package/src/{index.js → index.ts} +12 -2
  106. package/src/main.ts +229 -0
  107. package/src/manage-record.ts +161 -0
  108. package/src/{meta-request.js → meta-request.ts} +17 -14
  109. package/src/migrate.ts +72 -0
  110. package/src/model-property.ts +35 -0
  111. package/src/model.ts +21 -0
  112. package/src/mysql/connection.ts +43 -0
  113. package/src/mysql/migration-generator.ts +337 -0
  114. package/src/mysql/migration-runner.ts +121 -0
  115. package/src/mysql/mysql-db.ts +543 -0
  116. package/src/mysql/query-builder.ts +69 -0
  117. package/src/mysql/schema-introspector.ts +310 -0
  118. package/src/mysql/type-map.ts +42 -0
  119. package/src/orm-request.ts +582 -0
  120. package/src/plural-registry.ts +12 -0
  121. package/src/postgres/connection.ts +48 -0
  122. package/src/postgres/migration-generator.ts +370 -0
  123. package/src/postgres/migration-runner.ts +115 -0
  124. package/src/postgres/postgres-db.ts +616 -0
  125. package/src/postgres/query-builder.ts +148 -0
  126. package/src/postgres/schema-introspector.ts +360 -0
  127. package/src/postgres/type-map.ts +61 -0
  128. package/src/record.ts +186 -0
  129. package/src/relationships.ts +54 -0
  130. package/src/schema-helpers.ts +59 -0
  131. package/src/serializer.ts +161 -0
  132. package/src/setup-rest-server.ts +62 -0
  133. package/src/standalone-db.ts +185 -0
  134. package/src/store.ts +373 -0
  135. package/src/timescale/query-builder.ts +174 -0
  136. package/src/timescale/timescale-db.ts +119 -0
  137. package/src/transforms.ts +20 -0
  138. package/src/types/mysql2.d.ts +49 -0
  139. package/src/types/orm-types.ts +158 -0
  140. package/src/types/pg.d.ts +32 -0
  141. package/src/types/stonyx-cron.d.ts +5 -0
  142. package/src/types/stonyx-events.d.ts +4 -0
  143. package/src/types/stonyx-rest-server.d.ts +16 -0
  144. package/src/types/stonyx-utils.d.ts +33 -0
  145. package/src/types/stonyx.d.ts +21 -0
  146. package/src/utils.ts +22 -0
  147. package/src/view-resolver.ts +211 -0
  148. package/src/view.ts +22 -0
  149. package/.claude/project-structure.md +0 -578
  150. package/.github/workflows/ci.yml +0 -36
  151. package/.github/workflows/publish.yml +0 -143
  152. package/src/belongs-to.js +0 -63
  153. package/src/db.js +0 -80
  154. package/src/has-many.js +0 -61
  155. package/src/main.js +0 -119
  156. package/src/manage-record.js +0 -103
  157. package/src/model-property.js +0 -29
  158. package/src/model.js +0 -9
  159. package/src/orm-request.js +0 -249
  160. package/src/record.js +0 -100
  161. package/src/relationships.js +0 -43
  162. package/src/serializer.js +0 -138
  163. package/src/setup-rest-server.js +0 -57
  164. package/src/store.js +0 -211
  165. package/src/transforms.js +0 -20
  166. package/stonyx-bootstrap.cjs +0 -30
@@ -0,0 +1,296 @@
1
+ import Orm from '@stonyx/orm';
2
+ import { getPgType, getVectorType } from './type-map.js';
3
+ import { camelCaseToKebabCase } from '@stonyx/utils/string';
4
+ import { getPluralName } from '../plural-registry.js';
5
+ import { dbKey } from '../db.js';
6
+ import { AggregateProperty } from '../aggregates.js';
7
+ import { getRelationshipInfo, sanitizeTableName } from '../schema-helpers.js';
8
+ import ModelProperty from '../model-property.js';
9
+ export function introspectModels() {
10
+ const { models } = Orm.instance;
11
+ const schemas = {};
12
+ for (const [modelKey, modelClass] of Object.entries(models)) {
13
+ const name = camelCaseToKebabCase(modelKey.slice(0, -5));
14
+ if (name === dbKey)
15
+ continue;
16
+ const model = new modelClass(modelKey);
17
+ const columns = {};
18
+ const foreignKeys = {};
19
+ const relationships = { belongsTo: {}, hasMany: {} };
20
+ const vectorColumns = {};
21
+ let idType = 'number';
22
+ const transforms = Orm.instance.transforms;
23
+ for (const [key, property] of Object.entries(model)) {
24
+ if (key.startsWith('__'))
25
+ continue;
26
+ const relInfo = getRelationshipInfo(property);
27
+ if (relInfo?.type === 'belongsTo') {
28
+ relationships.belongsTo[key] = relInfo.modelName;
29
+ }
30
+ else if (relInfo?.type === 'hasMany') {
31
+ relationships.hasMany[key] = relInfo.modelName;
32
+ }
33
+ else if (property instanceof ModelProperty) {
34
+ const prop = property;
35
+ if (key === 'id') {
36
+ idType = prop.type;
37
+ }
38
+ else if (prop.type === 'vector') {
39
+ const dimensions = prop.dimensions || 1536;
40
+ columns[key] = getVectorType(dimensions);
41
+ vectorColumns[key] = dimensions;
42
+ }
43
+ else {
44
+ columns[key] = getPgType(prop.type, transforms[prop.type]);
45
+ }
46
+ }
47
+ }
48
+ // Build foreign keys from belongsTo relationships
49
+ for (const [relName, targetModelName] of Object.entries(relationships.belongsTo)) {
50
+ if (!targetModelName)
51
+ continue;
52
+ const fkColumn = `${relName}_id`;
53
+ foreignKeys[fkColumn] = {
54
+ references: sanitizeTableName(getPluralName(targetModelName)),
55
+ column: 'id',
56
+ };
57
+ }
58
+ const hypertable = modelClass.hypertable;
59
+ schemas[name] = {
60
+ table: sanitizeTableName(getPluralName(name)),
61
+ idType,
62
+ columns,
63
+ foreignKeys,
64
+ relationships,
65
+ vectorColumns,
66
+ hypertable: hypertable || undefined,
67
+ memory: modelClass.memory === true,
68
+ };
69
+ }
70
+ return schemas;
71
+ }
72
+ export function buildTableDDL(name, schema, allSchemas = {}) {
73
+ const { idType, columns, foreignKeys, hypertable } = schema;
74
+ const table = sanitizeTableName(schema.table);
75
+ const lines = [];
76
+ const useCompositePK = hypertable && idType !== 'string';
77
+ // Primary key
78
+ if (idType === 'string') {
79
+ lines.push(' "id" VARCHAR(255) PRIMARY KEY');
80
+ }
81
+ else if (useCompositePK) {
82
+ lines.push(' "id" INTEGER GENERATED ALWAYS AS IDENTITY');
83
+ }
84
+ else {
85
+ lines.push(' "id" INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY');
86
+ }
87
+ // Attribute columns
88
+ for (const [col, pgType] of Object.entries(columns)) {
89
+ lines.push(` "${col}" ${pgType}`);
90
+ }
91
+ // Foreign key columns
92
+ for (const [fkCol, fkDef] of Object.entries(foreignKeys)) {
93
+ const refIdType = getReferencedIdType(fkDef.references, allSchemas);
94
+ lines.push(` "${fkCol}" ${refIdType}`);
95
+ }
96
+ // Timestamps
97
+ if (useCompositePK) {
98
+ lines.push(' "created_at" TIMESTAMPTZ NOT NULL DEFAULT NOW()');
99
+ }
100
+ else {
101
+ lines.push(' "created_at" TIMESTAMPTZ DEFAULT NOW()');
102
+ }
103
+ lines.push(' "updated_at" TIMESTAMPTZ DEFAULT NOW()');
104
+ // Foreign key constraints
105
+ for (const [fkCol, fkDef] of Object.entries(foreignKeys)) {
106
+ const refTable = sanitizeTableName(fkDef.references);
107
+ lines.push(` FOREIGN KEY ("${fkCol}") REFERENCES "${refTable}"("${fkDef.column}") ON DELETE SET NULL`);
108
+ }
109
+ // Composite primary key for hypertable models
110
+ if (useCompositePK) {
111
+ lines.push(` PRIMARY KEY ("id", "${hypertable.timeColumn}")`);
112
+ }
113
+ return `CREATE TABLE IF NOT EXISTS "${table}" (\n${lines.join(',\n')}\n)`;
114
+ }
115
+ /**
116
+ * Build HNSW index DDL for vector columns on a model.
117
+ */
118
+ export function buildVectorIndexDDL(name, schema) {
119
+ const table = sanitizeTableName(schema.table);
120
+ const statements = [];
121
+ for (const [col] of Object.entries(schema.vectorColumns || {})) {
122
+ statements.push(`CREATE INDEX IF NOT EXISTS "idx_${table}_${col}_hnsw" ON "${table}" USING hnsw ("${col}" vector_cosine_ops) WITH (m = 16, ef_construction = 200)`);
123
+ }
124
+ return statements;
125
+ }
126
+ function getReferencedIdType(tableName, allSchemas) {
127
+ for (const schema of Object.values(allSchemas)) {
128
+ if (schema.table === tableName) {
129
+ return schema.idType === 'string' ? 'VARCHAR(255)' : 'INTEGER';
130
+ }
131
+ }
132
+ return 'INTEGER';
133
+ }
134
+ export { getTopologicalOrder } from '../schema-helpers.js';
135
+ export function introspectViews() {
136
+ const orm = Orm.instance;
137
+ if (!orm.views)
138
+ return {};
139
+ const schemas = {};
140
+ for (const [viewKey, viewClass] of Object.entries(orm.views)) {
141
+ const name = camelCaseToKebabCase(viewKey.slice(0, -4)); // Remove 'View' suffix
142
+ const source = viewClass.source;
143
+ if (!source)
144
+ continue;
145
+ const model = new viewClass(name);
146
+ const columns = {};
147
+ const foreignKeys = {};
148
+ const aggregates = {};
149
+ const relationships = { belongsTo: {}, hasMany: {} };
150
+ for (const [key, property] of Object.entries(model)) {
151
+ if (key.startsWith('__'))
152
+ continue;
153
+ if (key === 'id')
154
+ continue;
155
+ if (property instanceof AggregateProperty) {
156
+ aggregates[key] = property;
157
+ continue;
158
+ }
159
+ const relInfo = getRelationshipInfo(property);
160
+ if (relInfo?.type === 'belongsTo') {
161
+ relationships.belongsTo[key] = relInfo.modelName;
162
+ if (relInfo.modelName) {
163
+ const fkColumn = `${key}_id`;
164
+ foreignKeys[fkColumn] = {
165
+ references: sanitizeTableName(getPluralName(relInfo.modelName)),
166
+ column: 'id',
167
+ };
168
+ }
169
+ }
170
+ else if (relInfo?.type === 'hasMany') {
171
+ relationships.hasMany[key] = relInfo.modelName;
172
+ }
173
+ else if (property instanceof ModelProperty) {
174
+ const transforms = Orm.instance.transforms;
175
+ const prop = property;
176
+ columns[key] = getPgType(prop.type, transforms[prop.type]);
177
+ }
178
+ }
179
+ schemas[name] = {
180
+ viewName: sanitizeTableName(getPluralName(name)),
181
+ source,
182
+ groupBy: viewClass.groupBy || undefined,
183
+ columns,
184
+ foreignKeys,
185
+ aggregates,
186
+ relationships,
187
+ isView: true,
188
+ memory: false, // Views default to memory:false
189
+ };
190
+ }
191
+ return schemas;
192
+ }
193
+ export function buildViewDDL(name, viewSchema, modelSchemas = {}) {
194
+ if (!viewSchema.source) {
195
+ throw new Error(`View '${name}' must define a source model`);
196
+ }
197
+ const sourceModelName = viewSchema.source;
198
+ const sourceSchema = modelSchemas[sourceModelName];
199
+ const sourceTable = sanitizeTableName(sourceSchema
200
+ ? sourceSchema.table
201
+ : getPluralName(sourceModelName));
202
+ const selectColumns = [];
203
+ const joins = [];
204
+ const hasAggregates = Object.keys(viewSchema.aggregates || {}).length > 0;
205
+ const groupByField = viewSchema.groupBy;
206
+ // ID column: groupBy field or source table PK
207
+ if (groupByField) {
208
+ selectColumns.push(`"${sourceTable}"."${groupByField}" AS "id"`);
209
+ }
210
+ else {
211
+ selectColumns.push(`"${sourceTable}"."id" AS "id"`);
212
+ }
213
+ // Aggregate columns
214
+ for (const [key, aggProp] of Object.entries(viewSchema.aggregates || {})) {
215
+ // Use pgFunction if available, fall back to mysqlFunction
216
+ const fn = aggProp.pgFunction || aggProp.mysqlFunction;
217
+ if (aggProp.relationship === undefined) {
218
+ // Field-level aggregate (groupBy views)
219
+ if (aggProp.aggregateType === 'count') {
220
+ selectColumns.push(`COUNT(*) AS "${key}"`);
221
+ }
222
+ else {
223
+ selectColumns.push(`${fn}("${sourceTable}"."${aggProp.field}") AS "${key}"`);
224
+ }
225
+ }
226
+ else {
227
+ // Relationship aggregate
228
+ const relName = aggProp.relationship;
229
+ const relTable = sanitizeTableName(getPluralName(relName));
230
+ if (aggProp.aggregateType === 'count') {
231
+ selectColumns.push(`${fn}("${relTable}"."id") AS "${key}"`);
232
+ }
233
+ else {
234
+ const field = aggProp.field;
235
+ selectColumns.push(`${fn}("${relTable}"."${field}") AS "${key}"`);
236
+ }
237
+ // Add LEFT JOIN for the relationship if not already added
238
+ const joinKey = `${relTable}`;
239
+ if (!joins.find(j => j.table === joinKey)) {
240
+ const fkColumn = `${sourceModelName}_id`;
241
+ joins.push({
242
+ table: relTable,
243
+ condition: `"${relTable}"."${fkColumn}" = "${sourceTable}"."id"`
244
+ });
245
+ }
246
+ }
247
+ }
248
+ // Regular columns
249
+ for (const [key] of Object.entries(viewSchema.columns || {})) {
250
+ selectColumns.push(`"${sourceTable}"."${key}" AS "${key}"`);
251
+ }
252
+ // Build JOIN clauses
253
+ const joinClauses = joins.map(j => `LEFT JOIN "${j.table}" ON ${j.condition}`).join('\n ');
254
+ // Build GROUP BY
255
+ let groupBy = '';
256
+ if (groupByField) {
257
+ groupBy = `\nGROUP BY "${sourceTable}"."${groupByField}"`;
258
+ }
259
+ else if (hasAggregates) {
260
+ groupBy = `\nGROUP BY "${sourceTable}"."id"`;
261
+ }
262
+ const viewName = sanitizeTableName(viewSchema.viewName);
263
+ const sql = `CREATE OR REPLACE VIEW "${viewName}" AS\nSELECT\n ${selectColumns.join(',\n ')}\nFROM "${sourceTable}"${joinClauses ? '\n ' + joinClauses : ''}${groupBy}`;
264
+ return sql;
265
+ }
266
+ export function viewSchemasToSnapshot(viewSchemas) {
267
+ const snapshot = {};
268
+ for (const [name, schema] of Object.entries(viewSchemas)) {
269
+ snapshot[name] = {
270
+ viewName: schema.viewName,
271
+ source: schema.source,
272
+ ...(schema.groupBy ? { groupBy: schema.groupBy } : {}),
273
+ columns: { ...schema.columns },
274
+ foreignKeys: { ...schema.foreignKeys },
275
+ isView: true,
276
+ viewQuery: buildViewDDL(name, schema),
277
+ };
278
+ }
279
+ return snapshot;
280
+ }
281
+ export function schemasToSnapshot(schemas) {
282
+ const snapshot = {};
283
+ for (const [name, schema] of Object.entries(schemas)) {
284
+ snapshot[name] = {
285
+ table: schema.table,
286
+ idType: schema.idType,
287
+ columns: { ...schema.columns },
288
+ foreignKeys: { ...schema.foreignKeys },
289
+ ...(schema.vectorColumns && Object.keys(schema.vectorColumns).length > 0
290
+ ? { vectorColumns: { ...schema.vectorColumns } }
291
+ : {}),
292
+ ...(schema.hypertable ? { hypertable: schema.hypertable } : {}),
293
+ };
294
+ }
295
+ return snapshot;
296
+ }
@@ -0,0 +1,23 @@
1
+ interface TransformFn {
2
+ pgType?: string;
3
+ mysqlType?: string;
4
+ (...args: unknown[]): unknown;
5
+ }
6
+ declare const typeMap: Record<string, string>;
7
+ /**
8
+ * Resolves a Stonyx ORM attribute type to a PostgreSQL column type.
9
+ *
10
+ * For built-in types, returns the mapped PostgreSQL type directly.
11
+ *
12
+ * For custom transforms (e.g. an `animal` transform that maps strings to ints):
13
+ * - If the transform function exports a `pgType` property, that value is used.
14
+ * - Otherwise, if `mysqlType` is defined, it is mapped to a PG equivalent.
15
+ * - Otherwise, defaults to JSONB. Values are JSON-stringified on write and
16
+ * JSON-parsed on read by PostgreSQL natively.
17
+ */
18
+ export declare function getPgType(attrType: string, transformFn?: TransformFn): string;
19
+ /**
20
+ * Returns a vector column type for the given dimensions.
21
+ */
22
+ export declare function getVectorType(dimensions: number): string;
23
+ export default typeMap;
@@ -0,0 +1,56 @@
1
+ const typeMap = {
2
+ string: 'VARCHAR(255)',
3
+ number: 'INTEGER',
4
+ float: 'REAL',
5
+ boolean: 'BOOLEAN',
6
+ date: 'TIMESTAMPTZ',
7
+ timestamp: 'BIGINT',
8
+ passthrough: 'TEXT',
9
+ trim: 'VARCHAR(255)',
10
+ uppercase: 'VARCHAR(255)',
11
+ ceil: 'INTEGER',
12
+ floor: 'INTEGER',
13
+ round: 'INTEGER',
14
+ };
15
+ /**
16
+ * Resolves a Stonyx ORM attribute type to a PostgreSQL column type.
17
+ *
18
+ * For built-in types, returns the mapped PostgreSQL type directly.
19
+ *
20
+ * For custom transforms (e.g. an `animal` transform that maps strings to ints):
21
+ * - If the transform function exports a `pgType` property, that value is used.
22
+ * - Otherwise, if `mysqlType` is defined, it is mapped to a PG equivalent.
23
+ * - Otherwise, defaults to JSONB. Values are JSON-stringified on write and
24
+ * JSON-parsed on read by PostgreSQL natively.
25
+ */
26
+ export function getPgType(attrType, transformFn) {
27
+ if (typeMap[attrType])
28
+ return typeMap[attrType];
29
+ if (transformFn?.pgType)
30
+ return transformFn.pgType;
31
+ if (transformFn?.mysqlType)
32
+ return mysqlTypeToPg(transformFn.mysqlType);
33
+ return 'JSONB';
34
+ }
35
+ /**
36
+ * Returns a vector column type for the given dimensions.
37
+ */
38
+ export function getVectorType(dimensions) {
39
+ if (!Number.isInteger(dimensions) || dimensions < 1 || dimensions > 16000) {
40
+ throw new Error(`Invalid vector dimensions: ${dimensions}. Must be an integer between 1 and 16000.`);
41
+ }
42
+ return `vector(${dimensions})`;
43
+ }
44
+ function mysqlTypeToPg(mysqlType) {
45
+ const upper = mysqlType.toUpperCase();
46
+ if (upper === 'TINYINT(1)')
47
+ return 'BOOLEAN';
48
+ if (upper === 'INT' || upper === 'INT AUTO_INCREMENT')
49
+ return 'INTEGER';
50
+ if (upper === 'DATETIME')
51
+ return 'TIMESTAMPTZ';
52
+ if (upper === 'JSON')
53
+ return 'JSONB';
54
+ return mysqlType;
55
+ }
56
+ export default typeMap;
@@ -0,0 +1,75 @@
1
+ import type Serializer from './serializer.js';
2
+ interface ToJSONOptions {
3
+ fields?: Set<string>;
4
+ baseUrl?: string;
5
+ }
6
+ interface SerializeOptions {
7
+ update?: boolean;
8
+ serialize?: boolean;
9
+ transform?: boolean;
10
+ [key: string]: unknown;
11
+ }
12
+ interface UnloadOptions {
13
+ [key: string]: unknown;
14
+ }
15
+ interface RelationshipLinks {
16
+ self: string;
17
+ related: string;
18
+ }
19
+ interface RelationshipEntry {
20
+ data: {
21
+ type: string;
22
+ id: unknown;
23
+ } | {
24
+ type: string;
25
+ id: unknown;
26
+ }[] | null;
27
+ links?: RelationshipLinks;
28
+ }
29
+ interface JSONAPIResult {
30
+ attributes: {
31
+ [key: string]: unknown;
32
+ };
33
+ relationships: {
34
+ [key: string]: RelationshipEntry;
35
+ };
36
+ id: unknown;
37
+ type: string;
38
+ links?: {
39
+ self: string;
40
+ };
41
+ }
42
+ export default class Record {
43
+ /** @private */
44
+ __data: {
45
+ [key: string]: unknown;
46
+ };
47
+ /** @private */
48
+ __relationships: {
49
+ [key: string]: unknown;
50
+ };
51
+ /** @private */
52
+ __serialized: boolean;
53
+ /** @private */
54
+ __model: {
55
+ __name: string;
56
+ [key: string]: unknown;
57
+ };
58
+ /** @private */
59
+ __serializer: Serializer;
60
+ [key: string]: unknown;
61
+ constructor(model: {
62
+ __name: string;
63
+ [key: string]: unknown;
64
+ }, serializer: Serializer);
65
+ serialize(rawData?: unknown, options?: SerializeOptions): {
66
+ [key: string]: unknown;
67
+ };
68
+ format(): {
69
+ [key: string]: unknown;
70
+ };
71
+ toJSON(options?: ToJSONOptions): JSONAPIResult;
72
+ unload(options?: UnloadOptions): void;
73
+ clean(): void;
74
+ }
75
+ export {};
package/dist/record.js ADDED
@@ -0,0 +1,129 @@
1
+ import { store } from '@stonyx/orm';
2
+ import { getComputedProperties } from "./serializer.js";
3
+ import { camelCaseToKebabCase } from '@stonyx/utils/string';
4
+ import { getPluralName } from './plural-registry.js';
5
+ export default class Record {
6
+ /** @private */
7
+ __data = {};
8
+ /** @private */
9
+ __relationships = {};
10
+ /** @private */
11
+ __serialized = false;
12
+ /** @private */
13
+ __model;
14
+ /** @private */
15
+ __serializer;
16
+ constructor(model, serializer) {
17
+ this.__model = model;
18
+ this.__serializer = serializer;
19
+ }
20
+ serialize(rawData, options = {}) {
21
+ const { __data: data } = this;
22
+ if (this.__serialized && !options.update) {
23
+ const relatedIds = {};
24
+ for (const [key, childRecord] of Object.entries(this.__relationships)) {
25
+ relatedIds[key] = Array.isArray(childRecord)
26
+ ? childRecord.map((r) => r.id)
27
+ : childRecord?.id ?? null;
28
+ }
29
+ return { ...data, ...relatedIds };
30
+ }
31
+ const normalizedData = this.__serializer.normalize(rawData);
32
+ this.__serializer.setProperties(normalizedData, this, options);
33
+ return data;
34
+ }
35
+ // Similar to serialize, but preserves top level relationship records
36
+ format() {
37
+ if (!this.__serialized)
38
+ throw new Error('Record must be serialized before being converted to JSON');
39
+ const { __data: data } = this;
40
+ const records = {};
41
+ for (const [key, childRecord] of Object.entries(this.__relationships)) {
42
+ if (Array.isArray(childRecord)) {
43
+ // Deduplicate by record ID — keep last occurrence (latest data wins)
44
+ const seen = new Set();
45
+ const unique = [];
46
+ for (let i = childRecord.length - 1; i >= 0; i--) {
47
+ const r = childRecord[i];
48
+ if (!seen.has(r.id)) {
49
+ seen.add(r.id);
50
+ unique.push(r);
51
+ }
52
+ }
53
+ unique.reverse();
54
+ records[key] = unique.map((r) => r.serialize());
55
+ }
56
+ else {
57
+ records[key] = childRecord?.serialize() ?? null;
58
+ }
59
+ }
60
+ return { ...data, ...records };
61
+ }
62
+ // Formats record for JSON API output
63
+ toJSON(options = {}) {
64
+ if (!this.__serialized)
65
+ throw new Error('Record must be serialized before being converted to JSON');
66
+ const { fields, baseUrl } = options;
67
+ const { __data: data } = this;
68
+ const modelName = this.__model.__name;
69
+ const pluralizedModelName = getPluralName(modelName);
70
+ const recordId = data.id;
71
+ const relationships = {};
72
+ const attributes = {};
73
+ for (const [key, value] of Object.entries(data)) {
74
+ if (key === 'id')
75
+ continue;
76
+ if (fields && !fields.has(key))
77
+ continue;
78
+ attributes[key] = value;
79
+ }
80
+ for (const [key, getter] of getComputedProperties(this.__model)) {
81
+ if (fields && !fields.has(key))
82
+ continue;
83
+ attributes[key] = getter.call(this);
84
+ }
85
+ for (const [key, childRecord] of Object.entries(this.__relationships)) {
86
+ if (fields && !fields.has(key))
87
+ continue;
88
+ const relationshipData = Array.isArray(childRecord)
89
+ ? childRecord.map((r) => ({ type: r.__model.__name, id: r.id }))
90
+ : childRecord ? { type: childRecord.__model.__name, id: childRecord.id } : null;
91
+ // Dasherize the key for URL paths (e.g., accessLinks -> access-links)
92
+ const dasherizedKey = camelCaseToKebabCase(key);
93
+ relationships[dasherizedKey] = { data: relationshipData };
94
+ // Add links to relationship if baseUrl provided
95
+ if (baseUrl) {
96
+ relationships[dasherizedKey].links = {
97
+ self: `${baseUrl}/${pluralizedModelName}/${recordId}/relationships/${dasherizedKey}`,
98
+ related: `${baseUrl}/${pluralizedModelName}/${recordId}/${dasherizedKey}`
99
+ };
100
+ }
101
+ }
102
+ const result = {
103
+ attributes,
104
+ relationships,
105
+ id: recordId,
106
+ type: modelName,
107
+ };
108
+ // Add resource links if baseUrl provided
109
+ if (baseUrl) {
110
+ result.links = {
111
+ self: `${baseUrl}/${pluralizedModelName}/${recordId}`
112
+ };
113
+ }
114
+ return result;
115
+ }
116
+ unload(options = {}) {
117
+ store.unloadRecord(this.__model.__name, this.id, options);
118
+ }
119
+ clean() {
120
+ try {
121
+ for (const key of Object.keys(this)) {
122
+ delete this[key];
123
+ }
124
+ }
125
+ catch {
126
+ // Ignore errors during cleanup, as some keys may not be deletable
127
+ }
128
+ }
129
+ }
@@ -0,0 +1,10 @@
1
+ import type { HasManyMap, BelongsToMap, GlobalMap, PendingMap, PendingBelongsToMap } from './types/orm-types.js';
2
+ export declare function getRelationships(type: string, sourceModel: string, targetModel: string, relationshipId?: string): Map<unknown, unknown> | undefined;
3
+ export declare function getHasManyRelationships(sourceModel: string, targetModel: string): Map<unknown, unknown> | undefined;
4
+ /** Typed accessors for the relationship registry */
5
+ export declare function getHasManyRegistry(): HasManyMap;
6
+ export declare function getBelongsToRegistry(): BelongsToMap;
7
+ export declare function getGlobalRegistry(): GlobalMap;
8
+ export declare function getPendingRegistry(): PendingMap;
9
+ export declare function getPendingBelongsToRegistry(): PendingBelongsToMap;
10
+ export declare const TYPES: string[];
@@ -0,0 +1,41 @@
1
+ import { relationships } from '@stonyx/orm';
2
+ // TODO: Refactor mapping to remove a level of iteration
3
+ export function getRelationships(type, sourceModel, targetModel, relationshipId) {
4
+ let allRelationships = relationships.get(type);
5
+ if (!allRelationships) {
6
+ allRelationships = new Map();
7
+ relationships.set(type, allRelationships);
8
+ }
9
+ // create relationship map for this type of it doesn't already exist
10
+ if (!allRelationships.has(sourceModel))
11
+ allRelationships.set(sourceModel, new Map());
12
+ const modelRelationship = allRelationships.get(sourceModel);
13
+ if (!modelRelationship)
14
+ return undefined;
15
+ if (!modelRelationship.has(targetModel))
16
+ modelRelationship.set(targetModel, new Map());
17
+ const relationship = modelRelationship.get(targetModel);
18
+ // TODO: Determine whether already having id should be handled differently
19
+ //if (relationship.has(relationshipId)) return;
20
+ return relationship;
21
+ }
22
+ export function getHasManyRelationships(sourceModel, targetModel) {
23
+ return relationships.get('hasMany')?.get(sourceModel)?.get(targetModel);
24
+ }
25
+ /** Typed accessors for the relationship registry */
26
+ export function getHasManyRegistry() {
27
+ return relationships.get('hasMany');
28
+ }
29
+ export function getBelongsToRegistry() {
30
+ return relationships.get('belongsTo');
31
+ }
32
+ export function getGlobalRegistry() {
33
+ return relationships.get('global');
34
+ }
35
+ export function getPendingRegistry() {
36
+ return relationships.get('pending');
37
+ }
38
+ export function getPendingBelongsToRegistry() {
39
+ return relationships.get('pendingBelongsTo');
40
+ }
41
+ export const TYPES = ['global', 'hasMany', 'belongsTo', 'pending'];
@@ -0,0 +1,20 @@
1
+ import type { ModelSchema } from './types/orm-types.js';
2
+ export interface SchemaRelationshipInfo {
3
+ type: 'belongsTo' | 'hasMany';
4
+ modelName: string | null;
5
+ }
6
+ /**
7
+ * Detect relationship type and target model from a model property function.
8
+ * Returns null if the property is not a relationship.
9
+ */
10
+ export declare function getRelationshipInfo(property: unknown): SchemaRelationshipInfo | null;
11
+ /**
12
+ * Sanitize a model/table name for use in SQL identifiers.
13
+ * Replaces hyphens and slashes with underscores.
14
+ */
15
+ export declare function sanitizeTableName(name: string): string;
16
+ /**
17
+ * Sort model schemas in dependency order (belongsTo targets before dependents).
18
+ * Uses depth-first traversal to ensure referenced tables are created first.
19
+ */
20
+ export declare function getTopologicalOrder(schemas: Record<string, ModelSchema>): string[];