Files
base/migrations/1778828400_normalize_indexes.go
zeekay d9f7c4da8e the storage tier can address the backend it selects
BASE_DB_TIER=sql opened PostgreSQL and then spoke to it in SQLite: strftime,
sqlite_master, json_extract, json_each, an INTEGER column holding an int64, an
outer join with no ON, backticked identifiers, and a rowid that only one engine
has. The tier picked a backend the queries could not reach.

Every one of those now comes from hanzoai/orm/dialect, resolved once from the
driver the data DB was opened with and reachable as app.Dialect(). Base holds no
switch on the engine — it asks for the JSON accessors, the schema catalog, the
generated instant and identifier, and the column types, and it asks whether a
feature exists at all where one engine has nothing to offer: an insertion-order
column, a write-ahead log to fold, a function that renders an instant. Empty
means the caller falls back or refuses rather than emitting something the engine
will reject.

Some differences turned out not to need a dialect at all. An instant is stored
as text in a fixed layout, so bucketing the log rollup to the hour is a
substring rather than a calendar function, which every engine spells the same
way and an index can be built on. Null-safe equality is IS NOT DISTINCT FROM.
An int64 column is BIGINT. A join with nothing of its own to match still states
a condition. Case-insensitive comparison stays COLLATE NOCASE, because the
schema now asks the engine for the collation that name refers to.

The proof is a Postgres 18 running the data plane: migrations apply, a
collection created over /v1 lands as a table with text, numeric and jsonb
columns and its declared index, and records insert, page, sort, filter across
scalars, multi-value elements and JSON paths, update and delete. A unique index
declared COLLATE NOCASE rejects the second spelling of a handle.

Comparing a JSON sub-path to a number is refused there: the extraction yields
text, the literal binds as a number, and the filter language does not say which
the comparison meant. Compared as text it works.
2026-08-11 10:39:19 -07:00

121 lines
3.4 KiB
Go

package migrations
import (
"fmt"
"strings"
"github.com/hanzoai/base/core"
"github.com/hanzoai/base/tools/dbutils"
"github.com/hanzoai/dbx"
)
// see https://github.com/hanzoai/base/issues/7689
func init() {
core.SystemMigrations.Register(func(txApp core.App) error {
collections, err := txApp.FindAllCollections()
if err != nil {
return err
}
for _, collection := range collections {
// existing system collection indexes can't be modified and view don't have indexes
if collection.System || collection.IsView() {
continue
}
masterIndexes := []struct {
Name string `db:"name"`
SQL string `db:"sql"`
}{}
err := txApp.DB().Select("name", "sql").
From(txApp.Dialect().Catalog()).
AndWhere(dbx.HashExp{
"type": "index",
"tbl_name": collection.Name,
}).
AndWhere(dbx.NewExp("sql IS NOT NULL")).
All(&masterIndexes)
if err != nil {
return err
}
// no indexes
if len(masterIndexes) == 0 && len(collection.Indexes) == 0 {
continue
}
missingParsedIndexes := map[string]dbutils.Index{}
// find missing master indexes
masterLoop:
for _, masterIndex := range masterIndexes {
mParsed := dbutils.ParseIndex(masterIndex.SQL)
mParsed.SchemaName = ""
mParsed.TableName = collection.Name
for _, raw := range collection.Indexes {
cParsed := dbutils.ParseIndex(raw)
// index already exists (if needed it will be normalized on resave)
if cParsed.IndexName != "" && strings.EqualFold(cParsed.IndexName, mParsed.IndexName) {
continue masterLoop
}
}
missingParsedIndexes[masterIndex.Name] = mParsed
}
missingIndexesLoop:
for _, missing := range missingParsedIndexes {
missingSQL := missing.Build(txApp.Dialect())
// it shouldn't be possible but for just in case if there is an edge case the regex doesn't cover
if missingSQL == "" {
return fmt.Errorf("failed to build catalog index: %v", missing)
}
// drop the missing index to recreate later
_, err := txApp.DB().DropIndex(missing.TableName, missing.IndexName).Execute()
if err != nil {
return fmt.Errorf("failed to drop index %s: %w", missing.IndexName, err)
}
// no recreate: duplicated single unique tokenKey or email
// (auth collections are guaranteed to have them)
if collection.IsAuth() && missing.Unique && len(missing.Columns) == 1 &&
(strings.EqualFold(missing.Columns[0].Name, core.FieldNameTokenKey) || strings.EqualFold(missing.Columns[0].Name, core.FieldNameEmail)) {
continue missingIndexesLoop
}
// no recreate: the same index definition alreay exists
// in the collection but with different name
for _, raw := range collection.Indexes {
cParsed := dbutils.ParseIndex(raw)
cParsed.IndexName = missing.IndexName
cParsed.SchemaName = missing.SchemaName
cParsed.TableName = missing.TableName
cSQL := cParsed.Build(txApp.Dialect())
if missingSQL == cSQL {
continue missingIndexesLoop
}
}
// recreate: add the missing index to the collection list and
// leave the user to decide whether they want to keep it or not
// (the index could have been previously created externally, e.g. via the sqlite3 cli)
collection.Indexes = append(collection.Indexes, missingSQL)
}
// resave to trigger indexes normalization
err = txApp.Save(collection)
if err != nil {
return err
}
}
return nil
}, nil)
}