@dudousxd/nestjs-media-database-drizzle 0.7.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.
@@ -5,7 +5,7 @@ var __name = (target, value) => __defProp(target, "name", { value, configurable:
5
5
  import { getDrizzleToken } from "@nestjs/drizzle";
6
6
 
7
7
  // src/drizzle-media-store.ts
8
- import { and, asc, count, eq, gt, max, or, sql, sum } from "drizzle-orm";
8
+ import { and, asc, count, eq as eq2, getTableColumns, gt, max, or as or2, sql, sum } from "drizzle-orm";
9
9
 
10
10
  // src/list-cursor.ts
11
11
  function encodeListCursor(record) {
@@ -26,85 +26,150 @@ function decodeListCursor(cursor) {
26
26
  }
27
27
  __name(decodeListCursor, "decodeListCursor");
28
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
+
29
61
  // src/media.schema.ts
30
- import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
31
- var mediaTable = sqliteTable("media", {
32
- id: text("id").primaryKey(),
33
- ownerType: text("owner_type").notNull(),
34
- ownerId: text("owner_id").notNull(),
35
- collection: text("collection").notNull(),
36
- name: text("name").notNull(),
37
- fileName: text("file_name").notNull(),
38
- mimeType: text("mime_type").notNull(),
39
- size: integer("size").notNull(),
40
- disk: text("disk").notNull(),
41
- path: text("path").notNull(),
42
- order: integer("position").notNull(),
43
- customProperties: text("custom_properties", {
44
- mode: "json"
45
- }).notNull(),
46
- conversions: text("conversions", {
47
- mode: "json"
48
- }).notNull(),
49
- createdAt: integer("created_at", {
50
- mode: "timestamp_ms"
51
- }).notNull(),
52
- updatedAt: integer("updated_at", {
53
- mode: "timestamp_ms"
54
- }).notNull()
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")
55
67
  }, (table) => ({
56
68
  ownerIdx: index("idx_media_owner").on(table.ownerType, table.ownerId, table.collection),
57
69
  collectionIdx: index("idx_media_collection").on(table.collection),
58
70
  diskIdx: index("idx_media_disk").on(table.disk),
59
71
  createdAtIdx: index("idx_media_created_at").on(table.createdAt),
60
- collectionCreatedAtIdx: index("idx_media_collection_created_at").on(table.collection, table.createdAt, table.id)
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)
61
74
  }));
62
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
+
63
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");
64
110
  var DrizzleMediaStore = class {
65
111
  static {
66
112
  __name(this, "DrizzleMediaStore");
67
113
  }
68
114
  db;
115
+ tenancy = false;
69
116
  constructor(db) {
70
117
  this.db = db;
71
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
+ }
72
133
  async save(record) {
73
- await this.db.insert(mediaTable).values(record).onConflictDoUpdate({
134
+ const row = toRow(record, this.tenancy);
135
+ await this.db.insert(this.tenancy ? mediaTable : mediaTableWithoutTenant).values(row).onConflictDoUpdate({
74
136
  target: mediaTable.id,
75
- set: record
137
+ set: row
76
138
  });
77
- return record;
139
+ return row;
78
140
  }
79
141
  async find(id) {
80
- const rows = await this.db.select().from(mediaTable).where(eq(mediaTable.id, id)).limit(1);
142
+ const rows = await this.db.select(this.columns).from(mediaTable).where(eq2(mediaTable.id, id)).limit(1);
81
143
  return rows[0] ?? null;
82
144
  }
83
145
  async listByOwner(ownerType, ownerId, collection) {
84
- const where = collection === void 0 ? and(eq(mediaTable.ownerType, ownerType), eq(mediaTable.ownerId, ownerId)) : and(eq(mediaTable.ownerType, ownerType), eq(mediaTable.ownerId, ownerId), eq(mediaTable.collection, collection));
85
- const rows = await this.db.select().from(mediaTable).where(where).orderBy(asc(mediaTable.order));
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));
86
148
  return rows;
87
149
  }
88
150
  async delete(id) {
89
- await this.db.delete(mediaTable).where(eq(mediaTable.id, id));
151
+ await this.db.delete(mediaTable).where(eq2(mediaTable.id, id));
90
152
  }
91
153
  async nextOrder(ownerType, ownerId, collection) {
92
154
  const rows = await this.db.select({
93
155
  max: max(mediaTable.order)
94
- }).from(mediaTable).where(and(eq(mediaTable.ownerType, ownerType), eq(mediaTable.ownerId, ownerId), eq(mediaTable.collection, collection)));
156
+ }).from(mediaTable).where(and(eq2(mediaTable.ownerType, ownerType), eq2(mediaTable.ownerId, ownerId), eq2(mediaTable.collection, collection)));
95
157
  const top = rows[0]?.max;
96
158
  return top == null ? 0 : Number(top) + 1;
97
159
  }
98
160
  async count(filter = {}) {
99
161
  const conditions = [
100
162
  ...filter.ownerType !== void 0 ? [
101
- eq(mediaTable.ownerType, filter.ownerType)
163
+ eq2(mediaTable.ownerType, filter.ownerType)
102
164
  ] : [],
103
165
  ...filter.collection !== void 0 ? [
104
- eq(mediaTable.collection, filter.collection)
166
+ eq2(mediaTable.collection, filter.collection)
105
167
  ] : [],
106
168
  ...filter.disk !== void 0 ? [
107
- eq(mediaTable.disk, filter.disk)
169
+ eq2(mediaTable.disk, filter.disk)
170
+ ] : [],
171
+ ...filter.tenant ? [
172
+ tenantCondition(mediaTable.tenantId, filter.tenant)
108
173
  ] : []
109
174
  ];
110
175
  const rows = await this.db.select({
@@ -118,7 +183,7 @@ var DrizzleMediaStore = class {
118
183
  key: column,
119
184
  count: count(),
120
185
  sumSize: sum(mediaTable.size)
121
- }).from(mediaTable).groupBy(column);
186
+ }).from(mediaTable).where(query.tenant ? tenantCondition(mediaTable.tenantId, query.tenant) : void 0).groupBy(column);
122
187
  return rows.map((row) => ({
123
188
  key: row.key,
124
189
  count: Number(row.count),
@@ -130,19 +195,22 @@ var DrizzleMediaStore = class {
130
195
  const cursor = page.cursor ? decodeListCursor(page.cursor) : null;
131
196
  const filterConditions = [
132
197
  ...filter.ownerType !== void 0 ? [
133
- eq(mediaTable.ownerType, filter.ownerType)
198
+ eq2(mediaTable.ownerType, filter.ownerType)
134
199
  ] : [],
135
200
  ...filter.collection !== void 0 ? [
136
- eq(mediaTable.collection, filter.collection)
201
+ eq2(mediaTable.collection, filter.collection)
137
202
  ] : [],
138
203
  ...filter.disk !== void 0 ? [
139
- eq(mediaTable.disk, filter.disk)
204
+ eq2(mediaTable.disk, filter.disk)
205
+ ] : [],
206
+ ...filter.tenant ? [
207
+ tenantCondition(mediaTable.tenantId, filter.tenant)
140
208
  ] : [],
141
209
  ...cursor ? [
142
- or(gt(mediaTable.createdAt, cursor.createdAt), and(eq(mediaTable.createdAt, cursor.createdAt), gt(mediaTable.id, cursor.id)))
210
+ or2(gt(mediaTable.createdAt, cursor.createdAt), and(eq2(mediaTable.createdAt, cursor.createdAt), gt(mediaTable.id, cursor.id)))
143
211
  ] : []
144
212
  ];
145
- const rows = await this.db.select().from(mediaTable).where(filterConditions.length ? and(...filterConditions) : void 0).orderBy(asc(mediaTable.createdAt), asc(mediaTable.id)).limit(limit + 1);
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);
146
214
  const hasMore = rows.length > limit;
147
215
  const records = rows.slice(0, limit).map((record) => ({
148
216
  ...record
@@ -159,70 +227,94 @@ var DrizzleMediaStore = class {
159
227
  };
160
228
 
161
229
  // src/pg/drizzle-pg-media-store.ts
162
- import { and as and2, asc as asc2, count as count2, eq as eq2, gt as gt2, max as max2, or as or2, sum as sum2 } from "drizzle-orm";
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());
163
290
 
164
291
  // src/pg/schema.ts
165
- import { bigint, index as index2, integer as integer2, jsonb, pgTable, primaryKey, text as text2, timestamp } from "drizzle-orm/pg-core";
166
- var mediaPgTable = pgTable("media", {
167
- id: text2("id").primaryKey(),
168
- ownerType: text2("owner_type").notNull(),
169
- ownerId: text2("owner_id").notNull(),
170
- collection: text2("collection").notNull(),
171
- name: text2("name").notNull(),
172
- fileName: text2("file_name").notNull(),
173
- mimeType: text2("mime_type").notNull(),
174
- size: bigint("size", {
175
- mode: "number"
176
- }).notNull(),
177
- disk: text2("disk").notNull(),
178
- path: text2("path").notNull(),
179
- order: integer2("position").notNull(),
180
- customProperties: jsonb("custom_properties").$type().notNull(),
181
- conversions: jsonb("conversions").$type().notNull(),
182
- createdAt: timestamp("created_at", {
183
- withTimezone: true,
184
- mode: "date"
185
- }).notNull(),
186
- updatedAt: timestamp("updated_at", {
187
- withTimezone: true,
188
- mode: "date"
189
- }).notNull()
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")
190
297
  }, (table) => [
191
298
  index2("idx_media_owner").on(table.ownerType, table.ownerId, table.collection),
192
299
  index2("idx_media_collection").on(table.collection),
193
300
  index2("idx_media_disk").on(table.disk),
194
301
  index2("idx_media_created_at").on(table.createdAt),
195
- index2("idx_media_collection_created_at").on(table.collection, table.createdAt, table.id)
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)
196
304
  ]);
197
- var mediaUploadSessionsPgTable = pgTable("media_upload_sessions", {
198
- id: text2("id").primaryKey(),
199
- disk: text2("disk").notNull(),
200
- key: text2("key").notNull(),
201
- contentType: text2("content_type"),
202
- size: bigint("size", {
203
- mode: "number"
204
- }),
205
- offset: bigint("offset", {
206
- mode: "number"
207
- }).notNull().default(0),
208
- parts: integer2("parts").notNull().default(0),
209
- multipartUploadId: text2("multipart_upload_id"),
210
- metadata: jsonb("metadata").$type(),
211
- createdAt: timestamp("created_at", {
212
- withTimezone: true,
213
- mode: "date"
214
- }).notNull().defaultNow(),
215
- updatedAt: timestamp("updated_at", {
216
- withTimezone: true,
217
- mode: "date"
218
- }).notNull().defaultNow()
219
- });
220
- var mediaUploadPartsPgTable = pgTable("media_upload_parts", {
221
- sessionId: text2("session_id").notNull().references(() => mediaUploadSessionsPgTable.id, {
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, {
222
314
  onDelete: "cascade"
223
315
  }),
224
- partNumber: integer2("part_number").notNull(),
225
- etag: text2("etag").notNull()
316
+ partNumber: integer3("part_number").notNull(),
317
+ etag: text4("etag").notNull()
226
318
  }, (table) => [
227
319
  primaryKey({
228
320
  columns: [
@@ -240,52 +332,79 @@ function toRecord(row) {
240
332
  };
241
333
  }
242
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");
243
343
  var DrizzlePgMediaStore = class {
244
344
  static {
245
345
  __name(this, "DrizzlePgMediaStore");
246
346
  }
247
347
  db;
348
+ tenancy = false;
248
349
  constructor(db) {
249
350
  this.db = db;
250
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
+ }
251
366
  async save(record) {
252
- const { id: _id, ...rest } = record;
253
- await this.db.insert(mediaPgTable).values(record).onConflictDoUpdate({
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({
254
370
  target: mediaPgTable.id,
255
371
  set: rest
256
372
  });
257
- return record;
373
+ return row;
258
374
  }
259
375
  async find(id) {
260
- const rows = await this.db.select().from(mediaPgTable).where(eq2(mediaPgTable.id, id)).limit(1);
376
+ const rows = await this.db.select(this.columns).from(mediaPgTable).where(eq3(mediaPgTable.id, id)).limit(1);
261
377
  const row = rows[0];
262
378
  return row ? toRecord(row) : null;
263
379
  }
264
380
  async listByOwner(ownerType, ownerId, collection) {
265
- const where = collection === void 0 ? and2(eq2(mediaPgTable.ownerType, ownerType), eq2(mediaPgTable.ownerId, ownerId)) : and2(eq2(mediaPgTable.ownerType, ownerType), eq2(mediaPgTable.ownerId, ownerId), eq2(mediaPgTable.collection, collection));
266
- const rows = await this.db.select().from(mediaPgTable).where(where).orderBy(asc2(mediaPgTable.order), asc2(mediaPgTable.id));
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));
267
383
  return rows.map(toRecord);
268
384
  }
269
385
  async delete(id) {
270
- await this.db.delete(mediaPgTable).where(eq2(mediaPgTable.id, id));
386
+ await this.db.delete(mediaPgTable).where(eq3(mediaPgTable.id, id));
271
387
  }
272
388
  async nextOrder(ownerType, ownerId, collection) {
273
389
  const rows = await this.db.select({
274
390
  max: max2(mediaPgTable.order)
275
- }).from(mediaPgTable).where(and2(eq2(mediaPgTable.ownerType, ownerType), eq2(mediaPgTable.ownerId, ownerId), eq2(mediaPgTable.collection, collection)));
391
+ }).from(mediaPgTable).where(and2(eq3(mediaPgTable.ownerType, ownerType), eq3(mediaPgTable.ownerId, ownerId), eq3(mediaPgTable.collection, collection)));
276
392
  const top = rows[0]?.max;
277
393
  return top == null ? 0 : Number(top) + 1;
278
394
  }
279
395
  async count(filter = {}) {
280
396
  const conditions = [
281
397
  ...filter.ownerType !== void 0 ? [
282
- eq2(mediaPgTable.ownerType, filter.ownerType)
398
+ eq3(mediaPgTable.ownerType, filter.ownerType)
283
399
  ] : [],
284
400
  ...filter.collection !== void 0 ? [
285
- eq2(mediaPgTable.collection, filter.collection)
401
+ eq3(mediaPgTable.collection, filter.collection)
286
402
  ] : [],
287
403
  ...filter.disk !== void 0 ? [
288
- eq2(mediaPgTable.disk, filter.disk)
404
+ eq3(mediaPgTable.disk, filter.disk)
405
+ ] : [],
406
+ ...filter.tenant ? [
407
+ tenantCondition(mediaPgTable.tenantId, filter.tenant)
289
408
  ] : []
290
409
  ];
291
410
  const rows = await this.db.select({
@@ -299,7 +418,7 @@ var DrizzlePgMediaStore = class {
299
418
  key: column,
300
419
  count: count2(),
301
420
  sumSize: sum2(mediaPgTable.size)
302
- }).from(mediaPgTable).groupBy(column);
421
+ }).from(mediaPgTable).where(query.tenant ? tenantCondition(mediaPgTable.tenantId, query.tenant) : void 0).groupBy(column);
303
422
  return rows.map((row) => ({
304
423
  key: row.key,
305
424
  count: Number(row.count),
@@ -312,19 +431,22 @@ var DrizzlePgMediaStore = class {
312
431
  const cursor = page.cursor ? decodeListCursor(page.cursor) : null;
313
432
  const filterConditions = [
314
433
  ...filter.ownerType !== void 0 ? [
315
- eq2(mediaPgTable.ownerType, filter.ownerType)
434
+ eq3(mediaPgTable.ownerType, filter.ownerType)
316
435
  ] : [],
317
436
  ...filter.collection !== void 0 ? [
318
- eq2(mediaPgTable.collection, filter.collection)
437
+ eq3(mediaPgTable.collection, filter.collection)
319
438
  ] : [],
320
439
  ...filter.disk !== void 0 ? [
321
- eq2(mediaPgTable.disk, filter.disk)
440
+ eq3(mediaPgTable.disk, filter.disk)
441
+ ] : [],
442
+ ...filter.tenant ? [
443
+ tenantCondition(mediaPgTable.tenantId, filter.tenant)
322
444
  ] : [],
323
445
  ...cursor ? [
324
- or2(gt2(mediaPgTable.createdAt, cursor.createdAt), and2(eq2(mediaPgTable.createdAt, cursor.createdAt), gt2(mediaPgTable.id, cursor.id)))
446
+ or3(gt2(mediaPgTable.createdAt, cursor.createdAt), and2(eq3(mediaPgTable.createdAt, cursor.createdAt), gt2(mediaPgTable.id, cursor.id)))
325
447
  ] : []
326
448
  ];
327
- const rows = await this.db.select().from(mediaPgTable).where(filterConditions.length ? and2(...filterConditions) : void 0).orderBy(asc2(mediaPgTable.createdAt), asc2(mediaPgTable.id)).limit(limit + 1);
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);
328
450
  const hasMore = rows.length > limit;
329
451
  const records = rows.slice(0, limit).map(toRecord);
330
452
  const result = {
@@ -339,7 +461,7 @@ var DrizzlePgMediaStore = class {
339
461
  };
340
462
 
341
463
  // src/pg/drizzle-pg-upload-session-store.ts
342
- import { and as and3, asc as asc3, eq as eq3, like, sql as sql2 } from "drizzle-orm";
464
+ import { and as and3, asc as asc3, eq as eq4, getTableColumns as getTableColumns3, like, sql as sql2 } from "drizzle-orm";
343
465
  function escapeLike(value) {
344
466
  return value.replace(/[\\%_]/g, (char) => `\\${char}`);
345
467
  }
@@ -357,11 +479,15 @@ function toSession(row) {
357
479
  };
358
480
  if (row.multipartUploadId != null) session.multipartUploadId = row.multipartUploadId;
359
481
  if (row.metadata != null) session.metadata = row.metadata;
482
+ if (row.tenantId !== void 0) session.tenantId = row.tenantId;
360
483
  return session;
361
484
  }
362
485
  __name(toSession, "toSession");
363
- function toColumns(session) {
486
+ function toColumns(session, tenancy) {
364
487
  return {
488
+ ...tenancy ? {
489
+ tenantId: session.tenantId ?? null
490
+ } : {},
365
491
  disk: session.disk,
366
492
  key: session.key,
367
493
  contentType: session.contentType ?? null,
@@ -378,48 +504,73 @@ var DrizzlePgUploadSessionStore = class {
378
504
  __name(this, "DrizzlePgUploadSessionStore");
379
505
  }
380
506
  db;
507
+ tenancy = false;
381
508
  constructor(db) {
382
509
  this.db = db;
383
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
+ }
384
537
  async create(session) {
385
538
  const createdAt = session.createdAt ?? /* @__PURE__ */ new Date();
386
- await this.db.insert(mediaUploadSessionsPgTable).values({
539
+ await this.db.insert(this.sessionsTable).values({
387
540
  id: session.id,
388
- ...toColumns(session),
541
+ ...toColumns(session, this.tenancy),
389
542
  createdAt,
390
543
  updatedAt: /* @__PURE__ */ new Date()
391
544
  });
392
545
  return {
393
- ...session,
546
+ ...this.persisted(session),
394
547
  createdAt
395
548
  };
396
549
  }
397
550
  async get(id) {
398
- const rows = await this.db.select().from(mediaUploadSessionsPgTable).where(eq3(mediaUploadSessionsPgTable.id, id)).limit(1);
551
+ const rows = await this.db.select(this.columns).from(mediaUploadSessionsPgTable).where(eq4(mediaUploadSessionsPgTable.id, id)).limit(1);
399
552
  const row = rows[0];
400
553
  return row ? toSession(row) : null;
401
554
  }
402
555
  async update(session) {
403
556
  const columns = {
404
- ...toColumns(session),
557
+ ...toColumns(session, this.tenancy),
405
558
  ...session.createdAt !== void 0 ? {
406
559
  createdAt: session.createdAt
407
560
  } : {},
408
561
  updatedAt: /* @__PURE__ */ new Date()
409
562
  };
410
- await this.db.insert(mediaUploadSessionsPgTable).values({
563
+ await this.db.insert(this.sessionsTable).values({
411
564
  id: session.id,
412
565
  ...columns
413
566
  }).onConflictDoUpdate({
414
567
  target: mediaUploadSessionsPgTable.id,
415
568
  set: columns
416
569
  });
417
- return {
418
- ...session
419
- };
570
+ return this.persisted(session);
420
571
  }
421
572
  async delete(id) {
422
- await this.db.delete(mediaUploadSessionsPgTable).where(eq3(mediaUploadSessionsPgTable.id, id));
573
+ await this.db.delete(mediaUploadSessionsPgTable).where(eq4(mediaUploadSessionsPgTable.id, id));
423
574
  }
424
575
  async addPart(id, part) {
425
576
  await this.db.insert(mediaUploadPartsPgTable).values({
@@ -440,7 +591,7 @@ var DrizzlePgUploadSessionStore = class {
440
591
  const rows = await this.db.select({
441
592
  partNumber: mediaUploadPartsPgTable.partNumber,
442
593
  etag: mediaUploadPartsPgTable.etag
443
- }).from(mediaUploadPartsPgTable).where(eq3(mediaUploadPartsPgTable.sessionId, id)).orderBy(asc3(mediaUploadPartsPgTable.partNumber));
594
+ }).from(mediaUploadPartsPgTable).where(eq4(mediaUploadPartsPgTable.sessionId, id)).orderBy(asc3(mediaUploadPartsPgTable.partNumber));
444
595
  return rows.map((row) => ({
445
596
  partNumber: Number(row.partNumber),
446
597
  etag: row.etag
@@ -449,13 +600,16 @@ var DrizzlePgUploadSessionStore = class {
449
600
  async list(filter = {}) {
450
601
  const conditions = [
451
602
  ...filter.disk !== void 0 ? [
452
- eq3(mediaUploadSessionsPgTable.disk, filter.disk)
603
+ eq4(mediaUploadSessionsPgTable.disk, filter.disk)
453
604
  ] : [],
454
605
  ...filter.keyPrefix !== void 0 ? [
455
606
  like(mediaUploadSessionsPgTable.key, `${escapeLike(filter.keyPrefix)}%`)
607
+ ] : [],
608
+ ...filter.tenant ? [
609
+ tenantCondition(mediaUploadSessionsPgTable.tenantId, filter.tenant)
456
610
  ] : []
457
611
  ];
458
- const rows = await this.db.select().from(mediaUploadSessionsPgTable).where(conditions.length ? and3(...conditions) : void 0).orderBy(asc3(mediaUploadSessionsPgTable.createdAt), asc3(mediaUploadSessionsPgTable.id));
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));
459
613
  return rows.map(toSession);
460
614
  }
461
615
  };