89 lines
2.5 KiB
TypeScript
89 lines
2.5 KiB
TypeScript
import { eq } from 'drizzle-orm';
|
|
import type { ItemState } from '../../sync/core/model';
|
|
import type { ItemRepository } from '../../sync/core/ports';
|
|
import type { Db } from './database';
|
|
import { items, projects } from './schema';
|
|
|
|
type ItemRow = typeof items.$inferSelect;
|
|
type Tx = Parameters<Parameters<Db['transaction']>[0]>[0];
|
|
|
|
export class SqliteItemRepository implements ItemRepository {
|
|
constructor(private readonly db: Db) {}
|
|
|
|
async listByProject(projectId: string): Promise<ItemState[]> {
|
|
return this.db.select().from(items).where(eq(items.projectId, projectId)).all().map(toItem);
|
|
}
|
|
|
|
async commitIngest(projectId: string, states: ItemState[], cursor: string): Promise<void> {
|
|
this.db.transaction((tx) => {
|
|
upsert(tx, projectId, states);
|
|
tx.update(projects).set({ deltaCursor: cursor }).where(eq(projects.id, projectId)).run();
|
|
});
|
|
}
|
|
|
|
async save(projectId: string, states: ItemState[]): Promise<void> {
|
|
this.db.transaction((tx) => upsert(tx, projectId, states));
|
|
}
|
|
}
|
|
|
|
function upsert(tx: Tx, projectId: string, states: ItemState[]): void {
|
|
for (const state of states) {
|
|
const row = toRow(projectId, state);
|
|
tx.insert(items)
|
|
.values(row)
|
|
.onConflictDoUpdate({ target: [items.projectId, items.sourceId], set: row })
|
|
.run();
|
|
}
|
|
}
|
|
|
|
function toRow(projectId: string, { sourceId, desired, synced, ...rest }: ItemState): ItemRow {
|
|
return {
|
|
projectId,
|
|
sourceId,
|
|
parentSourceId: desired.parentSourceId,
|
|
name: desired.name,
|
|
isFolder: desired.isFolder,
|
|
contentTag: desired.contentTag,
|
|
sourceModifiedAt: desired.modifiedAt,
|
|
size: desired.size,
|
|
deleted: desired.deleted,
|
|
targetId: synced.targetId,
|
|
syncedParentSourceId: synced.parentSourceId,
|
|
syncedName: synced.name,
|
|
syncedContentTag: synced.contentTag,
|
|
syncedDeleted: synced.deleted,
|
|
syncedAt: synced.at,
|
|
status: rest.status,
|
|
attemptCount: rest.attemptCount,
|
|
lastError: rest.lastError,
|
|
lastAttemptAt: rest.lastAttemptAt
|
|
};
|
|
}
|
|
|
|
function toItem(row: ItemRow): ItemState {
|
|
return {
|
|
sourceId: row.sourceId,
|
|
desired: {
|
|
parentSourceId: row.parentSourceId,
|
|
name: row.name,
|
|
isFolder: row.isFolder,
|
|
contentTag: row.contentTag,
|
|
modifiedAt: row.sourceModifiedAt,
|
|
size: row.size,
|
|
deleted: row.deleted
|
|
},
|
|
synced: {
|
|
targetId: row.targetId,
|
|
parentSourceId: row.syncedParentSourceId,
|
|
name: row.syncedName,
|
|
contentTag: row.syncedContentTag,
|
|
deleted: row.syncedDeleted,
|
|
at: row.syncedAt
|
|
},
|
|
status: row.status,
|
|
attemptCount: row.attemptCount,
|
|
lastError: row.lastError,
|
|
lastAttemptAt: row.lastAttemptAt
|
|
};
|
|
}
|