Adding implementation for sqlite database

This commit is contained in:
Micheal Wilkinson
2026-03-17 22:37:25 +00:00
parent 412d237244
commit 6a10b4cf3e

View File

@@ -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
}