diff --git a/packages/drizzle/README.md b/packages/drizzle/README.md index 9e1313a..01606c6 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); ``` +`of` also takes the paging spec, and its entity type flows into the repository: a spec +typed for a narrower entity, `pagingById` for instance, produces a repository of +`Asset` rather than of the row widened by `Entity`. Without one it pages by the row id and +the entity is the table's own row. + 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 diff --git a/packages/drizzle/src/pg-core/repositories.ts b/packages/drizzle/src/pg-core/repositories.ts index 3f35bc3..f5cb280 100644 --- a/packages/drizzle/src/pg-core/repositories.ts +++ b/packages/drizzle/src/pg-core/repositories.ts @@ -6,12 +6,15 @@ import type { } from "@softzweig/spindle-core/repository"; import type { InferInsertModel, InferSelectModel, SQL } from "drizzle-orm"; import type { PgTable } from "drizzle-orm/pg-core"; -import { AbstractDrizzleRepository, type DrizzleDatabase, pagingById } from "../repository.js"; +import { + AbstractDrizzleRepository, + type DrizzleDatabase, + type DrizzlePaging, + pagingById, + type RowEntity, +} from "../repository.js"; -type PostgresIdentityFilter = EntityFilter< - Entity & InferSelectModel, - SQL ->; +type PostgresIdentityFilter = EntityFilter, SQL>; /** * Postgres binding for entities whose DTO is exactly their table row, so both @@ -27,19 +30,29 @@ type PostgresIdentityFilter = EntityFilter< */ export class PostgresRepository< TTable extends PgTable, - TEntity extends Entity = Entity & InferSelectModel, + TEntity extends Entity = RowEntity, TFilter extends EntityFilter = EntityFilter, TCursor = EntityId, > extends AbstractDrizzleRepository> { + /** + * Binds the identity repository for `table`. + * + * The paging spec decides the entity and the cursor: one typed for a narrower entity + * yields a repository of that entity instead of the row widened by `Entity`. Without + * one, the entity is {@link RowEntity} of the table. + */ static of< TTable extends PgTable, TFilter extends PostgresIdentityFilter = PostgresIdentityFilter, - >(db: DrizzleDatabase, table: TTable) { - return new PostgresRepository, TFilter>( - db, - table, - pagingById(table), - ); + TEntity extends Entity = RowEntity, + TCursor = EntityId, + >( + db: DrizzleDatabase, + table: TTable, + paging: (table: TTable) => DrizzlePaging = (table) => + pagingById(table) as DrizzlePaging, + ): PostgresRepository, TCursor> { + return new PostgresRepository(db, table, paging(table)); } protected toDto(row: InferSelectModel): TEntity { diff --git a/packages/drizzle/src/repository.ts b/packages/drizzle/src/repository.ts index beb4028..a0c42ef 100644 --- a/packages/drizzle/src/repository.ts +++ b/packages/drizzle/src/repository.ts @@ -32,6 +32,23 @@ import { toRepositoryError } from "./errors.js"; /** A row as returned by a statement whose table type is only known generically. */ type Row = Record; +/** + * A row that can stand as an entity: the columns the table selects, and an id a repository + * addresses rows by. + * + * A row that already carries a string or number id is used as it is, so the entity stays + * exactly the selected type. A table without one gets the id added. + * + * Unlike `Entity & InferSelectModel`, no index signature is added, so the entity + * keeps exactly the table's keys and a property the table does not have is a type error. + */ +export type RowEntity = + InferSelectModel extends { + id: string | number; + } + ? InferSelectModel + : InferSelectModel & { id: string | number }; + /** A selected row set, with the limit step every dialect supports. */ interface SelectedTable { where(condition: SQL | undefined): PromiseLike; @@ -225,7 +242,7 @@ export const pagingByCreatedAt = (table: { */ export abstract class AbstractDrizzleRepository< TTable extends Table, - TEntity extends Entity = Entity & InferSelectModel, + TEntity extends Entity = RowEntity, TFilter extends EntityFilter = EntityFilter, TCursor = EntityId, TInsert extends Row = EntityInsert, diff --git a/packages/drizzle/src/sqlite-core/repositories.ts b/packages/drizzle/src/sqlite-core/repositories.ts index 5d11d3c..55f3e35 100644 --- a/packages/drizzle/src/sqlite-core/repositories.ts +++ b/packages/drizzle/src/sqlite-core/repositories.ts @@ -6,12 +6,15 @@ import type { } from "@softzweig/spindle-core/repository"; import type { InferInsertModel, InferSelectModel, SQL } from "drizzle-orm"; import type { SQLiteTable } from "drizzle-orm/sqlite-core"; -import { AbstractDrizzleRepository, type DrizzleDatabase, pagingById } from "../repository.js"; +import { + AbstractDrizzleRepository, + type DrizzleDatabase, + type DrizzlePaging, + pagingById, + type RowEntity, +} from "../repository.js"; -type SqliteIdentityFilter = EntityFilter< - Entity & InferSelectModel, - SQL ->; +type SqliteIdentityFilter = EntityFilter, SQL>; /** * SQLite binding for entities whose DTO is exactly their table row, so both @@ -26,19 +29,29 @@ type SqliteIdentityFilter = EntityFilter< */ export class SqliteRepository< TTable extends SQLiteTable, - TEntity extends Entity = Entity & InferSelectModel, + TEntity extends Entity = RowEntity, TFilter extends EntityFilter = EntityFilter, TCursor = EntityId, > extends AbstractDrizzleRepository> { + /** + * Binds the identity repository for `table`. + * + * The paging spec decides the entity and the cursor: one typed for a narrower entity + * yields a repository of that entity instead of the row widened by `Entity`. Without + * one, the entity is {@link RowEntity} of the table. + */ static of< TTable extends SQLiteTable, TFilter extends SqliteIdentityFilter = SqliteIdentityFilter, - >(db: DrizzleDatabase, table: TTable) { - return new SqliteRepository, TFilter>( - db, - table, - pagingById(table), - ); + TEntity extends Entity = RowEntity, + TCursor = EntityId, + >( + db: DrizzleDatabase, + table: TTable, + paging: (table: TTable) => DrizzlePaging = (table) => + pagingById(table) as DrizzlePaging, + ): SqliteRepository, TCursor> { + return new SqliteRepository(db, table, paging(table)); } protected toDto(row: InferSelectModel): TEntity { diff --git a/packages/drizzle/test/pg-core/repositories.unit.test.ts b/packages/drizzle/test/pg-core/repositories.unit.test.ts new file mode 100644 index 0000000..6ad9ff6 --- /dev/null +++ b/packages/drizzle/test/pg-core/repositories.unit.test.ts @@ -0,0 +1,49 @@ +import type { Page } from "@softzweig/spindle-core/repository"; +import { drizzle } from "drizzle-orm/pg-proxy"; +import { describe, expect, expectTypeOf, it } from "vitest"; +import type { Asset } from "../../../core/test/contract/repository.contract.js"; +import { PostgresRepository } from "../../src/pg-core/repositories.js"; +import { type CreatedAtCursor, pagingByCreatedAt, type RowEntity } from "../../src/repository.js"; +import { assets } from "../support/assets.js"; + +type Query = { sql: string; params: unknown[] }; + +/** A pg-proxy connection that records the statements it runs and answers with no rows. */ +const createProxy = (queries: Query[] = []) => + drizzle(async (sql, params) => { + queries.push({ sql, params }); + + return { rows: [] }; + }); + +describe("PostgresRepository.of", () => { + it("takes the entity and cursor from the paging spec", () => { + const repository = PostgresRepository.of(createProxy(), assets, pagingByCreatedAt); + + expectTypeOf(repository.findMany).returns.toEqualTypeOf>(); + expectTypeOf(repository.list).returns.toEqualTypeOf< + Promise>> + >(); + }); + + it("defaults to the row itself instead of widening it with `Entity`", () => { + const repository = PostgresRepository.of(createProxy(), assets); + + expectTypeOf(repository.findMany).returns.toEqualTypeOf[]>>(); + // The row already has an id, so the conditional keeps the selected type as it is. + expectTypeOf>().toEqualTypeOf(); + }); + + it("pages in the order its paging spec declares", async () => { + const queries: Query[] = []; + const repository = PostgresRepository.of( + createProxy(queries), + assets, + pagingByCreatedAt, + ); + + await repository.list({ limit: 1 }); + + expect(queries[0]?.sql).toContain('order by "assets"."created_at" desc, "assets"."id" desc'); + }); +}); diff --git a/packages/drizzle/test/repository.unit.test.ts b/packages/drizzle/test/repository.unit.test.ts index 135ed10..45c7e03 100644 --- a/packages/drizzle/test/repository.unit.test.ts +++ b/packages/drizzle/test/repository.unit.test.ts @@ -211,6 +211,17 @@ describe("AbstractDrizzleRepository", () => { ).rejects.toThrow(TypeError); }); + it("keeps the entity insert shape when the binding maps its own rows", () => { + const repository = new AssetRepository(createProxy([], () => [])); + + const insertWithoutTimestamp = () => { + // @ts-expect-error a mapper binding has no column defaults to fall back on + return repository.insert({ key: "assets/a.png", size: 42, note: null }); + }; + + expect(insertWithoutTimestamp).toBeTypeOf("function"); + }); + it("patches by id and maps the returned row", async () => { const { repository, queries } = createRepository(); diff --git a/packages/drizzle/test/sqlite-core/repositories.unit.test.ts b/packages/drizzle/test/sqlite-core/repositories.unit.test.ts new file mode 100644 index 0000000..b0c532b --- /dev/null +++ b/packages/drizzle/test/sqlite-core/repositories.unit.test.ts @@ -0,0 +1,55 @@ +import type { Page } from "@softzweig/spindle-core/repository"; +import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; +import { drizzle } from "drizzle-orm/sqlite-proxy"; +import { describe, expect, expectTypeOf, it } from "vitest"; +import { type CreatedAtCursor, pagingByCreatedAt, type RowEntity } from "../../src/repository.js"; +import { SqliteRepository } from "../../src/sqlite-core/repositories.js"; + +const notes = sqliteTable("notes", { + id: text("id").primaryKey(), + body: text("body").notNull(), + createdAt: integer("created_at", { mode: "timestamp" }).notNull(), +}); + +type Note = { readonly id: string; readonly body: string; readonly createdAt: Date }; + +/** A sqlite-proxy connection that records the statements it runs and answers with no rows. */ +const createProxy = (queries: string[] = []) => + drizzle(async (statement) => { + queries.push(statement); + + return { rows: [] }; + }); + +describe("SqliteRepository.of", () => { + it("takes the entity and cursor from the paging spec", () => { + const repository = SqliteRepository.of(createProxy(), notes, pagingByCreatedAt); + + expectTypeOf(repository.findMany).returns.toEqualTypeOf>(); + expectTypeOf(repository.list).returns.toEqualTypeOf< + Promise>> + >(); + }); + + it("defaults to the row itself instead of widening it with `Entity`", () => { + const repository = SqliteRepository.of(createProxy(), notes); + + expectTypeOf(repository.findMany).returns.toEqualTypeOf[]>>(); + expectTypeOf>().toEqualTypeOf(); + }); + + it("adds an id to a row that has none", () => { + const keys = sqliteTable("keys", { key: text("key").notNull() }); + + expectTypeOf>().toHaveProperty("id").toEqualTypeOf(); + }); + + it("pages in the order its paging spec declares", async () => { + const queries: string[] = []; + const repository = SqliteRepository.of(createProxy(queries), notes, pagingByCreatedAt); + + await repository.list({ limit: 1 }); + + expect(queries[0]).toContain('order by "notes"."created_at" desc, "notes"."id" desc'); + }); +});