@stonyx/orm 0.2.1-beta.9 → 0.2.1-beta.91

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 (175) hide show
  1. package/README.md +64 -6
  2. package/config/environment.js +37 -1
  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 +261 -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 +28 -0
  64. package/dist/postgres/schema-introspector.js +280 -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 +142 -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 +57 -15
  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.js → commands.ts} +179 -170
  101. package/src/{db.js → db.ts} +55 -29
  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} +11 -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.js → migrate.ts} +9 -9
  110. package/src/model-property.ts +35 -0
  111. package/src/model.ts +21 -0
  112. package/src/mysql/{connection.js → connection.ts} +43 -28
  113. package/src/mysql/migration-generator.ts +337 -0
  114. package/src/mysql/{migration-runner.js → migration-runner.ts} +121 -110
  115. package/src/mysql/mysql-db.ts +543 -0
  116. package/src/mysql/{query-builder.js → query-builder.ts} +69 -64
  117. package/src/mysql/schema-introspector.ts +310 -0
  118. package/src/mysql/{type-map.js → type-map.ts} +42 -37
  119. package/src/{orm-request.js → orm-request.ts} +187 -108
  120. package/src/plural-registry.ts +12 -0
  121. package/src/postgres/connection.ts +48 -0
  122. package/src/postgres/migration-generator.ts +348 -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 +343 -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.js → setup-rest-server.ts} +18 -16
  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 +146 -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/code-style-rules.md +0 -44
  150. package/.claude/hooks.md +0 -250
  151. package/.claude/index.md +0 -279
  152. package/.claude/usage-patterns.md +0 -217
  153. package/.github/workflows/ci.yml +0 -16
  154. package/.github/workflows/publish.yml +0 -51
  155. package/improvements.md +0 -139
  156. package/project-structure.md +0 -343
  157. package/src/belongs-to.js +0 -63
  158. package/src/has-many.js +0 -61
  159. package/src/hooks.js +0 -124
  160. package/src/main.js +0 -148
  161. package/src/manage-record.js +0 -118
  162. package/src/model-property.js +0 -29
  163. package/src/model.js +0 -9
  164. package/src/mysql/migration-generator.js +0 -188
  165. package/src/mysql/mysql-db.js +0 -320
  166. package/src/mysql/schema-introspector.js +0 -158
  167. package/src/record.js +0 -127
  168. package/src/relationships.js +0 -43
  169. package/src/serializer.js +0 -138
  170. package/src/store.js +0 -211
  171. package/src/transforms.js +0 -20
  172. package/src/utils.js +0 -12
  173. package/test-events-setup.js +0 -41
  174. package/test-hooks-manual.js +0 -54
  175. package/test-hooks-with-logging.js +0 -52
