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);
```

`of` also takes the paging spec, and its entity type flows into the repository: a spec
typed for a narrower entity, `pagingById<Asset>` 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
Expand Down
37 changes: 25 additions & 12 deletions packages/drizzle/src/pg-core/repositories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<TTable extends PgTable> = EntityFilter<
Entity & InferSelectModel<TTable>,
SQL
>;
type PostgresIdentityFilter<TTable extends PgTable> = EntityFilter<RowEntity<TTable>, SQL>;

/**
* Postgres binding for entities whose DTO is exactly their table row, so both
Expand All @@ -27,19 +30,29 @@ type PostgresIdentityFilter<TTable extends PgTable> = EntityFilter<
*/
export class PostgresRepository<
TTable extends PgTable,
TEntity extends Entity = Entity & InferSelectModel<TTable>,
TEntity extends Entity = RowEntity<TTable>,
TFilter extends EntityFilter<TEntity, SQL> = EntityFilter<TEntity, SQL>,
TCursor = EntityId<TEntity>,
> extends AbstractDrizzleRepository<TTable, TEntity, TFilter, TCursor, InferInsertModel<TTable>> {
/**
* 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<TTable> = PostgresIdentityFilter<TTable>,
>(db: DrizzleDatabase, table: TTable) {
return new PostgresRepository<TTable, Entity & InferSelectModel<TTable>, TFilter>(
db,
table,
pagingById(table),
);
TEntity extends Entity = RowEntity<TTable>,
TCursor = EntityId<TEntity>,
>(
db: DrizzleDatabase,
table: TTable,
paging: (table: TTable) => DrizzlePaging<TEntity, TCursor> = (table) =>
pagingById<TEntity>(table) as DrizzlePaging<TEntity, TCursor>,
): PostgresRepository<TTable, TEntity, TFilter & EntityFilter<TEntity, SQL>, TCursor> {
return new PostgresRepository(db, table, paging(table));
}

protected toDto(row: InferSelectModel<TTable>): TEntity {
Expand Down
19 changes: 18 additions & 1 deletion packages/drizzle/src/repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>;

/**
* 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<TTable>`, 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<TTable extends Table> =
InferSelectModel<TTable> extends {
id: string | number;
}
? InferSelectModel<TTable>
: InferSelectModel<TTable> & { id: string | number };

/** A selected row set, with the limit step every dialect supports. */
interface SelectedTable {
where(condition: SQL | undefined): PromiseLike<Row[]>;
Expand Down Expand Up @@ -225,7 +242,7 @@ export const pagingByCreatedAt = <TEntity extends CreatedAtEntity>(table: {
*/
export abstract class AbstractDrizzleRepository<
TTable extends Table,
TEntity extends Entity = Entity & InferSelectModel<TTable>,
TEntity extends Entity = RowEntity<TTable>,
TFilter extends EntityFilter<TEntity, SQL> = EntityFilter<TEntity, SQL>,
TCursor = EntityId<TEntity>,
TInsert extends Row = EntityInsert<TEntity>,
Expand Down
37 changes: 25 additions & 12 deletions packages/drizzle/src/sqlite-core/repositories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<TTable extends SQLiteTable> = EntityFilter<
Entity & InferSelectModel<TTable>,
SQL
>;
type SqliteIdentityFilter<TTable extends SQLiteTable> = EntityFilter<RowEntity<TTable>, SQL>;

/**
* SQLite binding for entities whose DTO is exactly their table row, so both
Expand All @@ -26,19 +29,29 @@ type SqliteIdentityFilter<TTable extends SQLiteTable> = EntityFilter<
*/
export class SqliteRepository<
TTable extends SQLiteTable,
TEntity extends Entity = Entity & InferSelectModel<TTable>,
TEntity extends Entity = RowEntity<TTable>,
TFilter extends EntityFilter<TEntity, SQL> = EntityFilter<TEntity, SQL>,
TCursor = EntityId<TEntity>,
> extends AbstractDrizzleRepository<TTable, TEntity, TFilter, TCursor, InferInsertModel<TTable>> {
/**
* 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<TTable> = SqliteIdentityFilter<TTable>,
>(db: DrizzleDatabase, table: TTable) {
return new SqliteRepository<TTable, Entity & InferSelectModel<TTable>, TFilter>(
db,
table,
pagingById(table),
);
TEntity extends Entity = RowEntity<TTable>,
TCursor = EntityId<TEntity>,
>(
db: DrizzleDatabase,
table: TTable,
paging: (table: TTable) => DrizzlePaging<TEntity, TCursor> = (table) =>
pagingById<TEntity>(table) as DrizzlePaging<TEntity, TCursor>,
): SqliteRepository<TTable, TEntity, TFilter & EntityFilter<TEntity, SQL>, TCursor> {
return new SqliteRepository(db, table, paging(table));
}

protected toDto(row: InferSelectModel<TTable>): TEntity {
Expand Down
49 changes: 49 additions & 0 deletions packages/drizzle/test/pg-core/repositories.unit.test.ts
Original file line number Diff line number Diff line change
@@ -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<Asset>);

expectTypeOf(repository.findMany).returns.toEqualTypeOf<Promise<Asset[]>>();
expectTypeOf(repository.list).returns.toEqualTypeOf<
Promise<Page<Asset, CreatedAtCursor<Asset>>>
>();
});

it("defaults to the row itself instead of widening it with `Entity`", () => {
const repository = PostgresRepository.of(createProxy(), assets);

expectTypeOf(repository.findMany).returns.toEqualTypeOf<Promise<RowEntity<typeof assets>[]>>();
// The row already has an id, so the conditional keeps the selected type as it is.
expectTypeOf<RowEntity<typeof assets>>().toEqualTypeOf<typeof assets.$inferSelect>();
});

it("pages in the order its paging spec declares", async () => {
const queries: Query[] = [];
const repository = PostgresRepository.of(
createProxy(queries),
assets,
pagingByCreatedAt<Asset>,
);

await repository.list({ limit: 1 });

expect(queries[0]?.sql).toContain('order by "assets"."created_at" desc, "assets"."id" desc');
});
});
11 changes: 11 additions & 0 deletions packages/drizzle/test/repository.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down
55 changes: 55 additions & 0 deletions packages/drizzle/test/sqlite-core/repositories.unit.test.ts
Original file line number Diff line number Diff line change
@@ -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<Note>);

expectTypeOf(repository.findMany).returns.toEqualTypeOf<Promise<Note[]>>();
expectTypeOf(repository.list).returns.toEqualTypeOf<
Promise<Page<Note, CreatedAtCursor<Note>>>
>();
});

it("defaults to the row itself instead of widening it with `Entity`", () => {
const repository = SqliteRepository.of(createProxy(), notes);

expectTypeOf(repository.findMany).returns.toEqualTypeOf<Promise<RowEntity<typeof notes>[]>>();
expectTypeOf<RowEntity<typeof notes>>().toEqualTypeOf<typeof notes.$inferSelect>();
});

it("adds an id to a row that has none", () => {
const keys = sqliteTable("keys", { key: text("key").notNull() });

expectTypeOf<RowEntity<typeof keys>>().toHaveProperty("id").toEqualTypeOf<string | number>();
});

it("pages in the order its paging spec declares", async () => {
const queries: string[] = [];
const repository = SqliteRepository.of(createProxy(queries), notes, pagingByCreatedAt<Note>);

await repository.list({ limit: 1 });

expect(queries[0]).toContain('order by "notes"."created_at" desc, "notes"."id" desc');
});
});
Loading