summaryrefslogtreecommitdiff
path: root/srv/src/post/sql.go
diff options
context:
space:
mode:
Diffstat (limited to 'srv/src/post/sql.go')
-rw-r--r--srv/src/post/sql.go34
1 files changed, 28 insertions, 6 deletions
diff --git a/srv/src/post/sql.go b/srv/src/post/sql.go
index fb9468f..16cdc95 100644
--- a/srv/src/post/sql.go
+++ b/srv/src/post/sql.go
@@ -7,10 +7,12 @@ import (
"github.com/mediocregopher/blog.mediocregopher.com/srv/cfg"
migrate "github.com/rubenv/sql-migrate"
+
+ _ "github.com/mattn/go-sqlite3" // we need dis
)
-var migrations = []*migrate.Migration{
- &migrate.Migration{
+var migrations = &migrate.MemoryMigrationSource{Migrations: []*migrate.Migration{
+ {
Id: "1",
Up: []string{
`CREATE TABLE posts (
@@ -24,18 +26,25 @@ var migrations = []*migrate.Migration{
body TEXT NOT NULL
)`,
+
`CREATE TABLE post_tags (
post_id TEXT NOT NULL,
tag TEXT NOT NULL,
UNIQUE(post_id, tag)
)`,
+
+ `CREATE TABLE assets (
+ id TEXT NOT NULL PRIMARY KEY,
+ body BLOB NOT NULL
+ )`,
},
Down: []string{
+ "DROP TABLE assets",
"DROP TABLE post_tags",
"DROP TABLE posts",
},
},
-}
+}}
// SQLDB is a sqlite3 database which can be used by storage interfaces within
// this package.
@@ -43,7 +52,7 @@ type SQLDB struct {
db *sql.DB
}
-// NewSQLDB initializes and returns a new sqlite3 database for post storage
+// NewSQLDB initializes and returns a new sqlite3 database for storage
// intefaces. The db will be created within the given data directory.
func NewSQLDB(dataDir cfg.DataDir) (*SQLDB, error) {
@@ -54,8 +63,6 @@ func NewSQLDB(dataDir cfg.DataDir) (*SQLDB, error) {
return nil, fmt.Errorf("opening sqlite file at %q: %w", path, err)
}
- migrations := &migrate.MemoryMigrationSource{Migrations: migrations}
-
if _, err := migrate.Exec(db, "sqlite3", migrations, migrate.Up); err != nil {
return nil, fmt.Errorf("running migrations: %w", err)
}
@@ -63,6 +70,21 @@ func NewSQLDB(dataDir cfg.DataDir) (*SQLDB, error) {
return &SQLDB{db}, nil
}
+// NewSQLDB is like NewSQLDB, but the database will be initialized in memory.
+func NewInMemSQLDB() *SQLDB {
+
+ db, err := sql.Open("sqlite3", ":memory:")
+ if err != nil {
+ panic(fmt.Errorf("opening sqlite in memory: %w", err))
+ }
+
+ if _, err := migrate.Exec(db, "sqlite3", migrations, migrate.Up); err != nil {
+ panic(fmt.Errorf("running migrations: %w", err))
+ }
+
+ return &SQLDB{db}
+}
+
// Close cleans up loose resources being held by the db.
func (db *SQLDB) Close() error {
return db.db.Close()