context-ops.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /**
  2. * Context management operations for store.ts
  3. * These will be integrated into store.ts
  4. */
  5. import { Database } from "bun:sqlite";
  6. // =============================================================================
  7. // Context Management Operations
  8. // =============================================================================
  9. /**
  10. * Insert or update a context for a specific collection and path prefix.
  11. */
  12. export function insertContext(db: Database, collectionId: number, pathPrefix: string, context: string): void {
  13. const now = new Date().toISOString();
  14. db.prepare(`
  15. INSERT INTO path_contexts (collection_id, path_prefix, context, created_at)
  16. VALUES (?, ?, ?, ?)
  17. ON CONFLICT(collection_id, path_prefix) DO UPDATE SET context = excluded.context
  18. `).run(collectionId, pathPrefix, context, now);
  19. }
  20. /**
  21. * Delete a context for a specific collection and path prefix.
  22. * Returns the number of contexts deleted.
  23. */
  24. export function deleteContext(db: Database, collectionId: number, pathPrefix: string): number {
  25. const result = db.prepare(`
  26. DELETE FROM path_contexts
  27. WHERE collection_id = ? AND path_prefix = ?
  28. `).run(collectionId, pathPrefix);
  29. return result.changes;
  30. }
  31. /**
  32. * Delete all global contexts (contexts with empty path_prefix).
  33. * Returns the number of contexts deleted.
  34. */
  35. export function deleteGlobalContexts(db: Database): number {
  36. const result = db.prepare(`DELETE FROM path_contexts WHERE path_prefix = ''`).run();
  37. return result.changes;
  38. }
  39. /**
  40. * List all contexts, grouped by collection.
  41. * Returns contexts ordered by collection name, then by path prefix length (longest first).
  42. */
  43. export function listPathContexts(db: Database): { collection_name: string; path_prefix: string; context: string }[] {
  44. const contexts = db.prepare(`
  45. SELECT c.name as collection_name, pc.path_prefix, pc.context
  46. FROM path_contexts pc
  47. JOIN collections c ON c.id = pc.collection_id
  48. ORDER BY c.name, LENGTH(pc.path_prefix) DESC, pc.path_prefix
  49. `).all() as { collection_name: string; path_prefix: string; context: string }[];
  50. return contexts;
  51. }
  52. /**
  53. * Get all collections (id and name).
  54. */
  55. export function getAllCollections(db: Database): { id: number; name: string }[] {
  56. return db.prepare(`SELECT id, name FROM collections`).all() as { id: number; name: string }[];
  57. }