@@ -0,0 +1,280 @@
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
+ schemas[name] = {
59
+ table: sanitizeTableName(getPluralName(name)),
60
+ idType,
61
+ columns,
62
+ foreignKeys,
63
+ relationships,
64
+ vectorColumns,
65
+ memory: modelClass.memory === true,
66
+ };
67
+ }
68
+ return schemas;
69
+ }
70
+ export function buildTableDDL(name, schema, allSchemas = {}) {
71
+ const { idType, columns, foreignKeys } = schema;
72
+ const table = sanitizeTableName(schema.table);
73
+ const lines = [];
74
+ // Primary key
75
+ if (idType === 'string') {
76
+ lines.push(' "id" VARCHAR(255) PRIMARY KEY');
77
+ }
78
+ else {
79
+ lines.push(' "id" INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY');
80
+ }
81
+ // Attribute columns
82
+ for (const [col, pgType] of Object.entries(columns)) {
83
+ lines.push(` "${col}" ${pgType}`);
84
+ }
85
+ // Foreign key columns
86
+ for (const [fkCol, fkDef] of Object.entries(foreignKeys)) {
87
+ const refIdType = getReferencedIdType(fkDef.references, allSchemas);
88
+ lines.push(` "${fkCol}" ${refIdType}`);
89
+ }
90
+ // Timestamps
91
+ lines.push(' "created_at" TIMESTAMPTZ DEFAULT NOW()');
92
+ lines.push(' "updated_at" TIMESTAMPTZ DEFAULT NOW()');
93
+ // Foreign key constraints
94
+ for (const [fkCol, fkDef] of Object.entries(foreignKeys)) {
95
+ const refTable = sanitizeTableName(fkDef.references);
96
+ lines.push(` FOREIGN KEY ("${fkCol}") REFERENCES "${refTable}"("${fkDef.column}") ON DELETE SET NULL`);
97
+ }
98
+ return `CREATE TABLE IF NOT EXISTS "${table}" (\n${lines.join(',\n')}\n)`;
99
+ }
100
+ /**
101
+ * Build HNSW index DDL for vector columns on a model.
102
+ */
103
+ export function buildVectorIndexDDL(name, schema) {
104
+ const table = sanitizeTableName(schema.table);
105
+ const statements = [];
106
+ for (const [col] of Object.entries(schema.vectorColumns || {})) {
107
+ 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)`);
108
+ }
109
+ return statements;
110
+ }
111
+ function getReferencedIdType(tableName, allSchemas) {
112
+ for (const schema of Object.values(allSchemas)) {
113
+ if (schema.table === tableName) {
114
+ return schema.idType === 'string' ? 'VARCHAR(255)' : 'INTEGER';
115
+ }
116
+ }
117
+ return 'INTEGER';
118
+ }
119
+ export { getTopologicalOrder } from '../schema-helpers.js';
120
+ export function introspectViews() {
121
+ const orm = Orm.instance;
122
+ if (!orm.views)
123
+ return {};
124
+ const schemas = {};
125
+ for (const [viewKey, viewClass] of Object.entries(orm.views)) {
126
+ const name = camelCaseToKebabCase(viewKey.slice(0, -4)); // Remove 'View' suffix
127
+ const source = viewClass.source;
128
+ if (!source)
129
+ continue;
130
+ const model = new viewClass(name);
131
+ const columns = {};
132
+ const foreignKeys = {};
133
+ const aggregates = {};
134
+ const relationships = { belongsTo: {}, hasMany: {} };
135
+ for (const [key, property] of Object.entries(model)) {
136
+ if (key.startsWith('__'))
137
+ continue;
138
+ if (key === 'id')
139
+ continue;
140
+ if (property instanceof AggregateProperty) {
141
+ aggregates[key] = property;
142
+ continue;
143
+ }
144
+ const relInfo = getRelationshipInfo(property);
145
+ if (relInfo?.type === 'belongsTo') {
146
+ relationships.belongsTo[key] = relInfo.modelName;
147
+ if (relInfo.modelName) {
148
+ const fkColumn = `${key}_id`;
149
+ foreignKeys[fkColumn] = {
150
+ references: sanitizeTableName(getPluralName(relInfo.modelName)),
151
+ column: 'id',
152
+ };
153
+ }
154
+ }
155
+ else if (relInfo?.type === 'hasMany') {
156
+ relationships.hasMany[key] = relInfo.modelName;
157
+ }
158
+ else if (property instanceof ModelProperty) {
159
+ const transforms = Orm.instance.transforms;
160
+ const prop = property;
161
+ columns[key] = getPgType(prop.type, transforms[prop.type]);
162
+ }
163
+ }
164
+ schemas[name] = {
165
+ viewName: sanitizeTableName(getPluralName(name)),
166
+ source,
167
+ groupBy: viewClass.groupBy || undefined,
168
+ columns,
169
+ foreignKeys,
170
+ aggregates,
171
+ relationships,
172
+ isView: true,
173
+ memory: false, // Views default to memory:false
174
+ };
175
+ }
176
+ return schemas;
177
+ }
178
+ export function buildViewDDL(name, viewSchema, modelSchemas = {}) {
179
+ if (!viewSchema.source) {
180
+ throw new Error(`View '${name}' must define a source model`);
181
+ }
182
+ const sourceModelName = viewSchema.source;
183
+ const sourceSchema = modelSchemas[sourceModelName];
184
+ const sourceTable = sanitizeTableName(sourceSchema
185
+ ? sourceSchema.table
186
+ : getPluralName(sourceModelName));
187
+ const selectColumns = [];
188
+ const joins = [];
189
+ const hasAggregates = Object.keys(viewSchema.aggregates || {}).length > 0;
190
+ const groupByField = viewSchema.groupBy;
191
+ // ID column: groupBy field or source table PK
192
+ if (groupByField) {
193
+ selectColumns.push(`"${sourceTable}"."${groupByField}" AS "id"`);
194
+ }
195
+ else {
196
+ selectColumns.push(`"${sourceTable}"."id" AS "id"`);
197
+ }
198
+ // Aggregate columns
199
+ for (const [key, aggProp] of Object.entries(viewSchema.aggregates || {})) {
200
+ // Use pgFunction if available, fall back to mysqlFunction
201
+ const fn = aggProp.pgFunction || aggProp.mysqlFunction;
202
+ if (aggProp.relationship === undefined) {
203
+ // Field-level aggregate (groupBy views)
204
+ if (aggProp.aggregateType === 'count') {
205
+ selectColumns.push(`COUNT(*) AS "${key}"`);
206
+ }
207
+ else {
208
+ selectColumns.push(`${fn}("${sourceTable}"."${aggProp.field}") AS "${key}"`);
209
+ }
210
+ }
211
+ else {
212
+ // Relationship aggregate
213
+ const relName = aggProp.relationship;
214
+ const relTable = sanitizeTableName(getPluralName(relName));
215
+ if (aggProp.aggregateType === 'count') {
216
+ selectColumns.push(`${fn}("${relTable}"."id") AS "${key}"`);
217
+ }
218
+ else {
219
+ const field = aggProp.field;
220
+ selectColumns.push(`${fn}("${relTable}"."${field}") AS "${key}"`);
221
+ }
222
+ // Add LEFT JOIN for the relationship if not already added
223
+ const joinKey = `${relTable}`;
224
+ if (!joins.find(j => j.table === joinKey)) {
225
+ const fkColumn = `${sourceModelName}_id`;
226
+ joins.push({
227
+ table: relTable,
228
+ condition: `"${relTable}"."${fkColumn}" = "${sourceTable}"."id"`
229
+ });
230
+ }
231
+ }
232
+ }
233
+ // Regular columns
234
+ for (const [key] of Object.entries(viewSchema.columns || {})) {
235
+ selectColumns.push(`"${sourceTable}"."${key}" AS "${key}"`);
236
+ }
237
+ // Build JOIN clauses
238
+ const joinClauses = joins.map(j => `LEFT JOIN "${j.table}" ON ${j.condition}`).join('\n ');
239
+ // Build GROUP BY
240
+ let groupBy = '';
241
+ if (groupByField) {
242
+ groupBy = `\nGROUP BY "${sourceTable}"."${groupByField}"`;
243
+ }
244
+ else if (hasAggregates) {
245
+ groupBy = `\nGROUP BY "${sourceTable}"."id"`;
246
+ }
247
+ const viewName = sanitizeTableName(viewSchema.viewName);
248
+ const sql = `CREATE OR REPLACE VIEW "${viewName}" AS\nSELECT\n ${selectColumns.join(',\n ')}\nFROM "${sourceTable}"${joinClauses ? '\n ' + joinClauses : ''}${groupBy}`;
249
+ return sql;
250
+ }
251
+ export function viewSchemasToSnapshot(viewSchemas) {
252
+ const snapshot = {};
253
+ for (const [name, schema] of Object.entries(viewSchemas)) {
254
+ snapshot[name] = {
255
+ viewName: schema.viewName,
256
+ source: schema.source,
257
+ ...(schema.groupBy ? { groupBy: schema.groupBy } : {}),
258
+ columns: { ...schema.columns },
259
+ foreignKeys: { ...schema.foreignKeys },
260
+ isView: true,
261
+ viewQuery: buildViewDDL(name, schema),
262
+ };
263
+ }
264
+ return snapshot;
265
+ }
266
+ export function schemasToSnapshot(schemas) {
267
+ const snapshot = {};
268
+ for (const [name, schema] of Object.entries(schemas)) {
269
+ snapshot[name] = {
270
+ table: schema.table,
271
+ idType: schema.idType,
272
+ columns: { ...schema.columns },
273
+ foreignKeys: { ...schema.foreignKeys },
274
+ ...(schema.vectorColumns && Object.keys(schema.vectorColumns).length > 0
275
+ ? { vectorColumns: { ...schema.vectorColumns } }
276
+ : {}),
277
+ };
278
+ }
279
+ return snapshot;
280
+ }
@@ -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[];
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Detect relationship type and target model from a model property function.
3
+ * Returns null if the property is not a relationship.
4
+ */
5
+ export function getRelationshipInfo(property) {
6
+ if (typeof property !== 'function')
7
+ return null;
8
+ const relType = property.__relationshipType;
9
+ const modelName = property.__relatedModelName || null;
10
+ if (relType === 'belongsTo')
11
+ return { type: 'belongsTo', modelName };
12
+ if (relType === 'hasMany')
13
+ return { type: 'hasMany', modelName };
14
+ return null;
15
+ }
16
+ /**
17
+ * Sanitize a model/table name for use in SQL identifiers.
18
+ * Replaces hyphens and slashes with underscores.
19
+ */
20
+ export function sanitizeTableName(name) {
21
+ return name.replace(/[-/]/g, '_');
22
+ }
23
+ /**
24
+ * Sort model schemas in dependency order (belongsTo targets before dependents).
25
+ * Uses depth-first traversal to ensure referenced tables are created first.
26
+ */
27
+ export function getTopologicalOrder(schemas) {
28
+ const visited = new Set();
29
+ const order = [];
30
+ function visit(name) {
31
+ if (visited.has(name))
32
+ return;
33
+ visited.add(name);
34
+ const schema = schemas[name];
35
+ if (!schema)
36
+ return;
37
+ // Visit dependencies (belongsTo targets) first
38
+ for (const targetModelName of Object.values(schema.relationships.belongsTo)) {
39
+ if (targetModelName)
40
+ visit(targetModelName);
41
+ }
42
+ order.push(name);
43
+ }
44
+ for (const name of Object.keys(schemas)) {
45
+ visit(name);
46
+ }
47
+ return order;
48
+ }