From abe623c57098071bc9592107dcb2d2e7e92f250c Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Wed, 2 Dec 2026 03:45:44 -0800 Subject: [PATCH] filer/sql: generators bind their own statement arguments (#13251) * filer/store_test: conformance suite for filer stores Entries in and out of buckets, byte-ordered and prefixed listings, key-value records, transactions, bucket tables and the snapshot scan. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * filer: run postgres2 and mysql2 through the conformance suite RUN_POSTGRES_TESTS and RUN_MYSQL_TESTS enable them, as RUN_REDIS_TESTS does the Redis stores; each test gets a schema or database of its own. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * ci: give the go test job Postgres and MySQL services Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * 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 Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * filer/sql: generators bind the arguments of directory statements Listing and deleting a directory's children take the directory and return their arguments with the query. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * filer/sql: batch lookup takes row keys and matches rows by name and directory A key-value key's directory column already determines its dirhash, so the batch read no longer selects dirhash to match its rows. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * filer/sql: scan pages take the row key of the last row as their cursor Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * filer/sql: test the arguments each generator binds Each statement's arguments must match its placeholders in count and column. Check them for every generator method, including the Postgres UPDATE whose parameters are now numbered key first. Co-Authored-By: Claude Opus 5.5 * filer/postgres: escape the table name inside its quotes A double quote in it is doubled, as PostgreSQL reads a quoted identifier. Bucket names cannot hold one; the statements no longer rely on that. Reported by CodeQL (go/unsafe-quoting) on the lines this branch changed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * filer/postgres: keep the nameExpr doc comment on nameExpr Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- weed/filer/abstract_sql/abstract_sql_store.go | 71 ++++++++++----- .../abstract_sql/abstract_sql_store_kv.go | 40 +++++---- .../abstract_sql/abstract_sql_store_scan.go | 12 +-- .../abstract_sql/abstract_sql_store_test.go | 16 ++-- weed/filer/mysql/mysql_sql_gen.go | 48 +++++----- weed/filer/mysql/mysql_sql_gen_test.go | 63 ++++++++++++-- weed/filer/postgres/postgres_sql_gen.go | 60 +++++++------ weed/filer/postgres/postgres_sql_gen_test.go | 87 +++++++++++++++++-- weed/filer/sqlite/sqlite_store.go | 4 +- weed/filer/sqlite/sqlite_store_scan_test.go | 2 +- 10 files changed, 294 insertions(+), 109 deletions(-) diff --git a/weed/filer/abstract_sql/abstract_sql_store.go b/weed/filer/abstract_sql/abstract_sql_store.go index b523cae6ce..be70779aa7 100644 --- a/weed/filer/abstract_sql/abstract_sql_store.go +++ b/weed/filer/abstract_sql/abstract_sql_store.go @@ -15,20 +15,39 @@ 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 - // 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 - GetSqlDeleteFolderChildren(tableName string) string - GetSqlListExclusive(tableName string) string - GetSqlListInclusive(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 name, directory and meta of the rows of keys. + GetSqlFindBatch(tableName string, keys []RowKey) (string, []interface{}) + GetSqlDelete(tableName string, key RowKey) (string, []interface{}) + GetSqlDeleteFolderChildren(tableName string, dir string) (string, []interface{}) + // GetSqlListExclusive selects name and meta of the entries in dir after + // startFileName whose name is LIKE namePattern, in name order. + GetSqlListExclusive(tableName string, dir, startFileName, namePattern string, limit int64) (string, []interface{}) + GetSqlListInclusive(tableName string, dir, startFileName, namePattern string, limit int64) (string, []interface{}) // GetSqlScanPage returns the query and arguments selecting dirhash, name, - // directory and meta of up to limit rows after the (dirhash, name) cursor. - GetSqlScanPage(tableName string, dirhash int64, name string, limit int) (string, []interface{}) + // directory and meta of up to limit rows after the cursor row. + GetSqlScanPage(tableName string, after RowKey, limit int) (string, []interface{}) GetSqlCreateTable(tableName string) string GetSqlDropTable(tableName string) string } @@ -247,13 +266,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 +313,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 +343,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 +375,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) } @@ -392,8 +417,9 @@ func (store *AbstractSqlStore) DeleteFolderChildren(ctx context.Context, fullpat } } - glog.V(4).InfofCtx(ctx, "delete %s SQL %s %d", string(shortPath), store.GetSqlDeleteFolderChildren(bucket), util.HashStringToLong(string(shortPath))) - res, err := db.ExecContext(ctx, store.GetSqlDeleteFolderChildren(bucket), util.HashStringToLong(string(shortPath)), string(shortPath)) + sqlText, args := store.GetSqlDeleteFolderChildren(bucket, string(shortPath)) + glog.V(4).InfofCtx(ctx, "delete %s SQL %s %v", string(shortPath), sqlText, args) + res, err := db.ExecContext(ctx, sqlText, args...) if err != nil { return fmt.Errorf("deleteFolderChildren %s: %w", fullpath, err) } @@ -429,12 +455,13 @@ func (store *AbstractSqlStore) ListDirectoryPrefixedEntries(ctx context.Context, return lastFileName, fmt.Errorf("findDB %s : %v", dirPath, err) } - sqlText := store.GetSqlListExclusive(bucket) + getSqlList := store.GetSqlListExclusive if includeStartFile { - sqlText = store.GetSqlListInclusive(bucket) + getSqlList = store.GetSqlListInclusive } + sqlText, args := getSqlList(bucket, string(shortPath), startFileName, LikePattern(prefix), limit+1) - rows, err := db.QueryContext(ctx, sqlText, util.HashStringToLong(string(shortPath)), startFileName, string(shortPath), LikePattern(prefix), limit+1) + rows, err := db.QueryContext(ctx, sqlText, args...) if err != nil { return lastFileName, fmt.Errorf("list %s : %v", dirPath, err) } diff --git a/weed/filer/abstract_sql/abstract_sql_store_kv.go b/weed/filer/abstract_sql/abstract_sql_store_kv.go index 5202ac49b6..043ff1f85f 100644 --- a/weed/filer/abstract_sql/abstract_sql_store_kv.go +++ b/weed/filer/abstract_sql/abstract_sql_store_kv.go @@ -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) @@ -85,20 +87,18 @@ func (store *AbstractSqlStore) KvBatchGet(ctx context.Context, keys [][]byte) (m values := make(map[string][]byte, len(keys)) for start := 0; start < len(keys); start += kvBatchGetSize { batch := keys[start:min(start+kvBatchGetSize, len(keys))] - type row struct { - dirHash int64 - name, directory string - } + type row struct{ name, directory string } asked := make(map[row][]string, len(batch)) - args := make([]interface{}, 0, 3*len(batch)) + rowKeys := make([]RowKey, 0, len(batch)) for _, key := range batch { - dirStr, dirHash, name := GenDirAndName(key) - r := row{dirHash, name, dirStr} + rowKey := kvRowKey(key) + r := row{rowKey.Name, rowKey.Directory} asked[r] = append(asked[r], string(key)) - args = append(args, dirHash, name, dirStr) + rowKeys = append(rowKeys, rowKey) } if err := func() error { - rows, err := db.QueryContext(ctx, store.GetSqlFindBatch(DEFAULT_TABLE, len(batch)), args...) + sqlText, args := store.GetSqlFindBatch(DEFAULT_TABLE, rowKeys) + rows, err := db.QueryContext(ctx, sqlText, args...) if err != nil { return err } @@ -106,7 +106,7 @@ func (store *AbstractSqlStore) KvBatchGet(ctx context.Context, keys [][]byte) (m for rows.Next() { var r row var value []byte - if err := rows.Scan(&r.dirHash, &r.name, &r.directory, &value); err != nil { + if err := rows.Scan(&r.name, &r.directory, &value); err != nil { return err } for _, key := range asked[r] { @@ -125,9 +125,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 +140,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) diff --git a/weed/filer/abstract_sql/abstract_sql_store_scan.go b/weed/filer/abstract_sql/abstract_sql_store_scan.go index 2028643755..a9c18ca616 100644 --- a/weed/filer/abstract_sql/abstract_sql_store_scan.go +++ b/weed/filer/abstract_sql/abstract_sql_store_scan.go @@ -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 } @@ -227,7 +228,8 @@ func (store *AbstractSqlStore) listBucketNames(ctx context.Context, tx *sql.Tx, } var rows []row if err := func() error { - res, err := tx.QueryContext(ctx, store.GetSqlListExclusive(DEFAULT_TABLE), util.HashStringToLong(bucketsRoot), startFrom, bucketsRoot, "%", page) + sqlText, args := store.GetSqlListExclusive(DEFAULT_TABLE, bucketsRoot, startFrom, "%", page) + res, err := tx.QueryContext(ctx, sqlText, args...) if err != nil { return fmt.Errorf("list %s: %v", bucketsRoot, err) } @@ -276,7 +278,7 @@ func (store *AbstractSqlStore) scanOneTable(ctx context.Context, tx *sql.Tx, t s name, dir string data []byte } - cursorHash, cursorName := int64(math.MinInt64), "" + cursor := RowKey{DirHash: math.MinInt64} firstPage := true for { var page []row @@ -289,7 +291,7 @@ func (store *AbstractSqlStore) scanOneTable(ctx context.Context, tx *sql.Tx, t s return fmt.Errorf("scan table %s: %v", t.table, err) } } - sqlText, args := store.GetSqlScanPage(t.table, cursorHash, cursorName, scanPageSize) + sqlText, args := store.GetSqlScanPage(t.table, cursor, scanPageSize) rows, err := tx.QueryContext(ctx, sqlText, args...) if err != nil { if t.cachedOnly && isMissingTableError(err) { @@ -314,7 +316,7 @@ func (store *AbstractSqlStore) scanOneTable(ctx context.Context, tx *sql.Tx, t s } for _, r := range page { - cursorHash, cursorName = r.dirHash, r.name + cursor = RowKey{DirHash: r.dirHash, Name: r.name, Directory: r.dir} if r.dirHash != util.HashStringToLong(r.dir) { continue // a key-value record, see GenDirAndName } diff --git a/weed/filer/abstract_sql/abstract_sql_store_test.go b/weed/filer/abstract_sql/abstract_sql_store_test.go index 0b51aed007..c9fba3f53b 100644 --- a/weed/filer/abstract_sql/abstract_sql_store_test.go +++ b/weed/filer/abstract_sql/abstract_sql_store_test.go @@ -149,8 +149,12 @@ func TestBucketHooksSkipInvalidBucketNames(t *testing.T) { type listGen struct{ SqlGenerator } -func (listGen) GetSqlListExclusive(string) string { return "SELECT name, meta" } -func (listGen) GetSqlListInclusive(string) string { return "SELECT name, meta" } +func (listGen) GetSqlListExclusive(string, string, string, string, int64) (string, []interface{}) { + return "SELECT name, meta", nil +} +func (listGen) GetSqlListInclusive(string, string, string, string, int64) (string, []interface{}) { + return "SELECT name, meta", nil +} // A listing that loses its connection partway through must report the error, // not return the rows read so far as if the directory ended there. @@ -220,8 +224,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 +337,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. diff --git a/weed/filer/mysql/mysql_sql_gen.go b/weed/filer/mysql/mysql_sql_gen.go index 0cd24e3fa1..dc4e9d1372 100644 --- a/weed/filer/mysql/mysql_sql_gen.go +++ b/weed/filer/mysql/mysql_sql_gen.go @@ -6,6 +6,7 @@ import ( _ "github.com/go-sql-driver/mysql" "github.com/seaweedfs/seaweedfs/weed/filer/abstract_sql" + "github.com/seaweedfs/seaweedfs/weed/util" ) type SqlGenMysql struct { @@ -31,35 +32,38 @@ 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 // primary-key lookup per key. -func (gen *SqlGenMysql) GetSqlFindBatch(tableName string, count int) string { - match := strings.TrimSuffix(strings.Repeat("(`dirhash` = ? AND `name` = ? AND `directory` = ?) OR ", count), " OR ") - return fmt.Sprintf("SELECT `dirhash`, `name`, `directory`, `meta` FROM `%s` WHERE %s", tableName, match) +func (gen *SqlGenMysql) GetSqlFindBatch(tableName string, keys []abstract_sql.RowKey) (string, []interface{}) { + match := strings.TrimSuffix(strings.Repeat("(`dirhash` = ? AND `name` = ? AND `directory` = ?) OR ", len(keys)), " OR ") + args := make([]interface{}, 0, 3*len(keys)) + for _, key := range keys { + args = append(args, key.Args()...) + } + return fmt.Sprintf("SELECT `name`, `directory`, `meta` FROM `%s` WHERE %s", tableName, match), args } -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 { - return fmt.Sprintf("DELETE FROM `%s` WHERE `dirhash` = ? AND `directory` = ?", tableName) +func (gen *SqlGenMysql) GetSqlDeleteFolderChildren(tableName string, dir string) (string, []interface{}) { + return fmt.Sprintf("DELETE FROM `%s` WHERE `dirhash` = ? AND `directory` = ?", tableName), []interface{}{util.HashStringToLong(dir), dir} } // nameExpr forces byte ordering on a non-binary column at the cost of a filesort. @@ -74,19 +78,21 @@ func (gen *SqlGenMysql) nameExpr() string { // not turn a row-value comparison into a range seek. The name keeps the // column's own collation (BINARY would filesort every page); the scan promises // no lexical order. SQLite overrides this method. -func (gen *SqlGenMysql) GetSqlScanPage(tableName string, dirhash int64, name string, limit int) (string, []interface{}) { +func (gen *SqlGenMysql) GetSqlScanPage(tableName string, after abstract_sql.RowKey, limit int) (string, []interface{}) { return fmt.Sprintf("SELECT `dirhash`, `name`, `directory`, `meta` FROM `%s` WHERE `dirhash` > ? OR (`dirhash` = ? AND `name` > ?) ORDER BY `dirhash` ASC, `name` ASC LIMIT ?", tableName), - []interface{}{dirhash, dirhash, name, limit} + []interface{}{after.DirHash, after.DirHash, after.Name, limit} } -func (gen *SqlGenMysql) GetSqlListExclusive(tableName string) string { +func (gen *SqlGenMysql) GetSqlListExclusive(tableName string, dir, startFileName, namePattern string, limit int64) (string, []interface{}) { name := gen.nameExpr() - return fmt.Sprintf("SELECT `name`, `meta` FROM `%s` WHERE `dirhash` = ? AND %s > ? AND `directory` = ? AND %s LIKE ? ESCAPE '!' ORDER BY %s ASC LIMIT ?", tableName, name, name, name) + return fmt.Sprintf("SELECT `name`, `meta` FROM `%s` WHERE `dirhash` = ? AND %s > ? AND `directory` = ? AND %s LIKE ? ESCAPE '!' ORDER BY %s ASC LIMIT ?", tableName, name, name, name), + []interface{}{util.HashStringToLong(dir), startFileName, dir, namePattern, limit} } -func (gen *SqlGenMysql) GetSqlListInclusive(tableName string) string { +func (gen *SqlGenMysql) GetSqlListInclusive(tableName string, dir, startFileName, namePattern string, limit int64) (string, []interface{}) { name := gen.nameExpr() - return fmt.Sprintf("SELECT `name`, `meta` FROM `%s` WHERE `dirhash` = ? AND %s >= ? AND `directory` = ? AND %s LIKE ? ESCAPE '!' ORDER BY %s ASC LIMIT ?", tableName, name, name, name) + return fmt.Sprintf("SELECT `name`, `meta` FROM `%s` WHERE `dirhash` = ? AND %s >= ? AND `directory` = ? AND %s LIKE ? ESCAPE '!' ORDER BY %s ASC LIMIT ?", tableName, name, name, name), + []interface{}{util.HashStringToLong(dir), startFileName, dir, namePattern, limit} } func (gen *SqlGenMysql) GetSqlCreateTable(tableName string) string { diff --git a/weed/filer/mysql/mysql_sql_gen_test.go b/weed/filer/mysql/mysql_sql_gen_test.go index d032fc7b74..1e2e13e110 100644 --- a/weed/filer/mysql/mysql_sql_gen_test.go +++ b/weed/filer/mysql/mysql_sql_gen_test.go @@ -1,13 +1,17 @@ package mysql import ( + "reflect" + "regexp" "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 +36,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) } @@ -40,7 +44,7 @@ func TestEmptyUpsertTemplateFallsBackToPlainInsert(t *testing.T) { func TestListSqlDefaultOrderingFollowsColumn(t *testing.T) { gen := &SqlGenMysql{} - for _, got := range []string{gen.GetSqlListExclusive("filemeta"), gen.GetSqlListInclusive("filemeta")} { + for _, got := range listQueries(gen) { if strings.Contains(got, "BINARY") { t.Fatalf("default list query should not force BINARY, got: %s", got) } @@ -52,7 +56,7 @@ func TestListSqlDefaultOrderingFollowsColumn(t *testing.T) { func TestListSqlBinaryOrderingOnNonBinaryColumn(t *testing.T) { gen := &SqlGenMysql{ForceBinaryCollation: true} - for _, got := range []string{gen.GetSqlListExclusive("filemeta"), gen.GetSqlListInclusive("filemeta")} { + for _, got := range listQueries(gen) { if !strings.Contains(got, "ORDER BY BINARY `name` ASC") { t.Fatalf("expected BINARY ordering, got: %s", got) } @@ -67,7 +71,7 @@ func TestListSqlBinaryOrderingOnNonBinaryColumn(t *testing.T) { func TestListSqlEscapesLikeWildcards(t *testing.T) { gen := &SqlGenMysql{} - for _, got := range []string{gen.GetSqlListExclusive("filemeta"), gen.GetSqlListInclusive("filemeta")} { + for _, got := range listQueries(gen) { if !strings.Contains(got, "LIKE ? ESCAPE '!'") { t.Fatalf("list query must declare the escape char matching LikePattern, got: %s", got) } @@ -88,3 +92,52 @@ func TestIsBinaryCollation(t *testing.T) { } } } + +func listQueries(gen *SqlGenMysql) []string { + exclusive, _ := gen.GetSqlListExclusive("filemeta", "/dir", "", "%", 10) + inclusive, _ := gen.GetSqlListInclusive("filemeta", "/dir", "", "%", 10) + return []string{exclusive, inclusive} +} + +func TestStatementArguments(t *testing.T) { + key := abstract_sql.EntryRowKey("/dir", "name") + other := abstract_sql.EntryRowKey("/other", "file") + meta := []byte("meta") + column := map[string]interface{}{"dirhash": key.DirHash, "name": key.Name, "directory": key.Directory, "meta": meta} + plain, upsert := &SqlGenMysql{}, &SqlGenMysql{UpsertQueryTemplate: DefaultUpsertQuery} + type statement struct { + sql string + args []interface{} + } + stmt := func(sql string, args []interface{}) statement { return statement{sql, args} } + for name, tc := range map[string]struct { + got statement + want []interface{} + }{ + "insert": {stmt(plain.GetSqlInsert("t", key, meta)), []interface{}{key.DirHash, "name", "/dir", meta}}, + "upsert": {stmt(upsert.GetSqlInsert("t", key, meta)), []interface{}{key.DirHash, "name", "/dir", meta}}, + "update": {stmt(plain.GetSqlUpdate("t", key, meta)), []interface{}{meta, key.DirHash, "name", "/dir"}}, + "find": {stmt(plain.GetSqlFind("t", key)), []interface{}{key.DirHash, "name", "/dir"}}, + "find batch": {stmt(plain.GetSqlFindBatch("t", []abstract_sql.RowKey{key, other})), []interface{}{key.DirHash, "name", "/dir", other.DirHash, "file", "/other"}}, + "delete": {stmt(plain.GetSqlDelete("t", key)), []interface{}{key.DirHash, "name", "/dir"}}, + "delete children": {stmt(plain.GetSqlDeleteFolderChildren("t", "/dir")), []interface{}{key.DirHash, "/dir"}}, + "list exclusive": {stmt(plain.GetSqlListExclusive("t", "/dir", "start", "p%", 10)), []interface{}{key.DirHash, "start", "/dir", "p%", int64(10)}}, + "list inclusive": {stmt(plain.GetSqlListInclusive("t", "/dir", "start", "p%", 10)), []interface{}{key.DirHash, "start", "/dir", "p%", int64(10)}}, + "scan page": {stmt(plain.GetSqlScanPage("t", key, 10)), []interface{}{key.DirHash, key.DirHash, "name", 10}}, + } { + if !reflect.DeepEqual(tc.got.args, tc.want) { + t.Errorf("%s: args %v, want %v", name, tc.got.args, tc.want) + } + if n := strings.Count(tc.got.sql, "?"); n != len(tc.got.args) { + t.Errorf("%s: %d placeholders for %d args in %s", name, n, len(tc.got.args), tc.got.sql) + } + if name == "find batch" { + continue + } + for i, m := range regexp.MustCompile("(?:`(\\w+)` = )?\\?").FindAllStringSubmatch(tc.got.sql, -1) { + if want, ok := column[m[1]]; ok && i < len(tc.got.args) && !reflect.DeepEqual(tc.got.args[i], want) { + t.Errorf("%s: `%s` bound to %v, want %v", name, m[1], tc.got.args[i], want) + } + } + } +} diff --git a/weed/filer/postgres/postgres_sql_gen.go b/weed/filer/postgres/postgres_sql_gen.go index 571f4470c7..e8677789bf 100644 --- a/weed/filer/postgres/postgres_sql_gen.go +++ b/weed/filer/postgres/postgres_sql_gen.go @@ -6,6 +6,7 @@ import ( _ "github.com/jackc/pgx/v5/stdlib" "github.com/seaweedfs/seaweedfs/weed/filer/abstract_sql" + "github.com/seaweedfs/seaweedfs/weed/util" ) type SqlGenPostgres struct { @@ -44,36 +45,43 @@ 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, tableIdent(tableName)), key.Args(meta) } + return fmt.Sprintf(`INSERT INTO "%s" (dirhash,name,directory,meta) VALUES($1,$2,$3,$4)`, tableIdent(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`, tableIdent(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`, tableIdent(tableName)), key.Args() } -func (gen *SqlGenPostgres) GetSqlFindBatch(tableName string, count int) string { - rows := make([]string, count) - for i := range rows { +func (gen *SqlGenPostgres) GetSqlFindBatch(tableName string, keys []abstract_sql.RowKey) (string, []interface{}) { + rows := make([]string, len(keys)) + args := make([]interface{}, 0, 3*len(keys)) + for i, key := range keys { rows[i] = fmt.Sprintf("($%d,$%d,$%d)", 3*i+1, 3*i+2, 3*i+3) + args = append(args, key.Args()...) } - return fmt.Sprintf(`SELECT dirhash, name, directory, meta FROM "%s" WHERE (dirhash, name, directory) IN (%s)`, tableName, strings.Join(rows, ",")) + return fmt.Sprintf(`SELECT name, directory, meta FROM "%s" WHERE (dirhash, name, directory) IN (%s)`, tableIdent(tableName), strings.Join(rows, ",")), args } -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`, tableIdent(tableName)), key.Args() } -func (gen *SqlGenPostgres) GetSqlDeleteFolderChildren(tableName string) string { - return fmt.Sprintf(`DELETE FROM "%s" WHERE dirhash=$1 AND directory=$2`, tableName) +func (gen *SqlGenPostgres) GetSqlDeleteFolderChildren(tableName string, dir string) (string, []interface{}) { + return fmt.Sprintf(`DELETE FROM "%s" WHERE dirhash=$1 AND directory=$2`, tableIdent(tableName)), []interface{}{util.HashStringToLong(dir), dir} +} + +// tableIdent escapes a table name for the double quotes the statements put +// around it. +func tableIdent(tableName string) string { + return strings.ReplaceAll(tableName, `"`, `""`) } // nameExpr forces byte ordering on a locale-aware column via COLLATE "C". @@ -87,28 +95,30 @@ func (gen *SqlGenPostgres) nameExpr() string { // GetSqlScanPage uses a row-value comparison, one primary-key range seek on // PostgreSQL. The name keeps the column's own collation (COLLATE "C" would // sort every page); the scan promises no lexical order. -func (gen *SqlGenPostgres) GetSqlScanPage(tableName string, dirhash int64, name string, limit int) (string, []interface{}) { - return fmt.Sprintf(`SELECT dirhash, name, directory, meta FROM "%s" WHERE (dirhash, name) > ($1, $2) ORDER BY dirhash ASC, name ASC LIMIT $3`, tableName), - []interface{}{dirhash, name, limit} +func (gen *SqlGenPostgres) GetSqlScanPage(tableName string, after abstract_sql.RowKey, limit int) (string, []interface{}) { + return fmt.Sprintf(`SELECT dirhash, name, directory, meta FROM "%s" WHERE (dirhash, name) > ($1, $2) ORDER BY dirhash ASC, name ASC LIMIT $3`, tableIdent(tableName)), + []interface{}{after.DirHash, after.Name, limit} } -func (gen *SqlGenPostgres) GetSqlListExclusive(tableName string) string { +func (gen *SqlGenPostgres) GetSqlListExclusive(tableName string, dir, startFileName, namePattern string, limit int64) (string, []interface{}) { name := gen.nameExpr() - return fmt.Sprintf(`SELECT NAME, meta FROM "%s" WHERE dirhash=$1 AND %s>$2 AND directory=$3 AND %s like $4 ESCAPE '!' ORDER BY %s ASC LIMIT $5`, tableName, name, name, name) + return fmt.Sprintf(`SELECT NAME, meta FROM "%s" WHERE dirhash=$1 AND %s>$2 AND directory=$3 AND %s like $4 ESCAPE '!' ORDER BY %s ASC LIMIT $5`, tableIdent(tableName), name, name, name), + []interface{}{util.HashStringToLong(dir), startFileName, dir, namePattern, limit} } -func (gen *SqlGenPostgres) GetSqlListInclusive(tableName string) string { +func (gen *SqlGenPostgres) GetSqlListInclusive(tableName string, dir, startFileName, namePattern string, limit int64) (string, []interface{}) { name := gen.nameExpr() - return fmt.Sprintf(`SELECT NAME, meta FROM "%s" WHERE dirhash=$1 AND %s>=$2 AND directory=$3 AND %s like $4 ESCAPE '!' ORDER BY %s ASC LIMIT $5`, tableName, name, name, name) + return fmt.Sprintf(`SELECT NAME, meta FROM "%s" WHERE dirhash=$1 AND %s>=$2 AND directory=$3 AND %s like $4 ESCAPE '!' ORDER BY %s ASC LIMIT $5`, tableIdent(tableName), name, name, name), + []interface{}{util.HashStringToLong(dir), startFileName, dir, namePattern, limit} } func (gen *SqlGenPostgres) GetSqlCreateTable(tableName string) string { if gen.CreateTableSqlTemplate == "" { return "" } - return fmt.Sprintf(gen.CreateTableSqlTemplate, tableName) + return fmt.Sprintf(gen.CreateTableSqlTemplate, tableIdent(tableName)) } func (gen *SqlGenPostgres) GetSqlDropTable(tableName string) string { - return fmt.Sprintf(gen.DropTableSqlTemplate, tableName) + return fmt.Sprintf(gen.DropTableSqlTemplate, tableIdent(tableName)) } diff --git a/weed/filer/postgres/postgres_sql_gen_test.go b/weed/filer/postgres/postgres_sql_gen_test.go index 1cb947bd77..04abbb71b6 100644 --- a/weed/filer/postgres/postgres_sql_gen_test.go +++ b/weed/filer/postgres/postgres_sql_gen_test.go @@ -1,13 +1,18 @@ package postgres import ( + "reflect" + "regexp" + "strconv" "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 +34,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) } @@ -37,7 +42,7 @@ func TestEmptyUpsertTemplateFallsBackToPlainInsert(t *testing.T) { func TestListSqlDefaultOrderingFollowsColumn(t *testing.T) { gen := &SqlGenPostgres{} - for _, got := range []string{gen.GetSqlListExclusive("filemeta"), gen.GetSqlListInclusive("filemeta")} { + for _, got := range listQueries(gen) { if strings.Contains(got, "COLLATE") { t.Fatalf("default list query should not force a collation, got: %s", got) } @@ -49,7 +54,7 @@ func TestListSqlDefaultOrderingFollowsColumn(t *testing.T) { func TestListSqlBinaryOrderingOnNonBinaryColumn(t *testing.T) { gen := &SqlGenPostgres{ForceBinaryCollation: true} - for _, got := range []string{gen.GetSqlListExclusive("filemeta"), gen.GetSqlListInclusive("filemeta")} { + for _, got := range listQueries(gen) { if !strings.Contains(got, `ORDER BY name COLLATE "C" ASC`) { t.Fatalf(`expected COLLATE "C" ordering, got: %s`, got) } @@ -64,7 +69,7 @@ func TestListSqlBinaryOrderingOnNonBinaryColumn(t *testing.T) { func TestListSqlEscapesLikeWildcards(t *testing.T) { gen := &SqlGenPostgres{} - for _, got := range []string{gen.GetSqlListExclusive("filemeta"), gen.GetSqlListInclusive("filemeta")} { + for _, got := range listQueries(gen) { if !strings.Contains(got, "like $4 ESCAPE '!'") { t.Fatalf("list query must declare the escape char matching LikePattern, got: %s", got) } @@ -101,3 +106,75 @@ func TestResolveCreateTableQuery(t *testing.T) { } } } + +func listQueries(gen *SqlGenPostgres) []string { + exclusive, _ := gen.GetSqlListExclusive("filemeta", "/dir", "", "%", 10) + inclusive, _ := gen.GetSqlListInclusive("filemeta", "/dir", "", "%", 10) + return []string{exclusive, inclusive} +} + +func TestStatementArguments(t *testing.T) { + key := abstract_sql.EntryRowKey("/dir", "name") + other := abstract_sql.EntryRowKey("/other", "file") + meta := []byte("meta") + column := map[string]interface{}{"dirhash": key.DirHash, "name": key.Name, "directory": key.Directory, "meta": meta} + plain, upsert := &SqlGenPostgres{}, &SqlGenPostgres{UpsertQueryTemplate: DefaultUpsertQuery} + type statement struct { + sql string + args []interface{} + } + stmt := func(sql string, args []interface{}) statement { return statement{sql, args} } + for name, tc := range map[string]struct { + got statement + want []interface{} + }{ + "insert": {stmt(plain.GetSqlInsert("t", key, meta)), []interface{}{key.DirHash, "name", "/dir", meta}}, + "upsert": {stmt(upsert.GetSqlInsert("t", key, meta)), []interface{}{key.DirHash, "name", "/dir", meta}}, + "update": {stmt(plain.GetSqlUpdate("t", key, meta)), []interface{}{key.DirHash, "name", "/dir", meta}}, + "find": {stmt(plain.GetSqlFind("t", key)), []interface{}{key.DirHash, "name", "/dir"}}, + "find batch": {stmt(plain.GetSqlFindBatch("t", []abstract_sql.RowKey{key, other})), []interface{}{key.DirHash, "name", "/dir", other.DirHash, "file", "/other"}}, + "delete": {stmt(plain.GetSqlDelete("t", key)), []interface{}{key.DirHash, "name", "/dir"}}, + "delete children": {stmt(plain.GetSqlDeleteFolderChildren("t", "/dir")), []interface{}{key.DirHash, "/dir"}}, + "list exclusive": {stmt(plain.GetSqlListExclusive("t", "/dir", "start", "p%", 10)), []interface{}{key.DirHash, "start", "/dir", "p%", int64(10)}}, + "list inclusive": {stmt(plain.GetSqlListInclusive("t", "/dir", "start", "p%", 10)), []interface{}{key.DirHash, "start", "/dir", "p%", int64(10)}}, + "scan page": {stmt(plain.GetSqlScanPage("t", key, 10)), []interface{}{key.DirHash, "name", 10}}, + } { + if !reflect.DeepEqual(tc.got.args, tc.want) { + t.Errorf("%s: args %v, want %v", name, tc.got.args, tc.want) + } + used := map[int]bool{} + for _, m := range regexp.MustCompile(`\$(\d+)`).FindAllStringSubmatch(tc.got.sql, -1) { + n, _ := strconv.Atoi(m[1]) + used[n] = true + } + for n := 1; n <= len(tc.got.args); n++ { + if !used[n] { + t.Errorf("%s: $%d unused in %s", name, n, tc.got.sql) + } + } + if len(used) != len(tc.got.args) { + t.Errorf("%s: %d placeholders for %d args in %s", name, len(used), len(tc.got.args), tc.got.sql) + } + if name == "find batch" { + continue + } + for _, m := range regexp.MustCompile(`(\w+)\s*=\s*\$(\d+)`).FindAllStringSubmatch(tc.got.sql, -1) { + n, _ := strconv.Atoi(m[2]) + if want, ok := column[m[1]]; ok && n <= len(tc.got.args) && !reflect.DeepEqual(tc.got.args[n-1], want) { + t.Errorf("%s: %s bound to %v, want %v", name, m[1], tc.got.args[n-1], want) + } + } + } +} + +func TestStatementsEscapeTheTableName(t *testing.T) { + gen := &SqlGenPostgres{UpsertQueryTemplate: DefaultUpsertQuery, CreateTableSqlTemplate: DefaultCreateTableQuery} + key := abstract_sql.EntryRowKey("/", "x") + insert, _ := gen.GetSqlInsert(`a"b`, key, nil) + find, _ := gen.GetSqlFind(`a"b`, key) + for _, statement := range []string{insert, find, gen.GetSqlCreateTable(`a"b`)} { + if !strings.Contains(statement, `"a""b"`) { + t.Fatalf("table name not escaped: %s", statement) + } + } +} diff --git a/weed/filer/sqlite/sqlite_store.go b/weed/filer/sqlite/sqlite_store.go index 7a45ef83ca..619f716e8a 100644 --- a/weed/filer/sqlite/sqlite_store.go +++ b/weed/filer/sqlite/sqlite_store.go @@ -36,9 +36,9 @@ type sqliteSqlGen struct { *mysql.SqlGenMysql } -func (gen sqliteSqlGen) GetSqlScanPage(tableName string, dirhash int64, name string, limit int) (string, []interface{}) { +func (gen sqliteSqlGen) GetSqlScanPage(tableName string, after abstract_sql.RowKey, limit int) (string, []interface{}) { return fmt.Sprintf("SELECT `dirhash`, `name`, `directory`, `meta` FROM `%s` WHERE (`dirhash`, `name`) > (?, ?) ORDER BY `dirhash` ASC, `name` ASC LIMIT ?", tableName), - []interface{}{dirhash, name, limit} + []interface{}{after.DirHash, after.Name, limit} } // ScanEntries offers the snapshot scan only in WAL mode: with a rollback diff --git a/weed/filer/sqlite/sqlite_store_scan_test.go b/weed/filer/sqlite/sqlite_store_scan_test.go index b859229171..1c4982db61 100644 --- a/weed/filer/sqlite/sqlite_store_scan_test.go +++ b/weed/filer/sqlite/sqlite_store_scan_test.go @@ -249,7 +249,7 @@ func TestScanPageQuerySeeksPrimaryKey(t *testing.T) { t.Fatal(err) } defer store.Shutdown() - sqlText, args := store.GetSqlScanPage("filemeta", int64(-1), "", 10) + sqlText, args := store.GetSqlScanPage("filemeta", abstract_sql.RowKey{DirHash: -1}, 10) rows, err := store.DB.Query("EXPLAIN QUERY PLAN "+sqlText, args...) if err != nil { t.Fatal(err)