orchid-orm 1.3.16 → 1.4.16

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 (38) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/index.d.ts +39 -32
  3. package/dist/index.esm.js +102 -100
  4. package/dist/index.esm.js.map +1 -1
  5. package/dist/index.js +102 -100
  6. package/dist/index.js.map +1 -1
  7. package/jest-setup.ts +4 -0
  8. package/package.json +8 -4
  9. package/src/appCodeUpdater/appCodeUpdater.ts +19 -0
  10. package/src/appCodeUpdater/fileChanges.ts +41 -0
  11. package/src/appCodeUpdater/testUtils.ts +31 -0
  12. package/src/appCodeUpdater/tsUtils.ts +137 -0
  13. package/src/appCodeUpdater/updateMainFile.test.ts +230 -0
  14. package/src/appCodeUpdater/updateMainFile.ts +163 -0
  15. package/src/appCodeUpdater/updateTableFile.ts +19 -0
  16. package/src/index.ts +5 -1
  17. package/src/orm.test.ts +13 -13
  18. package/src/orm.ts +21 -21
  19. package/src/relations/belongsTo.test.ts +1 -1
  20. package/src/relations/belongsTo.ts +2 -2
  21. package/src/relations/hasAndBelongsToMany.test.ts +1 -1
  22. package/src/relations/hasAndBelongsToMany.ts +9 -9
  23. package/src/relations/hasMany.test.ts +16 -10
  24. package/src/relations/hasMany.ts +6 -6
  25. package/src/relations/hasOne.test.ts +10 -10
  26. package/src/relations/hasOne.ts +6 -6
  27. package/src/relations/relations.ts +73 -71
  28. package/src/relations/utils.ts +3 -3
  29. package/src/repo.test.ts +29 -29
  30. package/src/repo.ts +6 -6
  31. package/src/{model.test.ts → table.test.ts} +15 -15
  32. package/src/{model.ts → table.ts} +17 -17
  33. package/src/test-utils/test-db.ts +15 -15
  34. package/src/test-utils/{test-models.ts → test-tables.ts} +42 -42
  35. package/src/transaction.test.ts +1 -1
  36. package/src/transaction.ts +4 -4
  37. package/src/utils.ts +9 -0
  38. package/tsconfig.json +1 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # orchid-orm
2
2
 
3
+ ## 2.0.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 3f25b4d: Rename all model words to table words, because all models here are not models in OOP meaning
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies [3f25b4d]
12
+ - pqb@0.8.0
13
+ - rake-db@2.2.0
14
+
3
15
  ## 1.3.16
4
16
 
5
17
  ### Patch Changes
package/dist/index.d.ts CHANGED
@@ -1,11 +1,12 @@
1
1
  import { BelongsToRelation, HasManyRelation, HasOneRelation, Db, Adapter, AdapterOptions, QueryLogOptions, NoPrimaryKeyOption, HasAndBelongsToManyRelation, Query, defaultsKey, EmptyObject, BaseRelation, RelationQuery, SetQueryReturnsOne, SetQueryReturnsOneOptional, SetQueryReturnsAll, ColumnTypesBase, ColumnsShape, ColumnShapeOutput, WhereResult, MergeQuery, SetQueryReturns, QueryReturnType } from 'pqb';
2
+ import { AppCodeUpdater } from 'rake-db';
2
3
 
3
4
  interface BelongsTo extends RelationThunkBase {
4
5
  type: 'belongsTo';
5
6
  returns: 'one';
6
7
  options: BelongsToRelation['options'];
7
8
  }
