package db import ( "context" "database/sql" "os" _ "embed" _ "github.com/mattn/go-sqlite3" "github.com/sirupsen/logrus" "git.kapelle.org/niklas/s3share/internal/types" ) //go:embed sqlite.sql var setupSql string type sqlLiteDB struct { db *sql.DB } func NewSqlLiteDB(path string) (DB, error) { os.Remove(path) logrus.Info("Opening database") db, err := sql.Open("sqlite3", path) if err != nil { return nil, err } logrus.Info("Initializing database") _, err = db.Exec(setupSql) if err != nil { return nil, err } return &sqlLiteDB{ db: db, }, nil } func (db *sqlLiteDB) GetShare(ctx context.Context, slug string) (*types.Share, error) { res, err := db.db.QueryContext(ctx, "SELECT slug, objKey FROM shares WHERE slug = ?", slug) if err != nil { return nil, err } if !res.Next() { return nil, nil } var share types.Share err = res.Scan(&share.Slug, &share.Key) if err != nil { return nil, err } return &share, nil } func (db *sqlLiteDB) CreateShare(ctx context.Context, share *types.Share) error { _, err := db.db.ExecContext(ctx, "INSERT INTO shares (slug, objKey) VALUES (?, ?)", share.Slug, share.Key) if err != nil { return err } return nil } func (db *sqlLiteDB) DeleteShare(ctx context.Context, slug string) error { _, err := db.db.ExecContext(ctx, "DELETE FROM shares WHERE slug = ?", slug) if err != nil { return err } return nil } func (db *sqlLiteDB) GetAllShares(ctx context.Context) ([]*types.Share, error) { res, err := db.db.QueryContext(ctx, "SELECT slug, objKey FROM shares") if err != nil { return nil, err } var shares []*types.Share for res.Next() { var share types.Share err = res.Scan(&share.Slug, &share.Key) if err != nil { return nil, err } shares = append(shares, &share) } return shares, nil } func (db *sqlLiteDB) Close() error { return db.db.Close() }