Files
remanso-jetstream/src/data/db.ts
2026-02-17 15:32:05 +01:00

94 lines
2.6 KiB
TypeScript

import { Database } from "@db/sqlite";
import type { Note } from "./note.ts";
export const db = new Database(Deno.env.get("SQLITE_PATH") ?? "notes.db");
try {
db.exec("PRAGMA journal_mode=WAL");
db.exec("PRAGMA busy_timeout=5000");
const [row] = db.prepare("PRAGMA journal_mode").all<{ journal_mode: string }>();
console.log(`[db] journal_mode=${row.journal_mode}, busy_timeout=5000`);
} catch (e) {
console.error("[db] failed to set PRAGMAs:", e);
}
type NoteRow = {
did: string;
rkey: string;
title: string;
publishedAt: string;
createdAt: string;
};
export const getNotes = (cursor?: string, limit = 20) => {
const notes = cursor
? db.prepare(
"SELECT did, rkey, title, publishedAt, createdAt FROM note WHERE rkey < ? ORDER BY rkey DESC LIMIT ?",
).all<NoteRow>(cursor, limit)
: db.prepare(
"SELECT did, rkey, title, publishedAt, createdAt FROM note ORDER BY rkey DESC LIMIT ?",
).all<NoteRow>(limit);
return {
notes,
cursor: notes.length === limit ? notes[notes.length - 1].rkey : undefined,
};
};
export const getNotesByDid = (did: string, cursor?: string, limit = 20) => {
const notes = cursor
? db.prepare(
"SELECT did, rkey, title, publishedAt, createdAt FROM note WHERE did = ? AND rkey < ? ORDER BY rkey DESC LIMIT ?",
).all<NoteRow>(did, cursor, limit)
: db.prepare(
"SELECT did, rkey, title, publishedAt, createdAt FROM note WHERE did = ? ORDER BY rkey DESC LIMIT ?",
).all<NoteRow>(did, limit);
return {
notes,
cursor: notes.length === limit ? notes[notes.length - 1].rkey : undefined,
};
};
export const deleteNote = ({ did, rkey }: { did: string; rkey: string }) => {
db.exec("DELETE FROM note WHERE did = ? AND rkey = ?", did, rkey);
};
export const getCursor = (): string | undefined => {
const row = db.prepare(
"SELECT value FROM state WHERE key = 'cursor'",
).get<{ value: string }>();
return row?.value;
};
export const saveCursor = (cursor: number) => {
db.exec(
"INSERT OR REPLACE INTO state (key, value) VALUES ('cursor', ?)",
String(cursor),
);
};
export const upsertNote = (note: Note) => {
const now = new Date().toISOString();
db.exec(
`
INSERT INTO note (
title,
publishedAt,
createdAt,
did,
rkey
)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(did, rkey)
DO UPDATE SET
title = excluded.title,
publishedAt = excluded.publishedAt
`,
note.title,
note.publishedAt ? new Date(note.publishedAt).toISOString() : now,
note.createdAt ? new Date(note.createdAt).toISOString() : now,
note.did,
note.rkey,
);
};