From 6a10b4cf3ecc46eef6d9d9d488864d3b41187324 Mon Sep 17 00:00:00 2001 From: Micheal Wilkinson Date: Tue, 17 Mar 2026 22:37:25 +0000 Subject: [PATCH] Adding implementation for sqlite database --- internal/store/sqlite/sqlite.go | 62 +++++++++++++++++++++++++++++++-- 1 file changed, 60 insertions(+), 2 deletions(-) diff --git a/internal/store/sqlite/sqlite.go b/internal/store/sqlite/sqlite.go index 21477f7..231aad0 100644 --- a/internal/store/sqlite/sqlite.go +++ b/internal/store/sqlite/sqlite.go @@ -4,6 +4,9 @@ import ( "context" "database/sql" "fmt" + "time" + + "modernc.org/sqlite" ) const sqlSet = ` @@ -17,9 +20,64 @@ type SQLiteStore struct { } func NewSQLiteStore(ctx context.Context, dbPath string) (*SQLiteStore, error) { - return nil, fmt.Errorf("not implemented") + sqliteDB := &SQLiteStore{} + + sqlite.RegisterConnectionHook(func(conn sqlite.ExecQuerierContext, _ string) error { + _, err := conn.ExecContext(ctx, sqlSet, nil) + return err + }) + + write, err := sql.Open("sqlite", "file:"+dbPath) + if err != nil { + return nil, err + } + err = write.PingContext(ctx) + if err != nil { + return nil, fmt.Errorf("failed to ping database: %w", err) + } + // only a single writer ever, no concurrency I don't trust it + write.SetMaxOpenConns(1) + write.SetConnMaxIdleTime(time.Minute) + + read, err := sql.Open("sqlite", "file:"+dbPath) + if err != nil { + return nil, err + } + err = read.PingContext(ctx) + if err != nil { + return nil, fmt.Errorf("failed to ping database: %w", err) + } + // readers can be concurrent + read.SetMaxOpenConns(100) + read.SetConnMaxIdleTime(time.Minute) + + sqliteDB.read = read + sqliteDB.write = write + + err = sqliteDB.validateSchema(ctx) + if err != nil { + return nil, fmt.Errorf("failed to validate schema: %w", err) + } + + return sqliteDB, nil } func (s *SQLiteStore) Close() error { - return fmt.Errorf("not implemented") + readErr := s.read.Close() + writeErr := s.write.Close() + if readErr != nil || writeErr != nil { + return fmt.Errorf("failed to close connections: read error: %v, write error: %v", readErr, writeErr) + } + return nil +} + +func (s *SQLiteStore) validateSchema(ctx context.Context) error { + _, err := s.write.ExecContext(ctx, ` + CREATE TABLE IF NOT EXISTS notes ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + last_update TIMESTAMP NOT NULL, + content TEXT NOT NULL + ); + `, nil) + return err }