parent
c2a27a0751
commit
c19a675e36
2 changed files with 46 additions and 0 deletions
38
internal/database/database.go
Normal file
38
internal/database/database.go
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
package database
|
||||||
|
|
||||||
|
import (
|
||||||
|
"embed"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/jmoiron/sqlx"
|
||||||
|
_ "github.com/mattn/go-sqlite3"
|
||||||
|
migrate "github.com/rubenv/sql-migrate"
|
||||||
|
)
|
||||||
|
|
||||||
|
var DB *sqlx.DB
|
||||||
|
|
||||||
|
//go:embed migrations/*
|
||||||
|
var dbMigrations embed.FS
|
||||||
|
|
||||||
|
func Connect(filename string) error {
|
||||||
|
DB, err := sqlx.Open("sqlite3", filename)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
migrations := migrate.EmbedFileSystemMigrationSource{
|
||||||
|
FileSystem: dbMigrations,
|
||||||
|
Root: "migrations",
|
||||||
|
}
|
||||||
|
|
||||||
|
n, err := migrate.Exec(DB.DB, "sqlite3", migrations, migrate.Up)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("Applied %d migrations - Database is ready!\n", n)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
8
internal/database/migrations/1_initial.sql
Normal file
8
internal/database/migrations/1_initial.sql
Normal file
|
|
@ -0,0 +1,8 @@
|
||||||
|
-- +migrate Up
|
||||||
|
CREATE table users (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
name text NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- +migrate Down
|
||||||
|
DROP TABLE users;
|
||||||
Loading…
Add table
Add a link
Reference in a new issue