package db import ( "context" "database/sql" "time" _ "embed" _ "github.com/go-sql-driver/mysql" "github.com/sirupsen/logrus" "git.kapelle.org/niklas/s3share/internal/types" ) //go:embed setup.sql var setupSql string type sqlDB struct { db *sql.DB } func NewSQLDB(dataSourceName string) (DB, error) { db, err := sql.Open("mysql", dataSourceName) if err != nil { return nil, err } // https://github.com/go-sql-driver/mysql#important-settings db.SetConnMaxLifetime(time.Minute * 3) db.SetMaxOpenConns(10) db.SetMaxIdleConns(10) // Connect and check the server version var version string db.QueryRow("SELECT VERSION()").Scan(&version) logrus.Info("DB Version:", version) _, err = db.Exec(setupSql) if err != nil { return nil, err } return &sqlDB{ db: db, }, nil } func (db *sqlDB) 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 *sqlDB) 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 *sqlDB) DeleteShare(ctx context.Context, slug string) error { result, err := db.db.ExecContext(ctx, "DELETE FROM shares WHERE slug = ?", slug) if err != nil { return err } rowsAffected, err := result.RowsAffected() if err != nil { return err } if rowsAffected == 0 { return types.ErrShareNotFound } return nil } func (db *sqlDB) 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 *sqlDB) Close() error { return db.db.Close() }