@dudousxd/nestjs-media-database-drizzle 0.6.0 → 0.8.0

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.
@@ -0,0 +1,644 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/nest/index.ts
5
+ import { getDrizzleToken } from "@nestjs/drizzle";
6
+
7
+ // src/drizzle-media-store.ts
8
+ import { and, asc, count, eq as eq2, getTableColumns, gt, max, or as or2, sql, sum } from "drizzle-orm";
9
+
10
+ // src/list-cursor.ts
11
+ function encodeListCursor(record) {
12
+ return Buffer.from(`${record.createdAt.toISOString()}|${record.id}`, "utf8").toString("base64");
13
+ }
14
+ __name(encodeListCursor, "encodeListCursor");
15
+ function decodeListCursor(cursor) {
16
+ const decoded = Buffer.from(cursor, "base64").toString("utf8");
17
+ const separator = decoded.indexOf("|");
18
+ if (separator === -1) return null;
19
+ const createdAt = new Date(decoded.slice(0, separator));
20
+ if (Number.isNaN(createdAt.getTime())) return null;
21
+ const id = decoded.slice(separator + 1);
22
+ return {
23
+ createdAt,
24
+ id
25
+ };
26
+ }
27
+ __name(decodeListCursor, "decodeListCursor");
28
+
29
+ // src/media-columns.ts
30
+ import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
31
+ function mediaColumns() {
32
+ return {
33
+ id: text("id").primaryKey(),
34
+ ownerType: text("owner_type").notNull(),
35
+ ownerId: text("owner_id").notNull(),
36
+ collection: text("collection").notNull(),
37
+ name: text("name").notNull(),
38
+ fileName: text("file_name").notNull(),
39
+ mimeType: text("mime_type").notNull(),
40
+ size: integer("size").notNull(),
41
+ disk: text("disk").notNull(),
42
+ path: text("path").notNull(),
43
+ order: integer("position").notNull(),
44
+ customProperties: text("custom_properties", {
45
+ mode: "json"
46
+ }).notNull(),
47
+ conversions: text("conversions", {
48
+ mode: "json"
49
+ }).notNull(),
50
+ createdAt: integer("created_at", {
51
+ mode: "timestamp_ms"
52
+ }).notNull(),
53
+ updatedAt: integer("updated_at", {
54
+ mode: "timestamp_ms"
55
+ }).notNull()
56
+ };
57
+ }
58
+ __name(mediaColumns, "mediaColumns");
59
+ var mediaTableWithoutTenant = sqliteTable("media", mediaColumns());
60
+
61
+ // src/media.schema.ts
62
+ import { index, sqliteTable as sqliteTable2, text as text2 } from "drizzle-orm/sqlite-core";
63
+ var mediaTable = sqliteTable2("media", {
64
+ ...mediaColumns(),
65
+ /** Tenancy only: read and written once the store's `enableTenancy()` ran. */
66
+ tenantId: text2("tenant_id")
67
+ }, (table) => ({
68
+ ownerIdx: index("idx_media_owner").on(table.ownerType, table.ownerId, table.collection),
69
+ collectionIdx: index("idx_media_collection").on(table.collection),
70
+ diskIdx: index("idx_media_disk").on(table.disk),
71
+ createdAtIdx: index("idx_media_created_at").on(table.createdAt),
72
+ collectionCreatedAtIdx: index("idx_media_collection_created_at").on(table.collection, table.createdAt, table.id),
73
+ tenantIdx: index("idx_media_tenant").on(table.tenantId, table.ownerType, table.ownerId, table.collection)
74
+ }));
75
+
76
+ // src/tenancy.ts
77
+ import { MediaTenancyUnavailableError } from "@dudousxd/nestjs-media-core";
78
+ import { eq, isNull, or } from "drizzle-orm";
79
+ function tenantCondition(column, match) {
80
+ if (match.id === null) return isNull(column);
81
+ return match.orNull ? or(eq(column, match.id), isNull(column)) : eq(column, match.id);
82
+ }
83
+ __name(tenantCondition, "tenantCondition");
84
+ function selectable(columns, tenancy) {
85
+ if (tenancy) return columns;
86
+ const { tenantId: _tenantId, ...rest } = columns;
87
+ return rest;
88
+ }
89
+ __name(selectable, "selectable");
90
+ async function assertTenantColumn(table, probe, fix) {
91
+ try {
92
+ await probe();
93
+ } catch (error) {
94
+ throw Object.assign(new MediaTenancyUnavailableError(`the \`${table}\` table has no \`tenant_id\` column`, fix), {
95
+ cause: error
96
+ });
97
+ }
98
+ }
99
+ __name(assertTenantColumn, "assertTenantColumn");
100
+
101
+ // src/drizzle-media-store.ts
102
+ function toRow(record, tenancy) {
103
+ const { tenantId, ...rest } = record;
104
+ return tenancy ? {
105
+ ...rest,
106
+ tenantId: tenantId ?? null
107
+ } : rest;
108
+ }
109
+ __name(toRow, "toRow");
110
+ var DrizzleMediaStore = class {
111
+ static {
112
+ __name(this, "DrizzleMediaStore");
113
+ }
114
+ db;
115
+ tenancy = false;
116
+ constructor(db) {
117
+ this.db = db;
118
+ }
119
+ /** The columns to read: `tenant_id` only once tenancy is on. */
120
+ get columns() {
121
+ return selectable(getTableColumns(mediaTable), this.tenancy);
122
+ }
123
+ /**
124
+ * Tenancy: checks the `tenant_id` column exists, then reads and writes it. Called by the
125
+ * library when tenancy is on; until then the column is never touched.
126
+ */
127
+ async enableTenancy() {
128
+ await assertTenantColumn("media", () => this.db.select({
129
+ tenantId: mediaTable.tenantId
130
+ }).from(mediaTable).limit(1), "Generate a migration with drizzle-kit from `mediaTable` (it declares `tenant_id` and the `idx_media_tenant` index), or run `ALTER TABLE media ADD COLUMN tenant_id text; CREATE INDEX idx_media_tenant ON media (tenant_id, owner_type, owner_id, collection);`.");
131
+ this.tenancy = true;
132
+ }
133
+ async save(record) {
134
+ const row = toRow(record, this.tenancy);
135
+ await this.db.insert(this.tenancy ? mediaTable : mediaTableWithoutTenant).values(row).onConflictDoUpdate({
136
+ target: mediaTable.id,
137
+ set: row
138
+ });
139
+ return row;
140
+ }
141
+ async find(id) {
142
+ const rows = await this.db.select(this.columns).from(mediaTable).where(eq2(mediaTable.id, id)).limit(1);
143
+ return rows[0] ?? null;
144
+ }
145
+ async listByOwner(ownerType, ownerId, collection) {
146
+ const where = collection === void 0 ? and(eq2(mediaTable.ownerType, ownerType), eq2(mediaTable.ownerId, ownerId)) : and(eq2(mediaTable.ownerType, ownerType), eq2(mediaTable.ownerId, ownerId), eq2(mediaTable.collection, collection));
147
+ const rows = await this.db.select(this.columns).from(mediaTable).where(where).orderBy(asc(mediaTable.order));
148
+ return rows;
149
+ }
150
+ async delete(id) {
151
+ await this.db.delete(mediaTable).where(eq2(mediaTable.id, id));
152
+ }
153
+ async nextOrder(ownerType, ownerId, collection) {
154
+ const rows = await this.db.select({
155
+ max: max(mediaTable.order)
156
+ }).from(mediaTable).where(and(eq2(mediaTable.ownerType, ownerType), eq2(mediaTable.ownerId, ownerId), eq2(mediaTable.collection, collection)));
157
+ const top = rows[0]?.max;
158
+ return top == null ? 0 : Number(top) + 1;
159
+ }
160
+ async count(filter = {}) {
161
+ const conditions = [
162
+ ...filter.ownerType !== void 0 ? [
163
+ eq2(mediaTable.ownerType, filter.ownerType)
164
+ ] : [],
165
+ ...filter.collection !== void 0 ? [
166
+ eq2(mediaTable.collection, filter.collection)
167
+ ] : [],
168
+ ...filter.disk !== void 0 ? [
169
+ eq2(mediaTable.disk, filter.disk)
170
+ ] : [],
171
+ ...filter.tenant ? [
172
+ tenantCondition(mediaTable.tenantId, filter.tenant)
173
+ ] : []
174
+ ];
175
+ const rows = await this.db.select({
176
+ value: count()
177
+ }).from(mediaTable).where(conditions.length ? and(...conditions) : void 0);
178
+ return Number(rows[0]?.value ?? 0);
179
+ }
180
+ async aggregate(query) {
181
+ const column = query.groupBy === "collection" ? mediaTable.collection : mediaTable.disk;
182
+ const rows = await this.db.select({
183
+ key: column,
184
+ count: count(),
185
+ sumSize: sum(mediaTable.size)
186
+ }).from(mediaTable).where(query.tenant ? tenantCondition(mediaTable.tenantId, query.tenant) : void 0).groupBy(column);
187
+ return rows.map((row) => ({
188
+ key: row.key,
189
+ count: Number(row.count),
190
+ sumSize: query.sum === "size" ? Number(row.sumSize ?? 0) : 0
191
+ }));
192
+ }
193
+ async list(filter = {}, page = {}) {
194
+ const limit = page.limit ?? 50;
195
+ const cursor = page.cursor ? decodeListCursor(page.cursor) : null;
196
+ const filterConditions = [
197
+ ...filter.ownerType !== void 0 ? [
198
+ eq2(mediaTable.ownerType, filter.ownerType)
199
+ ] : [],
200
+ ...filter.collection !== void 0 ? [
201
+ eq2(mediaTable.collection, filter.collection)
202
+ ] : [],
203
+ ...filter.disk !== void 0 ? [
204
+ eq2(mediaTable.disk, filter.disk)
205
+ ] : [],
206
+ ...filter.tenant ? [
207
+ tenantCondition(mediaTable.tenantId, filter.tenant)
208
+ ] : [],
209
+ ...cursor ? [
210
+ or2(gt(mediaTable.createdAt, cursor.createdAt), and(eq2(mediaTable.createdAt, cursor.createdAt), gt(mediaTable.id, cursor.id)))
211
+ ] : []
212
+ ];
213
+ const rows = await this.db.select(this.columns).from(mediaTable).where(filterConditions.length ? and(...filterConditions) : void 0).orderBy(asc(mediaTable.createdAt), asc(mediaTable.id)).limit(limit + 1);
214
+ const hasMore = rows.length > limit;
215
+ const records = rows.slice(0, limit).map((record) => ({
216
+ ...record
217
+ }));
218
+ const result = {
219
+ records
220
+ };
221
+ const lastRecord = records.at(-1);
222
+ if (hasMore && lastRecord !== void 0) {
223
+ result.cursor = encodeListCursor(lastRecord);
224
+ }
225
+ return result;
226
+ }
227
+ };
228
+
229
+ // src/pg/drizzle-pg-media-store.ts
230
+ import { and as and2, asc as asc2, count as count2, eq as eq3, getTableColumns as getTableColumns2, gt as gt2, max as max2, or as or3, sum as sum2 } from "drizzle-orm";
231
+
232
+ // src/pg/columns.ts
233
+ import { bigint, integer as integer2, jsonb, pgTable, text as text3, timestamp } from "drizzle-orm/pg-core";
234
+ function mediaPgColumns() {
235
+ return {
236
+ id: text3("id").primaryKey(),
237
+ ownerType: text3("owner_type").notNull(),
238
+ ownerId: text3("owner_id").notNull(),
239
+ collection: text3("collection").notNull(),
240
+ name: text3("name").notNull(),
241
+ fileName: text3("file_name").notNull(),
242
+ mimeType: text3("mime_type").notNull(),
243
+ size: bigint("size", {
244
+ mode: "number"
245
+ }).notNull(),
246
+ disk: text3("disk").notNull(),
247
+ path: text3("path").notNull(),
248
+ order: integer2("position").notNull(),
249
+ customProperties: jsonb("custom_properties").$type().notNull(),
250
+ conversions: jsonb("conversions").$type().notNull(),
251
+ createdAt: timestamp("created_at", {
252
+ withTimezone: true,
253
+ mode: "date"
254
+ }).notNull(),
255
+ updatedAt: timestamp("updated_at", {
256
+ withTimezone: true,
257
+ mode: "date"
258
+ }).notNull()
259
+ };
260
+ }
261
+ __name(mediaPgColumns, "mediaPgColumns");
262
+ function uploadSessionPgColumns() {
263
+ return {
264
+ id: text3("id").primaryKey(),
265
+ disk: text3("disk").notNull(),
266
+ key: text3("key").notNull(),
267
+ contentType: text3("content_type"),
268
+ size: bigint("size", {
269
+ mode: "number"
270
+ }),
271
+ offset: bigint("offset", {
272
+ mode: "number"
273
+ }).notNull().default(0),
274
+ parts: integer2("parts").notNull().default(0),
275
+ multipartUploadId: text3("multipart_upload_id"),
276
+ metadata: jsonb("metadata").$type(),
277
+ createdAt: timestamp("created_at", {
278
+ withTimezone: true,
279
+ mode: "date"
280
+ }).notNull().defaultNow(),
281
+ updatedAt: timestamp("updated_at", {
282
+ withTimezone: true,
283
+ mode: "date"
284
+ }).notNull().defaultNow()
285
+ };
286
+ }
287
+ __name(uploadSessionPgColumns, "uploadSessionPgColumns");
288
+ var mediaPgTableWithoutTenant = pgTable("media", mediaPgColumns());
289
+ var mediaUploadSessionsPgTableWithoutTenant = pgTable("media_upload_sessions", uploadSessionPgColumns());
290
+
291
+ // src/pg/schema.ts
292
+ import { index as index2, integer as integer3, pgTable as pgTable2, primaryKey, text as text4 } from "drizzle-orm/pg-core";
293
+ var mediaPgTable = pgTable2("media", {
294
+ ...mediaPgColumns(),
295
+ /** Tenancy only: read and written once the store's `enableTenancy()` ran. */
296
+ tenantId: text4("tenant_id")
297
+ }, (table) => [
298
+ index2("idx_media_owner").on(table.ownerType, table.ownerId, table.collection),
299
+ index2("idx_media_collection").on(table.collection),
300
+ index2("idx_media_disk").on(table.disk),
301
+ index2("idx_media_created_at").on(table.createdAt),
302
+ index2("idx_media_collection_created_at").on(table.collection, table.createdAt, table.id),
303
+ index2("idx_media_tenant").on(table.tenantId, table.ownerType, table.ownerId, table.collection)
304
+ ]);
305
+ var mediaUploadSessionsPgTable = pgTable2("media_upload_sessions", {
306
+ ...uploadSessionPgColumns(),
307
+ /** Tenancy only: read and written once the store's `enableTenancy()` ran. */
308
+ tenantId: text4("tenant_id")
309
+ }, (table) => [
310
+ index2("idx_media_upload_sessions_tenant").on(table.tenantId)
311
+ ]);
312
+ var mediaUploadPartsPgTable = pgTable2("media_upload_parts", {
313
+ sessionId: text4("session_id").notNull().references(() => mediaUploadSessionsPgTable.id, {
314
+ onDelete: "cascade"
315
+ }),
316
+ partNumber: integer3("part_number").notNull(),
317
+ etag: text4("etag").notNull()
318
+ }, (table) => [
319
+ primaryKey({
320
+ columns: [
321
+ table.sessionId,
322
+ table.partNumber
323
+ ]
324
+ })
325
+ ]);
326
+
327
+ // src/pg/drizzle-pg-media-store.ts
328
+ function toRecord(row) {
329
+ return {
330
+ ...row,
331
+ size: Number(row.size)
332
+ };
333
+ }
334
+ __name(toRecord, "toRecord");
335
+ function toRow2(record, tenancy) {
336
+ const { tenantId, ...rest } = record;
337
+ return tenancy ? {
338
+ ...rest,
339
+ tenantId: tenantId ?? null
340
+ } : rest;
341
+ }
342
+ __name(toRow2, "toRow");
343
+ var DrizzlePgMediaStore = class {
344
+ static {
345
+ __name(this, "DrizzlePgMediaStore");
346
+ }
347
+ db;
348
+ tenancy = false;
349
+ constructor(db) {
350
+ this.db = db;
351
+ }
352
+ /** The columns to read: `tenant_id` only once tenancy is on. */
353
+ get columns() {
354
+ return selectable(getTableColumns2(mediaPgTable), this.tenancy);
355
+ }
356
+ /**
357
+ * Tenancy: checks the `tenant_id` column exists, then reads and writes it. Called by the
358
+ * library when tenancy is on; until then the column is never touched.
359
+ */
360
+ async enableTenancy() {
361
+ await assertTenantColumn("media", () => this.db.select({
362
+ tenantId: mediaPgTable.tenantId
363
+ }).from(mediaPgTable).limit(1), "Generate a migration with drizzle-kit from `mediaPgTable` (it declares `tenant_id` and the `idx_media_tenant` index), or run `ALTER TABLE media ADD COLUMN tenant_id text; CREATE INDEX idx_media_tenant ON media (tenant_id, owner_type, owner_id, collection);`.");
364
+ this.tenancy = true;
365
+ }
366
+ async save(record) {
367
+ const row = toRow2(record, this.tenancy);
368
+ const { id: _id, ...rest } = row;
369
+ await this.db.insert(this.tenancy ? mediaPgTable : mediaPgTableWithoutTenant).values(row).onConflictDoUpdate({
370
+ target: mediaPgTable.id,
371
+ set: rest
372
+ });
373
+ return row;
374
+ }
375
+ async find(id) {
376
+ const rows = await this.db.select(this.columns).from(mediaPgTable).where(eq3(mediaPgTable.id, id)).limit(1);
377
+ const row = rows[0];
378
+ return row ? toRecord(row) : null;
379
+ }
380
+ async listByOwner(ownerType, ownerId, collection) {
381
+ const where = collection === void 0 ? and2(eq3(mediaPgTable.ownerType, ownerType), eq3(mediaPgTable.ownerId, ownerId)) : and2(eq3(mediaPgTable.ownerType, ownerType), eq3(mediaPgTable.ownerId, ownerId), eq3(mediaPgTable.collection, collection));
382
+ const rows = await this.db.select(this.columns).from(mediaPgTable).where(where).orderBy(asc2(mediaPgTable.order), asc2(mediaPgTable.id));
383
+ return rows.map(toRecord);
384
+ }
385
+ async delete(id) {
386
+ await this.db.delete(mediaPgTable).where(eq3(mediaPgTable.id, id));
387
+ }
388
+ async nextOrder(ownerType, ownerId, collection) {
389
+ const rows = await this.db.select({
390
+ max: max2(mediaPgTable.order)
391
+ }).from(mediaPgTable).where(and2(eq3(mediaPgTable.ownerType, ownerType), eq3(mediaPgTable.ownerId, ownerId), eq3(mediaPgTable.collection, collection)));
392
+ const top = rows[0]?.max;
393
+ return top == null ? 0 : Number(top) + 1;
394
+ }
395
+ async count(filter = {}) {
396
+ const conditions = [
397
+ ...filter.ownerType !== void 0 ? [
398
+ eq3(mediaPgTable.ownerType, filter.ownerType)
399
+ ] : [],
400
+ ...filter.collection !== void 0 ? [
401
+ eq3(mediaPgTable.collection, filter.collection)
402
+ ] : [],
403
+ ...filter.disk !== void 0 ? [
404
+ eq3(mediaPgTable.disk, filter.disk)
405
+ ] : [],
406
+ ...filter.tenant ? [
407
+ tenantCondition(mediaPgTable.tenantId, filter.tenant)
408
+ ] : []
409
+ ];
410
+ const rows = await this.db.select({
411
+ value: count2()
412
+ }).from(mediaPgTable).where(conditions.length ? and2(...conditions) : void 0);
413
+ return Number(rows[0]?.value ?? 0);
414
+ }
415
+ async aggregate(query) {
416
+ const column = query.groupBy === "collection" ? mediaPgTable.collection : mediaPgTable.disk;
417
+ const rows = await this.db.select({
418
+ key: column,
419
+ count: count2(),
420
+ sumSize: sum2(mediaPgTable.size)
421
+ }).from(mediaPgTable).where(query.tenant ? tenantCondition(mediaPgTable.tenantId, query.tenant) : void 0).groupBy(column);
422
+ return rows.map((row) => ({
423
+ key: row.key,
424
+ count: Number(row.count),
425
+ // `sum(bigint)` is `numeric` in Postgres — drivers hand it back as a string.
426
+ sumSize: query.sum === "size" ? Number(row.sumSize ?? 0) : 0
427
+ }));
428
+ }
429
+ async list(filter = {}, page = {}) {
430
+ const limit = page.limit ?? 50;
431
+ const cursor = page.cursor ? decodeListCursor(page.cursor) : null;
432
+ const filterConditions = [
433
+ ...filter.ownerType !== void 0 ? [
434
+ eq3(mediaPgTable.ownerType, filter.ownerType)
435
+ ] : [],
436
+ ...filter.collection !== void 0 ? [
437
+ eq3(mediaPgTable.collection, filter.collection)
438
+ ] : [],
439
+ ...filter.disk !== void 0 ? [
440
+ eq3(mediaPgTable.disk, filter.disk)
441
+ ] : [],
442
+ ...filter.tenant ? [
443
+ tenantCondition(mediaPgTable.tenantId, filter.tenant)
444
+ ] : [],
445
+ ...cursor ? [
446
+ or3(gt2(mediaPgTable.createdAt, cursor.createdAt), and2(eq3(mediaPgTable.createdAt, cursor.createdAt), gt2(mediaPgTable.id, cursor.id)))
447
+ ] : []
448
+ ];
449
+ const rows = await this.db.select(this.columns).from(mediaPgTable).where(filterConditions.length ? and2(...filterConditions) : void 0).orderBy(asc2(mediaPgTable.createdAt), asc2(mediaPgTable.id)).limit(limit + 1);
450
+ const hasMore = rows.length > limit;
451
+ const records = rows.slice(0, limit).map(toRecord);
452
+ const result = {
453
+ records
454
+ };
455
+ const lastRecord = records.at(-1);
456
+ if (hasMore && lastRecord !== void 0) {
457
+ result.cursor = encodeListCursor(lastRecord);
458
+ }
459
+ return result;
460
+ }
461
+ };
462
+
463
+ // src/pg/drizzle-pg-upload-session-store.ts
464
+ import { and as and3, asc as asc3, eq as eq4, getTableColumns as getTableColumns3, like, sql as sql2 } from "drizzle-orm";
465
+ function escapeLike(value) {
466
+ return value.replace(/[\\%_]/g, (char) => `\\${char}`);
467
+ }
468
+ __name(escapeLike, "escapeLike");
469
+ function toSession(row) {
470
+ const session = {
471
+ id: row.id,
472
+ disk: row.disk,
473
+ key: row.key,
474
+ contentType: row.contentType ?? void 0,
475
+ size: row.size == null ? void 0 : Number(row.size),
476
+ offset: Number(row.offset),
477
+ parts: Number(row.parts),
478
+ createdAt: row.createdAt instanceof Date ? row.createdAt : new Date(row.createdAt)
479
+ };
480
+ if (row.multipartUploadId != null) session.multipartUploadId = row.multipartUploadId;
481
+ if (row.metadata != null) session.metadata = row.metadata;
482
+ if (row.tenantId !== void 0) session.tenantId = row.tenantId;
483
+ return session;
484
+ }
485
+ __name(toSession, "toSession");
486
+ function toColumns(session, tenancy) {
487
+ return {
488
+ ...tenancy ? {
489
+ tenantId: session.tenantId ?? null
490
+ } : {},
491
+ disk: session.disk,
492
+ key: session.key,
493
+ contentType: session.contentType ?? null,
494
+ size: session.size ?? null,
495
+ offset: session.offset,
496
+ parts: session.parts,
497
+ multipartUploadId: session.multipartUploadId ?? null,
498
+ metadata: session.metadata ?? null
499
+ };
500
+ }
501
+ __name(toColumns, "toColumns");
502
+ var DrizzlePgUploadSessionStore = class {
503
+ static {
504
+ __name(this, "DrizzlePgUploadSessionStore");
505
+ }
506
+ db;
507
+ tenancy = false;
508
+ constructor(db) {
509
+ this.db = db;
510
+ }
511
+ /** Off: the table without `tenant_id`, which Drizzle would otherwise list in an INSERT. */
512
+ get sessionsTable() {
513
+ return this.tenancy ? mediaUploadSessionsPgTable : mediaUploadSessionsPgTableWithoutTenant;
514
+ }
515
+ /** The columns to read: `tenant_id` only once tenancy is on. */
516
+ get columns() {
517
+ return selectable(getTableColumns3(mediaUploadSessionsPgTable), this.tenancy);
518
+ }
519
+ /**
520
+ * Tenancy: checks the `tenant_id` column exists, then reads and writes it. Called by the upload
521
+ * manager when tenancy is on; until then the column is never touched.
522
+ */
523
+ async enableTenancy() {
524
+ await assertTenantColumn("media_upload_sessions", () => this.db.select({
525
+ tenantId: mediaUploadSessionsPgTable.tenantId
526
+ }).from(mediaUploadSessionsPgTable).limit(1), "Generate a migration with drizzle-kit from `mediaUploadSessionsPgTable` (it declares `tenant_id` and its index), or run `ALTER TABLE media_upload_sessions ADD COLUMN tenant_id text; CREATE INDEX idx_media_upload_sessions_tenant ON media_upload_sessions (tenant_id);`.");
527
+ this.tenancy = true;
528
+ }
529
+ /** The session as persisted: off, no `tenantId`; on, `tenantId` or `null`. */
530
+ persisted(session) {
531
+ const { tenantId, ...rest } = session;
532
+ return this.tenancy ? {
533
+ ...rest,
534
+ tenantId: tenantId ?? null
535
+ } : rest;
536
+ }
537
+ async create(session) {
538
+ const createdAt = session.createdAt ?? /* @__PURE__ */ new Date();
539
+ await this.db.insert(this.sessionsTable).values({
540
+ id: session.id,
541
+ ...toColumns(session, this.tenancy),
542
+ createdAt,
543
+ updatedAt: /* @__PURE__ */ new Date()
544
+ });
545
+ return {
546
+ ...this.persisted(session),
547
+ createdAt
548
+ };
549
+ }
550
+ async get(id) {
551
+ const rows = await this.db.select(this.columns).from(mediaUploadSessionsPgTable).where(eq4(mediaUploadSessionsPgTable.id, id)).limit(1);
552
+ const row = rows[0];
553
+ return row ? toSession(row) : null;
554
+ }
555
+ async update(session) {
556
+ const columns = {
557
+ ...toColumns(session, this.tenancy),
558
+ ...session.createdAt !== void 0 ? {
559
+ createdAt: session.createdAt
560
+ } : {},
561
+ updatedAt: /* @__PURE__ */ new Date()
562
+ };
563
+ await this.db.insert(this.sessionsTable).values({
564
+ id: session.id,
565
+ ...columns
566
+ }).onConflictDoUpdate({
567
+ target: mediaUploadSessionsPgTable.id,
568
+ set: columns
569
+ });
570
+ return this.persisted(session);
571
+ }
572
+ async delete(id) {
573
+ await this.db.delete(mediaUploadSessionsPgTable).where(eq4(mediaUploadSessionsPgTable.id, id));
574
+ }
575
+ async addPart(id, part) {
576
+ await this.db.insert(mediaUploadPartsPgTable).values({
577
+ sessionId: id,
578
+ partNumber: part.partNumber,
579
+ etag: part.etag
580
+ }).onConflictDoUpdate({
581
+ target: [
582
+ mediaUploadPartsPgTable.sessionId,
583
+ mediaUploadPartsPgTable.partNumber
584
+ ],
585
+ set: {
586
+ etag: sql2`excluded.etag`
587
+ }
588
+ });
589
+ }
590
+ async listParts(id) {
591
+ const rows = await this.db.select({
592
+ partNumber: mediaUploadPartsPgTable.partNumber,
593
+ etag: mediaUploadPartsPgTable.etag
594
+ }).from(mediaUploadPartsPgTable).where(eq4(mediaUploadPartsPgTable.sessionId, id)).orderBy(asc3(mediaUploadPartsPgTable.partNumber));
595
+ return rows.map((row) => ({
596
+ partNumber: Number(row.partNumber),
597
+ etag: row.etag
598
+ }));
599
+ }
600
+ async list(filter = {}) {
601
+ const conditions = [
602
+ ...filter.disk !== void 0 ? [
603
+ eq4(mediaUploadSessionsPgTable.disk, filter.disk)
604
+ ] : [],
605
+ ...filter.keyPrefix !== void 0 ? [
606
+ like(mediaUploadSessionsPgTable.key, `${escapeLike(filter.keyPrefix)}%`)
607
+ ] : [],
608
+ ...filter.tenant ? [
609
+ tenantCondition(mediaUploadSessionsPgTable.tenantId, filter.tenant)
610
+ ] : []
611
+ ];
612
+ const rows = await this.db.select(this.columns).from(mediaUploadSessionsPgTable).where(conditions.length ? and3(...conditions) : void 0).orderBy(asc3(mediaUploadSessionsPgTable.createdAt), asc3(mediaUploadSessionsPgTable.id));
613
+ return rows.map(toSession);
614
+ }
615
+ };
616
+
617
+ // src/nest/index.ts
618
+ function factory(options, build) {
619
+ return {
620
+ inject: [
621
+ getDrizzleToken(options.connectionName)
622
+ ],
623
+ useFactory: build
624
+ };
625
+ }
626
+ __name(factory, "factory");
627
+ function drizzleMediaStore(options = {}) {
628
+ return factory(options, (db) => new DrizzleMediaStore(db));
629
+ }
630
+ __name(drizzleMediaStore, "drizzleMediaStore");
631
+ function drizzlePgMediaStore(options = {}) {
632
+ return factory(options, (db) => new DrizzlePgMediaStore(db));
633
+ }
634
+ __name(drizzlePgMediaStore, "drizzlePgMediaStore");
635
+ function drizzlePgUploadSessions(options = {}) {
636
+ return factory(options, (db) => new DrizzlePgUploadSessionStore(db));
637
+ }
638
+ __name(drizzlePgUploadSessions, "drizzlePgUploadSessions");
639
+ export {
640
+ drizzleMediaStore,
641
+ drizzlePgMediaStore,
642
+ drizzlePgUploadSessions
643
+ };
644
+ //# sourceMappingURL=index.js.map