snow-editor

small markdown and org-mode editor
Log | Files | Refs | README

versionUtils.js (824B)


      1 import { MAX_VERSIONS_PER_DOCUMENT } from './messages.js';
      2 import { newId } from './utils.js';
      3 
      4 export function saveDocumentVersion(db, doc, createdAt) {
      5   const versionId = newId();
      6   db.prepare(
      7     `INSERT INTO document_versions (id, document_id, title, mode, content, created_at)
      8      VALUES (?, ?, ?, ?, ?, ?)`,
      9   ).run(versionId, doc.id, doc.title, doc.mode, doc.content, createdAt);
     10 
     11   const excess = db
     12     .prepare(
     13       `SELECT id FROM document_versions
     14        WHERE document_id = ?
     15        ORDER BY created_at DESC
     16        LIMIT -1 OFFSET ?`,
     17     )
     18     .all(doc.id, MAX_VERSIONS_PER_DOCUMENT);
     19 
     20   if (excess.length > 0) {
     21     const placeholders = excess.map(() => '?').join(',');
     22     db.prepare(`DELETE FROM document_versions WHERE id IN (${placeholders})`).run(
     23       ...excess.map((row) => row.id),
     24     );
     25   }
     26 }