Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/drizzle/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion packages/drizzle/src/pg-core/repositories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export class PostgresRepository<
TEntity extends Entity = Entity & InferSelectModel<TTable>,
TFilter extends EntityFilter<TEntity, SQL> = EntityFilter<TEntity, SQL>,
TCursor = EntityId<TEntity>,
> extends AbstractDrizzleRepository<TTable, TEntity, TFilter, TCursor> {
> extends AbstractDrizzleRepository<TTable, TEntity, TFilter, TCursor, InferInsertModel<TTable>> {
static of<
TTable extends PgTable,
TFilter extends PostgresIdentityFilter<TTable> = PostgresIdentityFilter<TTable>,
Expand Down
23 changes: 18 additions & 5 deletions packages/drizzle/src/repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,13 +219,16 @@ export const pagingByCreatedAt = <TEntity extends CreatedAtEntity>(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<TTable>,
TFilter extends EntityFilter<TEntity, SQL> = EntityFilter<TEntity, SQL>,
TCursor = EntityId<TEntity>,
TInsert extends Row = EntityInsert<TEntity>,
> extends AbstractRepository<TEntity, DrizzleContext, TFilter, TCursor> {
/** The table this repository reads and writes. */
readonly table: TTable;
Expand Down Expand Up @@ -309,10 +312,20 @@ export abstract class AbstractDrizzleRepository<
return this.toDtos(rows);
}

override async insert(dto: Readonly<EntityInsert<TEntity>>): Promise<TEntity> {
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<TInsert> | Readonly<EntityInsert<TEntity>>,
): Promise<TEntity> {
// `TInsert` is the adapter's own insert shape, which `toRow` narrows to the columns
// the table accepts.
const values = this.toRow(dto as Readonly<Partial<EntityInsert<TEntity>>>);
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");
Expand Down
2 changes: 1 addition & 1 deletion packages/drizzle/src/sqlite-core/repositories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export class SqliteRepository<
TEntity extends Entity = Entity & InferSelectModel<TTable>,
TFilter extends EntityFilter<TEntity, SQL> = EntityFilter<TEntity, SQL>,
TCursor = EntityId<TEntity>,
> extends AbstractDrizzleRepository<TTable, TEntity, TFilter, TCursor> {
> extends AbstractDrizzleRepository<TTable, TEntity, TFilter, TCursor, InferInsertModel<TTable>> {
static of<
TTable extends SQLiteTable,
TFilter extends SqliteIdentityFilter<TTable> = SqliteIdentityFilter<TTable>,
Expand Down
32 changes: 32 additions & 0 deletions packages/drizzle/test/pg-core/repositories.integration.test.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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);
});
});
32 changes: 32 additions & 0 deletions packages/drizzle/test/sqlite-core/repositories.integration.test.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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);
});
});
Loading