8
- declare type BelongsToInfo<T extends Model, Relation extends BelongsTo, FK extends string = Relation['options']['foreignKey']> = {
9
+ declare type BelongsToInfo<T extends Table, Relation extends BelongsTo, FK extends string = Relation['options']['foreignKey']> = {
9
10
  params: Record<FK, T['columns']['shape'][FK]['type']>;
10
11
  populate: never;
11
12
  chainedCreate: false;
@@ -17,7 +18,7 @@ interface HasMany extends RelationThunkBase {
17
18
  returns: 'many';
18
19
  options: HasManyRelation['options'];
19
20
  }
20
- declare type HasManyInfo<T extends Model, Relations extends RelationThunks, Relation extends HasMany> = {
21
+ declare type HasManyInfo<T extends Table, Relations extends RelationThunks, Relation extends HasMany> = {
21
22
  params: Relation['options'] extends {
22
23
  primaryKey: string;
23
24
  } ? Record<Relation['options']['primaryKey'], T['columns']['shape'][Relation['options']['primaryKey']]['type']> : Relation['options'] extends {
@@ -37,7 +38,7 @@ interface HasOne extends RelationThunkBase {
37
38
  returns: 'one';
38
39
  options: HasOneRelation['options'];
39
40
  }
40
- declare type HasOneInfo<T extends Model, Relations extends RelationThunks, Relation extends HasOne> = {
41
+ declare type HasOneInfo<T extends Table, Relations extends RelationThunks, Relation extends HasOne> = {
41
42
  params: Relation['options'] extends {
42
43
  primaryKey: string;
43
44
  } ? Record<Relation['options']['primaryKey'], T['columns']['shape'][Relation['options']['primaryKey']]['type']> : Relation['options'] extends {
@@ -56,27 +57,27 @@ declare function transaction<T extends {
56
57
  $queryBuilder: Db;
57
58
  }, Result>(this: T, fn: (db: T) => Promise<Result>): Promise<Result>;
58
59
 
59
- declare type OrchidORM<T extends ModelClasses> = {
60
- [K in keyof T]: DbModel<T[K]>;
60
+ declare type OrchidORM<T extends TableClasses> = {
61
+ [K in keyof T]: DbTable<T[K]>;
61
62
  } & {
62
63
  $transaction: typeof transaction;
63
64
  $adapter: Adapter;
64
65
  $queryBuilder: Db;
65
66
  $close(): Promise<void>;
66
67
  };
67
- declare const orchidORM: <T extends ModelClasses>({ log, logger, autoPreparedStatements, noPrimaryKey, ...options }: (Omit<AdapterOptions, "log"> | {
68
+ declare const orchidORM: <T extends TableClasses>({ log, logger, autoPreparedStatements, noPrimaryKey, ...options }: (Omit<AdapterOptions, "log"> | {
68
69
  adapter: Adapter;
69
70
  }) & QueryLogOptions & {
70
71
  autoPreparedStatements?: boolean | undefined;
71
72
  noPrimaryKey?: NoPrimaryKeyOption | undefined;
72
- }, models: T) => OrchidORM<T>;
73
+ }, tables: T) => OrchidORM<T>;
73
74
 
74
75
  interface HasAndBelongsToMany extends RelationThunkBase {
75
76
  type: 'hasAndBelongsToMany';
76
77
  returns: 'many';
77
78
  options: HasAndBelongsToManyRelation['options'];
78
79
  }
79
- declare type HasAndBelongsToManyInfo<T extends Model, Relation extends HasAndBelongsToMany> = {
80
+ declare type HasAndBelongsToManyInfo<T extends Table, Relation extends HasAndBelongsToMany> = {
80
81
  params: Record<Relation['options']['primaryKey'], T['columns']['shape'][Relation['options']['primaryKey']]['type']>;
81
82
  populate: never;
82
83
  chainedCreate: true;
@@ -86,16 +87,16 @@ declare type HasAndBelongsToManyInfo<T extends Model, Relation extends HasAndBel
86
87
  interface RelationThunkBase {
87
88
  type: string;
88
89
  returns: 'one' | 'many';
89
- fn(): ModelClass;
90
+ fn(): TableClass;
90
91
  options: BaseRelation['options'];
91
92
  }
92
93
  declare type RelationThunk = BelongsTo | HasOne | HasMany | HasAndBelongsToMany;
93
94
  declare type RelationThunks = Record<string, RelationThunk>;
94
- declare type Relation<T extends Model, Relations extends RelationThunks, K extends keyof Relations, M extends Query = DbModel<ReturnType<Relations[K]['fn']>>, Info extends RelationInfo = RelationInfo<T, Relations, Relations[K]>> = {
95
+ declare type Relation<T extends Table, Relations extends RelationThunks, K extends keyof Relations, M extends Query = DbTable<ReturnType<Relations[K]['fn']>>, Info extends RelationInfo = RelationInfo<T, Relations, Relations[K]>> = {
95
96
  type: Relations[K]['type'];
96
97
  returns: Relations[K]['returns'];
97
98
  key: K;
98
- model: M;
99
+ table: M;
99
100
  query: M;
100
101
  joinQuery(fromQuery: Query, toQuery: Query): Query;
101
102
  defaults: Info['populate'];
@@ -105,45 +106,45 @@ declare type Relation<T extends Model, Relations extends RelationThunks, K exten
105
106
  primaryKey: string;
106
107
  options: Relations[K]['options'];
107
108
  };
108
- declare type RelationScopeOrModel<Relation extends RelationThunkBase> = Relation['options']['scope'] extends (q: Query) => Query ? ReturnType<Relation['options']['scope']> : DbModel<ReturnType<Relation['fn']>>;
109
- declare type RelationInfo<T extends Model = Model, Relations extends RelationThunks = RelationThunks, Relation extends RelationThunk = RelationThunk> = Relation extends BelongsTo ? BelongsToInfo<T, Relation> : Relation extends HasOne ? HasOneInfo<T, Relations, Relation> : Relation extends HasMany ? HasManyInfo<T, Relations, Relation> : Relation extends HasAndBelongsToMany ? HasAndBelongsToManyInfo<T, Relation> : never;
110
- declare type MapRelation<T extends Model, Relations extends RelationThunks, RelationName extends keyof Relations, Relation extends RelationThunk = Relations[RelationName], RelatedQuery extends Query = RelationScopeOrModel<Relation>, Info extends {
109
+ declare type RelationScopeOrTable<Relation extends RelationThunkBase> = Relation['options']['scope'] extends (q: Query) => Query ? ReturnType<Relation['options']['scope']> : DbTable<ReturnType<Relation['fn']>>;
110
+ declare type RelationInfo<T extends Table = Table, Relations extends RelationThunks = RelationThunks, Relation extends RelationThunk = RelationThunk> = Relation extends BelongsTo ? BelongsToInfo<T, Relation> : Relation extends HasOne ? HasOneInfo<T, Relations, Relation> : Relation extends HasMany ? HasManyInfo<T, Relations, Relation> : Relation extends HasAndBelongsToMany ? HasAndBelongsToManyInfo<T, Relation> : never;
111
+ declare type MapRelation<T extends Table, Relations extends RelationThunks, RelationName extends keyof Relations, Relation extends RelationThunk = Relations[RelationName], RelatedQuery extends Query = RelationScopeOrTable<Relation>, Info extends {
111
112
  params: Record<string, unknown>;
112
113
  populate: string;
113
114
  chainedCreate: boolean;
114
115
  chainedDelete: boolean;
115
116
  } = RelationInfo<T, Relations, Relation>> = RelationQuery<RelationName, Info['params'], Info['populate'], Relation['returns'] extends 'one' ? Relation['options']['required'] extends true ? SetQueryReturnsOne<RelatedQuery> : SetQueryReturnsOneOptional<RelatedQuery> : SetQueryReturnsAll<RelatedQuery>, Relation['options']['required'] extends boolean ? Relation['options']['required'] : false, Info['chainedCreate'], Info['chainedDelete']>;
116
- declare type MapRelations<T extends Model> = 'relations' extends keyof T ? T['relations'] extends RelationThunks ? {
117
+ declare type MapRelations<T extends Table> = 'relations' extends keyof T ? T['relations'] extends RelationThunks ? {
117
118
  [K in keyof T['relations']]: MapRelation<T, T['relations'], K>;
118
119
  } : EmptyObject : EmptyObject;
119
120
 
120
- declare type ModelClass<T extends Model = Model> = new () => T;
121
- declare type ModelClasses = Record<string, ModelClass>;
122
- declare type ModelToDb<T extends Model> = Db<T['table'], T['columns']['shape'], 'relations' extends keyof T ? T['relations'] extends RelationThunks ? {
121
+ declare type TableClass<T extends Table = Table> = new () => T;
122
+ declare type TableClasses = Record<string, TableClass>;
123
+ declare type TableToDb<T extends Table> = Db<T['table'], T['columns']['shape'], 'relations' extends keyof T ? T['relations'] extends RelationThunks ? {
123
124
  [K in keyof T['relations']]: Relation<T, T['relations'], K>;
124
125
  } : Query['relations'] : Query['relations'], T['columnTypes']> & {
125
126
  definedAs: string;
126
- db: OrchidORM<ModelClasses>;
127
+ db: OrchidORM<TableClasses>;
127
128
  };
128
- declare type DbModel<T extends ModelClass> = ModelToDb<InstanceType<T>> & Omit<MapRelations<InstanceType<T>>, keyof Query>;
129
- declare type ModelConfig = {
129
+ declare type DbTable<T extends TableClass> = TableToDb<InstanceType<T>> & Omit<MapRelations<InstanceType<T>>, keyof Query>;
130
+ declare type TableConfig = {
130
131
  shape: ColumnsShape;
131
132
  type: unknown;
132
133
  };
133
- declare type ScopeFn<Related extends ModelClass, Scope extends Query> = (q: DbModel<Related>) => Scope;
134
- declare type Model = {
134
+ declare type ScopeFn<Related extends TableClass, Scope extends Query> = (q: DbTable<Related>) => Scope;
135
+ declare type Table = {
135
136
  table: string;
136
- columns: ModelConfig;
137
+ columns: TableConfig;
137
138
  schema?: string;
138
139
  columnTypes: ColumnTypesBase;
139
140
  noPrimaryKey?: boolean;
140
141
  };
141
- declare const createModel: <CT extends ColumnTypesBase>(options: {
142
+ declare const createBaseTable: <CT extends ColumnTypesBase>(options: {
142
143
  columnTypes: CT;
143
144
  }) => {
144
145
  new (): {
145
146
  table: string;
146
- columns: ModelConfig;
147
+ columns: TableConfig;
147
148
  schema?: string | undefined;
148
149
  columnTypes: CT;
149
150
  noPrimaryKey?: boolean | undefined;
@@ -151,7 +152,7 @@ declare const createModel: <CT extends ColumnTypesBase>(options: {
151
152
  shape: T;
152
153
  type: ColumnShapeOutput<T>;
153
154
  };
154
- belongsTo<Self extends any, Related extends ModelClass<Model>, Scope extends Query, Options extends {
155
+ belongsTo<Self extends any, Related extends TableClass<Table>, Scope extends Query, Options extends {
155
156
  primaryKey: keyof InstanceType<Related>["columns"]["shape"];
156
157
  foreignKey: keyof Self["columns"]["shape"];
157
158
  scope?: ScopeFn<Related, Scope> | undefined;
@@ -162,7 +163,7 @@ declare const createModel: <CT extends ColumnTypesBase>(options: {
162
163
  fn: () => Related;
163
164
  options: Options;
164
165
  };
165
- hasOne<Self_1 extends any, Related_1 extends ModelClass<Model>, Scope_1 extends Query, Through extends string, Source extends string, Options_1 extends ({
166
+ hasOne<Self_1 extends any, Related_1 extends TableClass<Table>, Scope_1 extends Query, Through extends string, Source extends string, Options_1 extends ({
166
167
  primaryKey: keyof Self_1["columns"]["shape"];
167
168
  foreignKey: keyof InstanceType<Related_1>["columns"]["shape"];
168
169
  } | {
@@ -177,7 +178,7 @@ declare const createModel: <CT extends ColumnTypesBase>(options: {
177
178
  fn: () => Related_1;
178
179
  options: Options_1;
179
180
  };
180
- hasMany<Self_2 extends any, Related_2 extends ModelClass<Model>, Scope_2 extends Query, Through_1 extends string, Source_1 extends string, Options_2 extends ({
181
+ hasMany<Self_2 extends any, Related_2 extends TableClass<Table>, Scope_2 extends Query, Through_1 extends string, Source_1 extends string, Options_2 extends ({
181
182
  primaryKey: keyof Self_2["columns"]["shape"];
182
183
  foreignKey: keyof InstanceType<Related_2>["columns"]["shape"];
183
184
  } | {
@@ -192,7 +193,7 @@ declare const createModel: <CT extends ColumnTypesBase>(options: {
192
193
  fn: () => Related_2;
193
194
  options: Options_2;
194
195
  };
195
- hasAndBelongsToMany<Self_3 extends any, Related_3 extends ModelClass<Model>, Scope_3 extends Query, Options_3 extends {
196
+ hasAndBelongsToMany<Self_3 extends any, Related_3 extends TableClass<Table>, Scope_3 extends Query, Options_3 extends {
196
197
  primaryKey: keyof Self_3["columns"]["shape"];
197
198
  associationPrimaryKey: keyof InstanceType<Related_3>["columns"]["shape"];
198
199
  foreignKey: string;
@@ -226,6 +227,12 @@ declare type Repo<T extends Query, Methods extends MethodsBase<T>, Mapped = MapM
226
227
  table: T['table'];
227
228
  shape: T['shape'];
228
229
  }>(q: Q) => Q & Mapped) & T & Mapped;
229
- declare const createRepo: <T extends Query, Methods extends MethodsBase<T>>(model: T, methods: Methods) => Repo<T, Methods, MapMethods<T, Methods>>;
230
+ declare const createRepo: <T extends Query, Methods extends MethodsBase<T>>(table: T, methods: Methods) => Repo<T, Methods, MapMethods<T, Methods>>;
230
231
 
231
- export { DbModel, MapMethods, MapQueryMethods, MethodsBase, Model, ModelClass, ModelClasses, ModelToDb, OrchidORM, QueryMethods, Repo, createModel, createRepo, orchidORM };
232
+ declare type AppCodeUpdaterConfig = {
233
+ tablePath(tableName: string): string;
234
+ mainFilePath: string;
235
+ };
236
+ declare const appCodeUpdater: () => AppCodeUpdater;
237
+
238
+ export { AppCodeUpdaterConfig, DbTable, MapMethods, MapQueryMethods, MethodsBase, OrchidORM, QueryMethods, Repo, Table, TableClass, TableClasses, TableToDb, appCodeUpdater, createBaseTable, createRepo, orchidORM };
package/dist/index.esm.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { getColumnTypes, addQueryOn, VirtualColumn, pushQueryValue, isQueryReturnsAll, getQueryAs, toSqlCacheKey, NotFoundError, relationQueryKey, Db, Adapter, anyShape, columnTypes, getClonedQueryData } from 'pqb';
2
2
 
3
- const createModel = (options) => {
4
- return class Model {
3
+ const createBaseTable = (options) => {
4
+ return class BaseTable {
5
5
  constructor() {
6
6
  this.setColumns = (fn) => {
7
7
  const shape = getColumnTypes(options.columnTypes, fn);
@@ -239,11 +239,11 @@ const nestedUpdate$3 = ({ query, primaryKey, foreignKey }) => {
239
239
  };
240
240
  };
241
241
 
242
- const getThroughRelation = (model, through) => {
243
- return model.relations[through];
242
+ const getThroughRelation = (table, through) => {
243
+ return table.relations[through];
244
244
  };
245
245
  const getSourceRelation = (throughRelation, source) => {
246
- return throughRelation.model.relations[source];
246
+ return throughRelation.table.relations[source];
247
247
  };
248
248
  const hasRelationHandleCreate = (q, ctx, item, rowIndex, key, primaryKey, nestedInsert) => {
249
249
  const value = item[key];
@@ -341,7 +341,7 @@ class HasOneVirtualColumn extends VirtualColumn {
341
341
  );
342
342
  }
343
343
  }
344
- const makeHasOneMethod = (model, relation, relationName, query) => {
344
+ const makeHasOneMethod = (table, relation, relationName, query) => {
345
345
  if (relation.options.required) {
346
346
  query._take();
347
347
  } else {
@@ -349,14 +349,14 @@ const makeHasOneMethod = (model, relation, relationName, query) => {
349
349
  }
350
350
  if ("through" in relation.options) {
351
351
  const { through, source } = relation.options;
352
- const throughRelation = getThroughRelation(model, through);
352
+ const throughRelation = getThroughRelation(table, through);
353
353
  const sourceRelation = getSourceRelation(throughRelation, source);
354
354
  const sourceQuery = sourceRelation.joinQuery(throughRelation.query, sourceRelation.query).as(relationName);
355
355
  const whereExistsCallback = () => sourceQuery;
356
356
  return {
357
357
  returns: "one",
358
358
  method: (params) => {
359
- const throughQuery = model[through](params);
359
+ const throughQuery = table[through](params);
360
360
  return query.whereExists(
361
361
  throughQuery,
362
362
  whereExistsCallback
@@ -538,10 +538,10 @@ class HasManyVirtualColumn extends VirtualColumn {
538
538
  );
539
539
  }
540
540
  }
541
- const makeHasManyMethod = (model, relation, relationName, query) => {
541
+ const makeHasManyMethod = (table, relation, relationName, query) => {
542
542
  if ("through" in relation.options) {
543
543
  const { through, source } = relation.options;
544
- const throughRelation = getThroughRelation(model, through);
544
+ const throughRelation = getThroughRelation(table, through);
545
545
  const sourceRelation = getSourceRelation(throughRelation, source);
546
546
  const sourceRelationQuery = sourceRelation.query.as(relationName);
547
547
  const sourceQuery = sourceRelation.joinQuery(
@@ -552,7 +552,7 @@ const makeHasManyMethod = (model, relation, relationName, query) => {
552
552
  return {
553
553
  returns: "many",
554
554
  method: (params) => {
555
- const throughQuery = model[through](params);
555
+ const throughQuery = table[through](params);
556
556
  return query.whereExists(
557
557
  throughQuery,
558
558
  whereExistsCallback
@@ -784,7 +784,7 @@ class HasAndBelongsToManyVirtualColumn extends VirtualColumn {
784
784
  );
785
785
  }
786
786
  }
787
- const makeHasAndBelongsToManyMethod = (model, qb, relation, relationName, query) => {
787
+ const makeHasAndBelongsToManyMethod = (table, qb, relation, relationName, query) => {
788
788
  const {
789
789
  primaryKey: pk,
790
790
  foreignKey: fk,
@@ -795,14 +795,14 @@ const makeHasAndBelongsToManyMethod = (model, qb, relation, relationName, query)
795
795
  const foreignKeyFull = `${joinTable}.${fk}`;
796
796
  const associationForeignKeyFull = `${joinTable}.${afk}`;
797
797
  const associationPrimaryKeyFull = `${getQueryAs(query)}.${apk}`;
798
- const __model = Object.create(qb.__model);
799
- __model.__model = __model;
800
- __model.table = joinTable;
801
- __model.shape = {
802
- [fk]: model.shape[pk],
798
+ const __table = Object.create(qb.__table);
799
+ __table.__table = __table;
800
+ __table.table = joinTable;
801
+ __table.shape = {
802
+ [fk]: table.shape[pk],
803
803
  [afk]: query.shape[apk]
804
804
  };
805
- const subQuery = Object.create(__model);
805
+ const subQuery = Object.create(__table);
806
806
  subQuery.query = __spreadValues$2({}, subQuery.query);
807
807
  const state = {
808
808
  relatedTableQuery: query,
@@ -1052,38 +1052,40 @@ const nestedUpdate = (state) => {
1052
1052
  };
1053
1053
  };
1054
1054
 
1055
- const applyRelations = (qb, models, result) => {
1056
- const modelsEntries = Object.entries(models);
1055
+ const applyRelations = (qb, tables, result) => {
1056
+ const tableEntries = Object.entries(tables);
1057
1057
  const delayedRelations = /* @__PURE__ */ new Map();
1058
- for (const modelName in models) {
1059
- const model = models[modelName];
1060
- if (!("relations" in model) || typeof model.relations !== "object")
1058
+ for (const name in tables) {
1059
+ const table = tables[name];
1060
+ if (!("relations" in table) || typeof table.relations !== "object")
1061
1061
  continue;
1062
- const dbModel = result[modelName];
1063
- for (const relationName in model.relations) {
1064
- const relation = model.relations[relationName];
1065
- const otherModelClass = relation.fn();
1066
- const otherModel = modelsEntries.find(
1067
- (pair) => pair[1] instanceof otherModelClass
1062
+ const dbTable = result[name];
1063
+ for (const relationName in table.relations) {
1064
+ const relation = table.relations[relationName];
1065
+ const otherTableClass = relation.fn();
1066
+ const otherTable = tableEntries.find(
1067
+ (pair) => pair[1] instanceof otherTableClass
1068
1068
  );
1069
- if (!otherModel) {
1070
- throw new Error(`Cannot find model for class ${otherModelClass.name}`);
1069
+ if (!otherTable) {
1070
+ throw new Error(
1071
+ `Cannot find table class for class ${otherTableClass.name}`
1072
+ );
1071
1073
  }
1072
- const otherModelName = otherModel[0];
1073
- const otherDbModel = result[otherModelName];
1074
- if (!otherDbModel)
1075
- throw new Error(`Cannot find model by name ${otherModelName}`);
1074
+ const otherTableName = otherTable[0];
1075
+ const otherDbTable = result[otherTableName];
1076
+ if (!otherDbTable)
1077
+ throw new Error(`Cannot find table class by name ${otherTableName}`);
1076
1078
  const data = {
1077
1079
  relationName,
1078
1080
  relation,
1079
- dbModel,
1080
- otherDbModel
1081
+ dbTable,
1082
+ otherDbTable
1081
1083
  };
1082
1084
  const options = relation.options;
1083
1085
  if (typeof options.through === "string" && typeof options.source === "string") {
1084
- const throughRelation = getThroughRelation(dbModel, options.through);
1086
+ const throughRelation = getThroughRelation(dbTable, options.through);
1085
1087
  if (!throughRelation) {
1086
- delayRelation(delayedRelations, dbModel, options.through, data);
1088
+ delayRelation(delayedRelations, dbTable, options.through, data);
1087
1089
  continue;
1088
1090
  }
1089
1091
  const sourceRelation = getSourceRelation(
@@ -1093,7 +1095,7 @@ const applyRelations = (qb, models, result) => {
1093
1095
  if (!sourceRelation) {
1094
1096
  delayRelation(
1095
1097
  delayedRelations,
1096
- throughRelation.model,
1098
+ throughRelation.table,
1097
1099
  options.source,
1098
1100
  data
1099
1101
  );
@@ -1108,42 +1110,42 @@ const applyRelations = (qb, models, result) => {
1108
1110
  for (const key in value) {
1109
1111
  for (const item of value[key]) {
1110
1112
  const { relation } = item;
1111
- if (item.dbModel.relations[item.relationName])
1113
+ if (item.dbTable.relations[item.relationName])
1112
1114
  continue;
1113
- const as = item.dbModel.definedAs;
1115
+ const as = item.dbTable.definedAs;
1114
1116
  let message = `Cannot define a \`${item.relationName}\` relation on \`${as}\``;
1115
- const model = result[as];
1117
+ const table = result[as];
1116
1118
  const { through, source } = relation.options;
1117
- const throughRel = model.relations[through];
1119
+ const throughRel = table.relations[through];
1118
1120
  if (through && !throughRel) {
1119
1121
  message += `: cannot find \`${through}\` relation required by the \`through\` option`;
1120
- } else if (source && throughRel && !throughRel.model.relations[source]) {
1121
- message += `: cannot find \`${source}\` relation in \`${throughRel.model.definedAs}\` required by the \`source\` option`;
1122
+ } else if (source && throughRel && !throughRel.table.relations[source]) {
1123
+ message += `: cannot find \`${source}\` relation in \`${throughRel.table.definedAs}\` required by the \`source\` option`;
1122
1124
  }
1123
1125
  throw new Error(message);
1124
1126
  }
1125
1127
  }
1126
1128
  }
1127
1129
  };
1128
- const delayRelation = (delayedRelations, model, relationName, data) => {
1129
- let modelRelations = delayedRelations.get(model);
1130
- if (!modelRelations) {
1131
- modelRelations = {};
1132
- delayedRelations.set(model, modelRelations);
1130
+ const delayRelation = (delayedRelations, table, relationName, data) => {
1131
+ let tableRelations = delayedRelations.get(table);
1132
+ if (!tableRelations) {
1133
+ tableRelations = {};
1134
+ delayedRelations.set(table, tableRelations);
1133
1135
  }
1134
- if (modelRelations[relationName]) {
1135
- modelRelations[relationName].push(data);
1136
+ if (tableRelations[relationName]) {
1137
+ tableRelations[relationName].push(data);
1136
1138
  } else {
1137
- modelRelations[relationName] = [data];
1139
+ tableRelations[relationName] = [data];
1138
1140
  }
1139
1141
  };
1140
- const applyRelation = (qb, { relationName, relation, dbModel, otherDbModel }, delayedRelations) => {
1142
+ const applyRelation = (qb, { relationName, relation, dbTable, otherDbTable }, delayedRelations) => {
1141
1143
  var _a;
1142
- const query = (relation.options.scope ? relation.options.scope(otherDbModel) : otherDbModel).as(relationName);
1144
+ const query = (relation.options.scope ? relation.options.scope(otherDbTable) : otherDbTable).as(relationName);
1143
1145
  const definedAs = query.definedAs;
1144
1146
  if (!definedAs) {
1145
1147
  throw new Error(
1146
- `Model for table ${query.table} is not attached to db instance`
1148
+ `Table class for table ${query.table} is not attached to db instance`
1147
1149
  );
1148
1150
  }
1149
1151
  const { type } = relation;
@@ -1151,12 +1153,12 @@ const applyRelation = (qb, { relationName, relation, dbModel, otherDbModel }, de
1151
1153
  if (type === "belongsTo") {
1152
1154
  data = makeBelongsToMethod(relation, relationName, query);
1153
1155
  } else if (type === "hasOne") {
1154
- data = makeHasOneMethod(dbModel, relation, relationName, query);
1156
+ data = makeHasOneMethod(dbTable, relation, relationName, query);
1155
1157
  } else if (type === "hasMany") {
1156
- data = makeHasManyMethod(dbModel, relation, relationName, query);
1158
+ data = makeHasManyMethod(dbTable, relation, relationName, query);
1157
1159
  } else if (type === "hasAndBelongsToMany") {
1158
1160
  data = makeHasAndBelongsToManyMethod(
1159
- dbModel,
1161
+ dbTable,
1160
1162
  qb,
1161
1163
  relation,
1162
1164
  relationName,
@@ -1169,38 +1171,38 @@ const applyRelation = (qb, { relationName, relation, dbModel, otherDbModel }, de
1169
1171
  query._take();
1170
1172
  }
1171
1173
  if (data.virtualColumn) {
1172
- dbModel.shape[relationName] = data.virtualColumn;
1174
+ dbTable.shape[relationName] = data.virtualColumn;
1173
1175
  }
1174
- makeRelationQuery(dbModel, definedAs, relationName, data);
1175
- dbModel.relations[relationName] = {
1176
+ makeRelationQuery(dbTable, definedAs, relationName, data);
1177
+ dbTable.relations[relationName] = {
1176
1178
  type,
1177
1179
  key: relationName,
1178
- model: otherDbModel,
1180
+ table: otherDbTable,
1179
1181
  query,
1180
1182
  joinQuery: data.joinQuery,
1181
1183
  primaryKey: data.primaryKey,
1182
1184
  options: relation.options
1183
1185
  };
1184
- const modelRelations = delayedRelations.get(dbModel);
1185
- if (!modelRelations)
1186
+ const tableRelations = delayedRelations.get(dbTable);
1187
+ if (!tableRelations)
1186
1188
  return;
1187
- (_a = modelRelations[relationName]) == null ? void 0 : _a.forEach((data2) => {
1189
+ (_a = tableRelations[relationName]) == null ? void 0 : _a.forEach((data2) => {
1188
1190
  applyRelation(qb, data2, delayedRelations);
1189
1191
  });
1190
1192
  };
1191
- const makeRelationQuery = (model, definedAs, relationName, data) => {
1192
- Object.defineProperty(model, relationName, {
1193
+ const makeRelationQuery = (table, definedAs, relationName, data) => {
1194
+ Object.defineProperty(table, relationName, {
1193
1195
  get() {
1194
1196
  var _a;
1195
- const toModel = this.db[definedAs].as(relationName);
1197
+ const toTable = this.db[definedAs].as(relationName);
1196
1198
  if (data.returns === "one") {
1197
- toModel._take();
1199
+ toTable._take();
1198
1200
  }
1199
- const query = this.isSubQuery ? toModel : toModel._whereExists(data.reverseJoin(this, toModel), (q) => q);
1201
+ const query = this.isSubQuery ? toTable : toTable._whereExists(data.reverseJoin(this, toTable), (q) => q);
1200
1202
  query.query[relationQueryKey] = {
1201
1203
  relationName,
1202
1204
  sourceQuery: this,
1203
- relationQuery: toModel,
1205
+ relationQuery: toTable,
1204
1206
  joinQuery: data.joinQuery
1205
1207
  };
1206
1208
  const setQuery = (_a = data.modifyRelatedQuery) == null ? void 0 : _a.call(data, query);
@@ -1223,10 +1225,10 @@ function transaction(fn) {
1223
1225
  for (const key in this) {
1224
1226
  const value = this[key];
1225
1227
  if (value instanceof Db) {
1226
- const model = value.transacting(q);
1227
- model.__model = model;
1228
- model.db = orm;
1229
- orm[key] = model;
1228
+ const table = value.transacting(q);
1229
+ table.__table = table;
1230
+ table.db = orm;
1231
+ orm[key] = table;
1230
1232
  } else {
1231
1233
  orm[key] = value;
1232
1234
  }
@@ -1266,7 +1268,7 @@ var __objRest = (source, exclude) => {
1266
1268
  }
1267
1269
  return target;
1268
1270
  };
1269
- const orchidORM = (_a, models) => {
1271
+ const orchidORM = (_a, tables) => {
1270
1272
  var _b = _a, {
1271
1273
  log,
1272
1274
  logger,
@@ -1300,31 +1302,31 @@ const orchidORM = (_a, models) => {
1300
1302
  $queryBuilder: qb,
1301
1303
  $close: () => adapter.close()
1302
1304
  };
1303
- const modelInstances = {};
1304
- for (const key in models) {
1305
+ const tableInstances = {};
1306
+ for (const key in tables) {
1305
1307
  if (key[0] === "$") {
1306
- throw new Error(`Model name must not start with $`);
1308
+ throw new Error(`Table class name must not start with $`);
1307
1309
  }
1308
- const model = new models[key]();
1309
- modelInstances[key] = model;
1310
+ const table = new tables[key]();
1311
+ tableInstances[key] = table;
1310
1312
  const options2 = __spreadProps(__spreadValues$1({}, commonOptions), {
1311
- schema: model.schema
1313
+ schema: table.schema
1312
1314
  });
1313
- if (model.noPrimaryKey)
1315
+ if (table.noPrimaryKey)
1314
1316
  options2.noPrimaryKey = "ignore";
1315
- const dbModel = new Db(
1317
+ const dbTable = new Db(
1316
1318
  adapter,
1317
1319
  qb,
1318
- model.table,
1319
- model.columns.shape,
1320
- model.columnTypes,
1320
+ table.table,
1321
+ table.columns.shape,
1322
+ table.columnTypes,
1321
1323
  options2
1322
1324
  );
1323
- dbModel.definedAs = key;
1324
- dbModel.db = result;
1325
- result[key] = dbModel;
1325
+ dbTable.definedAs = key;
1326
+ dbTable.db = result;
1327
+ result[key] = dbTable;
1326
1328
  }
1327
- applyRelations(qb, modelInstances, result);
1329
+ applyRelations(qb, tableInstances, result);
1328
1330
  return result;
1329
1331
  };
1330
1332
 
@@ -1344,26 +1346,26 @@ var __spreadValues = (a, b) => {
1344
1346
  }
1345
1347
  return a;
1346
1348
  };
1347
- const createRepo = (model, methods) => {
1349
+ const createRepo = (table, methods) => {
1348
1350
  const queryMethods = __spreadValues(__spreadValues(__spreadValues(__spreadValues({}, methods.queryMethods), methods.queryOneMethods), methods.queryWithWhereMethods), methods.queryOneWithWhereMethods);
1349
1351
  const plainMethods = methods.methods;
1350
1352
  const repo = (q2) => {
1351
- const proto = Object.create(q2.__model);
1352
- proto.__model = proto;
1353
+ const proto = Object.create(q2.__table);
1354
+ proto.__table = proto;
1353
1355
  const result = Object.create(proto);
1354
1356
  result.query = getClonedQueryData(q2.query);
1355
1357
  if (plainMethods) {
1356
- Object.assign(proto.__model, plainMethods);
1358
+ Object.assign(proto.__table, plainMethods);
1357
1359
  }
1358
1360
  for (const key in queryMethods) {
1359
1361
  const method = queryMethods[key];
1360
- proto.__model[key] = function(...args) {
1362
+ proto.__table[key] = function(...args) {
1361
1363
  return method(this, ...args);
1362
1364
  };
1363
1365
  }
1364
1366
  return result;
1365
1367
  };
1366
- const q = repo(model);
1368
+ const q = repo(table);
1367
1369
  return new Proxy(repo, {
1368
1370
  get(_, key) {
1369
1371
  return q[key];
@@ -1371,5 +1373,5 @@ const createRepo = (model, methods) => {
1371
1373
  });
1372
1374
  };
1373
1375
 
1374
- export { createModel, createRepo, orchidORM };
1376
+ export { createBaseTable, createRepo, orchidORM };
1375
1377
  //# sourceMappingURL=index.esm.js.map