From 0fa7aa60232502216dbdeecd2dce7099fb8b4f18 Mon Sep 17 00:00:00 2001 From: Vinzent Zeband Date: Wed, 2 Dec 2026 06:30:33 +0100 Subject: [PATCH] feat(#18)!: enhance insert functionality to support optional generated columns in repositories --- packages/drizzle/README.md | 5 +++ packages/drizzle/src/pg-core/repositories.ts | 2 +- packages/drizzle/src/repository.ts | 23 ++++++++++--- .../drizzle/src/sqlite-core/repositories.ts | 2 +- .../pg-core/repositories.integration.test.ts | 32 +++++++++++++++++++ .../repositories.integration.test.ts | 32 +++++++++++++++++++ 6 files changed, 89 insertions(+), 7 deletions(-) diff --git a/packages/drizzle/README.md b/packages/drizzle/README.md index 313758e..9e1313a 100644 --- a/packages/drizzle/README.md +++ b/packages/drizzle/README.md @@ -70,6 +70,11 @@ import { SqliteRepository } from "@softzweig/spindle-drizzle/sqlite-core"; const assets = PostgresRepository.of(db, assetsTable); ``` +An identity repository takes the table's `$inferInsert` shape, so a column the database +generates, a serial id or a `defaultNow()` timestamp, can be left out of `insert` and comes +back filled from the returned row. A repository that maps rows to a domain entity keeps the +entity's own insert shape instead. + ## Pagination `list` returns one page and the cursor that continues it. A repository declares how its diff --git a/packages/drizzle/src/pg-core/repositories.ts b/packages/drizzle/src/pg-core/repositories.ts index 47331ea..3f35bc3 100644 --- a/packages/drizzle/src/pg-core/repositories.ts +++ b/packages/drizzle/src/pg-core/repositories.ts @@ -30,7 +30,7 @@ export class PostgresRepository< TEntity extends Entity = Entity & InferSelectModel, TFilter extends EntityFilter = EntityFilter, TCursor = EntityId, -> extends AbstractDrizzleRepository { +> extends AbstractDrizzleRepository> { static of< TTable extends PgTable, TFilter extends PostgresIdentityFilter = PostgresIdentityFilter, diff --git a/packages/drizzle/src/repository.ts b/packages/drizzle/src/repository.ts index 335fb20..beb4028 100644 --- a/packages/drizzle/src/repository.ts +++ b/packages/drizzle/src/repository.ts @@ -219,13 +219,16 @@ export const pagingByCreatedAt = (table: { * * The table is the first parameter and the entity defaults to its row type, so an * identity repository only has to name the table while a mapper-driven one names - * both. + * both. The last one is what a caller may supply to create a row: it defaults to the + * entity's insert shape, and an identity binding narrows it to the table's insert + * model, so columns the database generates are optional at the call site. */ export abstract class AbstractDrizzleRepository< TTable extends Table, TEntity extends Entity = Entity & InferSelectModel, TFilter extends EntityFilter = EntityFilter, TCursor = EntityId, + TInsert extends Row = EntityInsert, > extends AbstractRepository { /** The table this repository reads and writes. */ readonly table: TTable; @@ -309,10 +312,20 @@ export abstract class AbstractDrizzleRepository< return this.toDtos(rows); } - override async insert(dto: Readonly>): Promise { - const rows = await this.attempt(() => - this.db.insert(this.source()).values(this.toRow(dto)).returning(), - ); + /** + * Inserts a new entity and returns the row the database reports. + * + * Accepts the entity's insert shape, and the adapter's own when it binds one. An + * identity binding narrows that to the table's insert model, so an id or a timestamp + * the database generates may be left out instead of being supplied here. + */ + override async insert( + dto: Readonly | Readonly>, + ): Promise { + // `TInsert` is the adapter's own insert shape, which `toRow` narrows to the columns + // the table accepts. + const values = this.toRow(dto as Readonly>>); + const rows = await this.attempt(() => this.db.insert(this.source()).values(values).returning()); const [row] = rows; if (!row) throw new TypeError("insert returned no row"); diff --git a/packages/drizzle/src/sqlite-core/repositories.ts b/packages/drizzle/src/sqlite-core/repositories.ts index 6eebe2d..5d11d3c 100644 --- a/packages/drizzle/src/sqlite-core/repositories.ts +++ b/packages/drizzle/src/sqlite-core/repositories.ts @@ -29,7 +29,7 @@ export class SqliteRepository< TEntity extends Entity = Entity & InferSelectModel, TFilter extends EntityFilter = EntityFilter, TCursor = EntityId, -> extends AbstractDrizzleRepository { +> extends AbstractDrizzleRepository> { static of< TTable extends SQLiteTable, TFilter extends SqliteIdentityFilter = SqliteIdentityFilter, diff --git a/packages/drizzle/test/pg-core/repositories.integration.test.ts b/packages/drizzle/test/pg-core/repositories.integration.test.ts index 8701dea..44ba155 100644 --- a/packages/drizzle/test/pg-core/repositories.integration.test.ts +++ b/packages/drizzle/test/pg-core/repositories.integration.test.ts @@ -1,5 +1,7 @@ import { PGlite } from "@electric-sql/pglite"; +import { pgTable, serial, text, timestamp } from "drizzle-orm/pg-core"; import { drizzle } from "drizzle-orm/pglite"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { type Asset, describeRepositoryContract, @@ -29,3 +31,33 @@ describeRepositoryContract("pg-core", async () => { close: () => client.close(), }; }); + +/** A table whose id and timestamp come from the database, not the caller. */ +const notes = pgTable("notes", { + id: serial("id").primaryKey(), + body: text("body").notNull(), + createdAt: timestamp("created_at").notNull().defaultNow(), +}); + +describe("pg-core insert defaults", () => { + const client = new PGlite(); + const repository = PostgresRepository.of(drizzle(client), notes); + + beforeAll(async () => { + await client.exec( + 'create table "notes" ("id" serial primary key, "body" text not null, "created_at" timestamp not null default now())', + ); + }); + + afterAll(async () => { + await client.close(); + }); + + it("inserts a row the database fills and returns the filled entity", async () => { + const created = await repository.insert({ body: "hello" }); + + expect(created.body).toBe("hello"); + expect(created.id).toBeTypeOf("number"); + expect(created.createdAt).toBeInstanceOf(Date); + }); +}); diff --git a/packages/drizzle/test/sqlite-core/repositories.integration.test.ts b/packages/drizzle/test/sqlite-core/repositories.integration.test.ts index a334487..0b7d050 100644 --- a/packages/drizzle/test/sqlite-core/repositories.integration.test.ts +++ b/packages/drizzle/test/sqlite-core/repositories.integration.test.ts @@ -1,6 +1,8 @@ import { createClient } from "@libsql/client"; +import { sql } from "drizzle-orm"; import { drizzle } from "drizzle-orm/libsql"; import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { type Asset, describeRepositoryContract, @@ -40,3 +42,33 @@ describeRepositoryContract("sqlite-core", async () => { }, }; }); + +/** A table whose id and timestamp come from the database, not the caller. */ +const notes = sqliteTable("notes", { + id: integer("id").primaryKey({ autoIncrement: true }), + body: text("body").notNull(), + createdAt: integer("created_at", { mode: "timestamp" }).notNull().default(sql`(unixepoch())`), +}); + +describe("sqlite-core insert defaults", () => { + const client = createClient({ url: ":memory:" }); + const repository = SqliteRepository.of(drizzle(client), notes); + + beforeAll(async () => { + await client.execute( + 'create table "notes" ("id" integer primary key autoincrement, "body" text not null, "created_at" integer not null default (unixepoch()))', + ); + }); + + afterAll(() => { + client.close(); + }); + + it("inserts a row the database fills and returns the filled entity", async () => { + const created = await repository.insert({ body: "hello" }); + + expect(created.body).toBe("hello"); + expect(created.id).toBeTypeOf("number"); + expect(created.createdAt).toBeInstanceOf(Date); + }); +});