Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

Add sqlite and error skeleton file

天舟c601ece1ebed
diff --git a/backend/error.go b/backend/error.go
new file mode 100644
index 0000000000..db79d607a5
--- /dev/null
+++ b/backend/error.go
@@ -0,0 +1,72 @@
+package bytebase
+
+import (
+ "errors"
+ "fmt"
+)
+
+// Application error codes.
+//
+// NOTE: These are meant to be generic and they map well to HTTP error codes.
+// Different applications can have very different error code requirements so
+// these should be expanded as needed (or introduce subcodes).
+const (
+ ECONFLICT = "conflict"
+ EINTERNAL = "internal"
+ EINVALID = "invalid"
+ ENOTFOUND = "not_found"
+ ENOTIMPLEMENTED = "not_implemented"
+ EUNAUTHORIZED = "unauthorized"
+)
+
+// Error represents an application-specific error. Application errors can be
+// unwrapped by the caller to extract out the code & message.
+//
+// Any non-application error (such as a disk error) should be reported as an
+// EINTERNAL error and the human user should only see "Internal error" as the
+// message. These low-level internal error details should only be logged and
+// reported to the operator of the application (not the end user).
+type Error struct {
+ // Machine-readable error code.
+ Code string
+
+ // Human-readable error message.
+ Message string
+}
+
+// Error implements the error interface. Not used by the application otherwise.
+func (e *Error) Error() string {
+ return fmt.Sprintf("wtf error: code=%s message=%s", e.Code, e.Message)
+}
+
+// ErrorCode unwraps an application error and returns its code.
+// Non-application errors always return EINTERNAL.
+func ErrorCode(err error) string {
+ var e *Error
+ if err == nil {
+ return ""
+ } else if errors.As(err, &e) {
+ return e.Code
+ }
+ return EINTERNAL
+}
+
+// ErrorMessage unwraps an application error and returns its message.
+// Non-application errors always return "Internal error".
+func ErrorMessage(err error) string {
+ var e *Error
+ if err == nil {
+ return ""
+ } else if errors.As(err, &e) {
+ return e.Message
+ }
+ return "Internal error."
+}
+
+// Errorf is a helper function to return an Error with a given code and formatted message.
+func Errorf(code string, format string, args ...interface{}) *Error {
+ return &Error{
+ Code: code,
+ Message: fmt.Sprintf(format, args...),
+ }
+}
diff --git a/backend/go.mod b/backend/go.mod
index 217dce2f74..9eabe8ffb9 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -2,5 +2,4 @@ module github.com/bytebase/bytebase
go 1.16
-require (
-)
+require github.com/mattn/go-sqlite3 v1.14.7 // indirect
diff --git a/backend/go.sum b/backend/go.sum
new file mode 100644
index 0000000000..96ff82415a
--- /dev/null
+++ b/backend/go.sum
@@ -0,0 +1,2 @@
+github.com/mattn/go-sqlite3 v1.14.7 h1:fxWBnXkxfM6sRiuH3bqJ4CfzZojMOLVc0UTsTglEghA=
+github.com/mattn/go-sqlite3 v1.14.7/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
diff --git a/backend/main.go b/backend/main.go
index ebc9166304..f243906f47 100644
--- a/backend/main.go
+++ b/backend/main.go
@@ -7,10 +7,13 @@ import (
"os/signal"
"github.com/bytebase/bytebase/server"
+ "github.com/bytebase/bytebase/sqlite"
)
type Main struct {
Server *server.Server
+
+ DB *sqlite.DB
}
func main() {
@@ -55,13 +58,14 @@ func main() {
func NewMain() *Main {
return &Main{
Server: server.NewServer(),
+ DB: sqlite.NewDB(":memory:"),
}
}
func (m *Main) Run() error {
- // if err := m.DB.Open(); err != nil {
- // return fmt.Errorf("cannot open db: %w", err)
- // }
+ if err := m.DB.Open(); err != nil {
+ return fmt.Errorf("cannot open db: %w", err)
+ }
// m.Server.TodoService = sqlite.NewTodoService(m.DB)
@@ -79,10 +83,10 @@ func (m *Main) Close() error {
// return err
// }
// }
- // if m.DB != nil {
- // if err := m.DB.Close(); err != nil {
- // return err
- // }
- // }
+ if m.DB != nil {
+ if err := m.DB.Close(); err != nil {
+ return err
+ }
+ }
return nil
}
diff --git a/backend/sqlite/migration/1.sql b/backend/sqlite/migration/1.sql
new file mode 100644
index 0000000000..aae56acbc3
--- /dev/null
+++ b/backend/sqlite/migration/1.sql
@@ -0,0 +1,4 @@
+CREATE TABLE environment (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NOT NULL
+);
\ No newline at end of file
diff --git a/backend/sqlite/sqlite.go b/backend/sqlite/sqlite.go
new file mode 100644
index 0000000000..3d3489cf8e
--- /dev/null
+++ b/backend/sqlite/sqlite.go
@@ -0,0 +1,181 @@
+package sqlite
+
+import (
+ "context"
+ "database/sql"
+ "embed"
+ "fmt"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "sort"
+ "time"
+
+ _ "github.com/mattn/go-sqlite3"
+)
+
+//go:embed migration/*.sql
+var migrationFS embed.FS
+
+// DB represents the database connection.
+type DB struct {
+ db *sql.DB
+ ctx context.Context // background context
+ cancel func() // cancel background context
+
+ // Datasource name.
+ DSN string
+
+ // Returns the current time. Defaults to time.Now().
+ // Can be mocked for tests.
+ Now func() time.Time
+}
+
+// NewDB returns a new instance of DB associated with the given datasource name.
+func NewDB(dsn string) *DB {
+ db := &DB{
+ DSN: dsn,
+ Now: time.Now,
+ }
+ db.ctx, db.cancel = context.WithCancel(context.Background())
+ return db
+}
+
+// Open opens the database connection.
+func (db *DB) Open() (err error) {
+ // Ensure a DSN is set before attempting to open the database.
+ if db.DSN == "" {
+ return fmt.Errorf("dsn required")
+ }
+
+ // Make the parent directory unless using an in-memory db.
+ if db.DSN != ":memory:" {
+ if err := os.MkdirAll(filepath.Dir(db.DSN), 0700); err != nil {
+ return err
+ }
+ }
+
+ // Connect to the database.
+ if db.db, err = sql.Open("sqlite3", db.DSN); err != nil {
+ return err
+ }
+
+ // Enable WAL. SQLite performs better with the WAL because it allows
+ // multiple readers to operate while data is being written.
+ if _, err := db.db.Exec(`PRAGMA journal_mode = wal;`); err != nil {
+ return fmt.Errorf("enable wal: %w", err)
+ }
+
+ // Enable foreign key checks. For historical reasons, SQLite does not check
+ // foreign key constraints by default... which is kinda insane. There's some
+ // overhead on inserts to verify foreign key integrity but it's definitely
+ // worth it.
+ if _, err := db.db.Exec(`PRAGMA foreign_keys = ON;`); err != nil {
+ return fmt.Errorf("foreign keys pragma: %w", err)
+ }
+
+ if err := db.migrate(); err != nil {
+ return fmt.Errorf("migrate: %w", err)
+ }
+
+ return nil
+}
+
+// migrate sets up migration tracking and executes pending migration files.
+//
+// Migration files are embedded in the sqlite/migration folder and are executed
+// in lexigraphical order.
+//
+// Once a migration is run, its name is stored in the 'migrations' table so it
+// is not re-executed. Migrations run in a transaction to prevent partial
+// migrations.
+func (db *DB) migrate() error {
+ // Ensure the 'migrations' table exists so we don't duplicate migrations.
+ if _, err := db.db.Exec(`CREATE TABLE IF NOT EXISTS migrations (name TEXT PRIMARY KEY);`); err != nil {
+ return fmt.Errorf("cannot create migrations table: %w", err)
+ }
+
+ // Read migration files from our embedded file system.
+ // This uses Go 1.16's 'embed' package.
+ names, err := fs.Glob(migrationFS, "migration/*.sql")
+ if err != nil {
+ return err
+ }
+ sort.Strings(names)
+
+ // Loop over all migration files and execute them in order.
+ for _, name := range names {
+ if err := db.migrateFile(name); err != nil {
+ return fmt.Errorf("migration error: name=%q err=%w", name, err)
+ }
+ }
+ return nil
+}
+
+// migrate runs a single migration file within a transaction. On success, the
+// migration file name is saved to the "migrations" table to prevent re-running.
+func (db *DB) migrateFile(name string) error {
+ tx, err := db.db.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+
+ // Ensure migration has not already been run.
+ var n int
+ if err := tx.QueryRow(`SELECT COUNT(*) FROM migrations WHERE name = ?`, name).Scan(&n); err != nil {
+ return err
+ } else if n != 0 {
+ return nil // already run migration, skip
+ }
+
+ // Read and execute migration file.
+ if buf, err := fs.ReadFile(migrationFS, name); err != nil {
+ return err
+ } else if _, err := tx.Exec(string(buf)); err != nil {
+ return err
+ }
+
+ // Insert record into migrations to prevent re-running migration.
+ if _, err := tx.Exec(`INSERT INTO migrations (name) VALUES (?)`, name); err != nil {
+ return err
+ }
+
+ return tx.Commit()
+}
+
+// Close closes the database connection.
+func (db *DB) Close() error {
+ // Cancel background context.
+ db.cancel()
+
+ // Close database.
+ if db.db != nil {
+ return db.db.Close()
+ }
+ return nil
+}
+
+// BeginTx starts a transaction and returns a wrapper Tx type. This type
+// provides a reference to the database and a fixed timestamp at the start of
+// the transaction. The timestamp allows us to mock time during tests as well.
+func (db *DB) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
+ tx, err := db.db.BeginTx(ctx, opts)
+ if err != nil {
+ return nil, err
+ }
+
+ // Return wrapper Tx that includes the transaction start time.
+ return &Tx{
+ Tx: tx,
+ db: db,
+ now: db.Now().UTC().Truncate(time.Second),
+ }, nil
+}
+
+// Tx wraps the SQL Tx object to provide a timestamp at the start of the transaction.
+type Tx struct {
+ *sql.Tx
+ db *DB
+ now time.Time
+}