feat(web): Go W-G2 txn/migrate/FTS and W-G3 form ABI
Wire begin/commit/rollback, migrations, FTS search, and form rules/validate/render/submit/from_schema plus mount_form; pass web-db-w2, web-db-w6, and web-form-smoke against libweb.so. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
09b549a862
commit
364428ca1e
11 files changed
+1942
-103
No files matched your search
@@ -78,8 +78,9 @@ func open(url string) (*sql.DB, error) {
|
||||
return db, nil
|
||||
}
|
||||
|
||||
// ResetPool closes pooled connections (tests).
|
||||
// ResetPool closes pooled connections and open transactions (tests).
|
||||
func ResetPool() {
|
||||
resetTxns()
|
||||
poolMu.Lock()
|
||||
defer poolMu.Unlock()
|
||||
for k, db := range pool {
|
||||
@@ -291,8 +292,8 @@ func Init(url, name string, fields any) (map[string]any, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
func columnNames(db *sql.DB, tableName string) ([]string, error) {
|
||||
rows, err := db.Query(fmt.Sprintf(`PRAGMA table_info("%s")`, tableName))
|
||||
func columnNames(c dbConn, tableName string) ([]string, error) {
|
||||
rows, err := c.Query(fmt.Sprintf(`PRAGMA table_info("%s")`, tableName))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -363,25 +364,26 @@ func fromSQL(v any) any {
|
||||
}
|
||||
|
||||
// Insert inserts row maps. Returns {"ok":true,"inserted":n}.
|
||||
func Insert(url, tableName string, rows any) (map[string]any, error) {
|
||||
// Optional txnID routes through an open Begin transaction.
|
||||
func Insert(url, tableName string, rows any, txnID ...string) (map[string]any, error) {
|
||||
tn, err := ident(tableName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
db, err := open(url)
|
||||
c, err := connFor(url, optTxn(txnID))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
colsPresent, err := columnNames(db, tn)
|
||||
colsPresent, err := columnNames(c, tn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hasCreated, hasUpdated := false, false
|
||||
for _, c := range colsPresent {
|
||||
if c == "created_at" {
|
||||
for _, col := range colsPresent {
|
||||
if col == "created_at" {
|
||||
hasCreated = true
|
||||
}
|
||||
if c == "updated_at" {
|
||||
if col == "updated_at" {
|
||||
hasUpdated = true
|
||||
}
|
||||
}
|
||||
@@ -434,7 +436,7 @@ func Insert(url, tableName string, rows any) (map[string]any, error) {
|
||||
`INSERT INTO "%s" (%s) VALUES (%s)`,
|
||||
tn, strings.Join(cols, ", "), strings.Join(placeholders, ", "),
|
||||
)
|
||||
if _, err := db.Exec(sqlStmt, vals...); err != nil {
|
||||
if _, err := c.Exec(sqlStmt, vals...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n++
|
||||
@@ -719,7 +721,8 @@ type SelectOpts struct {
|
||||
|
||||
// Select runs SELECT * FROM table with optional where/order/offset.
|
||||
// Without offset: {"rows":[…]}; with offset: {"rows":[…],"total":N}.
|
||||
func Select(url, tableName string, limit int64, opts SelectOpts) (map[string]any, error) {
|
||||
// Optional txnID routes through an open Begin transaction.
|
||||
func Select(url, tableName string, limit int64, opts SelectOpts, txnID ...string) (map[string]any, error) {
|
||||
tn, err := ident(tableName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -728,7 +731,7 @@ func Select(url, tableName string, limit int64, opts SelectOpts) (map[string]any
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
db, err := open(url)
|
||||
c, err := connFor(url, optTxn(txnID))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -752,11 +755,11 @@ func Select(url, tableName string, limit int64, opts SelectOpts) (map[string]any
|
||||
col = part[1:]
|
||||
dir = " DESC"
|
||||
}
|
||||
c, err := ident(col)
|
||||
cname, err := ident(col)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
orderExprs = append(orderExprs, fmt.Sprintf(`"%s"%s`, c, dir))
|
||||
orderExprs = append(orderExprs, fmt.Sprintf(`"%s"%s`, cname, dir))
|
||||
}
|
||||
if len(orderExprs) > 0 {
|
||||
sqlStmt += " ORDER BY " + strings.Join(orderExprs, ", ")
|
||||
@@ -768,7 +771,7 @@ func Select(url, tableName string, limit int64, opts SelectOpts) (map[string]any
|
||||
sqlStmt += " OFFSET ?"
|
||||
vals = append(vals, *opts.Offset)
|
||||
}
|
||||
rows, err := db.Query(sqlStmt, vals...)
|
||||
rows, err := c.Query(sqlStmt, vals...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -784,7 +787,7 @@ func Select(url, tableName string, limit int64, opts SelectOpts) (map[string]any
|
||||
countSQL := fmt.Sprintf(`SELECT COUNT(*) FROM "%s"%s`, tn, whereSQL)
|
||||
_, whereOnly, _ := parseWhere(opts.Where)
|
||||
var total int64
|
||||
if err := db.QueryRow(countSQL, whereOnly...).Scan(&total); err != nil {
|
||||
if err := c.QueryRow(countSQL, whereOnly...).Scan(&total); err != nil {
|
||||
total = int64(len(list))
|
||||
}
|
||||
return map[string]any{"rows": list, "total": float64(total)}, nil
|
||||
@@ -793,17 +796,18 @@ func Select(url, tableName string, limit int64, opts SelectOpts) (map[string]any
|
||||
}
|
||||
|
||||
// Get returns one row by id, or nil (JSON null).
|
||||
func Get(url, tableName, id string) (any, error) {
|
||||
// Optional txnID routes through an open Begin transaction.
|
||||
func Get(url, tableName, id string, txnID ...string) (any, error) {
|
||||
tn, err := ident(tableName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
db, err := open(url)
|
||||
c, err := connFor(url, optTxn(txnID))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sqlStmt := fmt.Sprintf(`SELECT * FROM "%s" WHERE "id" = ? LIMIT 1`, tn)
|
||||
rows, err := db.Query(sqlStmt, toSQLArg(id))
|
||||
rows, err := c.Query(sqlStmt, toSQLArg(id))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -834,13 +838,14 @@ func sqlArgs(args any) []any {
|
||||
}
|
||||
|
||||
// Exec runs a non-SELECT statement. Returns {"ok":true,"changes":N}.
|
||||
func Exec(url, sqlStmt string, args any) (map[string]any, error) {
|
||||
db, err := open(url)
|
||||
// Optional txnID routes through an open Begin transaction.
|
||||
func Exec(url, sqlStmt string, args any, txnID ...string) (map[string]any, error) {
|
||||
c, err := connFor(url, optTxn(txnID))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vals := sqlArgs(args)
|
||||
res, err := db.Exec(sqlStmt, vals...)
|
||||
res, err := c.Exec(sqlStmt, vals...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -850,7 +855,8 @@ func Exec(url, sqlStmt string, args any) (map[string]any, error) {
|
||||
|
||||
// Update sets columns from row (skips id). Auto-sets updated_at when present.
|
||||
// Returns {"ok":true,"updated":N}.
|
||||
func Update(url, tableName, id string, row any) (map[string]any, error) {
|
||||
// Optional txnID routes through an open Begin transaction.
|
||||
func Update(url, tableName, id string, row any, txnID ...string) (map[string]any, error) {
|
||||
tn, err := ident(tableName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -859,17 +865,17 @@ func Update(url, tableName, id string, row any) (map[string]any, error) {
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("row must be a map")
|
||||
}
|
||||
db, err := open(url)
|
||||
c, err := connFor(url, optTxn(txnID))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
colsPresent, err := columnNames(db, tn)
|
||||
colsPresent, err := columnNames(c, tn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hasUpdated := false
|
||||
for _, c := range colsPresent {
|
||||
if c == "updated_at" {
|
||||
for _, col := range colsPresent {
|
||||
if col == "updated_at" {
|
||||
hasUpdated = true
|
||||
break
|
||||
}
|
||||
@@ -899,7 +905,7 @@ func Update(url, tableName, id string, row any) (map[string]any, error) {
|
||||
}
|
||||
vals = append(vals, id) // Rust binds id as text; SQLite coerces
|
||||
sqlStmt := fmt.Sprintf(`UPDATE "%s" SET %s WHERE "id" = ?`, tn, strings.Join(sets, ", "))
|
||||
res, err := db.Exec(sqlStmt, vals...)
|
||||
res, err := c.Exec(sqlStmt, vals...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -908,17 +914,18 @@ func Update(url, tableName, id string, row any) (map[string]any, error) {
|
||||
}
|
||||
|
||||
// Delete removes a row by id. Returns {"ok":true,"deleted":N}.
|
||||
func Delete(url, tableName, id string) (map[string]any, error) {
|
||||
// Optional txnID routes through an open Begin transaction.
|
||||
func Delete(url, tableName, id string, txnID ...string) (map[string]any, error) {
|
||||
tn, err := ident(tableName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
db, err := open(url)
|
||||
c, err := connFor(url, optTxn(txnID))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sqlStmt := fmt.Sprintf(`DELETE FROM "%s" WHERE "id" = ?`, tn)
|
||||
res, err := db.Exec(sqlStmt, id)
|
||||
res, err := c.Exec(sqlStmt, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -927,13 +934,14 @@ func Delete(url, tableName, id string) (map[string]any, error) {
|
||||
}
|
||||
|
||||
// Query runs a SELECT (or any result-set SQL). Returns {"rows":[…],"count":N}.
|
||||
func Query(url, sqlStmt string, args any) (map[string]any, error) {
|
||||
db, err := open(url)
|
||||
// Optional txnID routes through an open Begin transaction.
|
||||
func Query(url, sqlStmt string, args any, txnID ...string) (map[string]any, error) {
|
||||
c, err := connFor(url, optTxn(txnID))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vals := sqlArgs(args)
|
||||
rows, err := db.Query(sqlStmt, vals...)
|
||||
rows, err := c.Query(sqlStmt, vals...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -949,7 +957,8 @@ func Query(url, sqlStmt string, args any) (map[string]any, error) {
|
||||
}
|
||||
|
||||
// Count returns {"count":N} for rows matching where (nil where → all).
|
||||
func Count(url, tableName string, where any) (map[string]any, error) {
|
||||
// Optional txnID routes through an open Begin transaction.
|
||||
func Count(url, tableName string, where any, txnID ...string) (map[string]any, error) {
|
||||
tn, err := ident(tableName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -958,7 +967,7 @@ func Count(url, tableName string, where any) (map[string]any, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
db, err := open(url)
|
||||
c, err := connFor(url, optTxn(txnID))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -967,8 +976,53 @@ func Count(url, tableName string, where any) (map[string]any, error) {
|
||||
sqlStmt += " WHERE " + strings.Join(exprs, " AND ")
|
||||
}
|
||||
var n int64
|
||||
if err := db.QueryRow(sqlStmt, vals...).Scan(&n); err != nil {
|
||||
if err := c.QueryRow(sqlStmt, vals...).Scan(&n); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"count": float64(n)}, nil
|
||||
}
|
||||
|
||||
// ColumnInfo is one PRAGMA table_info row (admin forms / schema introspection).
|
||||
type ColumnInfo struct {
|
||||
Name string
|
||||
SQLType string
|
||||
NotNull bool
|
||||
PK bool
|
||||
}
|
||||
|
||||
// TableInfo returns column metadata for a SQLite table.
|
||||
func TableInfo(url, tableName string) ([]ColumnInfo, error) {
|
||||
tn, err := ident(tableName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
db, err := open(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows, err := db.Query(fmt.Sprintf(`PRAGMA table_info("%s")`, tn))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []ColumnInfo
|
||||
for rows.Next() {
|
||||
var cid int
|
||||
var name, ctype string
|
||||
var notnull, pk int
|
||||
var dflt any
|
||||
if err := rows.Scan(&cid, &name, &ctype, ¬null, &dflt, &pk); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ctype == "" {
|
||||
ctype = "TEXT"
|
||||
}
|
||||
out = append(out, ColumnInfo{
|
||||
Name: name,
|
||||
SQLType: ctype,
|
||||
NotNull: notnull != 0,
|
||||
PK: pk != 0,
|
||||
})
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
@@ -191,3 +191,156 @@ func TestQueryAndCount(t *testing.T) {
|
||||
t.Fatalf("like=%v", like)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTxnCommitRollback(t *testing.T) {
|
||||
url := setupArticles(t)
|
||||
|
||||
begin, err := db.Begin(url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if begin["_type"] != "txn" {
|
||||
t.Fatalf("begin=%v", begin)
|
||||
}
|
||||
tid, _ := begin["txn"].(string)
|
||||
if tid == "" {
|
||||
t.Fatalf("missing txn id: %v", begin)
|
||||
}
|
||||
if begin["事务"] != tid || begin["地址"] != begin["url"] {
|
||||
t.Fatalf("bilingual keys: %v", begin)
|
||||
}
|
||||
|
||||
if _, err := db.Insert(url, "articles", []any{
|
||||
map[string]any{"id": float64(99), "title": "TxnRow", "body": "in-txn"},
|
||||
}, tid); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Visible inside the transaction.
|
||||
inside, err := db.Count(url, "articles", nil, tid)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if inside["count"] != float64(4) {
|
||||
t.Fatalf("in-txn count=%v", inside)
|
||||
}
|
||||
if _, err := db.Commit(tid); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, err := db.Count(url, "articles", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if after["count"] != float64(4) {
|
||||
t.Fatalf("after commit count=%v", after)
|
||||
}
|
||||
|
||||
begin2, err := db.Begin(url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tid2 := begin2["txn"].(string)
|
||||
if _, err := db.Insert(url, "articles", []any{
|
||||
map[string]any{"id": float64(100), "title": "Zeta", "body": "rolled"},
|
||||
}, tid2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Rollback(tid2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
final, err := db.Count(url, "articles", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if final["count"] != float64(4) {
|
||||
t.Fatalf("after rollback count=%v", final)
|
||||
}
|
||||
miss, err := db.Get(url, "articles", "100")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if miss != nil {
|
||||
t.Fatalf("expected rolled-back row absent, got %v", miss)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrate(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
url := "sqlite:" + filepath.Join(dir, "m.db")
|
||||
defer db.ResetPool()
|
||||
|
||||
steps := []any{
|
||||
map[string]any{
|
||||
"版本": float64(1),
|
||||
"SQL": `CREATE TABLE IF NOT EXISTS posts (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, body TEXT, status TEXT NOT NULL DEFAULT 'draft')`,
|
||||
},
|
||||
map[string]any{
|
||||
"版本": float64(2),
|
||||
"SQL": `CREATE TABLE IF NOT EXISTS comments (id INTEGER PRIMARY KEY AUTOINCREMENT, post_id INTEGER NOT NULL, body TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending')`,
|
||||
},
|
||||
}
|
||||
m1, err := db.Migrate(url, steps)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m1["ok"] != true || m1["from"] != float64(0) || m1["to"] != float64(2) {
|
||||
t.Fatalf("migrate1=%v", m1)
|
||||
}
|
||||
applied, ok := m1["applied"].([]any)
|
||||
if !ok || len(applied) != 2 {
|
||||
t.Fatalf("applied=%v", m1["applied"])
|
||||
}
|
||||
|
||||
m2, err := db.Migrate(url, steps)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
applied2 := m2["applied"].([]any)
|
||||
if len(applied2) != 0 || m2["from"] != float64(2) || m2["to"] != float64(2) {
|
||||
t.Fatalf("idempotent migrate=%v", m2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFtsCreateSearch(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
url := "sqlite:" + filepath.Join(dir, "fts.db")
|
||||
defer db.ResetPool()
|
||||
|
||||
steps := []any{
|
||||
map[string]any{
|
||||
"version": float64(1),
|
||||
"sql": `CREATE TABLE IF NOT EXISTS posts (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, body TEXT, status TEXT NOT NULL DEFAULT 'draft')`,
|
||||
},
|
||||
}
|
||||
if _, err := db.Migrate(url, steps); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Insert(url, "posts", []any{
|
||||
map[string]any{"title": "Alpha note", "body": "hello world search", "status": "published"},
|
||||
map[string]any{"title": "Beta draft", "body": "secret draft body", "status": "draft"},
|
||||
map[string]any{"title": "Gamma published", "body": "another hello", "status": "published"},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
fts, err := db.FtsCreate(url, "posts", "title,body", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fts["ok"] != true || fts["fts"] != "posts_fts" {
|
||||
t.Fatalf("fts=%v", fts)
|
||||
}
|
||||
|
||||
hit, err := db.Search(url, "posts", "hello", 10, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
n, _ := hit["count"].(float64)
|
||||
if n < 1 {
|
||||
t.Fatalf("search=%v", hit)
|
||||
}
|
||||
rows := hit["rows"].([]any)
|
||||
first := rows[0].(map[string]any)
|
||||
if cell, _ := first["title"].(string); cell == "" {
|
||||
t.Fatalf("expected title on FTS row: %v", first)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/table"
|
||||
)
|
||||
|
||||
func parseColumnList(columns any) ([]string, error) {
|
||||
switch t := columns.(type) {
|
||||
case string:
|
||||
parts := strings.Split(t, ",")
|
||||
var cols []string
|
||||
for _, p := range parts {
|
||||
p = strings.TrimSpace(p)
|
||||
if p == "" {
|
||||
continue
|
||||
}
|
||||
if _, err := ident(p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cols = append(cols, p)
|
||||
}
|
||||
if len(cols) == 0 {
|
||||
return nil, fmt.Errorf("fts columns is empty")
|
||||
}
|
||||
return cols, nil
|
||||
case []any:
|
||||
var cols []string
|
||||
for _, v := range t {
|
||||
name := cellStr(v)
|
||||
if _, err := ident(name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cols = append(cols, name)
|
||||
}
|
||||
if len(cols) == 0 {
|
||||
return nil, fmt.Errorf("fts columns is empty")
|
||||
}
|
||||
return cols, nil
|
||||
case map[string]any:
|
||||
rows := table.AsRows(columns)
|
||||
arr, ok := rows.([]any)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("fts columns must be a list or CSV string")
|
||||
}
|
||||
var cols []string
|
||||
for _, row := range arr {
|
||||
if obj, ok := row.(map[string]any); ok {
|
||||
name := ""
|
||||
for _, k := range []string{"name", "字段", "column"} {
|
||||
if v, ok := obj[k]; ok {
|
||||
name = cellStr(v)
|
||||
break
|
||||
}
|
||||
}
|
||||
if name == "" {
|
||||
for _, v := range obj {
|
||||
name = cellStr(v)
|
||||
break
|
||||
}
|
||||
}
|
||||
if name != "" {
|
||||
if _, err := ident(name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cols = append(cols, name)
|
||||
}
|
||||
} else {
|
||||
name := cellStr(row)
|
||||
if name != "" {
|
||||
if _, err := ident(name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cols = append(cols, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(cols) == 0 {
|
||||
return nil, fmt.Errorf("fts columns is empty")
|
||||
}
|
||||
return cols, nil
|
||||
case nil:
|
||||
return nil, fmt.Errorf("fts columns is empty")
|
||||
default:
|
||||
return nil, fmt.Errorf("fts columns must be a list or CSV string")
|
||||
}
|
||||
}
|
||||
|
||||
func ftsName(tableName string, name string) (string, error) {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
return tableName + "_fts", nil
|
||||
}
|
||||
return ident(name)
|
||||
}
|
||||
|
||||
// FtsCreate builds an FTS5 virtual table synced via content= + triggers.
|
||||
// Returns {"ok":true,"table":…,"fts":…,"columns":[…]}.
|
||||
func FtsCreate(url, tableName string, columns any, name string) (map[string]any, error) {
|
||||
lower := strings.ToLower(ResolveURL(url))
|
||||
if strings.HasPrefix(lower, "postgres://") || strings.HasPrefix(lower, "postgresql://") {
|
||||
return nil, fmt.Errorf("db.fts is SQLite-only in this wave")
|
||||
}
|
||||
tn, err := ident(tableName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cols, err := parseColumnList(columns)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fts, err := ftsName(tn, name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
quoted := make([]string, len(cols))
|
||||
for i, c := range cols {
|
||||
quoted[i] = `"` + c + `"`
|
||||
}
|
||||
colSQL := strings.Join(quoted, ", ")
|
||||
|
||||
db, err := open(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
create := fmt.Sprintf(
|
||||
`CREATE VIRTUAL TABLE IF NOT EXISTS "%s" USING fts5(%s, content="%s", content_rowid="id")`,
|
||||
fts, colSQL, tn,
|
||||
)
|
||||
if _, err := db.Exec(create); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ai, ad, au := fts+"_ai", fts+"_ad", fts+"_au"
|
||||
for _, trg := range []string{ai, ad, au} {
|
||||
if _, err := db.Exec(fmt.Sprintf(`DROP TRIGGER IF EXISTS "%s"`, trg)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
newCols := make([]string, len(cols))
|
||||
oldCols := make([]string, len(cols))
|
||||
for i, c := range cols {
|
||||
newCols[i] = `new."` + c + `"`
|
||||
oldCols[i] = `old."` + c + `"`
|
||||
}
|
||||
newSQL := strings.Join(newCols, ", ")
|
||||
oldSQL := strings.Join(oldCols, ", ")
|
||||
|
||||
aiSQL := fmt.Sprintf(
|
||||
`CREATE TRIGGER "%s" AFTER INSERT ON "%s" BEGIN
|
||||
INSERT INTO "%s"(rowid, %s) VALUES (new.id, %s);
|
||||
END`,
|
||||
ai, tn, fts, colSQL, newSQL,
|
||||
)
|
||||
adSQL := fmt.Sprintf(
|
||||
`CREATE TRIGGER "%s" AFTER DELETE ON "%s" BEGIN
|
||||
INSERT INTO "%s"("%s", rowid, %s) VALUES('delete', old.id, %s);
|
||||
END`,
|
||||
ad, tn, fts, fts, colSQL, oldSQL,
|
||||
)
|
||||
auSQL := fmt.Sprintf(
|
||||
`CREATE TRIGGER "%s" AFTER UPDATE ON "%s" BEGIN
|
||||
INSERT INTO "%s"("%s", rowid, %s) VALUES('delete', old.id, %s);
|
||||
INSERT INTO "%s"(rowid, %s) VALUES (new.id, %s);
|
||||
END`,
|
||||
au, tn, fts, fts, colSQL, oldSQL, fts, colSQL, newSQL,
|
||||
)
|
||||
for _, stmt := range []string{aiSQL, adSQL, auSQL} {
|
||||
if _, err := db.Exec(stmt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if _, err := db.Exec(fmt.Sprintf(`INSERT INTO "%s"("%s") VALUES('rebuild')`, fts, fts)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
colAny := make([]any, len(cols))
|
||||
for i, c := range cols {
|
||||
colAny[i] = c
|
||||
}
|
||||
return map[string]any{
|
||||
"ok": true,
|
||||
"table": tn,
|
||||
"fts": fts,
|
||||
"columns": colAny,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Search runs FTS5 MATCH against a table created by FtsCreate.
|
||||
// Returns {"rows":[…],"count":N}.
|
||||
func Search(url, tableName, q string, limit int64, name string) (map[string]any, error) {
|
||||
lower := strings.ToLower(ResolveURL(url))
|
||||
if strings.HasPrefix(lower, "postgres://") || strings.HasPrefix(lower, "postgresql://") {
|
||||
return nil, fmt.Errorf("db.search is SQLite-only in this wave")
|
||||
}
|
||||
tn, err := ident(tableName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fts, err := ftsName(tn, name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
q = strings.TrimSpace(q)
|
||||
if q == "" {
|
||||
return map[string]any{"rows": []any{}, "count": float64(0)}, nil
|
||||
}
|
||||
if limit <= 0 {
|
||||
limit = 20
|
||||
} else if limit > 500 {
|
||||
limit = 500
|
||||
}
|
||||
sqlStmt := fmt.Sprintf(
|
||||
`SELECT t.*, bm25("%s") AS rank
|
||||
FROM "%s"
|
||||
JOIN "%s" t ON t.id = "%s".rowid
|
||||
WHERE "%s" MATCH ?
|
||||
ORDER BY rank
|
||||
LIMIT ?`,
|
||||
fts, fts, tn, fts, fts,
|
||||
)
|
||||
db, err := open(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows, err := db.Query(sqlStmt, q, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
list, err := scanRows(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if list == nil {
|
||||
list = []any{}
|
||||
}
|
||||
return map[string]any{"rows": list, "count": float64(len(list))}, nil
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/table"
|
||||
)
|
||||
|
||||
// Migrate applies versioned SQL steps (SQLite only).
|
||||
// steps: list of {version|版本|ver, sql|SQL} maps (GFM columnar via AsRows).
|
||||
// Returns {"ok":true,"from":N,"to":M,"applied":[…]}.
|
||||
func Migrate(url string, steps any) (map[string]any, error) {
|
||||
lower := strings.ToLower(ResolveURL(url))
|
||||
if strings.HasPrefix(lower, "postgres://") || strings.HasPrefix(lower, "postgresql://") {
|
||||
return nil, fmt.Errorf("db.migrate is SQLite-only in this wave (use postgres migration tooling)")
|
||||
}
|
||||
|
||||
normalized := table.AsRows(steps)
|
||||
arr, ok := normalized.([]any)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("migrate steps must be a list")
|
||||
}
|
||||
|
||||
type step struct {
|
||||
version int64
|
||||
sql string
|
||||
}
|
||||
var parsed []step
|
||||
for _, row := range arr {
|
||||
// Bare SQL string → treat as sequential versions later if needed;
|
||||
// Rust requires maps; also accept plain SQL strings with auto version.
|
||||
if s, ok := row.(string); ok {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return nil, fmt.Errorf("migrate step has empty SQL")
|
||||
}
|
||||
parsed = append(parsed, step{version: 0, sql: s}) // version filled below
|
||||
continue
|
||||
}
|
||||
obj, ok := row.(map[string]any)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("migrate step must be a map")
|
||||
}
|
||||
var ver any
|
||||
for _, k := range []string{"version", "版本", "ver"} {
|
||||
if v, ok := obj[k]; ok {
|
||||
ver = v
|
||||
break
|
||||
}
|
||||
}
|
||||
if ver == nil {
|
||||
return nil, fmt.Errorf("migrate step missing `version`/`版本`")
|
||||
}
|
||||
version, err := migrateVersion(ver)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if version <= 0 {
|
||||
return nil, fmt.Errorf("migrate version must be positive, got %d", version)
|
||||
}
|
||||
sqlStmt := ""
|
||||
for _, k := range []string{"sql", "SQL", "Sql"} {
|
||||
if v, ok := obj[k]; ok {
|
||||
sqlStmt = cellStr(v)
|
||||
break
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(sqlStmt) == "" {
|
||||
return nil, fmt.Errorf("migrate version %d has empty SQL", version)
|
||||
}
|
||||
parsed = append(parsed, step{version: version, sql: sqlStmt})
|
||||
}
|
||||
|
||||
// Auto-number bare SQL strings (1-based in list order among string-only steps,
|
||||
// or continue after max explicit version when mixed — prefer Rust map path).
|
||||
var auto int64
|
||||
for i := range parsed {
|
||||
if parsed[i].version == 0 {
|
||||
auto++
|
||||
parsed[i].version = auto
|
||||
} else if parsed[i].version > auto {
|
||||
auto = parsed[i].version
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by version (stable insertion sort).
|
||||
for i := 1; i < len(parsed); i++ {
|
||||
j := i
|
||||
for j > 0 && parsed[j-1].version > parsed[j].version {
|
||||
parsed[j-1], parsed[j] = parsed[j], parsed[j-1]
|
||||
j--
|
||||
}
|
||||
}
|
||||
for i := 1; i < len(parsed); i++ {
|
||||
if parsed[i-1].version == parsed[i].version {
|
||||
return nil, fmt.Errorf("duplicate migrate version %d", parsed[i].version)
|
||||
}
|
||||
}
|
||||
|
||||
db, err := open(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := db.Exec(`CREATE TABLE IF NOT EXISTS "_marqdo_migrations" (
|
||||
version INTEGER PRIMARY KEY,
|
||||
applied_at TEXT NOT NULL
|
||||
)`); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var current int64
|
||||
if err := db.QueryRow(`SELECT COALESCE(MAX(version), 0) FROM "_marqdo_migrations"`).Scan(¤t); err != nil {
|
||||
current = 0
|
||||
}
|
||||
|
||||
var applied []any
|
||||
for _, st := range parsed {
|
||||
if st.version <= current {
|
||||
continue
|
||||
}
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := tx.Exec(st.sql); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return nil, fmt.Errorf("migrate version %d failed: %w", st.version, err)
|
||||
}
|
||||
if _, err := tx.Exec(
|
||||
`INSERT INTO "_marqdo_migrations" (version, applied_at) VALUES (?, datetime('now'))`,
|
||||
st.version,
|
||||
); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return nil, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
applied = append(applied, float64(st.version))
|
||||
}
|
||||
if applied == nil {
|
||||
applied = []any{}
|
||||
}
|
||||
to := current
|
||||
if len(applied) > 0 {
|
||||
to = int64(applied[len(applied)-1].(float64))
|
||||
}
|
||||
return map[string]any{
|
||||
"ok": true,
|
||||
"from": float64(current),
|
||||
"to": float64(to),
|
||||
"applied": applied,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func migrateVersion(ver any) (int64, error) {
|
||||
switch t := ver.(type) {
|
||||
case float64:
|
||||
return int64(t), nil
|
||||
case int64:
|
||||
return t, nil
|
||||
case int:
|
||||
return int64(t), nil
|
||||
case string:
|
||||
n, err := strconv.ParseInt(strings.TrimSpace(t), 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("bad migrate version `%s`", t)
|
||||
}
|
||||
return n, nil
|
||||
default:
|
||||
return 0, fmt.Errorf("migrate version must be an integer")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// dbConn is *sql.DB or a transaction-bound *sql.Conn.
|
||||
type dbConn interface {
|
||||
Exec(query string, args ...any) (sql.Result, error)
|
||||
Query(query string, args ...any) (*sql.Rows, error)
|
||||
QueryRow(query string, args ...any) *sql.Row
|
||||
}
|
||||
|
||||
type txnConn struct {
|
||||
conn *sql.Conn
|
||||
url string
|
||||
}
|
||||
|
||||
func (t *txnConn) Exec(query string, args ...any) (sql.Result, error) {
|
||||
return t.conn.ExecContext(context.Background(), query, args...)
|
||||
}
|
||||
|
||||
func (t *txnConn) Query(query string, args ...any) (*sql.Rows, error) {
|
||||
return t.conn.QueryContext(context.Background(), query, args...)
|
||||
}
|
||||
|
||||
func (t *txnConn) QueryRow(query string, args ...any) *sql.Row {
|
||||
return t.conn.QueryRowContext(context.Background(), query, args...)
|
||||
}
|
||||
|
||||
var (
|
||||
txnsMu sync.Mutex
|
||||
txns = map[string]*txnConn{}
|
||||
txnSeq atomic.Uint64
|
||||
txnSeedM sync.Mutex
|
||||
txnSeed = uint64(0x243f_6a88_85a3_08d3)
|
||||
)
|
||||
|
||||
func nextTxnID() string {
|
||||
nanos := time.Now().UnixNano() & 0xffffffff
|
||||
pid := os.Getpid()
|
||||
txnSeedM.Lock()
|
||||
x := txnSeed
|
||||
x ^= x << 13
|
||||
x ^= x >> 7
|
||||
x ^= x << 17
|
||||
txnSeed = x
|
||||
txnSeedM.Unlock()
|
||||
n := txnSeq.Add(1)
|
||||
return fmt.Sprintf("txn-%x%x%x%x", pid, nanos, x, n)
|
||||
}
|
||||
|
||||
func optTxn(txnID []string) string {
|
||||
if len(txnID) == 0 {
|
||||
return ""
|
||||
}
|
||||
return txnID[0]
|
||||
}
|
||||
|
||||
// connFor returns the pooled DB or an active transaction connection.
|
||||
func connFor(url, txnID string) (dbConn, error) {
|
||||
if txnID != "" {
|
||||
txnsMu.Lock()
|
||||
defer txnsMu.Unlock()
|
||||
t, ok := txns[txnID]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unknown transaction `%s`", txnID)
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
return open(url)
|
||||
}
|
||||
|
||||
func takeTxn(txnID string) (*txnConn, error) {
|
||||
txnsMu.Lock()
|
||||
defer txnsMu.Unlock()
|
||||
t, ok := txns[txnID]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unknown transaction `%s`", txnID)
|
||||
}
|
||||
delete(txns, txnID)
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func resetTxns() {
|
||||
txnsMu.Lock()
|
||||
defer txnsMu.Unlock()
|
||||
for id, t := range txns {
|
||||
_, _ = t.conn.ExecContext(context.Background(), "ROLLBACK")
|
||||
_ = t.conn.Close()
|
||||
delete(txns, id)
|
||||
}
|
||||
}
|
||||
|
||||
// Begin starts a SQLite transaction (BEGIN IMMEDIATE).
|
||||
// Returns {"_type":"txn","txn":id,"url":url,"事务":id,"地址":url}.
|
||||
func Begin(url string) (map[string]any, error) {
|
||||
db, err := open(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conn, err := db.Conn(context.Background())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := conn.ExecContext(context.Background(), "BEGIN IMMEDIATE"); err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
id := nextTxnID()
|
||||
resolved := ResolveURL(url)
|
||||
txnsMu.Lock()
|
||||
txns[id] = &txnConn{conn: conn, url: resolved}
|
||||
txnsMu.Unlock()
|
||||
return map[string]any{
|
||||
"_type": "txn",
|
||||
"txn": id,
|
||||
"url": resolved,
|
||||
"事务": id,
|
||||
"地址": resolved,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Commit commits a transaction. Returns {"ok":true}.
|
||||
func Commit(txnID string) (map[string]any, error) {
|
||||
t, err := takeTxn(txnID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer t.conn.Close()
|
||||
if _, err := t.conn.ExecContext(context.Background(), "COMMIT"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"ok": true}, nil
|
||||
}
|
||||
|
||||
// Rollback rolls back a transaction. Returns {"ok":true}.
|
||||
func Rollback(txnID string) (map[string]any, error) {
|
||||
t, err := takeTxn(txnID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer t.conn.Close()
|
||||
if _, err := t.conn.ExecContext(context.Background(), "ROLLBACK"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"ok": true}, nil
|
||||
}
|
||||
Reference in new issue
Block a user