@dudousxd/nestjs-media-database-drizzle 0.7.0 → 0.9.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.
package/dist/pg/index.cjs CHANGED
@@ -49,13 +49,16 @@ var MEDIA_PG_DDL = [
49
49
  "custom_properties" jsonb NOT NULL,
50
50
  "conversions" jsonb NOT NULL,
51
51
  "created_at" timestamp with time zone NOT NULL,
52
- "updated_at" timestamp with time zone NOT NULL
52
+ "updated_at" timestamp with time zone NOT NULL,
53
+ "tenant_id" text
53
54
  )`,
55
+ `ALTER TABLE "media" ADD COLUMN IF NOT EXISTS "tenant_id" text`,
54
56
  `CREATE INDEX IF NOT EXISTS "idx_media_owner" ON "media" ("owner_type", "owner_id", "collection")`,
55
57
  `CREATE INDEX IF NOT EXISTS "idx_media_collection" ON "media" ("collection")`,
56
58
  `CREATE INDEX IF NOT EXISTS "idx_media_disk" ON "media" ("disk")`,
57
59
  `CREATE INDEX IF NOT EXISTS "idx_media_created_at" ON "media" ("created_at")`,
58
60
  `CREATE INDEX IF NOT EXISTS "idx_media_collection_created_at" ON "media" ("collection", "created_at", "id")`,
61
+ `CREATE INDEX IF NOT EXISTS "idx_media_tenant" ON "media" ("tenant_id", "owner_type", "owner_id", "collection")`,
59
62
  `CREATE TABLE IF NOT EXISTS "media_upload_sessions" (
60
63
  "id" text PRIMARY KEY NOT NULL,
61
64
  "disk" text NOT NULL,
@@ -67,8 +70,11 @@ var MEDIA_PG_DDL = [
67
70
  "multipart_upload_id" text,
68
71
  "metadata" jsonb,
69
72
  "created_at" timestamp with time zone DEFAULT now() NOT NULL,
70
- "updated_at" timestamp with time zone DEFAULT now() NOT NULL
73
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL,
74
+ "tenant_id" text
71
75
  )`,
76
+ `ALTER TABLE "media_upload_sessions" ADD COLUMN IF NOT EXISTS "tenant_id" text`,
77
+ `CREATE INDEX IF NOT EXISTS "idx_media_upload_sessions_tenant" ON "media_upload_sessions" ("tenant_id")`,
72
78
  `CREATE TABLE IF NOT EXISTS "media_upload_parts" (
73
79
  "session_id" text NOT NULL REFERENCES "media_upload_sessions" ("id") ON DELETE CASCADE,
74
80
  "part_number" integer NOT NULL,
@@ -84,7 +90,7 @@ async function createMediaPgTables(db) {
84
90
  __name(createMediaPgTables, "createMediaPgTables");
85
91
 
86
92
  // src/pg/drizzle-pg-media-store.ts
87
- var import_drizzle_orm2 = require("drizzle-orm");
93
+ var import_drizzle_orm3 = require("drizzle-orm");
88
94
 
89
95
  // src/list-cursor.ts
90
96
  function encodeListCursor(record) {
@@ -105,70 +111,119 @@ function decodeListCursor(cursor) {
105
111
  }
106
112
  __name(decodeListCursor, "decodeListCursor");
107
113
 
108
- // src/pg/schema.ts
114
+ // src/tenancy.ts
115
+ var import_nestjs_media_core = require("@dudousxd/nestjs-media-core");
116
+ var import_drizzle_orm2 = require("drizzle-orm");
117
+ function tenantCondition(column, match) {
118
+ if (match.id === null) return (0, import_drizzle_orm2.isNull)(column);
119
+ return match.orNull ? (0, import_drizzle_orm2.or)((0, import_drizzle_orm2.eq)(column, match.id), (0, import_drizzle_orm2.isNull)(column)) : (0, import_drizzle_orm2.eq)(column, match.id);
120
+ }
121
+ __name(tenantCondition, "tenantCondition");
122
+ function selectable(columns, tenancy) {
123
+ if (tenancy) return columns;
124
+ const { tenantId: _tenantId, ...rest } = columns;
125
+ return rest;
126
+ }
127
+ __name(selectable, "selectable");
128
+ async function assertTenantColumn(table, probe, fix) {
129
+ try {
130
+ await probe();
131
+ } catch (error) {
132
+ throw Object.assign(new import_nestjs_media_core.MediaTenancyUnavailableError(`the \`${table}\` table has no \`tenant_id\` column`, fix), {
133
+ cause: error
134
+ });
135
+ }
136
+ }
137
+ __name(assertTenantColumn, "assertTenantColumn");
138
+
139
+ // src/pg/columns.ts
109
140
  var import_pg_core = require("drizzle-orm/pg-core");
110
- var mediaPgTable = (0, import_pg_core.pgTable)("media", {
111
- id: (0, import_pg_core.text)("id").primaryKey(),
112
- ownerType: (0, import_pg_core.text)("owner_type").notNull(),
113
- ownerId: (0, import_pg_core.text)("owner_id").notNull(),
114
- collection: (0, import_pg_core.text)("collection").notNull(),
115
- name: (0, import_pg_core.text)("name").notNull(),
116
- fileName: (0, import_pg_core.text)("file_name").notNull(),
117
- mimeType: (0, import_pg_core.text)("mime_type").notNull(),
118
- size: (0, import_pg_core.bigint)("size", {
119
- mode: "number"
120
- }).notNull(),
121
- disk: (0, import_pg_core.text)("disk").notNull(),
122
- path: (0, import_pg_core.text)("path").notNull(),
123
- order: (0, import_pg_core.integer)("position").notNull(),
124
- customProperties: (0, import_pg_core.jsonb)("custom_properties").$type().notNull(),
125
- conversions: (0, import_pg_core.jsonb)("conversions").$type().notNull(),
126
- createdAt: (0, import_pg_core.timestamp)("created_at", {
127
- withTimezone: true,
128
- mode: "date"
129
- }).notNull(),
130
- updatedAt: (0, import_pg_core.timestamp)("updated_at", {
131
- withTimezone: true,
132
- mode: "date"
133
- }).notNull()
141
+ function mediaPgColumns() {
142
+ return {
143
+ id: (0, import_pg_core.text)("id").primaryKey(),
144
+ ownerType: (0, import_pg_core.text)("owner_type").notNull(),
145
+ ownerId: (0, import_pg_core.text)("owner_id").notNull(),
146
+ collection: (0, import_pg_core.text)("collection").notNull(),
147
+ name: (0, import_pg_core.text)("name").notNull(),
148
+ fileName: (0, import_pg_core.text)("file_name").notNull(),
149
+ mimeType: (0, import_pg_core.text)("mime_type").notNull(),
150
+ size: (0, import_pg_core.bigint)("size", {
151
+ mode: "number"
152
+ }).notNull(),
153
+ disk: (0, import_pg_core.text)("disk").notNull(),
154
+ path: (0, import_pg_core.text)("path").notNull(),
155
+ order: (0, import_pg_core.integer)("position").notNull(),
156
+ customProperties: (0, import_pg_core.jsonb)("custom_properties").$type().notNull(),
157
+ conversions: (0, import_pg_core.jsonb)("conversions").$type().notNull(),
158
+ createdAt: (0, import_pg_core.timestamp)("created_at", {
159
+ withTimezone: true,
160
+ mode: "date"
161
+ }).notNull(),
162
+ updatedAt: (0, import_pg_core.timestamp)("updated_at", {
163
+ withTimezone: true,
164
+ mode: "date"
165
+ }).notNull()
166
+ };
167
+ }
168
+ __name(mediaPgColumns, "mediaPgColumns");
169
+ function uploadSessionPgColumns() {
170
+ return {
171
+ id: (0, import_pg_core.text)("id").primaryKey(),
172
+ disk: (0, import_pg_core.text)("disk").notNull(),
173
+ key: (0, import_pg_core.text)("key").notNull(),
174
+ contentType: (0, import_pg_core.text)("content_type"),
175
+ size: (0, import_pg_core.bigint)("size", {
176
+ mode: "number"
177
+ }),
178
+ offset: (0, import_pg_core.bigint)("offset", {
179
+ mode: "number"
180
+ }).notNull().default(0),
181
+ parts: (0, import_pg_core.integer)("parts").notNull().default(0),
182
+ multipartUploadId: (0, import_pg_core.text)("multipart_upload_id"),
183
+ metadata: (0, import_pg_core.jsonb)("metadata").$type(),
184
+ createdAt: (0, import_pg_core.timestamp)("created_at", {
185
+ withTimezone: true,
186
+ mode: "date"
187
+ }).notNull().defaultNow(),
188
+ updatedAt: (0, import_pg_core.timestamp)("updated_at", {
189
+ withTimezone: true,
190
+ mode: "date"
191
+ }).notNull().defaultNow()
192
+ };
193
+ }
194
+ __name(uploadSessionPgColumns, "uploadSessionPgColumns");
195
+ var mediaPgTableWithoutTenant = (0, import_pg_core.pgTable)("media", mediaPgColumns());
196
+ var mediaUploadSessionsPgTableWithoutTenant = (0, import_pg_core.pgTable)("media_upload_sessions", uploadSessionPgColumns());
197
+
198
+ // src/pg/schema.ts
199
+ var import_pg_core2 = require("drizzle-orm/pg-core");
200
+ var mediaPgTable = (0, import_pg_core2.pgTable)("media", {
201
+ ...mediaPgColumns(),
202
+ /** Tenancy only: read and written once the store's `enableTenancy()` ran. */
203
+ tenantId: (0, import_pg_core2.text)("tenant_id")
134
204
  }, (table) => [
135
- (0, import_pg_core.index)("idx_media_owner").on(table.ownerType, table.ownerId, table.collection),
136
- (0, import_pg_core.index)("idx_media_collection").on(table.collection),
137
- (0, import_pg_core.index)("idx_media_disk").on(table.disk),
138
- (0, import_pg_core.index)("idx_media_created_at").on(table.createdAt),
139
- (0, import_pg_core.index)("idx_media_collection_created_at").on(table.collection, table.createdAt, table.id)
205
+ (0, import_pg_core2.index)("idx_media_owner").on(table.ownerType, table.ownerId, table.collection),
206
+ (0, import_pg_core2.index)("idx_media_collection").on(table.collection),
207
+ (0, import_pg_core2.index)("idx_media_disk").on(table.disk),
208
+ (0, import_pg_core2.index)("idx_media_created_at").on(table.createdAt),
209
+ (0, import_pg_core2.index)("idx_media_collection_created_at").on(table.collection, table.createdAt, table.id),
210
+ (0, import_pg_core2.index)("idx_media_tenant").on(table.tenantId, table.ownerType, table.ownerId, table.collection)
140
211
  ]);
141
- var mediaUploadSessionsPgTable = (0, import_pg_core.pgTable)("media_upload_sessions", {
142
- id: (0, import_pg_core.text)("id").primaryKey(),
143
- disk: (0, import_pg_core.text)("disk").notNull(),
144
- key: (0, import_pg_core.text)("key").notNull(),
145
- contentType: (0, import_pg_core.text)("content_type"),
146
- size: (0, import_pg_core.bigint)("size", {
147
- mode: "number"
148
- }),
149
- offset: (0, import_pg_core.bigint)("offset", {
150
- mode: "number"
151
- }).notNull().default(0),
152
- parts: (0, import_pg_core.integer)("parts").notNull().default(0),
153
- multipartUploadId: (0, import_pg_core.text)("multipart_upload_id"),
154
- metadata: (0, import_pg_core.jsonb)("metadata").$type(),
155
- createdAt: (0, import_pg_core.timestamp)("created_at", {
156
- withTimezone: true,
157
- mode: "date"
158
- }).notNull().defaultNow(),
159
- updatedAt: (0, import_pg_core.timestamp)("updated_at", {
160
- withTimezone: true,
161
- mode: "date"
162
- }).notNull().defaultNow()
163
- });
164
- var mediaUploadPartsPgTable = (0, import_pg_core.pgTable)("media_upload_parts", {
165
- sessionId: (0, import_pg_core.text)("session_id").notNull().references(() => mediaUploadSessionsPgTable.id, {
212
+ var mediaUploadSessionsPgTable = (0, import_pg_core2.pgTable)("media_upload_sessions", {
213
+ ...uploadSessionPgColumns(),
214
+ /** Tenancy only: read and written once the store's `enableTenancy()` ran. */
215
+ tenantId: (0, import_pg_core2.text)("tenant_id")
216
+ }, (table) => [
217
+ (0, import_pg_core2.index)("idx_media_upload_sessions_tenant").on(table.tenantId)
218
+ ]);
219
+ var mediaUploadPartsPgTable = (0, import_pg_core2.pgTable)("media_upload_parts", {
220
+ sessionId: (0, import_pg_core2.text)("session_id").notNull().references(() => mediaUploadSessionsPgTable.id, {
166
221
  onDelete: "cascade"
167
222
  }),
168
- partNumber: (0, import_pg_core.integer)("part_number").notNull(),
169
- etag: (0, import_pg_core.text)("etag").notNull()
223
+ partNumber: (0, import_pg_core2.integer)("part_number").notNull(),
224
+ etag: (0, import_pg_core2.text)("etag").notNull()
170
225
  }, (table) => [
171
- (0, import_pg_core.primaryKey)({
226
+ (0, import_pg_core2.primaryKey)({
172
227
  columns: [
173
228
  table.sessionId,
174
229
  table.partNumber
@@ -184,66 +239,93 @@ function toRecord(row) {
184
239
  };
185
240
  }
186
241
  __name(toRecord, "toRecord");
242
+ function toRow(record, tenancy) {
243
+ const { tenantId, ...rest } = record;
244
+ return tenancy ? {
245
+ ...rest,
246
+ tenantId: tenantId ?? null
247
+ } : rest;
248
+ }
249
+ __name(toRow, "toRow");
187
250
  var DrizzlePgMediaStore = class {
188
251
  static {
189
252
  __name(this, "DrizzlePgMediaStore");
190
253
  }
191
254
  db;
255
+ tenancy = false;
192
256
  constructor(db) {
193
257
  this.db = db;
194
258
  }
259
+ /** The columns to read: `tenant_id` only once tenancy is on. */
260
+ get columns() {
261
+ return selectable((0, import_drizzle_orm3.getTableColumns)(mediaPgTable), this.tenancy);
262
+ }
263
+ /**
264
+ * Tenancy: checks the `tenant_id` column exists, then reads and writes it. Called by the
265
+ * library when tenancy is on; until then the column is never touched.
266
+ */
267
+ async enableTenancy() {
268
+ await assertTenantColumn("media", () => this.db.select({
269
+ tenantId: mediaPgTable.tenantId
270
+ }).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);`.");
271
+ this.tenancy = true;
272
+ }
195
273
  async save(record) {
196
- const { id: _id, ...rest } = record;
197
- await this.db.insert(mediaPgTable).values(record).onConflictDoUpdate({
274
+ const row = toRow(record, this.tenancy);
275
+ const { id: _id, ...rest } = row;
276
+ await this.db.insert(this.tenancy ? mediaPgTable : mediaPgTableWithoutTenant).values(row).onConflictDoUpdate({
198
277
  target: mediaPgTable.id,
199
278
  set: rest
200
279
  });
201
- return record;
280
+ return row;
202
281
  }
203
282
  async find(id) {
204
- const rows = await this.db.select().from(mediaPgTable).where((0, import_drizzle_orm2.eq)(mediaPgTable.id, id)).limit(1);
283
+ const rows = await this.db.select(this.columns).from(mediaPgTable).where((0, import_drizzle_orm3.eq)(mediaPgTable.id, id)).limit(1);
205
284
  const row = rows[0];
206
285
  return row ? toRecord(row) : null;
207
286
  }
208
287
  async listByOwner(ownerType, ownerId, collection) {
209
- const where = collection === void 0 ? (0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(mediaPgTable.ownerType, ownerType), (0, import_drizzle_orm2.eq)(mediaPgTable.ownerId, ownerId)) : (0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(mediaPgTable.ownerType, ownerType), (0, import_drizzle_orm2.eq)(mediaPgTable.ownerId, ownerId), (0, import_drizzle_orm2.eq)(mediaPgTable.collection, collection));
210
- const rows = await this.db.select().from(mediaPgTable).where(where).orderBy((0, import_drizzle_orm2.asc)(mediaPgTable.order), (0, import_drizzle_orm2.asc)(mediaPgTable.id));
288
+ const where = collection === void 0 ? (0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(mediaPgTable.ownerType, ownerType), (0, import_drizzle_orm3.eq)(mediaPgTable.ownerId, ownerId)) : (0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(mediaPgTable.ownerType, ownerType), (0, import_drizzle_orm3.eq)(mediaPgTable.ownerId, ownerId), (0, import_drizzle_orm3.eq)(mediaPgTable.collection, collection));
289
+ const rows = await this.db.select(this.columns).from(mediaPgTable).where(where).orderBy((0, import_drizzle_orm3.asc)(mediaPgTable.order), (0, import_drizzle_orm3.asc)(mediaPgTable.id));
211
290
  return rows.map(toRecord);
212
291
  }
213
292
  async delete(id) {
214
- await this.db.delete(mediaPgTable).where((0, import_drizzle_orm2.eq)(mediaPgTable.id, id));
293
+ await this.db.delete(mediaPgTable).where((0, import_drizzle_orm3.eq)(mediaPgTable.id, id));
215
294
  }
216
295
  async nextOrder(ownerType, ownerId, collection) {
217
296
  const rows = await this.db.select({
218
- max: (0, import_drizzle_orm2.max)(mediaPgTable.order)
219
- }).from(mediaPgTable).where((0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(mediaPgTable.ownerType, ownerType), (0, import_drizzle_orm2.eq)(mediaPgTable.ownerId, ownerId), (0, import_drizzle_orm2.eq)(mediaPgTable.collection, collection)));
297
+ max: (0, import_drizzle_orm3.max)(mediaPgTable.order)
298
+ }).from(mediaPgTable).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(mediaPgTable.ownerType, ownerType), (0, import_drizzle_orm3.eq)(mediaPgTable.ownerId, ownerId), (0, import_drizzle_orm3.eq)(mediaPgTable.collection, collection)));
220
299
  const top = rows[0]?.max;
221
300
  return top == null ? 0 : Number(top) + 1;
222
301
  }
223
302
  async count(filter = {}) {
224
303
  const conditions = [
225
304
  ...filter.ownerType !== void 0 ? [
226
- (0, import_drizzle_orm2.eq)(mediaPgTable.ownerType, filter.ownerType)
305
+ (0, import_drizzle_orm3.eq)(mediaPgTable.ownerType, filter.ownerType)
227
306
  ] : [],
228
307
  ...filter.collection !== void 0 ? [
229
- (0, import_drizzle_orm2.eq)(mediaPgTable.collection, filter.collection)
308
+ (0, import_drizzle_orm3.eq)(mediaPgTable.collection, filter.collection)
230
309
  ] : [],
231
310
  ...filter.disk !== void 0 ? [
232
- (0, import_drizzle_orm2.eq)(mediaPgTable.disk, filter.disk)
311
+ (0, import_drizzle_orm3.eq)(mediaPgTable.disk, filter.disk)
312
+ ] : [],
313
+ ...filter.tenant ? [
314
+ tenantCondition(mediaPgTable.tenantId, filter.tenant)
233
315
  ] : []
234
316
  ];
235
317
  const rows = await this.db.select({
236
- value: (0, import_drizzle_orm2.count)()
237
- }).from(mediaPgTable).where(conditions.length ? (0, import_drizzle_orm2.and)(...conditions) : void 0);
318
+ value: (0, import_drizzle_orm3.count)()
319
+ }).from(mediaPgTable).where(conditions.length ? (0, import_drizzle_orm3.and)(...conditions) : void 0);
238
320
  return Number(rows[0]?.value ?? 0);
239
321
  }
240
322
  async aggregate(query) {
241
323
  const column = query.groupBy === "collection" ? mediaPgTable.collection : mediaPgTable.disk;
242
324
  const rows = await this.db.select({
243
325
  key: column,
244
- count: (0, import_drizzle_orm2.count)(),
245
- sumSize: (0, import_drizzle_orm2.sum)(mediaPgTable.size)
246
- }).from(mediaPgTable).groupBy(column);
326
+ count: (0, import_drizzle_orm3.count)(),
327
+ sumSize: (0, import_drizzle_orm3.sum)(mediaPgTable.size)
328
+ }).from(mediaPgTable).where(query.tenant ? tenantCondition(mediaPgTable.tenantId, query.tenant) : void 0).groupBy(column);
247
329
  return rows.map((row) => ({
248
330
  key: row.key,
249
331
  count: Number(row.count),
@@ -256,19 +338,22 @@ var DrizzlePgMediaStore = class {
256
338
  const cursor = page.cursor ? decodeListCursor(page.cursor) : null;
257
339
  const filterConditions = [
258
340
  ...filter.ownerType !== void 0 ? [
259
- (0, import_drizzle_orm2.eq)(mediaPgTable.ownerType, filter.ownerType)
341
+ (0, import_drizzle_orm3.eq)(mediaPgTable.ownerType, filter.ownerType)
260
342
  ] : [],
261
343
  ...filter.collection !== void 0 ? [
262
- (0, import_drizzle_orm2.eq)(mediaPgTable.collection, filter.collection)
344
+ (0, import_drizzle_orm3.eq)(mediaPgTable.collection, filter.collection)
263
345
  ] : [],
264
346
  ...filter.disk !== void 0 ? [
265
- (0, import_drizzle_orm2.eq)(mediaPgTable.disk, filter.disk)
347
+ (0, import_drizzle_orm3.eq)(mediaPgTable.disk, filter.disk)
348
+ ] : [],
349
+ ...filter.tenant ? [
350
+ tenantCondition(mediaPgTable.tenantId, filter.tenant)
266
351
  ] : [],
267
352
  ...cursor ? [
268
- (0, import_drizzle_orm2.or)((0, import_drizzle_orm2.gt)(mediaPgTable.createdAt, cursor.createdAt), (0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(mediaPgTable.createdAt, cursor.createdAt), (0, import_drizzle_orm2.gt)(mediaPgTable.id, cursor.id)))
353
+ (0, import_drizzle_orm3.or)((0, import_drizzle_orm3.gt)(mediaPgTable.createdAt, cursor.createdAt), (0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(mediaPgTable.createdAt, cursor.createdAt), (0, import_drizzle_orm3.gt)(mediaPgTable.id, cursor.id)))
269
354
  ] : []
270
355
  ];
271
- const rows = await this.db.select().from(mediaPgTable).where(filterConditions.length ? (0, import_drizzle_orm2.and)(...filterConditions) : void 0).orderBy((0, import_drizzle_orm2.asc)(mediaPgTable.createdAt), (0, import_drizzle_orm2.asc)(mediaPgTable.id)).limit(limit + 1);
356
+ const rows = await this.db.select(this.columns).from(mediaPgTable).where(filterConditions.length ? (0, import_drizzle_orm3.and)(...filterConditions) : void 0).orderBy((0, import_drizzle_orm3.asc)(mediaPgTable.createdAt), (0, import_drizzle_orm3.asc)(mediaPgTable.id)).limit(limit + 1);
272
357
  const hasMore = rows.length > limit;
273
358
  const records = rows.slice(0, limit).map(toRecord);
274
359
  const result = {
@@ -283,7 +368,7 @@ var DrizzlePgMediaStore = class {
283
368
  };
284
369
 
285
370
  // src/pg/drizzle-pg-upload-session-store.ts
286
- var import_drizzle_orm3 = require("drizzle-orm");
371
+ var import_drizzle_orm4 = require("drizzle-orm");
287
372
  function escapeLike(value) {
288
373
  return value.replace(/[\\%_]/g, (char) => `\\${char}`);
289
374
  }
@@ -301,11 +386,15 @@ function toSession(row) {
301
386
  };
302
387
  if (row.multipartUploadId != null) session.multipartUploadId = row.multipartUploadId;
303
388
  if (row.metadata != null) session.metadata = row.metadata;
389
+ if (row.tenantId !== void 0) session.tenantId = row.tenantId;
304
390
  return session;
305
391
  }
306
392
  __name(toSession, "toSession");
307
- function toColumns(session) {
393
+ function toColumns(session, tenancy) {
308
394
  return {
395
+ ...tenancy ? {
396
+ tenantId: session.tenantId ?? null
397
+ } : {},
309
398
  disk: session.disk,
310
399
  key: session.key,
311
400
  contentType: session.contentType ?? null,
@@ -322,48 +411,73 @@ var DrizzlePgUploadSessionStore = class {
322
411
  __name(this, "DrizzlePgUploadSessionStore");
323
412
  }
324
413
  db;
414
+ tenancy = false;
325
415
  constructor(db) {
326
416
  this.db = db;
327
417
  }
418
+ /** Off: the table without `tenant_id`, which Drizzle would otherwise list in an INSERT. */
419
+ get sessionsTable() {
420
+ return this.tenancy ? mediaUploadSessionsPgTable : mediaUploadSessionsPgTableWithoutTenant;
421
+ }
422
+ /** The columns to read: `tenant_id` only once tenancy is on. */
423
+ get columns() {
424
+ return selectable((0, import_drizzle_orm4.getTableColumns)(mediaUploadSessionsPgTable), this.tenancy);
425
+ }
426
+ /**
427
+ * Tenancy: checks the `tenant_id` column exists, then reads and writes it. Called by the upload
428
+ * manager when tenancy is on; until then the column is never touched.
429
+ */
430
+ async enableTenancy() {
431
+ await assertTenantColumn("media_upload_sessions", () => this.db.select({
432
+ tenantId: mediaUploadSessionsPgTable.tenantId
433
+ }).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);`.");
434
+ this.tenancy = true;
435
+ }
436
+ /** The session as persisted: off, no `tenantId`; on, `tenantId` or `null`. */
437
+ persisted(session) {
438
+ const { tenantId, ...rest } = session;
439
+ return this.tenancy ? {
440
+ ...rest,
441
+ tenantId: tenantId ?? null
442
+ } : rest;
443
+ }
328
444
  async create(session) {
329
445
  const createdAt = session.createdAt ?? /* @__PURE__ */ new Date();
330
- await this.db.insert(mediaUploadSessionsPgTable).values({
446
+ await this.db.insert(this.sessionsTable).values({
331
447
  id: session.id,
332
- ...toColumns(session),
448
+ ...toColumns(session, this.tenancy),
333
449
  createdAt,
334
450
  updatedAt: /* @__PURE__ */ new Date()
335
451
  });
336
452
  return {
337
- ...session,
453
+ ...this.persisted(session),
338
454
  createdAt
339
455
  };
340
456
  }
341
457
  async get(id) {
342
- const rows = await this.db.select().from(mediaUploadSessionsPgTable).where((0, import_drizzle_orm3.eq)(mediaUploadSessionsPgTable.id, id)).limit(1);
458
+ const rows = await this.db.select(this.columns).from(mediaUploadSessionsPgTable).where((0, import_drizzle_orm4.eq)(mediaUploadSessionsPgTable.id, id)).limit(1);
343
459
  const row = rows[0];
344
460
  return row ? toSession(row) : null;
345
461
  }
346
462
  async update(session) {
347
463
  const columns = {
348
- ...toColumns(session),
464
+ ...toColumns(session, this.tenancy),
349
465
  ...session.createdAt !== void 0 ? {
350
466
  createdAt: session.createdAt
351
467
  } : {},
352
468
  updatedAt: /* @__PURE__ */ new Date()
353
469
  };
354
- await this.db.insert(mediaUploadSessionsPgTable).values({
470
+ await this.db.insert(this.sessionsTable).values({
355
471
  id: session.id,
356
472
  ...columns
357
473
  }).onConflictDoUpdate({
358
474
  target: mediaUploadSessionsPgTable.id,
359
475
  set: columns
360
476
  });
361
- return {
362
- ...session
363
- };
477
+ return this.persisted(session);
364
478
  }
365
479
  async delete(id) {
366
- await this.db.delete(mediaUploadSessionsPgTable).where((0, import_drizzle_orm3.eq)(mediaUploadSessionsPgTable.id, id));
480
+ await this.db.delete(mediaUploadSessionsPgTable).where((0, import_drizzle_orm4.eq)(mediaUploadSessionsPgTable.id, id));
367
481
  }
368
482
  async addPart(id, part) {
369
483
  await this.db.insert(mediaUploadPartsPgTable).values({
@@ -376,7 +490,7 @@ var DrizzlePgUploadSessionStore = class {
376
490
  mediaUploadPartsPgTable.partNumber
377
491
  ],
378
492
  set: {
379
- etag: import_drizzle_orm3.sql`excluded.etag`
493
+ etag: import_drizzle_orm4.sql`excluded.etag`
380
494
  }
381
495
  });
382
496
  }
@@ -384,7 +498,7 @@ var DrizzlePgUploadSessionStore = class {
384
498
  const rows = await this.db.select({
385
499
  partNumber: mediaUploadPartsPgTable.partNumber,
386
500
  etag: mediaUploadPartsPgTable.etag
387
- }).from(mediaUploadPartsPgTable).where((0, import_drizzle_orm3.eq)(mediaUploadPartsPgTable.sessionId, id)).orderBy((0, import_drizzle_orm3.asc)(mediaUploadPartsPgTable.partNumber));
501
+ }).from(mediaUploadPartsPgTable).where((0, import_drizzle_orm4.eq)(mediaUploadPartsPgTable.sessionId, id)).orderBy((0, import_drizzle_orm4.asc)(mediaUploadPartsPgTable.partNumber));
388
502
  return rows.map((row) => ({
389
503
  partNumber: Number(row.partNumber),
390
504
  etag: row.etag
@@ -393,13 +507,16 @@ var DrizzlePgUploadSessionStore = class {
393
507
  async list(filter = {}) {
394
508
  const conditions = [
395
509
  ...filter.disk !== void 0 ? [
396
- (0, import_drizzle_orm3.eq)(mediaUploadSessionsPgTable.disk, filter.disk)
510
+ (0, import_drizzle_orm4.eq)(mediaUploadSessionsPgTable.disk, filter.disk)
397
511
  ] : [],
398
512
  ...filter.keyPrefix !== void 0 ? [
399
- (0, import_drizzle_orm3.like)(mediaUploadSessionsPgTable.key, `${escapeLike(filter.keyPrefix)}%`)
513
+ (0, import_drizzle_orm4.like)(mediaUploadSessionsPgTable.key, `${escapeLike(filter.keyPrefix)}%`)
514
+ ] : [],
515
+ ...filter.tenant ? [
516
+ tenantCondition(mediaUploadSessionsPgTable.tenantId, filter.tenant)
400
517
  ] : []
401
518
  ];
402
- const rows = await this.db.select().from(mediaUploadSessionsPgTable).where(conditions.length ? (0, import_drizzle_orm3.and)(...conditions) : void 0).orderBy((0, import_drizzle_orm3.asc)(mediaUploadSessionsPgTable.createdAt), (0, import_drizzle_orm3.asc)(mediaUploadSessionsPgTable.id));
519
+ const rows = await this.db.select(this.columns).from(mediaUploadSessionsPgTable).where(conditions.length ? (0, import_drizzle_orm4.and)(...conditions) : void 0).orderBy((0, import_drizzle_orm4.asc)(mediaUploadSessionsPgTable.createdAt), (0, import_drizzle_orm4.asc)(mediaUploadSessionsPgTable.id));
403
520
  return rows.map(toSession);
404
521
  }
405
522
  };