filer/sql: generators bind the arguments of row statements

Insert, update, find and delete now take the row key and return their
arguments with the query, so a generator decides how a key maps to its
columns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK
This commit is contained in:
Chris LuandClaude Opus 5.5 committed 2026-12-01 16:34:58 -08:00
1 parent 88fb3c60eb
commit 4ae00a4728
8 files changed
+80 -45

No files matched your search

+33 -9
View File
@@ -15,14 +15,32 @@ import (
"github.com/seaweedfs/seaweedfs/weed/util"
)
// RowKey is the primary key of a row: an entry's directory and name, or the
// split of a key-value key that GenDirAndName makes.
type RowKey struct {
DirHash int64
Name string
Directory string
}
func EntryRowKey(dir, name string) RowKey {
return RowKey{DirHash: util.HashStringToLong(dir), Name: name, Directory: dir}
}
// Args returns the key's values in (dirhash, name, directory) order, then extra.
func (k RowKey) Args(extra ...interface{}) []interface{} {
return append([]interface{}{k.DirHash, k.Name, k.Directory}, extra...)
}
// SqlGenerator returns each statement together with its arguments.
type SqlGenerator interface {
GetSqlInsert(tableName string) string
GetSqlUpdate(tableName string) string
GetSqlFind(tableName string) string
GetSqlInsert(tableName string, key RowKey, meta []byte) (string, []interface{})
GetSqlUpdate(tableName string, key RowKey, meta []byte) (string, []interface{})
GetSqlFind(tableName string, key RowKey) (string, []interface{})
// GetSqlFindBatch selects dirhash, name, directory and meta of the rows
// matching count (dirhash, name, directory) triples, as GetSqlFind does one.
GetSqlFindBatch(tableName string, count int) string
GetSqlDelete(tableName string) string
GetSqlDelete(tableName string, key RowKey) (string, []interface{})
GetSqlDeleteFolderChildren(tableName string) string
GetSqlListExclusive(tableName string) string
GetSqlListInclusive(tableName string) string
@@ -247,13 +265,16 @@ func (store *AbstractSqlStore) InsertEntry(ctx context.Context, entry *filer.Ent
if len(entry.GetChunks()) > filer.CountEntryChunksForGzip {
meta = util.MaybeGzipData(meta)
}
key := EntryRowKey(dir, name)
sqlInsert := "insert"
res, err := db.ExecContext(ctx, store.GetSqlInsert(bucket), util.HashStringToLong(dir), name, dir, meta)
sqlText, args := store.GetSqlInsert(bucket, key, meta)
res, err := db.ExecContext(ctx, sqlText, args...)
if err != nil && strings.Contains(strings.ToLower(err.Error()), "duplicate entry") {
// now the insert failed possibly due to duplication constraints
sqlInsert = "falls back to update"
glog.V(1).InfofCtx(ctx, "insert %s %s: %v", entry.FullPath, sqlInsert, err)
res, err = db.ExecContext(ctx, store.GetSqlUpdate(bucket), meta, util.HashStringToLong(dir), name, dir)
sqlText, args = store.GetSqlUpdate(bucket, key, meta)
res, err = db.ExecContext(ctx, sqlText, args...)
}
if err != nil {
return fmt.Errorf("%s %s: %w", sqlInsert, entry.FullPath, err)
@@ -291,7 +312,8 @@ func (store *AbstractSqlStore) UpdateEntry(ctx context.Context, entry *filer.Ent
return fmt.Errorf("encode %s: %w", entry.FullPath, err)
}
res, err := db.ExecContext(ctx, store.GetSqlUpdate(bucket), meta, util.HashStringToLong(dir), name, dir)
sqlText, args := store.GetSqlUpdate(bucket, EntryRowKey(dir, name), meta)
res, err := db.ExecContext(ctx, sqlText, args...)
if err != nil {
return fmt.Errorf("update %s: %w", entry.FullPath, err)
}
@@ -320,7 +342,8 @@ func (store *AbstractSqlStore) FindEntry(ctx context.Context, fullpath util.Full
}
dir, name := shortPath.DirAndName()
row := db.QueryRowContext(ctx, store.GetSqlFind(bucket), util.HashStringToLong(dir), name, dir)
sqlText, args := store.GetSqlFind(bucket, EntryRowKey(dir, name))
row := db.QueryRowContext(ctx, sqlText, args...)
var data []byte
if err := row.Scan(&data); err != nil {
@@ -351,7 +374,8 @@ func (store *AbstractSqlStore) DeleteEntry(ctx context.Context, fullpath util.Fu
dir, name := shortPath.DirAndName()
res, err := db.ExecContext(ctx, store.GetSqlDelete(bucket), util.HashStringToLong(dir), name, dir)
sqlText, args := store.GetSqlDelete(bucket, EntryRowKey(dir, name))
res, err := db.ExecContext(ctx, sqlText, args...)
if err != nil {
return fmt.Errorf("delete %s: %w", fullpath, err)
}
@@ -28,9 +28,10 @@ func (store *AbstractSqlStore) KvPut(ctx context.Context, key []byte, value []by
db := store.kvDB(ctx)
dirStr, dirHash, name := GenDirAndName(key)
rowKey := kvRowKey(key)
_, err = db.ExecContext(ctx, store.GetSqlInsert(DEFAULT_TABLE), dirHash, name, dirStr, value)
sqlText, args := store.GetSqlInsert(DEFAULT_TABLE, rowKey, value)
_, err = db.ExecContext(ctx, sqlText, args...)
if err == nil {
return
}
@@ -43,7 +44,8 @@ func (store *AbstractSqlStore) KvPut(ctx context.Context, key []byte, value []by
// now the insert failed possibly due to duplication constraints
glog.V(1).InfofCtx(ctx, "kv insert falls back to update: %s", err)
res, err := db.ExecContext(ctx, store.GetSqlUpdate(DEFAULT_TABLE), value, dirHash, name, dirStr)
sqlText, args = store.GetSqlUpdate(DEFAULT_TABLE, rowKey, value)
res, err := db.ExecContext(ctx, sqlText, args...)
if err != nil {
return fmt.Errorf("kv upsert: %s", err)
}
@@ -60,8 +62,8 @@ func (store *AbstractSqlStore) KvGet(ctx context.Context, key []byte) (value []b
db := store.kvDB(ctx)
dirStr, dirHash, name := GenDirAndName(key)
row := db.QueryRowContext(ctx, store.GetSqlFind(DEFAULT_TABLE), dirHash, name, dirStr)
sqlText, args := store.GetSqlFind(DEFAULT_TABLE, kvRowKey(key))
row := db.QueryRowContext(ctx, sqlText, args...)
err = row.Scan(&value)
@@ -125,9 +127,8 @@ func (store *AbstractSqlStore) KvDelete(ctx context.Context, key []byte) (err er
db := store.kvDB(ctx)
dirStr, dirHash, name := GenDirAndName(key)
res, err := db.ExecContext(ctx, store.GetSqlDelete(DEFAULT_TABLE), dirHash, name, dirStr)
sqlText, args := store.GetSqlDelete(DEFAULT_TABLE, kvRowKey(key))
res, err := db.ExecContext(ctx, sqlText, args...)
if err != nil {
return fmt.Errorf("kv delete: %s", err)
}
@@ -141,6 +142,11 @@ func (store *AbstractSqlStore) KvDelete(ctx context.Context, key []byte) (err er
}
func kvRowKey(key []byte) RowKey {
dirStr, dirHash, name := GenDirAndName(key)
return RowKey{DirHash: dirHash, Name: name, Directory: dirStr}
}
func GenDirAndName(key []byte) (dirStr string, dirHash int64, name string) {
for len(key) < 8 {
key = append(key, 0)
@@ -100,7 +100,8 @@ func (store *AbstractSqlStore) readRowInSnapshot(ctx context.Context, tx *sql.Tx
}
}
var data []byte
err := tx.QueryRowContext(ctx, store.GetSqlFind(table), util.HashStringToLong(shortDir), name, shortDir).Scan(&data)
sqlText, args := store.GetSqlFind(table, EntryRowKey(shortDir, name))
err := tx.QueryRowContext(ctx, sqlText, args...).Scan(&data)
if err == sql.ErrNoRows {
return nil, nil
}
@@ -220,8 +220,10 @@ func TestListDirectoryEntriesStoppedByCallbackWithCanceledContext(t *testing.T)
type writeGen struct{ SqlGenerator }
func (writeGen) GetSqlInsert(string) string { return "INSERT entry" }
func (writeGen) GetSqlDelete(string) string { return "DELETE entry" }
func (writeGen) GetSqlInsert(string, RowKey, []byte) (string, []interface{}) {
return "INSERT entry", nil
}
func (writeGen) GetSqlDelete(string, RowKey) (string, []interface{}) { return "DELETE entry", nil }
// What IsolatesTransactions declares: an entry write, an entry delete and a KV
// write under a transaction's context all go through that transaction, the KV
@@ -331,7 +333,7 @@ func (r *busyRows) Next(dest []driver.Value) error {
type findGen struct{ listGen }
func (findGen) GetSqlFind(string) string { return "SELECT meta" }
func (findGen) GetSqlFind(string, RowKey) (string, []interface{}) { return "SELECT meta", nil }
// A transaction has one connection, so a listing in one (a directory rename)
// must close its rows before the callback reads a hard link on it.
+9 -10
View File
@@ -31,20 +31,19 @@ var (
_ = abstract_sql.SqlGenerator(&SqlGenMysql{})
)
func (gen *SqlGenMysql) GetSqlInsert(tableName string) string {
func (gen *SqlGenMysql) GetSqlInsert(tableName string, key abstract_sql.RowKey, meta []byte) (string, []interface{}) {
if gen.UpsertQueryTemplate != "" {
return fmt.Sprintf(gen.UpsertQueryTemplate, tableName)
} else {
return fmt.Sprintf("INSERT INTO `%s` (`dirhash`,`name`,`directory`,`meta`) VALUES(?,?,?,?)", tableName)
return fmt.Sprintf(gen.UpsertQueryTemplate, tableName), key.Args(meta)
}
return fmt.Sprintf("INSERT INTO `%s` (`dirhash`,`name`,`directory`,`meta`) VALUES(?,?,?,?)", tableName), key.Args(meta)
}
func (gen *SqlGenMysql) GetSqlUpdate(tableName string) string {
return fmt.Sprintf("UPDATE `%s` SET `meta` = ? WHERE `dirhash` = ? AND `name` = ? AND `directory` = ?", tableName)
func (gen *SqlGenMysql) GetSqlUpdate(tableName string, key abstract_sql.RowKey, meta []byte) (string, []interface{}) {
return fmt.Sprintf("UPDATE `%s` SET `meta` = ? WHERE `dirhash` = ? AND `name` = ? AND `directory` = ?", tableName), append([]interface{}{meta}, key.Args()...)
}
func (gen *SqlGenMysql) GetSqlFind(tableName string) string {
return fmt.Sprintf("SELECT `meta` FROM `%s` WHERE `dirhash` = ? AND `name` = ? AND `directory` = ?", tableName)
func (gen *SqlGenMysql) GetSqlFind(tableName string, key abstract_sql.RowKey) (string, []interface{}) {
return fmt.Sprintf("SELECT `meta` FROM `%s` WHERE `dirhash` = ? AND `name` = ? AND `directory` = ?", tableName), key.Args()
}
// GetSqlFindBatch matches each row by equality, which MySQL turns into one
@@ -54,8 +53,8 @@ func (gen *SqlGenMysql) GetSqlFindBatch(tableName string, count int) string {
return fmt.Sprintf("SELECT `dirhash`, `name`, `directory`, `meta` FROM `%s` WHERE %s", tableName, match)
}
func (gen *SqlGenMysql) GetSqlDelete(tableName string) string {
return fmt.Sprintf("DELETE FROM `%s` WHERE `dirhash` = ? AND `name` = ? AND `directory` = ?", tableName)
func (gen *SqlGenMysql) GetSqlDelete(tableName string, key abstract_sql.RowKey) (string, []interface{}) {
return fmt.Sprintf("DELETE FROM `%s` WHERE `dirhash` = ? AND `name` = ? AND `directory` = ?", tableName), key.Args()
}
func (gen *SqlGenMysql) GetSqlDeleteFolderChildren(tableName string) string {
+4 -2
View File
@@ -3,11 +3,13 @@ package mysql
import (
"strings"
"testing"
"github.com/seaweedfs/seaweedfs/weed/filer/abstract_sql"
)
func TestDefaultUpsertQueryUsesOnDuplicateKey(t *testing.T) {
gen := &SqlGenMysql{UpsertQueryTemplate: DefaultUpsertQuery}
got := gen.GetSqlInsert("filemeta")
got, _ := gen.GetSqlInsert("filemeta", abstract_sql.RowKey{}, nil)
if !strings.Contains(got, "ON DUPLICATE KEY UPDATE") {
t.Fatalf("expected ON DUPLICATE KEY UPDATE in default upsert, got: %s", got)
}
@@ -32,7 +34,7 @@ func TestDefaultCreateTableQueryRendersValidSql(t *testing.T) {
func TestEmptyUpsertTemplateFallsBackToPlainInsert(t *testing.T) {
gen := &SqlGenMysql{}
got := gen.GetSqlInsert("filemeta")
got, _ := gen.GetSqlInsert("filemeta", abstract_sql.RowKey{}, nil)
if strings.Contains(got, "ON DUPLICATE KEY UPDATE") {
t.Fatalf("plain INSERT path should not contain ON DUPLICATE KEY UPDATE, got: %s", got)
}
+9 -10
View File
@@ -44,20 +44,19 @@ func ResolveCreateTableQuery(createTable string) string {
}
}
func (gen *SqlGenPostgres) GetSqlInsert(tableName string) string {
func (gen *SqlGenPostgres) GetSqlInsert(tableName string, key abstract_sql.RowKey, meta []byte) (string, []interface{}) {
if gen.UpsertQueryTemplate != "" {
return fmt.Sprintf(gen.UpsertQueryTemplate, tableName)
} else {
return fmt.Sprintf(`INSERT INTO "%s" (dirhash,name,directory,meta) VALUES($1,$2,$3,$4)`, tableName)
return fmt.Sprintf(gen.UpsertQueryTemplate, tableName), key.Args(meta)
}
return fmt.Sprintf(`INSERT INTO "%s" (dirhash,name,directory,meta) VALUES($1,$2,$3,$4)`, tableName), key.Args(meta)
}
func (gen *SqlGenPostgres) GetSqlUpdate(tableName string) string {
return fmt.Sprintf(`UPDATE "%s" SET meta=$1 WHERE dirhash=$2 AND name=$3 AND directory=$4`, tableName)
func (gen *SqlGenPostgres) GetSqlUpdate(tableName string, key abstract_sql.RowKey, meta []byte) (string, []interface{}) {
return fmt.Sprintf(`UPDATE "%s" SET meta=$4 WHERE dirhash=$1 AND name=$2 AND directory=$3`, tableName), key.Args(meta)
}
func (gen *SqlGenPostgres) GetSqlFind(tableName string) string {
return fmt.Sprintf(`SELECT meta FROM "%s" WHERE dirhash=$1 AND name=$2 AND directory=$3`, tableName)
func (gen *SqlGenPostgres) GetSqlFind(tableName string, key abstract_sql.RowKey) (string, []interface{}) {
return fmt.Sprintf(`SELECT meta FROM "%s" WHERE dirhash=$1 AND name=$2 AND directory=$3`, tableName), key.Args()
}
func (gen *SqlGenPostgres) GetSqlFindBatch(tableName string, count int) string {
@@ -68,8 +67,8 @@ func (gen *SqlGenPostgres) GetSqlFindBatch(tableName string, count int) string {
return fmt.Sprintf(`SELECT dirhash, name, directory, meta FROM "%s" WHERE (dirhash, name, directory) IN (%s)`, tableName, strings.Join(rows, ","))
}
func (gen *SqlGenPostgres) GetSqlDelete(tableName string) string {
return fmt.Sprintf(`DELETE FROM "%s" WHERE dirhash=$1 AND name=$2 AND directory=$3`, tableName)
func (gen *SqlGenPostgres) GetSqlDelete(tableName string, key abstract_sql.RowKey) (string, []interface{}) {
return fmt.Sprintf(`DELETE FROM "%s" WHERE dirhash=$1 AND name=$2 AND directory=$3`, tableName), key.Args()
}
func (gen *SqlGenPostgres) GetSqlDeleteFolderChildren(tableName string) string {
+4 -2
View File
@@ -3,11 +3,13 @@ package postgres
import (
"strings"
"testing"
"github.com/seaweedfs/seaweedfs/weed/filer/abstract_sql"
)
func TestDefaultUpsertQueryIsConflictSafe(t *testing.T) {
gen := &SqlGenPostgres{UpsertQueryTemplate: DefaultUpsertQuery}
got := gen.GetSqlInsert("filemeta")
got, _ := gen.GetSqlInsert("filemeta", abstract_sql.RowKey{}, nil)
if !strings.Contains(got, "ON CONFLICT") {
t.Fatalf("expected ON CONFLICT in default upsert, got: %s", got)
}
@@ -29,7 +31,7 @@ func TestDefaultCreateTableQueryRendersValidSql(t *testing.T) {
func TestEmptyUpsertTemplateFallsBackToPlainInsert(t *testing.T) {
gen := &SqlGenPostgres{}
got := gen.GetSqlInsert("filemeta")
got, _ := gen.GetSqlInsert("filemeta", abstract_sql.RowKey{}, nil)
if strings.Contains(got, "ON CONFLICT") {
t.Fatalf("plain INSERT path should not contain ON CONFLICT, got: %s", got)
}