All files / storage attachment-storage.ts

100% Statements 4/4
50% Branches 1/2
100% Functions 1/1
100% Lines 4/4

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26                                  27x 27x 27x       27x    
/**
 * Content-addressable attachment storage.
 *
 * Each unique file is stored exactly once in attachment_blobs, keyed by its
 * SHA-256 hash. Attachment rows carry a content_hash FK instead of inline data,
 * so duplicate files (same bytes across many messages) are stored only once.
 */
 
import { createHash } from "node:crypto";
import type Database from "better-sqlite3-multiple-ciphers";
import { compressBuffer } from "./compression.js";
 
/**
 * Inserts attachment content into attachment_blobs if not already present,
 * and returns the SHA-256 hex hash for use as the content_hash FK.
 */
export function upsertAttachmentBlob(db: Database.Database, data: Buffer): string {
	const hash = createHash("sha256").update(data).digest("hex");
	const compressed = compressBuffer(data) ?? data;
	db.prepare("INSERT OR IGNORE INTO blobs.attachment_blobs (content_hash, data) VALUES (?, ?)").run(
		hash,
		compressed,
	);
	return hash;
}