Skip to content
Merged
22 changes: 22 additions & 0 deletions .changeset/33695-system-column-implicit-indexes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
---
'@objectstack/driver-sql': patch
'@objectstack/driver-turso': patch
---

feat(driver-sql, driver-turso): schema sync builds the `(created_at, id)` and `(owner_id)` indexes without a declaration

Clause-②: yes (widening)
Metadata-protocol: none

Schema sync now builds two indexes on system columns that no object has to declare:

- `(created_at, id)`, named `idx_<table>_created_at_id`, on every table that has both columns. This is the default list order, `created_at desc, id desc`. Without the index, every default-ordered page sorted all of its filtered rows. On PostgreSQL 16 with 1M rows, the admin list statement takes 1.3 ms instead of 317 ms.
- `(owner_id)`, named `idx_<table>_owner_id`, on an object whose fields include a single-valued `owner_id`. This is the column a private-OWD read filters on. An object with no `owner_id` gets no such index.

Both indexes are non-unique. They follow the #31882 rule for reference columns. If a declared index's key already starts with the same columns, it serves instead, and no second index is built. If an author declares the same key, it gets the same name, so the two converge. On an existing database, `os migrate plan` lists each missing index as a `safe` `create_index`. The next sync builds it, and on PostgreSQL it is built `CONCURRENTLY`. A second sync makes no changes. An existing table that has no `created_at` column gets no default-order index and no error line.

Turso's remote face (`libsql://`) now builds the full implicit set too: these two keys and the #31882 reference-column indexes. Until now it built only declared indexes, so the drift plan on a remote database showed a `create_index` for each implicit index after every sync.

On SQLite, the index does not speed up a default-ordered page yet. While the engine adds the empty controlled-by-parent chain to the query, the SQLite planner still sorts in a temporary B-tree. When the query has no chain, the same page takes 0.16 ms instead of 1.6 s at 1M rows.

