Files
seaweedfs/weed/filer/postgres/postgres_sql_gen_test.go
T
Chris LuandClaude Opus 5.5 abe623c570 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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres: keep the nameExpr doc comment on nameExpr

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 03:45:44 -08:00

181 lines
6.6 KiB
Go

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", abstract_sql.RowKey{}, nil)
if !strings.Contains(got, "ON CONFLICT") {
t.Fatalf("expected ON CONFLICT in default upsert, got: %s", got)
}
if !strings.Contains(got, `"filemeta"`) {
t.Fatalf("expected quoted table name, got: %s", got)
}
}
func TestDefaultCreateTableQueryRendersValidSql(t *testing.T) {
gen := &SqlGenPostgres{CreateTableSqlTemplate: DefaultCreateTableQuery}
got := gen.GetSqlCreateTable("filemeta")
if strings.Contains(got, "%!") {
t.Fatalf("template rendered to malformed SQL, got: %s", got)
}
if !strings.Contains(got, `"filemeta"`) {
t.Fatalf("expected quoted table name, got: %s", got)
}
}
func TestEmptyUpsertTemplateFallsBackToPlainInsert(t *testing.T) {
gen := &SqlGenPostgres{}
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)
}
}
func TestListSqlDefaultOrderingFollowsColumn(t *testing.T) {
gen := &SqlGenPostgres{}
for _, got := range listQueries(gen) {
if strings.Contains(got, "COLLATE") {
t.Fatalf("default list query should not force a collation, got: %s", got)
}
if !strings.Contains(got, "ORDER BY name ASC") {
t.Fatalf("expected plain name ordering, got: %s", got)
}
}
}
func TestListSqlBinaryOrderingOnNonBinaryColumn(t *testing.T) {
gen := &SqlGenPostgres{ForceBinaryCollation: true}
for _, got := range listQueries(gen) {
if !strings.Contains(got, `ORDER BY name COLLATE "C" ASC`) {
t.Fatalf(`expected COLLATE "C" ordering, got: %s`, got)
}
if !strings.Contains(got, `name COLLATE "C" like $4`) {
t.Fatalf(`expected COLLATE "C" prefix filter, got: %s`, got)
}
if strings.Contains(got, "AND name>$2") || strings.Contains(got, "AND name>=$2") {
t.Fatalf("pagination comparison must also be byte-ordered, got: %s", got)
}
}
}
func TestListSqlEscapesLikeWildcards(t *testing.T) {
gen := &SqlGenPostgres{}
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)
}
}
}
func TestIsByteOrderedCollation(t *testing.T) {
byteOrdered := []string{"C", "POSIX", "c", "C.UTF-8", "C.utf8"}
for _, c := range byteOrdered {
if !isByteOrderedCollation(c) {
t.Fatalf("expected %q to be treated as byte-ordered", c)
}
}
locale := []string{"en_US.UTF-8", "en_US.utf8", "en-US-x-icu", "und-x-icu", ""}
for _, c := range locale {
if isByteOrderedCollation(c) {
t.Fatalf("expected %q to be treated as locale-aware", c)
}
}
}
func TestResolveCreateTableQuery(t *testing.T) {
cases := []struct {
in, want string
}{
{"", ""},
{"true", DefaultCreateTableQuery},
{"false", ""},
{"CREATE TABLE custom", "CREATE TABLE custom"},
}
for _, c := range cases {
if got := ResolveCreateTableQuery(c.in); got != c.want {
t.Fatalf("ResolveCreateTableQuery(%q) = %q, want %q", c.in, got, c.want)
}
}
}
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)
}
}
}