From acff8078799ad2aa18bc5d84681aa0b2cf8018cc Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Wed, 2 Dec 2026 07:05:13 -0800 Subject: [PATCH] filer: postgres_flat store keyed by the full path (#13253) * 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/postgres: build the connection string with pgxutil.BuildDSN The credential store already does; it quotes values per libpq, so a password or certificate path with spaces or quotes no longer breaks the connection string. The OpenPGXDB alias has no callers left. 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/postgres: postgres and postgres2 share their connection setup ReadConnection reads the settings and their defaults, Connection.Open opens the store's pools. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * filer/sql: key-value records may live in a table of their own A store whose entry tables have another layout keeps its key-value records in KvTable, written by KvSqlGenerator; its scans then read only entries and need not tell the records apart. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * filer/postgres: SQL generator keyed by the full path Rows have path as their primary key; a (directory, name) unique constraint serves the directory listings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * filer: postgres_flat store Entries are keyed by their full path, the object key inside a bucket's table; buckets get tables of their own as in postgres2. Key-value records keep the postgres2 layout in filemeta_kv. The store refuses a filemeta table of another layout, so it needs a schema of its own. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * filer: register postgres_flat and add it to the filer.toml scaffold 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_flat: name a missing filemeta table instead of a foreign layout With createTable = false and no filemeta table, the layout check said the table had no path column and blamed a postgres2 layout. Report the missing table and the key-value table that also has to be created. Co-Authored-By: Claude Opus 5.5 * filer/postgres: postgres_flat escapes the table name inside its quotes A double quote in it is doubled, as PostgreSQL reads a quoted identifier. Bucket names cannot hold one, but the statements no longer rely on that. Reported by CodeQL (go/unsafe-quoting). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * 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: postgres_flat shares the generator's tableIdent 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 * filer/postgres_flat: find filemeta along the search path when checking its layout The store's queries name filemeta unqualified, so with schema = "a,b" they reach a table in b; the layout check looked in current_schema() only and refused it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * filer/postgres_flat: force byte order when the path column is locale-ordered Directory listings order and bound rows by path, but only the name column's collation was checked. A createTable with a locale-ordered path column listed in locale order, and byte-order bounds missed entries. Co-Authored-By: Claude Opus 5.5 * filer/postgres: read the ordered columns' collation along the search path The collation check looked for filemeta in current_schema() only. With the tables in a later schema of the search path it found no column and took the database's order, so a locale-ordered path column next to a C database went unforced, and byte-ordered columns in a locale database got a needless sort. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * filer/postgres_flat: list a directory from its path range A directory's children are the rows of its path range whose directory is the listed one. The listing reads that range in growing batches and skips the rows of the children's subtrees in Go, so a versioned object's .versions rows cost no query of their own. Past 64 rows of one subtree it queries again from that subtree's end. A name prefix narrows the range. Listing no longer reads the (directory, name) index. Co-Authored-By: Claude Opus 5.5 * filer/postgres_flat: find a folder's children in its path range Deleting a folder's children looked them up by directory alone, which only the (directory, name) index serves. Bound the delete by the folder's path range as well. Co-Authored-By: Claude Opus 5.5 * filer/postgres_flat: key the table by path alone Listing and deleting a folder's children both read the path range now, so the (directory, name) unique index only cost writes and storage: flatPath already makes the path unique per (directory, name). Co-Authored-By: Claude Opus 5.5 * filer/postgres: read the ICU or builtin database locale before datcollate An ICU-default database can report datcollate 'C' while its default collation orders by the ICU locale, so a name column on the database default looked byte-ordered and the listing kept locale order. Read datlocprovider and the provider locale (via to_jsonb, so servers before Postgres 15 still answer) and treat an ICU default as locale-ordered. Co-Authored-By: Claude Opus 5.5 * filer/postgres_flat: list a folder's children from its path range The bucket enumeration listed /buckets by directory and ordered by name, a sequential scan and sort now that path is the only index. Read the folder's path range in path order instead. Co-Authored-By: Claude Opus 5.5 * filer/postgres_flat: only the path column needs byte order Listings now order and range by path alone, and directory and name are only compared for equality, which no deterministic collation changes. Drop their COLLATE "C" and check only the path column's order. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- weed/command/imports.go | 1 + weed/command/scaffold/filer.toml | 34 ++ weed/filer/abstract_sql/abstract_sql_store.go | 13 +- .../abstract_sql/abstract_sql_store_kv.go | 21 +- .../abstract_sql_store_list_path.go | 164 +++++++++ .../abstract_sql_store_list_path_test.go | 25 ++ .../abstract_sql/abstract_sql_store_scan.go | 10 +- .../abstract_sql/abstract_sql_store_test.go | 30 ++ weed/filer/postgres/postgres_collation.go | 62 ++-- .../filer/postgres/postgres_collation_test.go | 55 +++- weed/filer/postgres/postgres_flat_sql_gen.go | 111 +++++++ .../postgres/postgres_flat_sql_gen_test.go | 86 +++++ .../postgres_flat/postgres_flat_store.go | 104 ++++++ .../postgres_flat/postgres_flat_store_test.go | 310 ++++++++++++++++++ weed/server/filer_server.go | 1 + 15 files changed, 991 insertions(+), 36 deletions(-) create mode 100644 weed/filer/abstract_sql/abstract_sql_store_list_path.go create mode 100644 weed/filer/abstract_sql/abstract_sql_store_list_path_test.go create mode 100644 weed/filer/postgres/postgres_flat_sql_gen.go create mode 100644 weed/filer/postgres/postgres_flat_sql_gen_test.go create mode 100644 weed/filer/postgres_flat/postgres_flat_store.go create mode 100644 weed/filer/postgres_flat/postgres_flat_store_test.go diff --git a/weed/command/imports.go b/weed/command/imports.go index 133513c319..65b5939945 100644 --- a/weed/command/imports.go +++ b/weed/command/imports.go @@ -28,6 +28,7 @@ import ( _ "github.com/seaweedfs/seaweedfs/weed/filer/mysql2" _ "github.com/seaweedfs/seaweedfs/weed/filer/postgres" _ "github.com/seaweedfs/seaweedfs/weed/filer/postgres2" + _ "github.com/seaweedfs/seaweedfs/weed/filer/postgres_flat" _ "github.com/seaweedfs/seaweedfs/weed/filer/redis" _ "github.com/seaweedfs/seaweedfs/weed/filer/redis2" _ "github.com/seaweedfs/seaweedfs/weed/filer/redis3" diff --git a/weed/command/scaffold/filer.toml b/weed/command/scaffold/filer.toml index 3800e1dc89..97d12a17ca 100644 --- a/weed/command/scaffold/filer.toml +++ b/weed/command/scaffold/filer.toml @@ -200,6 +200,40 @@ upsertQuery = """ meta=EXCLUDED.meta """ +[postgres_flat] +# Rows are keyed by their full path, which inside a bucket's table is the +# object key. Give it a database or schema apart from the postgres and +# postgres2 stores. The path index caps a path at about 2700 bytes. +enabled = false +createTable = """ + CREATE TABLE IF NOT EXISTS "%s" ( + path TEXT COLLATE "C" PRIMARY KEY, + directory TEXT NOT NULL, + name TEXT NOT NULL, + meta bytea + ); +""" +hostname = "localhost" +port = 5432 +username = "postgres" +password = "" +database = "postgres" # create or use an existing database +schema = "" +sslmode = "disable" +# sslcert = "/path/to/client.crt" +# sslkey = "/path/to/client.key" +# sslrootcert = "/path/to/ca.crt" +# sslcrl = "/path/to/client.crl" +connection_max_idle = 50 +connection_max_lifetime_seconds = 300 +pgbouncer_compatible = false +enableUpsert = true +upsertQuery = """ + INSERT INTO "%[1]s" (path, directory, name, meta) + VALUES($1, $2, $3, $4) + ON CONFLICT (path) DO UPDATE SET meta=EXCLUDED.meta +""" + [cassandra2] # CREATE TABLE filemeta ( # dirhash bigint, diff --git a/weed/filer/abstract_sql/abstract_sql_store.go b/weed/filer/abstract_sql/abstract_sql_store.go index be70779aa7..eaeddc6324 100644 --- a/weed/filer/abstract_sql/abstract_sql_store.go +++ b/weed/filer/abstract_sql/abstract_sql_store.go @@ -58,9 +58,13 @@ type AbstractSqlStore struct { KvDB *sql.DB // ScanDB, when set, is the pool snapshot scans run on (SQLite's main pool // is a single connection that a long scan must not hold). - ScanDB *sql.DB - SupportBucketTable bool - SkipDDL bool + ScanDB *sql.DB + SupportBucketTable bool + SkipDDL bool + // KvSqlGenerator, when set, keeps the key-value records in KvTable, out + // of the entry tables. + KvSqlGenerator SqlGenerator + KvTable string dbs map[string]bool dbsLock sync.Mutex RetryableErrorCallback func(err error) bool @@ -454,6 +458,9 @@ func (store *AbstractSqlStore) ListDirectoryPrefixedEntries(ctx context.Context, if err != nil { return lastFileName, fmt.Errorf("findDB %s : %v", dirPath, err) } + if gen, ok := store.SqlGenerator.(PathListSqlGenerator); ok { + return store.listDirectoryByPath(ctx, gen, db, bucket, dirPath, shortPath, startFileName, includeStartFile, limit, prefix, eachEntryFunc) + } getSqlList := store.GetSqlListExclusive if includeStartFile { diff --git a/weed/filer/abstract_sql/abstract_sql_store_kv.go b/weed/filer/abstract_sql/abstract_sql_store_kv.go index 043ff1f85f..2292e97ecb 100644 --- a/weed/filer/abstract_sql/abstract_sql_store_kv.go +++ b/weed/filer/abstract_sql/abstract_sql_store_kv.go @@ -24,13 +24,21 @@ func (store *AbstractSqlStore) kvDB(ctx context.Context) TxOrDB { return store.DB } +func (store *AbstractSqlStore) kvSql() (SqlGenerator, string) { + if store.KvSqlGenerator != nil { + return store.KvSqlGenerator, store.KvTable + } + return store.SqlGenerator, DEFAULT_TABLE +} + func (store *AbstractSqlStore) KvPut(ctx context.Context, key []byte, value []byte) (err error) { db := store.kvDB(ctx) rowKey := kvRowKey(key) - sqlText, args := store.GetSqlInsert(DEFAULT_TABLE, rowKey, value) + gen, table := store.kvSql() + sqlText, args := gen.GetSqlInsert(table, rowKey, value) _, err = db.ExecContext(ctx, sqlText, args...) if err == nil { return @@ -44,7 +52,7 @@ 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) - sqlText, args = store.GetSqlUpdate(DEFAULT_TABLE, rowKey, value) + sqlText, args = gen.GetSqlUpdate(table, rowKey, value) res, err := db.ExecContext(ctx, sqlText, args...) if err != nil { return fmt.Errorf("kv upsert: %s", err) @@ -62,7 +70,8 @@ func (store *AbstractSqlStore) KvGet(ctx context.Context, key []byte) (value []b db := store.kvDB(ctx) - sqlText, args := store.GetSqlFind(DEFAULT_TABLE, kvRowKey(key)) + gen, table := store.kvSql() + sqlText, args := gen.GetSqlFind(table, kvRowKey(key)) row := db.QueryRowContext(ctx, sqlText, args...) err = row.Scan(&value) @@ -84,6 +93,7 @@ const kvBatchGetSize = 256 func (store *AbstractSqlStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) { db := store.kvDB(ctx) + gen, table := store.kvSql() values := make(map[string][]byte, len(keys)) for start := 0; start < len(keys); start += kvBatchGetSize { batch := keys[start:min(start+kvBatchGetSize, len(keys))] @@ -97,7 +107,7 @@ func (store *AbstractSqlStore) KvBatchGet(ctx context.Context, keys [][]byte) (m rowKeys = append(rowKeys, rowKey) } if err := func() error { - sqlText, args := store.GetSqlFindBatch(DEFAULT_TABLE, rowKeys) + sqlText, args := gen.GetSqlFindBatch(table, rowKeys) rows, err := db.QueryContext(ctx, sqlText, args...) if err != nil { return err @@ -125,7 +135,8 @@ func (store *AbstractSqlStore) KvDelete(ctx context.Context, key []byte) (err er db := store.kvDB(ctx) - sqlText, args := store.GetSqlDelete(DEFAULT_TABLE, kvRowKey(key)) + gen, table := store.kvSql() + sqlText, args := gen.GetSqlDelete(table, kvRowKey(key)) res, err := db.ExecContext(ctx, sqlText, args...) if err != nil { return fmt.Errorf("kv delete: %s", err) diff --git a/weed/filer/abstract_sql/abstract_sql_store_list_path.go b/weed/filer/abstract_sql/abstract_sql_store_list_path.go new file mode 100644 index 0000000000..104484a25d --- /dev/null +++ b/weed/filer/abstract_sql/abstract_sql_store_list_path.go @@ -0,0 +1,164 @@ +package abstract_sql + +import ( + "context" + "fmt" + "strings" + "unicode/utf8" + + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +// PathListSqlGenerator is implemented by a generator whose rows are keyed by +// their path. GetSqlListPath selects directory, name and, for the rows of dir +// only, meta of the rows with after < path and from <= path < to, in path order. +type PathListSqlGenerator interface { + GetSqlListPath(tableName, dir, after, from, to string, limit int64) (string, []interface{}) +} + +// In path order a directory's children interleave with their own subtrees, +// such as the versions of an object. A listing reads growing batches of the +// directory's range and skips subtree rows in Go; past pathListMaxSkip rows of +// one subtree it queries again from the end of that subtree, starting over +// with a small batch, as the rows a cut-short batch still holds are read anyway. +var ( + pathListMinBatch int64 = 8 + pathListMaxBatch int64 = 4096 + pathListMaxSkip = 64 +) + +// SetPathListBatchesForTest lets tests drive a listing across batches and +// subtree skips. It returns the previous values. +func SetPathListBatchesForTest(minBatch, maxBatch int64, maxSkip int) (int64, int64, int) { + prevMin, prevMax, prevSkip := pathListMinBatch, pathListMaxBatch, pathListMaxSkip + pathListMinBatch, pathListMaxBatch, pathListMaxSkip = minBatch, maxBatch, maxSkip + return prevMin, prevMax, prevSkip +} + +// listDirectoryByPath lists the children of dirPath, stored under shortPath in +// table, from a generator that keys rows by path. +func (store *AbstractSqlStore) listDirectoryByPath(ctx context.Context, gen PathListSqlGenerator, db TxOrDB, table string, dirPath, shortPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) { + dir := string(shortPath) + childPrefix := strings.TrimSuffix(dir, "/") + "/" + from := childPrefix + prefix + to, _ := prefixEnd(from) + after := "" + if start := childPrefix + startFileName; !includeStartFile { + after = start + } else if start > from { + from = start + } + + // As in the directory-keyed listing, limit+1 entries are read. + want := limit + 1 + batch := min(max(want, pathListMinBatch), pathListMaxBatch) + for want > 0 { + sqlText, args := gen.GetSqlListPath(table, dir, after, from, to, batch) + entries, read, resume, err := readPathListBatch(ctx, db, sqlText, args, dirPath, dir, childPrefix, want) + if err != nil { + return lastFileName, err + } + for _, entry := range entries { + lastFileName = entry.Name() + more, eachErr := eachEntryFunc(entry) + if eachErr != nil { + return lastFileName, fmt.Errorf("failed to process eachEntryFunc: %w", eachErr) + } + if !more { + return lastFileName, nil + } + } + want -= int64(len(entries)) + switch { + case resume.cut: + after, from, batch = "", resume.skipTo, pathListMinBatch + continue + case read < batch: + return lastFileName, nil + case resume.skipTo != "": + after, from = "", resume.skipTo + default: + after = resume.after + } + next := batch * 2 + if n := int64(len(entries)); n > 0 { + // Closing the rows reads the rest of a batch, so ask for about + // as many rows as the remaining entries took so far. + next = min(next, min(want, pathListMaxBatch)*read/n*5/4+pathListMinBatch) + } + batch = min(next, pathListMaxBatch) + } + return lastFileName, nil +} + +type pathListResume struct { + after string // the last row read was a child with this path + skipTo string // the last row read lies in a subtree ending before this path + cut bool // the batch was left unread past pathListMaxSkip rows of that subtree +} + +// readPathListBatch returns up to want children of dir from one batch, and +// where the next batch starts. read counts the rows taken from the batch. +func readPathListBatch(ctx context.Context, db TxOrDB, sqlText string, args []interface{}, dirPath util.FullPath, dir, childPrefix string, want int64) (entries []*filer.Entry, read int64, resume pathListResume, err error) { + rows, err := db.QueryContext(ctx, sqlText, args...) + if err != nil { + return nil, 0, resume, fmt.Errorf("list %s : %v", dirPath, err) + } + // A transaction has one connection, and the callback may query on it (a + // hard link's KvGet), so entries are handed over after the rows close. + defer rows.Close() + + skipping, skipped := "", 0 + for rows.Next() { + var rowDir, name string + var data []byte + if err = rows.Scan(&rowDir, &name, &data); err != nil { + return nil, read, resume, fmt.Errorf("scan %s: %v", dirPath, err) + } + read++ + if rowDir != dir { + child, _, _ := strings.Cut(strings.TrimPrefix(rowDir, childPrefix), "/") + if child != skipping { + skipping, skipped = child, 0 + } + skipped++ + resume = pathListResume{skipTo: childPrefix + child + "0", cut: skipped >= pathListMaxSkip} + if resume.cut { + break + } + continue + } + resume = pathListResume{after: childPrefix + name} + entry := &filer.Entry{FullPath: util.NewFullPath(string(dirPath), name)} + if err = entry.DecodeAttributesAndChunks(util.MaybeDecompressData(data)); err != nil { + return nil, read, resume, fmt.Errorf("scan decode %s : %v", entry.FullPath, err) + } + entries = append(entries, entry) + if int64(len(entries)) == want { + break + } + } + if err = rows.Err(); err != nil { + return nil, read, resume, fmt.Errorf("list %s: %w", dirPath, err) + } + return entries, read, resume, nil +} + +// prefixEnd returns the least string greater than every string starting with +// p, in byte order. ok is false when there is none. +func prefixEnd(p string) (end string, ok bool) { + for len(p) > 0 { + r, size := utf8.DecodeLastRuneInString(p) + p = p[:len(p)-size] + if r == utf8.MaxRune || r == utf8.RuneError && size == 1 { + continue + } + r++ + if r >= 0xD800 && r <= 0xDFFF { + r = 0xE000 + } + return p + string(r), true + } + return "", false +} diff --git a/weed/filer/abstract_sql/abstract_sql_store_list_path_test.go b/weed/filer/abstract_sql/abstract_sql_store_list_path_test.go new file mode 100644 index 0000000000..3b5b01cd3f --- /dev/null +++ b/weed/filer/abstract_sql/abstract_sql_store_list_path_test.go @@ -0,0 +1,25 @@ +package abstract_sql + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestPrefixEnd(t *testing.T) { + for p, want := range map[string]string{ + "/a/": "/a0", + "/a": "/b", + "/日本": "/日\u672D", + "/a\U0010FFFF": "/b", + "/a퟿": "/a", + } { + end, ok := prefixEnd(p) + require.True(t, ok, p) + require.Equal(t, want, end, p) + require.Less(t, p, end) + require.Less(t, p+"\U0010FFFF\U0010FFFF", end) + } + _, ok := prefixEnd("\U0010FFFF") + require.False(t, ok) +} diff --git a/weed/filer/abstract_sql/abstract_sql_store_scan.go b/weed/filer/abstract_sql/abstract_sql_store_scan.go index a9c18ca616..b05ae7f372 100644 --- a/weed/filer/abstract_sql/abstract_sql_store_scan.go +++ b/weed/filer/abstract_sql/abstract_sql_store_scan.go @@ -268,10 +268,10 @@ func (store *AbstractSqlStore) listBucketNames(ctx context.Context, tx *sql.Tx, } // scanOneTable reads one table in primary-key pages and hands the entries -// strictly below dirPath to fn (the root itself is read separately). Key-value -// records share the default table; GenDirAndName stores the raw key bytes as -// their dirhash while entry rows hash the directory, so the mismatch -// identifies them exactly. +// strictly below dirPath to fn (the root itself is read separately). Unless +// they have a table of their own, key-value records share the default table; +// GenDirAndName stores the raw key bytes as their dirhash while entry rows +// hash the directory, so the mismatch identifies them exactly. func (store *AbstractSqlStore) scanOneTable(ctx context.Context, tx *sql.Tx, t scanTable, dirPath util.FullPath, fn func(ctx context.Context, entry *filer.Entry) error) error { type row struct { dirHash int64 @@ -317,7 +317,7 @@ func (store *AbstractSqlStore) scanOneTable(ctx context.Context, tx *sql.Tx, t s for _, r := range page { cursor = RowKey{DirHash: r.dirHash, Name: r.name, Directory: r.dir} - if r.dirHash != util.HashStringToLong(r.dir) { + if store.KvSqlGenerator == nil && r.dirHash != util.HashStringToLong(r.dir) { continue // a key-value record, see GenDirAndName } fullPath := util.NewFullPath(t.base+r.dir, r.name) diff --git a/weed/filer/abstract_sql/abstract_sql_store_test.go b/weed/filer/abstract_sql/abstract_sql_store_test.go index c9fba3f53b..6d8beb246c 100644 --- a/weed/filer/abstract_sql/abstract_sql_store_test.go +++ b/weed/filer/abstract_sql/abstract_sql_store_test.go @@ -372,3 +372,33 @@ func TestListDirectoryEntriesInTransactionClosesRowsBeforeCallback(t *testing.T) t.Errorf("listed %v, want %v", listed, want) } } + +type kvTableGen struct{ SqlGenerator } + +func (kvTableGen) GetSqlInsert(table string, key RowKey, meta []byte) (string, []interface{}) { + return "INSERT kv " + table, key.Args(meta) +} +func (kvTableGen) GetSqlFind(table string, key RowKey) (string, []interface{}) { + return "SELECT kv " + table, key.Args() +} + +func TestKvRecordsGoToTheirOwnTable(t *testing.T) { + db, mock, err := sqlmock.New() + if err != nil { + t.Fatal(err) + } + defer db.Close() + mock.ExpectExec("INSERT kv filemeta_kv").WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectQuery("SELECT kv filemeta_kv").WillReturnRows(sqlmock.NewRows([]string{"meta"}).AddRow([]byte("v"))) + + store := &AbstractSqlStore{SqlGenerator: writeGen{}, KvSqlGenerator: kvTableGen{}, KvTable: "filemeta_kv", DB: db} + if err := store.KvPut(context.Background(), []byte("key"), []byte("v")); err != nil { + t.Fatal(err) + } + if v, err := store.KvGet(context.Background(), []byte("key")); err != nil || string(v) != "v" { + t.Fatalf("KvGet = %q, %v", v, err) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Error(err) + } +} diff --git a/weed/filer/postgres/postgres_collation.go b/weed/filer/postgres/postgres_collation.go index 6dfa4b8d32..d21a478da6 100644 --- a/weed/filer/postgres/postgres_collation.go +++ b/weed/filer/postgres/postgres_collation.go @@ -9,24 +9,31 @@ import ( ) // ConfigureListOrdering switches the list queries to COLLATE "C" when the live -// filemeta.name collation is locale-aware, so S3 ListObjectsV2 stays -// lexicographic. The fallback costs a sort, so warn the operator to fix it. -func ConfigureListOrdering(db *sql.DB, gen *SqlGenPostgres) { +// collation of a filemeta column they order by (name, unless columns says +// otherwise) is locale-aware, so S3 ListObjectsV2 stays lexicographic. The +// fallback costs a sort, so warn the operator to fix it. +func ConfigureListOrdering(db *sql.DB, gen *SqlGenPostgres, columns ...string) { if isCockroachDB(db) { // CockroachDB string comparison is already byte-ordered, so the // fallback is redundant; older versions also reject COLLATE "C". return } - collation, isBinary, err := nameColumnCollation(db) - if err != nil { - glog.V(1).Infof("postgres: skip filemeta.name collation check: %v", err) + if len(columns) == 0 { + columns = []string{"name"} + } + for _, column := range columns { + collation, isBinary, err := columnCollation(db, column) + if err != nil { + glog.V(1).Infof("postgres: skip filemeta.%s collation check: %v", column, err) + continue + } + if isBinary { + continue + } + gen.ForceBinaryCollation = true + glog.Warningf(`postgres: filemeta.%s collation %q is not byte-ordered, so S3 list order is not byte-lexicographic and clients that merge sorted listings may report spurious diffs. Falling back to a slower COLLATE "C" sort; declare the %s column COLLATE "C" (or use a C/C.UTF-8 database collation) for correct, indexed ordering.`, column, collation, column) return } - if isBinary { - return - } - gen.ForceBinaryCollation = true - glog.Warningf(`postgres: filemeta.name collation %q is not byte-ordered, so S3 list order is not byte-lexicographic and clients that merge sorted listings may report spurious diffs. Falling back to a slower COLLATE "C" sort; declare the name column COLLATE "C" (or use a C/C.UTF-8 database collation) for correct, indexed ordering.`, collation) } // isCockroachDB reports whether db is a CockroachDB backend, whose version() @@ -40,20 +47,31 @@ func isCockroachDB(db *sql.DB) bool { return strings.Contains(version, "CockroachDB") } -func nameColumnCollation(db *sql.DB) (collation string, isBinary bool, err error) { - // information_schema reports NULL for a column on the database default, so - // fall back to datcollate for the effective ordering. +func columnCollation(db *sql.DB, column string) (collation string, isBinary bool, err error) { + // to_regclass resolves the table along the search path, as the store's + // queries do. A column on the database default has the "default" + // collation, so fall back to the database locale. An ICU or builtin + // default (Postgres 15+) orders by its own locale, not datcollate; to_jsonb + // reads those columns without failing on older servers that lack them. row := db.QueryRow(`SELECT - (SELECT collation_name FROM information_schema.columns - WHERE table_schema = current_schema() AND table_name = $1 AND column_name = 'name'), - (SELECT datcollate FROM pg_database WHERE datname = current_database())`, abstract_sql.DEFAULT_TABLE) - var columnCollation, dbCollate sql.NullString - if err = row.Scan(&columnCollation, &dbCollate); err != nil { + (SELECT NULLIF(c.collname, 'default') FROM pg_attribute a JOIN pg_collation c ON c.oid = a.attcollation + WHERE a.attrelid = to_regclass($1) AND a.attname = $2 AND NOT a.attisdropped), + d.datcollate, to_jsonb(d)->>'datlocprovider', COALESCE(to_jsonb(d)->>'datlocale', to_jsonb(d)->>'daticulocale') + FROM pg_database d WHERE d.datname = current_database()`, abstract_sql.DEFAULT_TABLE, column) + var declared, dbCollate, dbProvider, dbLocale sql.NullString + if err = row.Scan(&declared, &dbCollate, &dbProvider, &dbLocale); err != nil { return "", false, err } - effective := columnCollation.String - if !columnCollation.Valid || effective == "" { - effective = dbCollate.String + effective := declared.String + if effective == "" { + switch dbProvider.String { + case "i": + return "ICU " + dbLocale.String, false, nil + case "b": + effective = dbLocale.String + default: + effective = dbCollate.String + } } return effective, isByteOrderedCollation(effective), nil } diff --git a/weed/filer/postgres/postgres_collation_test.go b/weed/filer/postgres/postgres_collation_test.go index ca64de7d6b..8f36eab908 100644 --- a/weed/filer/postgres/postgres_collation_test.go +++ b/weed/filer/postgres/postgres_collation_test.go @@ -36,7 +36,7 @@ func TestConfigureListOrderingForcesBinaryOnLocalePostgres(t *testing.T) { mock.ExpectQuery("SELECT version\\(\\)").WillReturnRows( sqlmock.NewRows([]string{"version"}).AddRow("PostgreSQL 16.2 on x86_64-pc-linux-gnu")) mock.ExpectQuery("datcollate").WillReturnRows( - sqlmock.NewRows([]string{"collation_name", "datcollate"}).AddRow(nil, "en_US.UTF-8")) + sqlmock.NewRows([]string{"collation_name", "datcollate", "datlocprovider", "datlocale"}).AddRow(nil, "en_US.UTF-8", "c", nil)) gen := &SqlGenPostgres{} ConfigureListOrdering(db, gen) @@ -47,3 +47,56 @@ func TestConfigureListOrderingForcesBinaryOnLocalePostgres(t *testing.T) { t.Fatalf("unmet expectations: %v", err) } } + +func TestConfigureListOrderingChecksEveryOrderedColumn(t *testing.T) { + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("sqlmock: %v", err) + } + defer db.Close() + + mock.ExpectQuery("SELECT version\\(\\)").WillReturnRows( + sqlmock.NewRows([]string{"version"}).AddRow("PostgreSQL 16.2 on x86_64-pc-linux-gnu")) + mock.ExpectQuery("datcollate").WithArgs("filemeta", "name").WillReturnRows( + sqlmock.NewRows([]string{"collation_name", "datcollate", "datlocprovider", "datlocale"}).AddRow("C", "en_US.UTF-8", "c", nil)) + mock.ExpectQuery("datcollate").WithArgs("filemeta", "path").WillReturnRows( + sqlmock.NewRows([]string{"collation_name", "datcollate", "datlocprovider", "datlocale"}).AddRow(nil, "en_US.UTF-8", "c", nil)) + + gen := &SqlGenPostgres{} + ConfigureListOrdering(db, gen, "name", "path") + if !gen.ForceBinaryCollation { + t.Fatal("a locale-aware path column must force byte ordering") + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet expectations: %v", err) + } +} + +func TestConfigureListOrderingUsesDatabaseLocaleProvider(t *testing.T) { + for _, tc := range []struct { + provider, locale string + forced bool + }{ + {"i", "en-US", true}, + {"b", "C.UTF-8", false}, + } { + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("sqlmock: %v", err) + } + mock.ExpectQuery("SELECT version\\(\\)").WillReturnRows( + sqlmock.NewRows([]string{"version"}).AddRow("PostgreSQL 17.2 on x86_64-pc-linux-gnu")) + mock.ExpectQuery("datcollate").WillReturnRows( + sqlmock.NewRows([]string{"collation_name", "datcollate", "datlocprovider", "datlocale"}).AddRow(nil, "C", tc.provider, tc.locale)) + + gen := &SqlGenPostgres{} + ConfigureListOrdering(db, gen) + if gen.ForceBinaryCollation != tc.forced { + t.Errorf("provider %q locale %q with datcollate C: ForceBinaryCollation = %v, want %v", tc.provider, tc.locale, gen.ForceBinaryCollation, tc.forced) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Errorf("unmet expectations: %v", err) + } + db.Close() + } +} diff --git a/weed/filer/postgres/postgres_flat_sql_gen.go b/weed/filer/postgres/postgres_flat_sql_gen.go new file mode 100644 index 0000000000..24f03de50d --- /dev/null +++ b/weed/filer/postgres/postgres_flat_sql_gen.go @@ -0,0 +1,111 @@ +package postgres + +import ( + "fmt" + "strings" + + "github.com/seaweedfs/seaweedfs/weed/filer/abstract_sql" +) + +// SqlGenPostgresFlat keys each row by its full path, the only index. A +// directory listing reads the directory's path range. +type SqlGenPostgresFlat struct { + SqlGenPostgres +} + +const DefaultFlatCreateTableQuery = `CREATE TABLE IF NOT EXISTS "%s" (path TEXT COLLATE "C" PRIMARY KEY, directory TEXT NOT NULL, name TEXT NOT NULL, meta bytea)` + +// DefaultFlatUpsertQuery takes $1 path, $2 directory, $3 name and $4 meta. +const DefaultFlatUpsertQuery = `INSERT INTO "%s" (path,directory,name,meta) VALUES($1,$2,$3,$4) ON CONFLICT (path) DO UPDATE SET meta=EXCLUDED.meta` + +var ( + _ = abstract_sql.SqlGenerator(&SqlGenPostgresFlat{}) + _ = abstract_sql.PathListSqlGenerator(&SqlGenPostgresFlat{}) +) + +func flatPath(key abstract_sql.RowKey) string { + switch key.Directory { + case "": + return key.Name + case "/": + return "/" + key.Name + } + return key.Directory + "/" + key.Name +} + +func (gen *SqlGenPostgresFlat) GetSqlInsert(tableName string, key abstract_sql.RowKey, meta []byte) (string, []interface{}) { + args := []interface{}{flatPath(key), key.Directory, key.Name, meta} + if gen.UpsertQueryTemplate != "" { + return fmt.Sprintf(gen.UpsertQueryTemplate, tableIdent(tableName)), args + } + return fmt.Sprintf(`INSERT INTO "%s" (path,directory,name,meta) VALUES($1,$2,$3,$4)`, tableIdent(tableName)), args +} + +func (gen *SqlGenPostgresFlat) GetSqlUpdate(tableName string, key abstract_sql.RowKey, meta []byte) (string, []interface{}) { + return fmt.Sprintf(`UPDATE "%s" SET meta=$2 WHERE path=$1`, tableIdent(tableName)), []interface{}{flatPath(key), meta} +} + +func (gen *SqlGenPostgresFlat) GetSqlFind(tableName string, key abstract_sql.RowKey) (string, []interface{}) { + return fmt.Sprintf(`SELECT meta FROM "%s" WHERE path=$1`, tableIdent(tableName)), []interface{}{flatPath(key)} +} + +func (gen *SqlGenPostgresFlat) GetSqlFindBatch(tableName string, keys []abstract_sql.RowKey) (string, []interface{}) { + params := make([]string, len(keys)) + args := make([]interface{}, len(keys)) + for i, key := range keys { + params[i] = fmt.Sprintf("$%d", i+1) + args[i] = flatPath(key) + } + return fmt.Sprintf(`SELECT name, directory, meta FROM "%s" WHERE path IN (%s)`, tableIdent(tableName), strings.Join(params, ",")), args +} + +func (gen *SqlGenPostgresFlat) GetSqlDelete(tableName string, key abstract_sql.RowKey) (string, []interface{}) { + return fmt.Sprintf(`DELETE FROM "%s" WHERE path=$1`, tableIdent(tableName)), []interface{}{flatPath(key)} +} + +// GetSqlDeleteFolderChildren finds the children in the directory's path range. +func (gen *SqlGenPostgresFlat) GetSqlDeleteFolderChildren(tableName string, dir string) (string, []interface{}) { + path := "path" + if gen.ForceBinaryCollation { + path = `path COLLATE "C"` + } + base := strings.TrimSuffix(dir, "/") + return fmt.Sprintf(`DELETE FROM "%s" WHERE %s>=$1 AND %s<$2 AND directory=$3`, tableIdent(tableName), path, path), + []interface{}{base + "/", base + "0", dir} +} + +// GetSqlScanPage pages by path; the dirhash column is a placeholder. +func (gen *SqlGenPostgresFlat) GetSqlScanPage(tableName string, after abstract_sql.RowKey, limit int) (string, []interface{}) { + return fmt.Sprintf(`SELECT 0::bigint, name, directory, meta FROM "%s" WHERE path > $1 ORDER BY path ASC LIMIT $2`, tableIdent(tableName)), + []interface{}{flatPath(after), limit} +} + +func (gen *SqlGenPostgresFlat) GetSqlListExclusive(tableName string, dir, startFileName, namePattern string, limit int64) (string, []interface{}) { + return gen.listChildren(tableName, ">", dir, startFileName, namePattern, limit) +} + +func (gen *SqlGenPostgresFlat) GetSqlListInclusive(tableName string, dir, startFileName, namePattern string, limit int64) (string, []interface{}) { + return gen.listChildren(tableName, ">=", dir, startFileName, namePattern, limit) +} + +// listChildren reads dir's path range, so the children come in path order. +func (gen *SqlGenPostgresFlat) listChildren(tableName, op, dir, startFileName, namePattern string, limit int64) (string, []interface{}) { + path := "path" + if gen.ForceBinaryCollation { + path = `path COLLATE "C"` + } + base := strings.TrimSuffix(dir, "/") + return fmt.Sprintf(`SELECT name, meta FROM "%s" WHERE %s%s$2 AND %s<$3 AND directory=$1 AND name like $4 ESCAPE '!' ORDER BY %s ASC LIMIT $5`, tableIdent(tableName), path, op, path, path), + []interface{}{dir, base + "/" + startFileName, base + "0", namePattern, limit} +} + +// GetSqlListPath leaves meta out of the rows below dir's children, which a +// directory listing skips. +func (gen *SqlGenPostgresFlat) GetSqlListPath(tableName, dir, after, from, to string, limit int64) (string, []interface{}) { + path := "path" + if gen.ForceBinaryCollation { + path = `path COLLATE "C"` + } + return fmt.Sprintf(`SELECT directory, name, CASE WHEN directory=$1 THEN meta END FROM "%s" WHERE %s>$2 AND %s>=$3 AND %s<$4 ORDER BY %s ASC LIMIT $5`, tableIdent(tableName), path, path, path, path), + []interface{}{dir, after, from, to, limit} +} diff --git a/weed/filer/postgres/postgres_flat_sql_gen_test.go b/weed/filer/postgres/postgres_flat_sql_gen_test.go new file mode 100644 index 0000000000..a4f16ee830 --- /dev/null +++ b/weed/filer/postgres/postgres_flat_sql_gen_test.go @@ -0,0 +1,86 @@ +package postgres + +import ( + "fmt" + "strings" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/filer/abstract_sql" +) + +func TestFlatPath(t *testing.T) { + for _, c := range []struct{ dir, name, want string }{ + {"/", "", "/"}, + {"/", "a.txt", "/a.txt"}, + {"/dir/sub", "a.txt", "/dir/sub/a.txt"}, + {"", "", ""}, + } { + if got := flatPath(abstract_sql.EntryRowKey(c.dir, c.name)); got != c.want { + t.Errorf("flatPath(%q, %q) = %q, want %q", c.dir, c.name, got, c.want) + } + } +} + +func TestFlatStatementsAddressRowsByPath(t *testing.T) { + gen := &SqlGenPostgresFlat{SqlGenPostgres{UpsertQueryTemplate: DefaultFlatUpsertQuery}} + key := abstract_sql.EntryRowKey("/dir", "a.txt") + insert, args := gen.GetSqlInsert("filemeta", key, []byte("m")) + if !strings.Contains(insert, "ON CONFLICT (path)") || args[0] != "/dir/a.txt" || args[1] != "/dir" || args[2] != "a.txt" { + t.Fatalf("insert %s %v", insert, args) + } + update, args := gen.GetSqlUpdate("filemeta", key, []byte("m")) + if !strings.Contains(update, "WHERE path=$1") || args[0] != "/dir/a.txt" { + t.Fatalf("update %s %v", update, args) + } + list, args := gen.GetSqlListExclusive("filemeta", "/dir", "b", "%", 10) + if !strings.Contains(list, "WHERE path>$2 AND path<$3 AND directory=$1") || !strings.Contains(list, "ORDER BY path ASC") || + fmt.Sprint(args) != fmt.Sprint([]interface{}{"/dir", "/dir/b", "/dir0", "%", int64(10)}) { + t.Fatalf("list %s %v", list, args) + } + gen.ForceBinaryCollation = true + list, args = gen.GetSqlListInclusive("filemeta", "/", "", "%", 10) + if !strings.Contains(list, `WHERE path COLLATE "C">=$2`) || !strings.Contains(list, `ORDER BY path COLLATE "C"`) || args[1] != "/" || args[2] != "0" { + t.Fatalf("list without a byte-ordered column: %s %v", list, args) + } +} + +func TestFlatPathListing(t *testing.T) { + gen := &SqlGenPostgresFlat{} + list, args := gen.GetSqlListPath("bkt", "/a", "/a/b", "/a/", "/a0", 100) + if !strings.Contains(list, "CASE WHEN directory=$1 THEN meta END") || !strings.Contains(list, "WHERE path>$2 AND path>=$3 AND path<$4 ORDER BY path ASC LIMIT $5") || + fmt.Sprint(args) != fmt.Sprint([]interface{}{"/a", "/a/b", "/a/", "/a0", int64(100)}) { + t.Fatalf("list %s %v", list, args) + } + gen.ForceBinaryCollation = true + if list, _ = gen.GetSqlListPath("bkt", "/", "", "/", "0", 1); !strings.Contains(list, `ORDER BY path COLLATE "C"`) { + t.Fatalf("list without a byte-ordered column: %s", list) + } +} + +func TestFlatDeleteFolderChildrenReadsThePathRange(t *testing.T) { + gen := &SqlGenPostgresFlat{} + for dir, want := range map[string][]interface{}{ + "/": {"/", "0", "/"}, + "/a/b": {"/a/b/", "/a/b0", "/a/b"}, + } { + del, args := gen.GetSqlDeleteFolderChildren("filemeta", dir) + if !strings.Contains(del, "WHERE path>=$1 AND path<$2 AND directory=$3") || fmt.Sprint(args) != fmt.Sprint(want) { + t.Fatalf("delete children of %s: %s %v", dir, del, args) + } + } +} + +func TestFlatStatementsEscapeTheTableName(t *testing.T) { + gen := &SqlGenPostgresFlat{SqlGenPostgres{UpsertQueryTemplate: DefaultFlatUpsertQuery}} + for _, statement := range []string{ + first(gen.GetSqlInsert(`a"b`, abstract_sql.EntryRowKey("/", "x"), nil)), + first(gen.GetSqlFind(`a"b`, abstract_sql.EntryRowKey("/", "x"))), + first(gen.GetSqlListExclusive(`a"b`, "/", "", "%", 1)), + } { + if !strings.Contains(statement, `"a""b"`) { + t.Fatalf("table name not escaped: %s", statement) + } + } +} + +func first(s string, _ []interface{}) string { return s } diff --git a/weed/filer/postgres_flat/postgres_flat_store.go b/weed/filer/postgres_flat/postgres_flat_store.go new file mode 100644 index 0000000000..3912539531 --- /dev/null +++ b/weed/filer/postgres_flat/postgres_flat_store.go @@ -0,0 +1,104 @@ +// Package postgres_flat is a PostgreSQL filer store whose rows are keyed by +// their full path, one table per bucket as in postgres2. +package postgres_flat + +import ( + "context" + "database/sql" + "fmt" + + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/filer/abstract_sql" + "github.com/seaweedfs/seaweedfs/weed/filer/postgres" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +const kvTable = "filemeta_kv" + +var _ filer.BucketAware = (*PostgresFlatStore)(nil) + +func init() { + filer.Stores = append(filer.Stores, &PostgresFlatStore{}) +} + +type PostgresFlatStore struct { + abstract_sql.AbstractSqlStore +} + +func (store *PostgresFlatStore) GetName() string { + return "postgres_flat" +} + +func (store *PostgresFlatStore) Initialize(configuration util.Configuration, prefix string) (err error) { + configuration.SetDefault(prefix+"enableUpsert", true) + return store.initialize( + configuration.GetString(prefix+"createTable"), + configuration.GetString(prefix+"upsertQuery"), + configuration.GetBool(prefix+"enableUpsert"), + postgres.ReadConnection(configuration, prefix), + ) +} + +func (store *PostgresFlatStore) initialize(createTable, upsertQuery string, enableUpsert bool, conn postgres.Connection) (err error) { + + store.SupportBucketTable = true + store.SkipDDL = createTable == "false" + if createTable == "" || createTable == "true" || store.SkipDDL { + createTable = postgres.DefaultFlatCreateTableQuery + } + if !enableUpsert { + upsertQuery = "" + } else if upsertQuery == "" { + upsertQuery = postgres.DefaultFlatUpsertQuery + } + gen := &postgres.SqlGenPostgresFlat{SqlGenPostgres: postgres.SqlGenPostgres{ + CreateTableSqlTemplate: createTable, + DropTableSqlTemplate: `drop table if exists "%s"`, + UpsertQueryTemplate: upsertQuery, + }} + store.SqlGenerator = gen + store.KvSqlGenerator = &postgres.SqlGenPostgres{ + CreateTableSqlTemplate: postgres.DefaultCreateTableQuery, + UpsertQueryTemplate: postgres.DefaultUpsertQuery, + } + store.KvTable = kvTable + + if err = conn.Open(&store.AbstractSqlStore); err != nil { + return err + } + + ctx := context.Background() + if !store.SkipDDL { + if err = store.CreateTable(ctx, abstract_sql.DEFAULT_TABLE); err != nil { + return fmt.Errorf("init table %s: %v", abstract_sql.DEFAULT_TABLE, err) + } + if _, err = store.DB.ExecContext(ctx, store.KvSqlGenerator.GetSqlCreateTable(kvTable)); err != nil { + return fmt.Errorf("init table %s: %v", kvTable, err) + } + } + if err = checkFlatLayout(ctx, store.DB); err != nil { + return err + } + + postgres.ConfigureListOrdering(store.DB, &gen.SqlGenPostgres, "path") + + return nil +} + +// checkFlatLayout refuses a missing filemeta table, which only a createTable +// of false leaves, and one of the postgres or postgres2 layout. +func checkFlatLayout(ctx context.Context, db *sql.DB) error { + var columns, pathColumns int + // to_regclass resolves the name along the search path, as the store's queries do. + if err := db.QueryRowContext(ctx, `SELECT count(*), count(*) FILTER (WHERE attname = 'path') FROM pg_attribute + WHERE attrelid = to_regclass($1) AND attnum > 0 AND NOT attisdropped`, abstract_sql.DEFAULT_TABLE).Scan(&columns, &pathColumns); err != nil { + return fmt.Errorf("check table %s: %v", abstract_sql.DEFAULT_TABLE, err) + } + if columns == 0 { + return fmt.Errorf("table %s does not exist: with createTable = false, create it and %s beforehand", abstract_sql.DEFAULT_TABLE, kvTable) + } + if pathColumns == 0 { + return fmt.Errorf("table %s has no path column: postgres_flat needs a database or schema of its own, apart from the postgres and postgres2 stores", abstract_sql.DEFAULT_TABLE) + } + return nil +} diff --git a/weed/filer/postgres_flat/postgres_flat_store_test.go b/weed/filer/postgres_flat/postgres_flat_store_test.go new file mode 100644 index 0000000000..02117407bb --- /dev/null +++ b/weed/filer/postgres_flat/postgres_flat_store_test.go @@ -0,0 +1,310 @@ +package postgres_flat + +import ( + "context" + "fmt" + "os" + "sort" + "strings" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/filer/abstract_sql" + "github.com/seaweedfs/seaweedfs/weed/filer/postgres" + "github.com/seaweedfs/seaweedfs/weed/filer/store_test" + "github.com/seaweedfs/seaweedfs/weed/util" + "github.com/seaweedfs/seaweedfs/weed/util/pgxutil" +) + +func newTestStore(t *testing.T, db pgxutil.DSNOptions) *PostgresFlatStore { + store := &PostgresFlatStore{} + if err := store.initialize("", "", true, postgres.Connection{DSNOptions: db, MaxIdle: 10, MaxLifetimeSeconds: 60}); err != nil { + t.Fatal(err) + } + t.Cleanup(store.Shutdown) + return store +} + +func TestStoreConformance(t *testing.T) { + store := newTestStore(t, store_test.NewPostgresTestDatabase(t)) + defer abstract_sql.SetScanPageSizeForTest(abstract_sql.SetScanPageSizeForTest(3)) + store_test.TestFilerStoreConformance(t, store) +} + +func TestRowsAreKeyedByObjectKey(t *testing.T) { + store := newTestStore(t, store_test.NewPostgresTestDatabase(t)) + ctx := context.Background() + store.OnBucketCreation("photos") + for _, p := range []string{"/buckets/photos/2026/01/a.jpg", "/topics/t.log"} { + if err := store.InsertEntry(ctx, &filer.Entry{FullPath: util.FullPath(p)}); err != nil { + t.Fatal(err) + } + } + if err := store.KvPut(ctx, []byte("hardlink-id"), []byte("record")); err != nil { + t.Fatal(err) + } + for table, want := range map[string]string{"photos": "/2026/01/a.jpg", abstract_sql.DEFAULT_TABLE: "/topics/t.log"} { + var path, directory, name string + if err := store.DB.QueryRow(`SELECT path, directory, name FROM "`+table+`"`).Scan(&path, &directory, &name); err != nil { + t.Fatalf("%s: %v", table, err) + } + if path != want || directory+"/"+name != want { + t.Errorf("%s row is %q (%q, %q), want %q", table, path, directory, name, want) + } + } + var kvRows int + if err := store.DB.QueryRow(`SELECT count(*) FROM "` + kvTable + `"`).Scan(&kvRows); err != nil || kvRows != 1 { + t.Fatalf("%s holds %d rows, %v", kvTable, kvRows, err) + } +} + +func TestRefusesAnotherLayout(t *testing.T) { + db := store_test.NewPostgresTestDatabase(t) + old := &abstract_sql.AbstractSqlStore{} + if err := (postgres.Connection{DSNOptions: db}).Open(old); err != nil { + t.Fatal(err) + } + defer old.Shutdown() + if _, err := old.DB.Exec(strings.ReplaceAll(postgres.DefaultCreateTableQuery, "%s", abstract_sql.DEFAULT_TABLE)); err != nil { + t.Fatal(err) + } + store := &PostgresFlatStore{} + err := store.initialize("", "", true, postgres.Connection{DSNOptions: db}) + if err == nil || !strings.Contains(err.Error(), "no path column") { + t.Fatalf("initialize over a postgres2 table: %v", err) + } + store.Shutdown() +} + +// TestFindsTheTableAlongTheSearchPath keeps the tables in the second of two +// schemas: the store's queries reach them there, and so must the layout check. +func TestFindsTheTableAlongTheSearchPath(t *testing.T) { + tables := store_test.NewPostgresTestDatabase(t) + newTestStore(t, tables) + opts := tables + opts.Schema = store_test.NewPostgresTestDatabase(t).Schema + "," + tables.Schema + store := &PostgresFlatStore{} + if err := store.initialize("false", "", true, postgres.Connection{DSNOptions: opts}); err != nil { + t.Fatalf("initialize without DDL, tables second on the search path: %v", err) + } + defer store.Shutdown() + ctx := context.Background() + entry := &filer.Entry{FullPath: util.FullPath("/dir/k"), Attr: filer.Attr{Mode: 0644}} + if err := store.InsertEntry(ctx, entry); err != nil { + t.Fatal(err) + } + if _, err := store.FindEntry(ctx, entry.FullPath); err != nil { + t.Fatal(err) + } +} + +// TestChecksTheOrderOfTheTableAlongTheSearchPath keeps byte-ordered tables in +// the second of two schemas of a locale-ordered database: the ordering check +// must read those columns, not fall back to the database's order. +func TestChecksTheOrderOfTheTableAlongTheSearchPath(t *testing.T) { + tables := store_test.NewPostgresTestDatabase(t) + first := newTestStore(t, tables) + var dbCollate string + if err := first.DB.QueryRow(`SELECT datcollate FROM pg_database WHERE datname = current_database()`).Scan(&dbCollate); err != nil { + t.Fatal(err) + } + if strings.HasPrefix(strings.ToLower(dbCollate), "c") || strings.EqualFold(dbCollate, "posix") { + t.Skipf("database collation %q is byte-ordered already", dbCollate) + } + opts := tables + opts.Schema = store_test.NewPostgresTestDatabase(t).Schema + "," + tables.Schema + store := &PostgresFlatStore{} + if err := store.initialize("false", "", true, postgres.Connection{DSNOptions: opts}); err != nil { + t.Fatal(err) + } + defer store.Shutdown() + if store.SqlGenerator.(*postgres.SqlGenPostgresFlat).ForceBinaryCollation { + t.Fatalf("the tables' columns are COLLATE \"C\", but listings sort as if they followed the database's %q", dbCollate) + } +} + +func TestRefusesAMissingTableWithoutDDL(t *testing.T) { + store := &PostgresFlatStore{} + err := store.initialize("false", "", true, postgres.Connection{DSNOptions: store_test.NewPostgresTestDatabase(t)}) + if err == nil || !strings.Contains(err.Error(), "does not exist") { + t.Fatalf("initialize without DDL on an empty schema: %v", err) + } + store.Shutdown() +} + +func TestLocalePathColumnListsInByteOrder(t *testing.T) { + store := &PostgresFlatStore{} + createTable := `CREATE TABLE IF NOT EXISTS "%s" (path TEXT PRIMARY KEY, directory TEXT NOT NULL, name TEXT NOT NULL, meta bytea)` + conn := postgres.Connection{DSNOptions: store_test.NewPostgresTestDatabase(t), MaxIdle: 10, MaxLifetimeSeconds: 60} + if err := store.initialize(createTable, "", true, conn); err != nil { + t.Fatal(err) + } + t.Cleanup(store.Shutdown) + store_test.TestFilerStoreConformance(t, store) +} + +// TestListsChildrenBetweenSubtrees lists directories whose children sort +// between the rows of their siblings' subtrees, as versioned objects do. +func TestListsChildrenBetweenSubtrees(t *testing.T) { + store := newTestStore(t, store_test.NewPostgresTestDatabase(t)) + ctx := context.Background() + store.OnBucketCreation("bkt") + children := map[string][]string{} + add := func(p string) { + if err := store.InsertEntry(ctx, &filer.Entry{FullPath: util.FullPath(p), Attr: filer.Attr{Mode: 0644}}); err != nil { + t.Fatal(err) + } + dir, name := util.FullPath(p).DirAndName() + children[dir] = append(children[dir], name) + } + for _, dir := range []string{"/d", "/buckets/bkt", "/buckets/bkt/k"} { + for _, name := range []string{"a", "a-b", "a0", "big", "deep", "f1", "f2", "obj.versions", "obj", "z"} { + add(dir + "/" + name) + } + for i := 0; i < 3; i++ { + add(fmt.Sprintf("%s/a/x%d", dir, i)) + add(fmt.Sprintf("%s/obj.versions/v%d", dir, i)) + } + for i := 0; i < 40; i++ { + add(fmt.Sprintf("%s/big/f%02d", dir, i)) + } + add(dir + "/deep/x") + add(dir + "/deep/x/y") + add(dir + "/deep/x/y/z") + } + for dir := range children { + sort.Strings(children[dir]) + } + + list := func(dir, start string, inclusive bool, limit int64, prefix string) (names []string) { + _, err := store.ListDirectoryPrefixedEntries(ctx, util.FullPath(dir), start, inclusive, limit, prefix, func(entry *filer.Entry) (bool, error) { + names = append(names, entry.Name()) + return true, nil + }) + if err != nil { + t.Fatal(err) + } + return names + } + want := func(dir, start string, inclusive bool, limit int64, prefix string) (names []string) { + for _, name := range children[dir] { + if (name > start || inclusive && name == start) && strings.HasPrefix(name, prefix) && int64(len(names)) <= limit { + names = append(names, name) + } + } + return names + } + for _, batches := range [][3]int{{1, 4, 3}, {2, 3, 1}, {8, 4096, 64}} { + prevMin, prevMax, prevSkip := abstract_sql.SetPathListBatchesForTest(int64(batches[0]), int64(batches[1]), batches[2]) + for _, dir := range []string{"/d", "/d/big", "/d/deep", "/buckets/bkt", "/buckets/bkt/k", "/buckets/bkt/obj.versions", "/"} { + for _, start := range []string{"", "a", "a-b", "big", "obj", "obj.versions", "zz"} { + for _, prefix := range []string{"", "a", "obj", "f"} { + for _, limit := range []int64{0, 1, 2, 5, 1000} { + for _, inclusive := range []bool{false, true} { + got, expected := list(dir, start, inclusive, limit, prefix), want(dir, start, inclusive, limit, prefix) + if strings.Join(got, ",") != strings.Join(expected, ",") { + t.Fatalf("batches %v: list %s from %q (inclusive %v) prefix %q limit %d = %v, want %v", batches, dir, start, inclusive, prefix, limit, got, expected) + } + } + } + } + } + } + abstract_sql.SetPathListBatchesForTest(prevMin, prevMax, prevSkip) + } + + // Within a transaction the callback may query on the listing's connection. + txCtx, err := store.BeginTransaction(ctx) + if err != nil { + t.Fatal(err) + } + defer store.RollbackTransaction(txCtx) + var names []string + if _, err = store.ListDirectoryEntries(txCtx, "/d", "", false, 100, func(entry *filer.Entry) (bool, error) { + if _, err := store.FindEntry(txCtx, entry.FullPath); err != nil { + return false, err + } + names = append(names, entry.Name()) + return true, nil + }); err != nil { + t.Fatal(err) + } + if strings.Join(names, ",") != strings.Join(children["/d"], ",") { + t.Fatalf("list in a transaction = %v, want %v", names, children["/d"]) + } +} + +func TestDeleteFolderChildrenKeepsTheRestOfTheRange(t *testing.T) { + store := newTestStore(t, store_test.NewPostgresTestDatabase(t)) + ctx := context.Background() + paths := []string{"/a", "/a-b", "/a/x", "/a/y", "/a/y/z", "/a0", "/top"} + for _, p := range paths { + if err := store.InsertEntry(ctx, &filer.Entry{FullPath: util.FullPath(p), Attr: filer.Attr{Mode: 0644}}); err != nil { + t.Fatal(err) + } + } + if err := store.DeleteFolderChildren(ctx, "/a"); err != nil { + t.Fatal(err) + } + if err := store.DeleteFolderChildren(ctx, "/"); err != nil { + t.Fatal(err) + } + for _, p := range paths { + _, err := store.FindEntry(ctx, util.FullPath(p)) + if kept := p == "/a/y/z"; kept != (err == nil) { + t.Errorf("%s: kept %v, find error %v", p, kept, err) + } + } +} + +func TestTableHasOnlyThePathIndex(t *testing.T) { + store := newTestStore(t, store_test.NewPostgresTestDatabase(t)) + store.OnBucketCreation("bkt") + if err := store.InsertEntry(context.Background(), &filer.Entry{FullPath: "/buckets/bkt/k"}); err != nil { + t.Fatal(err) + } + for _, table := range []string{abstract_sql.DEFAULT_TABLE, "bkt"} { + var indexes int + if err := store.DB.QueryRow(`SELECT count(*) FROM pg_index WHERE indrelid = to_regclass($1)`, table).Scan(&indexes); err != nil || indexes != 1 { + t.Fatalf("%s has %d indexes, %v", table, indexes, err) + } + } +} + +// TestScanFindsEveryBucketTable scans from a store whose bucket cache is +// empty, so every bucket table must come from listing /buckets. +func TestScanFindsEveryBucketTable(t *testing.T) { + db := store_test.NewPostgresTestDatabase(t) + writer := newTestStore(t, db) + ctx := context.Background() + insert := func(p string, mode os.FileMode) { + if err := writer.InsertEntry(ctx, &filer.Entry{FullPath: util.FullPath(p), Attr: filer.Attr{Mode: mode}}); err != nil { + t.Fatal(err) + } + } + var want []string + for _, bucket := range []string{"abc", "abc-d", "abc.d", "abc0", "abcd", "abd"} { + writer.OnBucketCreation(bucket) + insert("/buckets/"+bucket, os.ModeDir|0755) + insert("/buckets/"+bucket+"/obj", 0644) + want = append(want, "/buckets/"+bucket, "/buckets/"+bucket+"/obj") + } + insert("/buckets/.system/x", 0644) + insert("/bucketsx", 0644) + want = append(want, "/buckets/.system/x", "/bucketsx") + + defer abstract_sql.SetScanPageSizeForTest(abstract_sql.SetScanPageSizeForTest(2)) + reader := newTestStore(t, db) + var got []string + if err := reader.ScanEntries(ctx, "/", func(ctx context.Context, entry *filer.Entry) error { + got = append(got, string(entry.FullPath)) + return nil + }); err != nil { + t.Fatal(err) + } + sort.Strings(got) + sort.Strings(want) + if fmt.Sprint(got) != fmt.Sprint(want) { + t.Fatalf("scan found %v, want %v", got, want) + } +} diff --git a/weed/server/filer_server.go b/weed/server/filer_server.go index e1052f0250..e30adc1194 100644 --- a/weed/server/filer_server.go +++ b/weed/server/filer_server.go @@ -45,6 +45,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/filer/posixlock" _ "github.com/seaweedfs/seaweedfs/weed/filer/postgres" _ "github.com/seaweedfs/seaweedfs/weed/filer/postgres2" + _ "github.com/seaweedfs/seaweedfs/weed/filer/postgres_flat" _ "github.com/seaweedfs/seaweedfs/weed/filer/redis" _ "github.com/seaweedfs/seaweedfs/weed/filer/redis2" _ "github.com/seaweedfs/seaweedfs/weed/filer/redis3"