2019-08-22 05:12:46 +00:00
|
|
|
package sqlite
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"database/sql"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"github.com/rancher/kine/pkg/drivers/generic"
|
|
|
|
"github.com/rancher/kine/pkg/logstructured"
|
|
|
|
"github.com/rancher/kine/pkg/logstructured/sqllog"
|
|
|
|
"github.com/rancher/kine/pkg/server"
|
|
|
|
|
|
|
|
// sqlite db driver
|
|
|
|
_ "github.com/mattn/go-sqlite3"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
schema = []string{
|
|
|
|
`CREATE TABLE IF NOT EXISTS kine
|
|
|
|
(
|
|
|
|
id INTEGER primary key autoincrement,
|
|
|
|
name INTEGER,
|
|
|
|
created INTEGER,
|
|
|
|
deleted INTEGER,
|
|
|
|
create_revision INTEGER,
|
|
|
|
prev_revision INTEGER,
|
|
|
|
lease INTEGER,
|
|
|
|
value BLOB,
|
|
|
|
old_value BLOB
|
|
|
|
)`,
|
|
|
|
`CREATE INDEX IF NOT EXISTS kine_name_index ON kine (name)`,
|
|
|
|
`CREATE UNIQUE INDEX IF NOT EXISTS kine_name_prev_revision_uindex ON kine (name, prev_revision)`,
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
func New(dataSourceName string) (server.Backend, error) {
|
2019-11-08 21:45:10 +00:00
|
|
|
backend, _, err := NewVariant("sqlite3", dataSourceName)
|
|
|
|
return backend, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewVariant(driverName, dataSourceName string) (server.Backend, *generic.Generic, error) {
|
2019-08-22 05:12:46 +00:00
|
|
|
if dataSourceName == "" {
|
|
|
|
if err := os.MkdirAll("./db", 0700); err != nil {
|
2019-11-08 21:45:10 +00:00
|
|
|
return nil, nil, err
|
2019-08-22 05:12:46 +00:00
|
|
|
}
|
|
|
|
dataSourceName = "./db/state.db?_journal=WAL&cache=shared"
|
|
|
|
}
|
|
|
|
|
2019-11-08 21:45:10 +00:00
|
|
|
dialect, err := generic.Open(driverName, dataSourceName, "?", false)
|
2019-08-22 05:12:46 +00:00
|
|
|
if err != nil {
|
2019-11-08 21:45:10 +00:00
|
|
|
return nil, nil, err
|
2019-08-22 05:12:46 +00:00
|
|
|
}
|
|
|
|
dialect.LastInsertID = true
|
|
|
|
|
|
|
|
if err := setup(dialect.DB); err != nil {
|
2019-11-08 21:45:10 +00:00
|
|
|
return nil, nil, err
|
2019-08-22 05:12:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
dialect.Migrate(context.Background())
|
2019-11-08 21:45:10 +00:00
|
|
|
return logstructured.New(sqllog.New(dialect)), dialect, nil
|
2019-08-22 05:12:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func setup(db *sql.DB) error {
|
|
|
|
for _, stmt := range schema {
|
|
|
|
_, err := db.Exec(stmt)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|