Widening: `@objectstack/driver-sql` now exports `implicitReferenceIndexes` from its main entry. Its arguments take an optional `physicalColumns` set, and when one is given, a key over a column the table lacks is left out.
1 change: 1 addition & 0 deletions packages/drivers/driver-sql/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ export {
buildIndexName,
diffManagedIndexes,
expectedIndexes,
implicitReferenceIndexes,
isIndexDriftOp,
isInPlaceSchemaWork,
isRefusedSchemaWork,
Expand Down
76 changes: 69 additions & 7 deletions packages/drivers/driver-sql/src/schema-drift.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2297,11 +2297,53 @@ const IMPLICIT_INDEX_REFERENCE_TYPES: ReadonlySet<string> = new Set(['master_det
* The platform's own system column names. The injection pass puts
* `created_by` / `updated_by` / `owner_id` / `owning_business_unit_id` on
* nearly every object, and the tenant column has the registry-provisioned
* tenant index already, so none of them is implicitly indexed (#31882 seat
* ruling, scope B: their write cost is not paid for by a measured read).
* tenant index already, so none of them is implicitly indexed AS A REFERENCE
* (#31882 seat ruling, scope B: their write cost is not paid for by a measured
* read). Two system keys have that measured read now and are indexed by
* {@link IMPLICIT_SYSTEM_COLUMN_KEYS} instead.
*/
const SYSTEM_COLUMN_NAMES: ReadonlySet<string> = new Set<string>(Object.values(SystemFieldName));

/**
* The system-column keys schema sync indexes without a declaration (#33695).
* The maintainer's ruling 「两个都加」 supersedes scope B of the #31882 ruling
* for exactly these two keys, on a measured read each:
*
* - `(created_at, id)`: the default list order, `created_at desc, id desc`.
* Without it every default-ordered page sorts its whole filtered set. Both
* are builtin columns, so every table the driver creates carries them.
* - `(owner_id)`: the column a private-OWD read filters on. Only an object
* whose fields carry it gets one: the injection pass withholds `owner_id`
* from `sys_*`, `managedBy` objects and every ownership tier but `user`.
*
* Non-unique, no organization key part, named by {@link buildIndexName} like
* the reference indexes, so an author's own `{ fields: [...] }` over the same
* key converges on the same index.
*/
const IMPLICIT_SYSTEM_COLUMN_KEYS: ReadonlyArray<readonly string[]> = [
[SystemFieldName.CREATED_AT, SystemFieldName.ID],
[SystemFieldName.OWNER_ID],
];

/**
* Does this object carry every column of an {@link IMPLICIT_SYSTEM_COLUMN_KEYS}
* key? A builtin column always; any other only as a declared, single-valued
* field that stores a column. Never the tenant column.
*/
function carriesImplicitSystemKey(
key: readonly string[],
fields: Record<string, any>,
tenantField: string | null,
): boolean {
return key.every((column) => {
if (column === tenantField) return false;
if (BUILTIN_COLUMNS.has(column)) return true;
const field = fields?.[column];
if (field == null || !fieldHasColumn(field)) return false;
return !isMultiValueField({ type: String(field.type ?? ''), multiple: field.multiple === true });
});
}

/**
* Is this field a column the driver indexes without a declaration (#31882)?
* An authored, single-valued `master_detail` / `lookup` / `user` field: a read
Expand Down Expand Up @@ -2334,12 +2376,20 @@ export function isImplicitlyIndexedReference(name: string, field: any, tenantFie
* It joins the declared set in {@link declaredIndexSet}, so the boot sync
* creates it, `os migrate plan` reports it as `create_index` on a database
* that lacks it, and the orphan pass never proposes dropping it.
*
* [#33695] After the reference indexes come the system-column keys
* ({@link IMPLICIT_SYSTEM_COLUMN_KEYS}) the object carries, each unless a
* declared index's key already STARTS WITH that whole key. With
* `physicalColumns`, a key whose columns the table does not all have is left
* out: an existing table the sync adopted without a `created_at` column is
* never given an index it cannot build.
*/
function implicitReferenceIndexesOver(
table: string,
fields: Record<string, any>,
tenantField: string | null,
declared: ReadonlyArray<ExpectedIndex>,
physicalColumns?: ReadonlySet<string>,
): ExpectedIndex[] {
const leading = new Set(declared.map((i) => i.columns[0]));
const names = new Set(declared.map((i) => i.name));
Expand All @@ -2351,27 +2401,39 @@ function implicitReferenceIndexesOver(
names.add(name);
out.push({ name, columns: [column], unique: false });
}
for (const key of IMPLICIT_SYSTEM_COLUMN_KEYS) {
if (!carriesImplicitSystemKey(key, fields, tenantField)) continue;
if (physicalColumns && !key.every((c) => physicalColumns.has(c))) continue;
if (declared.some((i) => key.every((c, k) => i.columns[k] === c))) continue;
const name = buildIndexName(table, [...key], false);
if (names.has(name)) continue;
names.add(name);
out.push({ name, columns: [...key], unique: false });
}
return out;
}

/**
* The implicit reference indexes for one object, against its declared set
* (see {@link implicitReferenceIndexesOver}). The boot sync
* (`syncTableIndexes`) adds these to what it materializes.
* The implicit indexes for one object, against its declared set (see
* {@link implicitReferenceIndexesOver}): the reference indexes (#31882) and
* the system-column keys (#33695). The boot sync (`syncTableIndexes`) adds
* these to what it materializes, passing the table's `physicalColumns` so a
* key over a column the table lacks is never attempted.
*/
export function implicitReferenceIndexes(args: {
table: string;
fields: Record<string, any>;
tenantField: string | null;
declaredIndexes?: DeclaredIndexInput[];
physicalColumns?: ReadonlySet<string>;
}): ExpectedIndex[] {
const { table, fields, tenantField, declaredIndexes } = args;
const { table, fields, tenantField, declaredIndexes, physicalColumns } = args;
const declared = uniqueIndexesFromFields(table, fields, tenantField);
for (const idx of Array.isArray(declaredIndexes) ? declaredIndexes : []) {
const norm = normalizeDeclaredIndex(table, idx, tenantField);
if (norm) declared.push(norm);
}
return implicitReferenceIndexesOver(table, fields, tenantField, declared);
return implicitReferenceIndexesOver(table, fields, tenantField, declared, physicalColumns);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,9 @@ describe('#11321 SQLite builtin audit columns take the canonical NOW() default',
`"when" datetime default (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')), ` +
`primary key ("id"))`,
);
// [#33695] The default-order index the first sync of this release builds,
// so the drift read below is about the audit DEFAULTS alone.
await raw.raw(`create index "idx_legacy_t_created_at_id" on "legacy_t" ("created_at", "id")`);

// Introspection DOES surface the legacy default — so a green below is
// drift declining to compare it, not drift failing to see it.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,11 @@ describe('diffUnbuildableIndexes — only a column that will NEVER materialize (
{ fields: ['code'] },
];
const args = { table: T, fields, tenantField: null, declaredIndexes, physicalColumns: physical('status') };
expect(expectedIndexes(args).map((i) => i.name)).toEqual([buildIndexName(T, ['status'], true)]);
expect(expectedIndexes(args).map((i) => i.name)).toEqual([
buildIndexName(T, ['status'], true),
// [#33695] The implicit default-order key: both builtin columns are physical.
buildIndexName(T, ['created_at', 'id'], false),
]);
expect(ops(diffUnbuildableIndexes(args)).map((o) => o.indexName)).toEqual([
buildIndexName(T, ['statsu'], true),
buildIndexName(T, ['doubled'], false),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,13 @@
* `idx_<table>_<column>` (the name an author's own `{ fields: [column] }`
* produces), unless a declared index already leads with that column. System
* columns (`created_by`, `updated_by`, `owner_id`, `owning_business_unit_id`,
* the tenant column) and multi-valued (JSON) columns are skipped.
* the tenant column) and multi-valued (JSON) columns are skipped AS
* REFERENCES.
*
* #33695 (maintainer ruling 「两个都加」) adds two system-column keys to the
* same implicit set: `(created_at, id)`, the default list order, and
* `(owner_id)`, the column a private-OWD read filters on. Their pins live in
* `sql-driver-33695-system-column-indexes.test.ts`.
*/

import { describe, it, expect, afterEach, beforeEach, vi } from 'vitest';
Expand Down Expand Up @@ -75,12 +81,15 @@ describe('the expected index set (#31882)', () => {
{ name: implicitName('project'), columns: ['project'], unique: false },
{ name: implicitName('task'), columns: ['task'], unique: false },
{ name: implicitName('member'), columns: ['member'], unique: false },
// #33695: the system-column key `owner_id` follows the reference indexes.
{ name: implicitName('owner_id'), columns: ['owner_id'], unique: false },
]);
});

it('skips multi-valued references and the system columns', () => {
const names = expectedFor(detailObject()).map((i) => i.name);
for (const column of ['watchers', 'tags', 'created_by', 'updated_by', 'owner_id', 'owning_business_unit_id']) {
// `owner_id` is indexed since #33695, as a system-column key, not as a reference.
for (const column of ['watchers', 'tags', 'created_by', 'updated_by', 'owning_business_unit_id']) {
expect(names, column).not.toContain(implicitName(column));
}
// The tenant column's one index is the provisioned declaration, not a second implicit one.
Expand Down Expand Up @@ -183,7 +192,8 @@ describe('the boot sync on an existing database (#31882, SQLite)', () => {
it('builds no index on a multi-valued reference or a system column', async () => {
await driver.initObjects([detailObject() as any]);
const names = await indexNames();
for (const column of ['watchers', 'tags', 'created_by', 'updated_by', 'owner_id', 'owning_business_unit_id']) {
// `owner_id` is indexed since #33695, as a system-column key, not as a reference.
for (const column of ['watchers', 'tags', 'created_by', 'updated_by', 'owning_business_unit_id']) {
expect(names, column).not.toContain(implicitName(column));
}
});
Expand Down
Loading
Loading