@guren/orm 0.1.1-alpha.5 → 0.2.0-alpha.7
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.
- package/dist/index.d.ts +104 -15
- package/dist/index.js +251 -5
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -2,41 +2,132 @@ import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
|
|
|
2
2
|
import postgres from 'postgres';
|
|
3
3
|
|
|
4
4
|
type PlainObject = Record<string, unknown>;
|
|
5
|
-
type
|
|
5
|
+
type RelationShape = Record<string, unknown>;
|
|
6
|
+
type WhereValue<Value> = Value | readonly Value[] | null;
|
|
7
|
+
type WhereClause<TRecord extends PlainObject = PlainObject> = Partial<{
|
|
8
|
+
[K in keyof TRecord & string]?: WhereValue<TRecord[K]>;
|
|
9
|
+
}>;
|
|
10
|
+
type OrderDirection = 'asc' | 'desc';
|
|
11
|
+
type OrderDefinition<TRecord extends PlainObject = PlainObject> = {
|
|
12
|
+
column: keyof TRecord & string;
|
|
13
|
+
direction: OrderDirection;
|
|
14
|
+
};
|
|
15
|
+
type OrderExpression<TRecord extends PlainObject = PlainObject> = (keyof TRecord & string) | readonly [keyof TRecord & string, OrderDirection] | {
|
|
16
|
+
column: keyof TRecord & string;
|
|
17
|
+
direction?: OrderDirection;
|
|
18
|
+
};
|
|
19
|
+
type OrderByInput<TRecord extends PlainObject = PlainObject> = OrderExpression<TRecord> | readonly OrderExpression<TRecord>[];
|
|
20
|
+
type OrderByClause<TRecord extends PlainObject = PlainObject> = readonly OrderDefinition<TRecord>[];
|
|
21
|
+
interface FindManyOptions<TRecord extends PlainObject = PlainObject> {
|
|
22
|
+
where?: WhereClause<TRecord>;
|
|
23
|
+
orderBy?: OrderByClause<TRecord>;
|
|
24
|
+
limit?: number;
|
|
25
|
+
offset?: number;
|
|
26
|
+
}
|
|
27
|
+
interface PaginateOptions<TRecord extends PlainObject = PlainObject> {
|
|
28
|
+
page?: number;
|
|
29
|
+
perPage?: number;
|
|
30
|
+
where?: WhereClause<TRecord>;
|
|
31
|
+
orderBy?: OrderByInput<TRecord>;
|
|
32
|
+
}
|
|
33
|
+
interface PaginationMeta {
|
|
34
|
+
total: number;
|
|
35
|
+
perPage: number;
|
|
36
|
+
currentPage: number;
|
|
37
|
+
totalPages: number;
|
|
38
|
+
hasMore: boolean;
|
|
39
|
+
from: number;
|
|
40
|
+
to: number;
|
|
41
|
+
}
|
|
42
|
+
interface PaginatedResult<TRecord extends PlainObject = PlainObject> {
|
|
43
|
+
data: TRecord[];
|
|
44
|
+
meta: PaginationMeta;
|
|
45
|
+
}
|
|
6
46
|
interface ORMAdapter {
|
|
7
|
-
findMany<TRecord = PlainObject>(table: unknown,
|
|
8
|
-
findUnique<TRecord = PlainObject>(table: unknown, where: WhereClause): Promise<TRecord | null>;
|
|
9
|
-
create<TRecord = PlainObject>(table: unknown, data: PlainObject): Promise<TRecord>;
|
|
10
|
-
update?<TRecord = PlainObject>(table: unknown, where: WhereClause
|
|
11
|
-
delete?<TRecord = PlainObject>(table: unknown, where: WhereClause): Promise<number | PlainObject | void>;
|
|
47
|
+
findMany<TRecord extends PlainObject = PlainObject>(table: unknown, options?: FindManyOptions<TRecord>): Promise<TRecord[]>;
|
|
48
|
+
findUnique<TRecord extends PlainObject = PlainObject>(table: unknown, where: WhereClause<TRecord>): Promise<TRecord | null>;
|
|
49
|
+
create<TRecord extends PlainObject = PlainObject>(table: unknown, data: PlainObject): Promise<TRecord>;
|
|
50
|
+
update?<TRecord extends PlainObject = PlainObject>(table: unknown, where: WhereClause<TRecord>, data: PlainObject): Promise<TRecord>;
|
|
51
|
+
delete?<TRecord extends PlainObject = PlainObject>(table: unknown, where: WhereClause<TRecord>): Promise<number | PlainObject | void>;
|
|
52
|
+
count?<TRecord extends PlainObject = PlainObject>(table: unknown, where?: WhereClause<TRecord>): Promise<number>;
|
|
12
53
|
}
|
|
13
54
|
/**
|
|
14
55
|
* Minimal ActiveRecord-like wrapper around the configured ORM adapter. The API
|
|
15
56
|
* mirrors a subset of Laravel's Eloquent helpers and can be expanded over time.
|
|
16
57
|
*/
|
|
17
|
-
declare abstract class Model<TRecord extends
|
|
58
|
+
declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
18
59
|
protected static ormAdapter: ORMAdapter;
|
|
19
60
|
protected static table: unknown;
|
|
20
61
|
static readonly recordType: unknown;
|
|
62
|
+
protected static relationDefinitions?: Map<string, RelationDefinition>;
|
|
63
|
+
static relationTypes: RelationShape;
|
|
21
64
|
static useAdapter(adapter: ORMAdapter): void;
|
|
22
65
|
static getAdapter(): ORMAdapter;
|
|
66
|
+
protected static preparePersistencePayload(data: PlainObject): Promise<PlainObject>;
|
|
67
|
+
protected static getRelationDefinitions(): Map<string, RelationDefinition>;
|
|
68
|
+
protected static getRelationDefinition(name: string): RelationDefinition | undefined;
|
|
23
69
|
protected static resolveTable(): unknown;
|
|
24
70
|
static all<T extends typeof Model>(this: T): Promise<Array<TRecordFor<T>>>;
|
|
25
71
|
static find<T extends typeof Model>(this: T, id: unknown, key?: string): Promise<TRecordFor<T> | null>;
|
|
26
|
-
static where<T extends typeof Model>(this: T, where:
|
|
72
|
+
static where<T extends typeof Model>(this: T, where: WhereClauseFor<T>): Promise<TRecordFor<T>[]>;
|
|
73
|
+
static hasMany<This extends typeof Model, Related extends typeof Model, ForeignKey extends keyof TRecordFor<Related> & string, LocalKey extends keyof TRecordFor<This> & string, Name extends RelationKeyOrString<This>>(this: This, name: Name, related: Related, foreignKey: ForeignKey, localKey: LocalKey): void;
|
|
74
|
+
static belongsTo<This extends typeof Model, Related extends typeof Model, ForeignKey extends keyof TRecordFor<This> & string, OwnerKey extends keyof TRecordFor<Related> & string, Name extends RelationKeyOrString<This>>(this: This, name: Name, related: Related, foreignKey: ForeignKey, ownerKey: OwnerKey): void;
|
|
75
|
+
static orderBy<T extends typeof Model>(this: T, order: OrderByInput<TRecordFor<T>>, where?: WhereClauseFor<T>): Promise<TRecordFor<T>[]>;
|
|
76
|
+
static paginate<T extends typeof Model>(this: T, options?: PaginateOptions<TRecordFor<T>>): Promise<PaginatedResult<TRecordFor<T>>>;
|
|
77
|
+
static withPaginate<T extends typeof Model, K extends RelationKey<T>>(this: T, relations: K | readonly K[], options?: PaginateOptions<TRecordFor<T>>): Promise<PaginatedResult<TRecordFor<T> & RelationTypePick<T, K | readonly K[]>>>;
|
|
27
78
|
static create<T extends typeof Model>(this: T, data: PlainObject): Promise<TRecordFor<T>>;
|
|
28
|
-
static update<T extends typeof Model>(this: T, where:
|
|
29
|
-
static delete<T extends typeof Model>(this: T, where:
|
|
79
|
+
static update<T extends typeof Model>(this: T, where: WhereClauseFor<T>, data: PlainObject): Promise<TRecordFor<T>>;
|
|
80
|
+
static delete<T extends typeof Model>(this: T, where: WhereClauseFor<T>): Promise<number | PlainObject | void>;
|
|
81
|
+
static with<T extends typeof Model, K extends RelationKey<T>>(this: T, relations: K | readonly K[], where?: WhereClauseFor<T>): Promise<Array<TRecordFor<T> & RelationTypePick<T, K | readonly K[]>>>;
|
|
82
|
+
protected static loadRelationInto<T extends typeof Model>(this: T, records: Array<PlainObject>, relationName: string): Promise<void>;
|
|
83
|
+
protected static loadHasMany(records: Array<PlainObject>, definition: HasManyRelationDefinition): Promise<void>;
|
|
84
|
+
protected static loadBelongsTo(records: Array<PlainObject>, definition: BelongsToRelationDefinition): Promise<void>;
|
|
30
85
|
}
|
|
31
86
|
type TRecordFor<T extends typeof Model> = T extends {
|
|
32
87
|
recordType: infer R;
|
|
33
|
-
} ? R extends
|
|
88
|
+
} ? R extends PlainObject ? R : PlainObject : PlainObject;
|
|
89
|
+
type WhereClauseFor<T extends typeof Model> = WhereClause<TRecordFor<T>>;
|
|
90
|
+
type RelationTypesFor<T extends typeof Model> = T extends {
|
|
91
|
+
relationTypes: infer R;
|
|
92
|
+
} ? R extends RelationShape ? R : {} : {};
|
|
93
|
+
type RelationKey<T extends typeof Model> = keyof RelationTypesFor<T> & string;
|
|
94
|
+
type RelationKeyOrString<T extends typeof Model> = RelationKey<T> extends never ? string : RelationKey<T>;
|
|
95
|
+
type RelationNameUnion<Names> = Names extends readonly (infer Items)[] ? Items : Names;
|
|
96
|
+
type RelationTypePick<T extends typeof Model, Names> = RelationNameUnion<Names> extends infer Keys ? Keys extends string ? {
|
|
97
|
+
[K in Keys & keyof RelationTypesFor<T>]: RelationTypesFor<T>[K];
|
|
98
|
+
} : {} : {};
|
|
99
|
+
interface BaseRelationDefinition {
|
|
100
|
+
type: 'hasMany' | 'belongsTo';
|
|
101
|
+
name: string;
|
|
102
|
+
related: typeof Model;
|
|
103
|
+
}
|
|
104
|
+
interface HasManyRelationDefinition extends BaseRelationDefinition {
|
|
105
|
+
type: 'hasMany';
|
|
106
|
+
foreignKey: string;
|
|
107
|
+
localKey: string;
|
|
108
|
+
}
|
|
109
|
+
interface BelongsToRelationDefinition extends BaseRelationDefinition {
|
|
110
|
+
type: 'belongsTo';
|
|
111
|
+
foreignKey: string;
|
|
112
|
+
ownerKey: string;
|
|
113
|
+
}
|
|
114
|
+
type RelationDefinition = HasManyRelationDefinition | BelongsToRelationDefinition;
|
|
115
|
+
type HasManyRelationResult<T extends typeof Model> = Array<TRecordFor<T>>;
|
|
116
|
+
type BelongsToRelationResult<T extends typeof Model> = TRecordFor<T> | null;
|
|
117
|
+
type HasManyRecord<TRecord extends PlainObject> = TRecord[];
|
|
118
|
+
type BelongsToRecord<TRecord extends PlainObject> = TRecord | null;
|
|
34
119
|
|
|
35
120
|
type DrizzleLikeSelect = {
|
|
36
121
|
where?: (clause: unknown) => DrizzleLikeSelect;
|
|
122
|
+
orderBy?: (...clauses: unknown[]) => DrizzleLikeSelect;
|
|
123
|
+
limit?: (value: number) => DrizzleLikeSelect;
|
|
124
|
+
offset?: (value: number) => DrizzleLikeSelect;
|
|
37
125
|
all?: () => Promise<unknown[]>;
|
|
38
126
|
get?: () => Promise<unknown>;
|
|
39
127
|
};
|
|
128
|
+
type DrizzleSelectBuilder = DrizzleLikeSelect & {
|
|
129
|
+
from(table: unknown): DrizzleLikeSelect;
|
|
130
|
+
};
|
|
40
131
|
type DrizzleLikeInsert = {
|
|
41
132
|
values: (record: PlainObject) => DrizzleLikeInsertResult;
|
|
42
133
|
};
|
|
@@ -55,9 +146,7 @@ type DrizzleLikeDelete = {
|
|
|
55
146
|
run?: () => Promise<unknown>;
|
|
56
147
|
};
|
|
57
148
|
type DrizzleDatabase = {
|
|
58
|
-
select():
|
|
59
|
-
from(table: unknown): DrizzleLikeSelect;
|
|
60
|
-
};
|
|
149
|
+
select(selection?: Record<string, unknown>): DrizzleSelectBuilder;
|
|
61
150
|
insert(table: unknown): DrizzleLikeInsert;
|
|
62
151
|
update?(table: unknown): DrizzleLikeUpdate;
|
|
63
152
|
delete?(table: unknown): DrizzleLikeDelete;
|
|
@@ -91,4 +180,4 @@ declare function loadSeeders<TSchema extends Record<string, unknown>>(directory:
|
|
|
91
180
|
declare function runSeeders<TSchema extends Record<string, unknown>>(db: PostgresJsDatabase<TSchema>, directory: string | URL): Promise<void>;
|
|
92
181
|
declare function defineSeeder<TSchema extends Record<string, unknown>>(handler: SeederHandler<TSchema>): SeederHandler<TSchema>;
|
|
93
182
|
|
|
94
|
-
export { DrizzleAdapter, Model, type ORMAdapter, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, type SeederContext, type SeederHandler, type WhereClause, createPostgresDatabase, defineSeeder, loadSeeders, runSeeders };
|
|
183
|
+
export { type BelongsToRecord, type BelongsToRelationResult, DrizzleAdapter, type FindManyOptions, type HasManyRecord, type HasManyRelationResult, Model, type ORMAdapter, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type PaginateOptions, type PaginatedResult, type PaginationMeta, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, type SeederContext, type SeederHandler, type WhereClause, createPostgresDatabase, defineSeeder, loadSeeders, runSeeders };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/adapters/drizzle-adapter.ts
|
|
2
|
-
import { and, eq, inArray, isNull } from "drizzle-orm";
|
|
2
|
+
import { and, asc, count, desc, eq, inArray, isNull } from "drizzle-orm";
|
|
3
3
|
var database;
|
|
4
4
|
function ensureDatabase() {
|
|
5
5
|
if (!database) {
|
|
@@ -46,6 +46,19 @@ function resolveWhere(table, where) {
|
|
|
46
46
|
}
|
|
47
47
|
return and(...clauses);
|
|
48
48
|
}
|
|
49
|
+
function resolveOrder(table, orderBy) {
|
|
50
|
+
if (!orderBy || orderBy.length === 0) {
|
|
51
|
+
return void 0;
|
|
52
|
+
}
|
|
53
|
+
const tableRecord = table;
|
|
54
|
+
return orderBy.map(({ column, direction }) => {
|
|
55
|
+
const columnRef = tableRecord[column];
|
|
56
|
+
if (!columnRef) {
|
|
57
|
+
throw new Error(`DrizzleAdapter: unknown column "${column}" on provided table.`);
|
|
58
|
+
}
|
|
59
|
+
return direction === "desc" ? desc(columnRef) : asc(columnRef);
|
|
60
|
+
});
|
|
61
|
+
}
|
|
49
62
|
async function resolveSingle(result) {
|
|
50
63
|
if (isPromiseLike(result)) {
|
|
51
64
|
const list = await result ?? [];
|
|
@@ -81,18 +94,46 @@ var DrizzleAdapter = {
|
|
|
81
94
|
configure(db) {
|
|
82
95
|
database = db;
|
|
83
96
|
},
|
|
84
|
-
async findMany(table,
|
|
97
|
+
async findMany(table, options) {
|
|
85
98
|
const db = ensureDatabase();
|
|
86
99
|
let query = db.select().from(table);
|
|
100
|
+
const { where, orderBy, limit, offset } = options ?? {};
|
|
87
101
|
if (typeof query.where === "function") {
|
|
88
102
|
const clause = resolveWhere(table, where);
|
|
89
103
|
if (clause) {
|
|
90
104
|
query = query.where(clause);
|
|
91
105
|
}
|
|
92
106
|
}
|
|
107
|
+
if (typeof query.orderBy === "function") {
|
|
108
|
+
const clauses = resolveOrder(table, orderBy);
|
|
109
|
+
if (clauses && clauses.length > 0) {
|
|
110
|
+
query = query.orderBy(...clauses);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
if (typeof query.limit === "function" && typeof limit === "number") {
|
|
114
|
+
query = query.limit(limit);
|
|
115
|
+
}
|
|
116
|
+
if (typeof query.offset === "function" && typeof offset === "number") {
|
|
117
|
+
query = query.offset(offset);
|
|
118
|
+
}
|
|
93
119
|
const rows = await resolveList(query);
|
|
94
120
|
return rows;
|
|
95
121
|
},
|
|
122
|
+
async count(table, where) {
|
|
123
|
+
const db = ensureDatabase();
|
|
124
|
+
let query = db.select({ value: count() }).from(table);
|
|
125
|
+
if (typeof query.where === "function") {
|
|
126
|
+
const clause = resolveWhere(table, where);
|
|
127
|
+
if (clause) {
|
|
128
|
+
query = query.where(clause);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
const rows = await resolveList(query);
|
|
132
|
+
const first = rows[0];
|
|
133
|
+
const raw = first?.value ?? 0;
|
|
134
|
+
const total = typeof raw === "bigint" ? Number(raw) : Number(raw);
|
|
135
|
+
return Number.isNaN(total) ? 0 : total;
|
|
136
|
+
},
|
|
96
137
|
async findUnique(table, where) {
|
|
97
138
|
const db = ensureDatabase();
|
|
98
139
|
let query = db.select().from(table);
|
|
@@ -136,16 +177,31 @@ var DrizzleAdapter = {
|
|
|
136
177
|
};
|
|
137
178
|
|
|
138
179
|
// src/Model.ts
|
|
180
|
+
var DEFAULT_PAGINATION_SIZE = 15;
|
|
139
181
|
var Model = class {
|
|
140
182
|
static ormAdapter = DrizzleAdapter;
|
|
141
183
|
static table;
|
|
142
184
|
static recordType = void 0;
|
|
185
|
+
static relationDefinitions;
|
|
186
|
+
static relationTypes = {};
|
|
143
187
|
static useAdapter(adapter) {
|
|
144
188
|
this.ormAdapter = adapter;
|
|
145
189
|
}
|
|
146
190
|
static getAdapter() {
|
|
147
191
|
return this.ormAdapter;
|
|
148
192
|
}
|
|
193
|
+
static async preparePersistencePayload(data) {
|
|
194
|
+
return { ...data };
|
|
195
|
+
}
|
|
196
|
+
static getRelationDefinitions() {
|
|
197
|
+
if (!Object.prototype.hasOwnProperty.call(this, "relationDefinitions") || !this.relationDefinitions) {
|
|
198
|
+
this.relationDefinitions = /* @__PURE__ */ new Map();
|
|
199
|
+
}
|
|
200
|
+
return this.relationDefinitions;
|
|
201
|
+
}
|
|
202
|
+
static getRelationDefinition(name) {
|
|
203
|
+
return this.getRelationDefinitions().get(name);
|
|
204
|
+
}
|
|
149
205
|
static resolveTable() {
|
|
150
206
|
if (!this.table) {
|
|
151
207
|
throw new Error(`${this.name}.table must be defined before using the model.`);
|
|
@@ -163,11 +219,94 @@ var Model = class {
|
|
|
163
219
|
}
|
|
164
220
|
static async where(where) {
|
|
165
221
|
const table = this.resolveTable();
|
|
166
|
-
return this.getAdapter().findMany(table, where);
|
|
222
|
+
return this.getAdapter().findMany(table, { where });
|
|
223
|
+
}
|
|
224
|
+
static hasMany(name, related, foreignKey, localKey) {
|
|
225
|
+
const definitions = this.getRelationDefinitions();
|
|
226
|
+
definitions.set(name, {
|
|
227
|
+
type: "hasMany",
|
|
228
|
+
name,
|
|
229
|
+
related,
|
|
230
|
+
foreignKey,
|
|
231
|
+
localKey
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
static belongsTo(name, related, foreignKey, ownerKey) {
|
|
235
|
+
const definitions = this.getRelationDefinitions();
|
|
236
|
+
definitions.set(name, {
|
|
237
|
+
type: "belongsTo",
|
|
238
|
+
name,
|
|
239
|
+
related,
|
|
240
|
+
foreignKey,
|
|
241
|
+
ownerKey
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
static async orderBy(order, where) {
|
|
245
|
+
const table = this.resolveTable();
|
|
246
|
+
const orderBy = normalizeOrderBy(order);
|
|
247
|
+
const options = { orderBy };
|
|
248
|
+
if (where && Object.keys(where).length > 0) {
|
|
249
|
+
options.where = where;
|
|
250
|
+
}
|
|
251
|
+
return this.getAdapter().findMany(table, options);
|
|
252
|
+
}
|
|
253
|
+
static async paginate(options = {}) {
|
|
254
|
+
const table = this.resolveTable();
|
|
255
|
+
const adapter = this.getAdapter();
|
|
256
|
+
const requestedPage = typeof options.page === "number" ? options.page : 1;
|
|
257
|
+
const sanitizedPage = Number.isFinite(requestedPage) && requestedPage >= 1 ? Math.floor(requestedPage) : 1;
|
|
258
|
+
const requestedPerPage = typeof options.perPage === "number" ? options.perPage : DEFAULT_PAGINATION_SIZE;
|
|
259
|
+
const perPage = Number.isFinite(requestedPerPage) && requestedPerPage >= 1 ? Math.floor(requestedPerPage) : DEFAULT_PAGINATION_SIZE;
|
|
260
|
+
let total = 0;
|
|
261
|
+
if (typeof adapter.count === "function") {
|
|
262
|
+
total = await adapter.count(table, options.where);
|
|
263
|
+
} else {
|
|
264
|
+
const records = options.where ? await this.where(options.where) : await this.all();
|
|
265
|
+
total = records.length;
|
|
266
|
+
}
|
|
267
|
+
const totalPages = total === 0 ? 1 : Math.max(1, Math.ceil(total / perPage));
|
|
268
|
+
const currentPage = Math.min(sanitizedPage, totalPages);
|
|
269
|
+
const offset = (currentPage - 1) * perPage;
|
|
270
|
+
const orderByClause = options.orderBy ? normalizeOrderBy(options.orderBy) : void 0;
|
|
271
|
+
const findOptions = {
|
|
272
|
+
where: options.where,
|
|
273
|
+
orderBy: orderByClause,
|
|
274
|
+
limit: perPage,
|
|
275
|
+
offset
|
|
276
|
+
};
|
|
277
|
+
const data = await adapter.findMany(table, findOptions);
|
|
278
|
+
const from = total === 0 ? 0 : offset + 1;
|
|
279
|
+
const to = total === 0 ? 0 : offset + data.length;
|
|
280
|
+
const meta = {
|
|
281
|
+
total,
|
|
282
|
+
perPage,
|
|
283
|
+
currentPage,
|
|
284
|
+
totalPages,
|
|
285
|
+
hasMore: currentPage < totalPages,
|
|
286
|
+
from,
|
|
287
|
+
to: Math.min(to, total)
|
|
288
|
+
};
|
|
289
|
+
return { data, meta };
|
|
290
|
+
}
|
|
291
|
+
static async withPaginate(relations, options = {}) {
|
|
292
|
+
const result = await this.paginate(options);
|
|
293
|
+
const relationList = normalizeRelations(relations);
|
|
294
|
+
if (relationList.length === 0 || result.data.length === 0) {
|
|
295
|
+
return result;
|
|
296
|
+
}
|
|
297
|
+
const records = result.data.map((record) => ({ ...record }));
|
|
298
|
+
for (const relationName of relationList) {
|
|
299
|
+
await this.loadRelationInto(records, relationName);
|
|
300
|
+
}
|
|
301
|
+
return {
|
|
302
|
+
data: records,
|
|
303
|
+
meta: result.meta
|
|
304
|
+
};
|
|
167
305
|
}
|
|
168
306
|
static async create(data) {
|
|
169
307
|
const table = this.resolveTable();
|
|
170
|
-
|
|
308
|
+
const payload = await this.preparePersistencePayload(data);
|
|
309
|
+
return this.getAdapter().create(table, payload);
|
|
171
310
|
}
|
|
172
311
|
static async update(where, data) {
|
|
173
312
|
const table = this.resolveTable();
|
|
@@ -175,7 +314,8 @@ var Model = class {
|
|
|
175
314
|
if (!adapter.update) {
|
|
176
315
|
throw new Error("Configured adapter does not support update operations.");
|
|
177
316
|
}
|
|
178
|
-
|
|
317
|
+
const payload = await this.preparePersistencePayload(data);
|
|
318
|
+
return adapter.update(table, where, payload);
|
|
179
319
|
}
|
|
180
320
|
static async delete(where) {
|
|
181
321
|
const table = this.resolveTable();
|
|
@@ -185,7 +325,113 @@ var Model = class {
|
|
|
185
325
|
}
|
|
186
326
|
return adapter.delete(table, where);
|
|
187
327
|
}
|
|
328
|
+
static async with(relations, where) {
|
|
329
|
+
const records = where ? await this.where(where) : await this.all();
|
|
330
|
+
if (!records.length) {
|
|
331
|
+
return records;
|
|
332
|
+
}
|
|
333
|
+
const relationList = normalizeRelations(relations);
|
|
334
|
+
if (relationList.length === 0) {
|
|
335
|
+
return records;
|
|
336
|
+
}
|
|
337
|
+
const copies = records.map((record) => ({ ...record }));
|
|
338
|
+
for (const relationName of relationList) {
|
|
339
|
+
await this.loadRelationInto(copies, relationName);
|
|
340
|
+
}
|
|
341
|
+
return copies;
|
|
342
|
+
}
|
|
343
|
+
static async loadRelationInto(records, relationName) {
|
|
344
|
+
const definition = this.getRelationDefinition(relationName);
|
|
345
|
+
if (!definition) {
|
|
346
|
+
throw new Error(`${this.name}: unknown relation "${relationName}".`);
|
|
347
|
+
}
|
|
348
|
+
if (definition.type === "hasMany") {
|
|
349
|
+
await this.loadHasMany(records, definition);
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
if (definition.type === "belongsTo") {
|
|
353
|
+
await this.loadBelongsTo(records, definition);
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
static async loadHasMany(records, definition) {
|
|
358
|
+
const { related, foreignKey, localKey, name } = definition;
|
|
359
|
+
const ownerValues = Array.from(
|
|
360
|
+
new Set(records.map((record) => record[localKey]).filter((value) => value !== void 0 && value !== null))
|
|
361
|
+
);
|
|
362
|
+
if (ownerValues.length === 0) {
|
|
363
|
+
records.forEach((record) => {
|
|
364
|
+
record[name] = [];
|
|
365
|
+
});
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
const relatedRecords = await related.where({ [foreignKey]: ownerValues });
|
|
369
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
370
|
+
for (const item of relatedRecords) {
|
|
371
|
+
const key = item[foreignKey];
|
|
372
|
+
if (!grouped.has(key)) {
|
|
373
|
+
grouped.set(key, []);
|
|
374
|
+
}
|
|
375
|
+
grouped.get(key)?.push({ ...item });
|
|
376
|
+
}
|
|
377
|
+
records.forEach((record) => {
|
|
378
|
+
const key = record[localKey];
|
|
379
|
+
record[name] = grouped.get(key) ?? [];
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
static async loadBelongsTo(records, definition) {
|
|
383
|
+
const { related, foreignKey, ownerKey, name } = definition;
|
|
384
|
+
const foreignValues = Array.from(
|
|
385
|
+
new Set(records.map((record) => record[foreignKey]).filter((value) => value !== void 0 && value !== null))
|
|
386
|
+
);
|
|
387
|
+
if (foreignValues.length === 0) {
|
|
388
|
+
records.forEach((record) => {
|
|
389
|
+
record[name] = null;
|
|
390
|
+
});
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
const relatedRecords = await related.where({ [ownerKey]: foreignValues });
|
|
394
|
+
const index = /* @__PURE__ */ new Map();
|
|
395
|
+
for (const item of relatedRecords) {
|
|
396
|
+
index.set(item[ownerKey], { ...item });
|
|
397
|
+
}
|
|
398
|
+
records.forEach((record) => {
|
|
399
|
+
const key = record[foreignKey];
|
|
400
|
+
record[name] = key == null ? null : index.get(key) ?? null;
|
|
401
|
+
});
|
|
402
|
+
}
|
|
188
403
|
};
|
|
404
|
+
function normalizeOrderBy(order) {
|
|
405
|
+
if (Array.isArray(order) && !isOrderTuple(order)) {
|
|
406
|
+
return order.map((expression) => toOrderDefinition(expression));
|
|
407
|
+
}
|
|
408
|
+
return [toOrderDefinition(order)];
|
|
409
|
+
}
|
|
410
|
+
function toOrderDefinition(expression) {
|
|
411
|
+
if (typeof expression === "string") {
|
|
412
|
+
return { column: expression, direction: "asc" };
|
|
413
|
+
}
|
|
414
|
+
if (isOrderTuple(expression)) {
|
|
415
|
+
const [column, direction] = expression;
|
|
416
|
+
return { column, direction };
|
|
417
|
+
}
|
|
418
|
+
return {
|
|
419
|
+
column: expression.column,
|
|
420
|
+
direction: expression.direction ?? "asc"
|
|
421
|
+
};
|
|
422
|
+
}
|
|
423
|
+
function isOrderTuple(value) {
|
|
424
|
+
return Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && (value[1] === "asc" || value[1] === "desc");
|
|
425
|
+
}
|
|
426
|
+
function normalizeRelations(relations) {
|
|
427
|
+
if (Array.isArray(relations)) {
|
|
428
|
+
return relations.map((relation) => relation.toString()).filter(Boolean);
|
|
429
|
+
}
|
|
430
|
+
if (typeof relations === "string" && relations) {
|
|
431
|
+
return [relations];
|
|
432
|
+
}
|
|
433
|
+
return [];
|
|
434
|
+
}
|
|
189
435
|
|
|
190
436
|
// src/postgres.ts
|
|
191
437
|
import { drizzle } from "drizzle-orm/postgres-js";
|