- Add pure Go SQLite driver (modernc.org/sqlite) to avoid CGO dependency - Implement database connection management with WAL mode - Add write mutex for serializing concurrent writes - Create schema for all tables matching DESIGN.md specifications - Implement repository pattern for all database entities: - Files, FileChunks, Chunks, Blobs, BlobChunks, ChunkFiles, Snapshots - Add transaction support with proper rollback handling - Add fatal error handling for database integrity issues - Add snapshot fields for tracking file sizes and compression ratios - Make index path configurable via VAULTIK_INDEX_PATH environment variable - Add comprehensive test coverage for all repositories - Add format check to Makefile to ensure code formatting
81 lines
1.7 KiB
Go
81 lines
1.7 KiB
Go
package database
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"fmt"
|
|
)
|
|
|
|
type FileChunkRepository struct {
|
|
db *DB
|
|
}
|
|
|
|
func NewFileChunkRepository(db *DB) *FileChunkRepository {
|
|
return &FileChunkRepository{db: db}
|
|
}
|
|
|
|
func (r *FileChunkRepository) Create(ctx context.Context, tx *sql.Tx, fc *FileChunk) error {
|
|
query := `
|
|
INSERT INTO file_chunks (path, idx, chunk_hash)
|
|
VALUES (?, ?, ?)
|
|
ON CONFLICT(path, idx) DO NOTHING
|
|
`
|
|
|
|
var err error
|
|
if tx != nil {
|
|
_, err = tx.ExecContext(ctx, query, fc.Path, fc.Idx, fc.ChunkHash)
|
|
} else {
|
|
_, err = r.db.ExecWithLock(ctx, query, fc.Path, fc.Idx, fc.ChunkHash)
|
|
}
|
|
|
|
if err != nil {
|
|
return fmt.Errorf("inserting file_chunk: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (r *FileChunkRepository) GetByPath(ctx context.Context, path string) ([]*FileChunk, error) {
|
|
query := `
|
|
SELECT path, idx, chunk_hash
|
|
FROM file_chunks
|
|
WHERE path = ?
|
|
ORDER BY idx
|
|
`
|
|
|
|
rows, err := r.db.conn.QueryContext(ctx, query, path)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("querying file chunks: %w", err)
|
|
}
|
|
defer CloseRows(rows)
|
|
|
|
var fileChunks []*FileChunk
|
|
for rows.Next() {
|
|
var fc FileChunk
|
|
err := rows.Scan(&fc.Path, &fc.Idx, &fc.ChunkHash)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("scanning file chunk: %w", err)
|
|
}
|
|
fileChunks = append(fileChunks, &fc)
|
|
}
|
|
|
|
return fileChunks, rows.Err()
|
|
}
|
|
|
|
func (r *FileChunkRepository) DeleteByPath(ctx context.Context, tx *sql.Tx, path string) error {
|
|
query := `DELETE FROM file_chunks WHERE path = ?`
|
|
|
|
var err error
|
|
if tx != nil {
|
|
_, err = tx.ExecContext(ctx, query, path)
|
|
} else {
|
|
_, err = r.db.ExecWithLock(ctx, query, path)
|
|
}
|
|
|
|
if err != nil {
|
|
return fmt.Errorf("deleting file chunks: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|