diff --git a/.changeset/33695-system-column-implicit-indexes.md b/.changeset/33695-system-column-implicit-indexes.md
new file mode 100644
index 00000000000..0982ca0aaba
--- /dev/null
+++ b/.changeset/33695-system-column-implicit-indexes.md
@@ -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_
_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__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.
diff --git a/packages/drivers/driver-sql/src/index.ts b/packages/drivers/driver-sql/src/index.ts
index 5da5f276c5c..78aa5d325f0 100644
--- a/packages/drivers/driver-sql/src/index.ts
+++ b/packages/drivers/driver-sql/src/index.ts
@@ -123,6 +123,7 @@ export {
buildIndexName,
diffManagedIndexes,
expectedIndexes,
+ implicitReferenceIndexes,
isIndexDriftOp,
isInPlaceSchemaWork,
isRefusedSchemaWork,
diff --git a/packages/drivers/driver-sql/src/schema-drift.ts b/packages/drivers/driver-sql/src/schema-drift.ts
index 027b769b74f..5580379a24b 100644
--- a/packages/drivers/driver-sql/src/schema-drift.ts
+++ b/packages/drivers/driver-sql/src/schema-drift.ts
@@ -2297,11 +2297,53 @@ const IMPLICIT_INDEX_REFERENCE_TYPES: ReadonlySet = 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 = new Set(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 = [
+ [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,
+ 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
@@ -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,
tenantField: string | null,
declared: ReadonlyArray,
+ physicalColumns?: ReadonlySet,
): ExpectedIndex[] {
const leading = new Set(declared.map((i) => i.columns[0]));
const names = new Set(declared.map((i) => i.name));
@@ -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;
tenantField: string | null;
declaredIndexes?: DeclaredIndexInput[];
+ physicalColumns?: ReadonlySet;
}): 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);
}
/**
diff --git a/packages/drivers/driver-sql/src/sql-driver-11321-sqlite-audit-default-canonical.test.ts b/packages/drivers/driver-sql/src/sql-driver-11321-sqlite-audit-default-canonical.test.ts
index 1a46a1b7709..b8db034ca4f 100644
--- a/packages/drivers/driver-sql/src/sql-driver-11321-sqlite-audit-default-canonical.test.ts
+++ b/packages/drivers/driver-sql/src/sql-driver-11321-sqlite-audit-default-canonical.test.ts
@@ -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.
diff --git a/packages/drivers/driver-sql/src/sql-driver-20432-unbuildable-declared-index.test.ts b/packages/drivers/driver-sql/src/sql-driver-20432-unbuildable-declared-index.test.ts
index c83530cc1bb..e16292c95a5 100644
--- a/packages/drivers/driver-sql/src/sql-driver-20432-unbuildable-declared-index.test.ts
+++ b/packages/drivers/driver-sql/src/sql-driver-20432-unbuildable-declared-index.test.ts
@@ -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),
diff --git a/packages/drivers/driver-sql/src/sql-driver-31882-reference-index-dialects.test.ts b/packages/drivers/driver-sql/src/sql-driver-31882-reference-index-dialects.test.ts
index dc3045887e9..f16dc4a42ca 100644
--- a/packages/drivers/driver-sql/src/sql-driver-31882-reference-index-dialects.test.ts
+++ b/packages/drivers/driver-sql/src/sql-driver-31882-reference-index-dialects.test.ts
@@ -17,7 +17,13 @@
* `idx__` (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';
@@ -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.
@@ -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));
}
});
diff --git a/packages/drivers/driver-sql/src/sql-driver-33695-system-column-indexes.test.ts b/packages/drivers/driver-sql/src/sql-driver-33695-system-column-indexes.test.ts
new file mode 100644
index 00000000000..a2dfb4be177
--- /dev/null
+++ b/packages/drivers/driver-sql/src/sql-driver-33695-system-column-indexes.test.ts
@@ -0,0 +1,278 @@
+// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
+
+/**
+ * Schema sync indexes two system-column keys without a declaration (#33695,
+ * maintainer ruling 「两个都加」, superseding scope B of the #31882 ruling for
+ * these two keys):
+ *
+ * - `(created_at, id)`: the default list order, `created_at desc, id desc`.
+ * Without it a default-ordered page sorts its whole filtered set
+ * (PostgreSQL 16, 1M rows: the admin page statement 317 ms before, 1.3 ms
+ * with the index).
+ * - `(owner_id)`: the column a private-OWD read filters on, on an object
+ * whose fields carry it.
+ *
+ * The keys join the implicit set the #31882 reference indexes started
+ * (`sql-driver-31882-reference-index-dialects.test.ts`), so the boot sync
+ * builds them, the drift differ expects them and a second sync is silent.
+ */
+
+import { describe, it, expect, afterEach, beforeEach, vi } from 'vitest';
+import { SqlDriver, expectedIndexes } from '../src/index.js';
+import { diffUnbuildableIndexes } from './schema-drift.js';
+import { declareDialectCell, dialectCell, PG_CELL, type DialectCell } from './live-dialect-matrix.testkit.js';
+
+const OWNED = 'os33695_deal';
+const UNOWNED = 'os33695_catalog';
+
+/** An object the injection pass gave an owner: `owner_id` is a declared field. */
+const ownedObject = (declared: any[] = []) => ({
+ name: OWNED,
+ fields: {
+ name: { type: 'text' },
+ amount: { type: 'number' },
+ owner_id: { type: 'lookup', reference: 'sys_user' },
+ },
+ ...(declared.length > 0 ? { indexes: declared } : {}),
+});
+
+/** No owner, no reference, no unique, no declared index: only the default-order key applies. */
+const unownedObject = () => ({ name: UNOWNED, fields: { name: { type: 'text' }, code: { type: 'number' } } });
+
+const defaultOrderIndex = (table: string) => `idx_${table}_created_at_id`;
+const ownerIndex = (table: string) => `idx_${table}_owner_id`;
+
+const expectedOver = (obj: { name: string; fields: Record; indexes?: any[] }, physical?: string[]) =>
+ expectedIndexes({
+ table: obj.name,
+ fields: obj.fields,
+ tenantField: null,
+ declaredIndexes: obj.indexes,
+ physicalColumns: new Set(physical ?? ['id', 'created_at', 'updated_at', ...Object.keys(obj.fields)]),
+ });
+
+describe('the expected index set: system-column keys (#33695)', () => {
+ it('adds (created_at, id) and (owner_id) on an owned object, after the declared set', () => {
+ expect(expectedOver(ownedObject())).toEqual([
+ { name: defaultOrderIndex(OWNED), columns: ['created_at', 'id'], unique: false },
+ { name: ownerIndex(OWNED), columns: ['owner_id'], unique: false },
+ ]);
+ });
+
+ it('adds only (created_at, id) on an object without owner_id: no dangling owner index', () => {
+ expect(expectedOver(unownedObject())).toEqual([
+ { name: defaultOrderIndex(UNOWNED), columns: ['created_at', 'id'], unique: false },
+ ]);
+ });
+
+ it('a declared index whose key STARTS WITH the whole system key replaces it; one that only leads with created_at does not', () => {
+ const covered = expectedOver(ownedObject([{ fields: ['created_at', 'id', 'amount'] }, { fields: ['owner_id', 'amount'] }]));
+ expect(covered.map((i) => i.name)).toEqual([
+ `idx_${OWNED}_created_at_id_amount`,
+ `idx_${OWNED}_owner_id_amount`,
+ ]);
+ const partial = expectedOver(ownedObject([{ fields: ['created_at'] }, { fields: ['amount', 'owner_id'] }]));
+ expect(partial.map((i) => i.name)).toEqual([
+ `idx_${OWNED}_created_at`,
+ `idx_${OWNED}_amount_owner_id`,
+ defaultOrderIndex(OWNED),
+ ownerIndex(OWNED),
+ ]);
+ });
+
+ it('an author who declares the same key converges on the same name: one index, not two', () => {
+ const names = expectedOver(ownedObject([{ fields: ['created_at', 'id'] }, { fields: ['owner_id'] }])).map((i) => i.name);
+ expect(names).toEqual([defaultOrderIndex(OWNED), ownerIndex(OWNED)]);
+ });
+
+ it('skips a multi-valued or formula owner_id: neither stores one id', () => {
+ for (const owner of [{ type: 'user', multiple: true }, { type: 'formula', expression: 'name' }]) {
+ const obj = { ...ownedObject(), fields: { ...ownedObject().fields, owner_id: owner } };
+ expect(expectedOver(obj).map((i) => i.name), JSON.stringify(owner)).not.toContain(ownerIndex(OWNED));
+ }
+ });
+
+ it('a table without a created_at column expects no default-order index, and reports nothing unbuildable', () => {
+ const obj = unownedObject();
+ const physical = ['id', ...Object.keys(obj.fields)];
+ expect(expectedOver(obj, physical)).toEqual([]);
+ expect(
+ diffUnbuildableIndexes({ table: obj.name, fields: obj.fields, tenantField: null, physicalColumns: new Set(physical) }),
+ ).toEqual([]);
+ });
+});
+
+describe('the boot sync builds the system-column keys (#33695, SQLite)', () => {
+ let driver: SqlDriver;
+ let knex: any;
+ let ddl: string[];
+ let errors: ReturnType;
+
+ beforeEach(async () => {
+ driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true });
+ knex = (driver as any).knex;
+ errors = vi.fn();
+ (driver as any).logger = { warn: vi.fn(), info: vi.fn(), debug: vi.fn(), error: errors };
+ ddl = [];
+ knex.on('query', (q: any) => {
+ if (/^\s*(create|alter|drop)\b/i.test(q.sql)) ddl.push(q.sql);
+ });
+ });
+
+ afterEach(async () => {
+ await driver.disconnect();
+ });
+
+ const indexesOn = async (table: string): Promise> => {
+ const out: Record = {};
+ for (const r of await knex.raw(`select name from pragma_index_list(?)`, [table])) {
+ if (String(r.name).startsWith('sqlite_autoindex_')) continue;
+ out[r.name] = (await knex.raw(`select name from pragma_index_info(?) order by seqno`, [r.name])).map((c: any) => c.name);
+ }
+ return out;
+ };
+
+ it('a new table gets both keys; an object with nothing else to index still gets (created_at, id)', async () => {
+ await driver.initObjects([ownedObject() as any, unownedObject() as any]);
+ expect(await indexesOn(OWNED)).toEqual({
+ [defaultOrderIndex(OWNED)]: ['created_at', 'id'],
+ [ownerIndex(OWNED)]: ['owner_id'],
+ });
+ expect(await indexesOn(UNOWNED)).toEqual({ [defaultOrderIndex(UNOWNED)]: ['created_at', 'id'] });
+ expect(errors).not.toHaveBeenCalled();
+ expect(await driver.detectManagedDrift()).toEqual([]);
+ });
+
+ it('an earlier release\'s table is planned as safe create_index, gains both on the next sync, and a third sync does nothing', async () => {
+ await driver.initObjects([ownedObject() as any, unownedObject() as any]);
+ for (const name of [defaultOrderIndex(OWNED), ownerIndex(OWNED), defaultOrderIndex(UNOWNED)]) {
+ await knex.raw(`drop index ${name}`);
+ }
+
+ const plan = await driver.detectManagedDrift();
+ expect(
+ plan.map((d) => [d.op.type, (d.op as any).indexName, (d.op as any).columns, d.category]).sort(),
+ ).toEqual(
+ [
+ ['create_index', defaultOrderIndex(OWNED), ['created_at', 'id'], 'safe'],
+ ['create_index', ownerIndex(OWNED), ['owner_id'], 'safe'],
+ ['create_index', defaultOrderIndex(UNOWNED), ['created_at', 'id'], 'safe'],
+ ].sort(),
+ );
+
+ ddl.length = 0;
+ await driver.initObjects([ownedObject() as any, unownedObject() as any]);
+ expect(ddl.filter((s) => /create index/i.test(s))).toHaveLength(3);
+ expect(await driver.detectManagedDrift()).toEqual([]);
+
+ ddl.length = 0;
+ await driver.initObjects([ownedObject() as any, unownedObject() as any]);
+ expect(ddl).toEqual([]);
+ });
+
+ it('an adopted table with no created_at column: no index attempted, no error line, no drift loop', async () => {
+ await knex.schema.createTable(UNOWNED, (t: any) => {
+ t.string('id').primary();
+ t.string('name');
+ t.float('code');
+ });
+ ddl.length = 0;
+ await driver.initObjects([unownedObject() as any]);
+ expect(ddl.filter((s) => /create index/i.test(s))).toEqual([]);
+ expect(errors).not.toHaveBeenCalled();
+ expect((await driver.detectManagedDrift()).filter((d) => /index/.test(d.op.type))).toEqual([]);
+ });
+});
+
+/** The default-ordered page and the owner read plan as index reads on the implicit keys. */
+function declareSystemKeyPlans(cell: DialectCell): void {
+ describe(`system-column keys serve their reads — ${cell.label} (#33695)`, () => {
+ let driver: SqlDriver;
+
+ beforeEach(async () => {
+ driver = new SqlDriver({ ...cell.config(), pool: { min: 1, max: 1 } } as any);
+ (driver as any).logger = { warn: vi.fn(), info: vi.fn(), debug: vi.fn(), error: vi.fn() };
+ await driver.execute(`drop table if exists ${OWNED}`).catch(() => {});
+ await driver.initObjects([ownedObject() as any]);
+ const rows = [];
+ for (let i = 0; i < 400; i++) {
+ rows.push({ id: `d_${String(i).padStart(4, '0')}`, name: `Deal ${i}`, amount: i, owner_id: `u_${i % 40}` });
+ }
+ await (driver as any).knex.batchInsert(OWNED, rows, 100);
+ await driver.execute(cell.id === 'pg' ? `analyze ${OWNED}` : 'analyze');
+ // PostgreSQL prefers a sequential scan on a table this small whatever
+ // indexes exist; with it off, the plan names the index it CAN use.
+ if (cell.id === 'pg') await driver.execute('set enable_seqscan = off');
+ });
+
+ afterEach(async () => {
+ await driver.execute(`drop table if exists ${OWNED}`).catch(() => {});
+ await driver.disconnect();
+ });
+
+ const planOf = async (query: Record) => {
+ const res = await driver.analyzeQuery(OWNED, { fields: ['id', 'name'], ...query } as any);
+ expect(res.error, res.error).toBeUndefined();
+ return JSON.stringify(cell.id === 'pg' ? res.plan.rows : res.plan);
+ };
+
+ it('the default-ordered page', async () => {
+ const plan = await planOf({
+ orderBy: [
+ { field: 'created_at', order: 'desc' },
+ { field: 'id', order: 'desc' },
+ ],
+ limit: 50,
+ });
+ expect(plan).toContain(defaultOrderIndex(OWNED));
+ });
+
+ it('the owner read', async () => {
+ expect(await planOf({ where: { owner_id: 'u_7' } })).toContain(ownerIndex(OWNED));
+ });
+ });
+}
+
+declareDialectCell(dialectCell('sqlite'), 'system-column key plans (#33695)', declareSystemKeyPlans);
+declareDialectCell(PG_CELL, 'system-column key plans (#33695)', declareSystemKeyPlans);
+
+/** An existing table gains both keys on the next sync (CONCURRENTLY on PostgreSQL, #31901), and the plan reads empty. */
+function declareExistingTableSync(cell: DialectCell): void {
+ describe(`an existing table gains the system-column keys — ${cell.label} (#33695)`, () => {
+ let driver: SqlDriver;
+
+ beforeEach(async () => {
+ driver = new SqlDriver(cell.config() as any);
+ (driver as any).logger = { warn: vi.fn(), info: vi.fn(), debug: vi.fn(), error: vi.fn() };
+ await driver.execute(`drop table if exists ${OWNED}`).catch(() => {});
+ });
+
+ afterEach(async () => {
+ await driver.execute(`drop table if exists ${OWNED}`).catch(() => {});
+ await driver.disconnect();
+ });
+
+ it('planned as safe create_index, built by the next sync, then silent', async () => {
+ await driver.initObjects([ownedObject() as any]);
+ for (const name of [defaultOrderIndex(OWNED), ownerIndex(OWNED)]) await driver.execute(`drop index ${name}`);
+
+ const plan = (await driver.detectManagedDrift([ownedObject() as any])).map((d) => [
+ d.op.type,
+ (d.op as any).indexName,
+ d.category,
+ ]);
+ expect(plan.sort()).toEqual(
+ [
+ ['create_index', defaultOrderIndex(OWNED), 'safe'],
+ ['create_index', ownerIndex(OWNED), 'safe'],
+ ].sort(),
+ );
+
+ await driver.initObjects([ownedObject() as any]);
+ expect(await driver.detectManagedDrift([ownedObject() as any])).toEqual([]);
+ expect((driver as any).logger.error).not.toHaveBeenCalled();
+ });
+ });
+}
+
+declareDialectCell(PG_CELL, 'existing-table system-column keys (#33695)', declareExistingTableSync);
diff --git a/packages/drivers/driver-sql/src/sql-driver-managed-drift.ts b/packages/drivers/driver-sql/src/sql-driver-managed-drift.ts
index a351edf5038..5a63d76dbc8 100644
--- a/packages/drivers/driver-sql/src/sql-driver-managed-drift.ts
+++ b/packages/drivers/driver-sql/src/sql-driver-managed-drift.ts
@@ -184,7 +184,7 @@ export class ManagedDriftFacet {
// [#31882] The implicit `(column)` index on each authored single-valued
// reference column, from the same composition the differ expects, so the
// boot sync and `os migrate plan` agree on what should exist.
- const implicit = implicitReferenceIndexes({ table: tableName, fields, tenantField, declaredIndexes: declared }).map(
+ const implicit = implicitReferenceIndexes({ table: tableName, fields, tenantField, declaredIndexes: declared, physicalColumns }).map(
(i) => ({ name: i.name, fields: i.columns, unique: false as const }),
);
if (fromFields.length === 0 && declared.length === 0 && implicit.length === 0) return;
diff --git a/packages/drivers/driver-sql/src/sql-driver-rotation.ts b/packages/drivers/driver-sql/src/sql-driver-rotation.ts
index af3904500b0..fac5f8345f9 100644
--- a/packages/drivers/driver-sql/src/sql-driver-rotation.ts
+++ b/packages/drivers/driver-sql/src/sql-driver-rotation.ts
@@ -37,7 +37,7 @@ import type { AutonumberToken } from '@objectstack/spec/data';
import { aggregandColumnClass } from '@objectstack/core';
import { StorageNameMapping, SystemObjectName } from '@objectstack/spec/system';
import { ExistingTableAdoptionRefusal } from './existing-table-refusal.js';
-import { indexedKeyColumns, isImplicitlyIndexedReference, isUniqueScopeDeclared } from './schema-drift.js';
+import { implicitReferenceIndexes, indexedKeyColumns, isUniqueScopeDeclared } from './schema-drift.js';
import {
AUDIT_TIMESTAMP_COLUMNS, MYSQL_DATETIME_PRECISION, NUMERIC_SCALAR_TYPES, declaredValueShapes,
isDeferredDdlLockWaitRefusal, isMultiValuedColumn, isNowDefaultValue,
@@ -619,12 +619,14 @@ export class RotationFacet {
const uniqueFields = Object.values(obj.fields ?? {}).some((f) =>
isUniqueScopeDeclared(f?.unique),
);
- // [#31882] An authored single-valued reference column is indexed without
- // a declaration, so it opens this path too.
- const referenceFields = Object.entries(obj.fields ?? {}).some(([name, f]) =>
- isImplicitlyIndexedReference(name, f, tenantField),
- );
- if (uniqueFields || referenceFields || (Array.isArray(declaredIndexes) && declaredIndexes.length > 0)) {
+ // [#31882 · #33695] The implicit indexes (an authored single-valued
+ // reference column, the `(created_at, id)` default order, `owner_id`) are
+ // built without a declaration, so they open this path too. The physical
+ // filter is `syncTableIndexes`' own: a key over a column this table lacks
+ // is left out there.
+ const implicitIndexes =
+ implicitReferenceIndexes({ table: tableName, fields: obj.fields ?? {}, tenantField, declaredIndexes }).length > 0;
+ if (uniqueFields || implicitIndexes || (Array.isArray(declaredIndexes) && declaredIndexes.length > 0)) {
const colInfo = await this.knex(tableName).columnInfo();
const physicalColumns = new Set(Object.keys(colInfo));
await this.syncTableIndexes(
diff --git a/packages/drivers/driver-sql/src/sql-driver-schema.test.ts b/packages/drivers/driver-sql/src/sql-driver-schema.test.ts
index 85bfc9e64fa..9e1904db422 100644
--- a/packages/drivers/driver-sql/src/sql-driver-schema.test.ts
+++ b/packages/drivers/driver-sql/src/sql-driver-schema.test.ts
@@ -347,7 +347,8 @@ describe('SqlDriver Schema Sync (SQLite)', () => {
// PRAGMA proves a non-PK unique index was actually created.
const list: any = await knexInstance.raw('PRAGMA index_list(idx_unique_obj)');
- const declared = list.filter((i: any) => !String(i.name).startsWith('sqlite_autoindex'));
+ // [#33695] Neither the PK autoindex nor the implicit `(created_at, id)` default-order index is declared.
+ const declared = list.filter((i: any) => !String(i.name).startsWith('sqlite_autoindex') && !String(i.name).endsWith('_created_at_id'));
expect(declared.length).toBe(1);
expect(declared[0].unique).toBe(1);
@@ -373,7 +374,8 @@ describe('SqlDriver Schema Sync (SQLite)', () => {
await driver.initObjects(objects);
const list: any = await knexInstance.raw('PRAGMA index_list(idx_multi_obj)');
- const declared = list.filter((i: any) => !String(i.name).startsWith('sqlite_autoindex'));
+ // [#33695] Neither the PK autoindex nor the implicit `(created_at, id)` default-order index is declared.
+ const declared = list.filter((i: any) => !String(i.name).startsWith('sqlite_autoindex') && !String(i.name).endsWith('_created_at_id'));
expect(declared.length).toBe(1);
expect(declared[0].unique).toBe(1);
@@ -423,7 +425,8 @@ describe('SqlDriver Schema Sync (SQLite)', () => {
await driver.initObjects(objects);
const list: any = await knexInstance.raw('PRAGMA index_list(idx_plain_obj)');
- const declared = list.filter((i: any) => !String(i.name).startsWith('sqlite_autoindex'));
+ // [#33695] Neither the PK autoindex nor the implicit `(created_at, id)` default-order index is declared.
+ const declared = list.filter((i: any) => !String(i.name).startsWith('sqlite_autoindex') && !String(i.name).endsWith('_created_at_id'));
expect(declared.length).toBe(1);
expect(declared[0].unique).toBe(0);
});
@@ -442,7 +445,8 @@ describe('SqlDriver Schema Sync (SQLite)', () => {
await driver.initObjects(objects);
const list: any = await knexInstance.raw('PRAGMA index_list(idx_idem_obj)');
- const declared = list.filter((i: any) => !String(i.name).startsWith('sqlite_autoindex'));
+ // [#33695] Neither the PK autoindex nor the implicit `(created_at, id)` default-order index is declared.
+ const declared = list.filter((i: any) => !String(i.name).startsWith('sqlite_autoindex') && !String(i.name).endsWith('_created_at_id'));
expect(declared.length).toBe(1);
});
@@ -465,7 +469,8 @@ describe('SqlDriver Schema Sync (SQLite)', () => {
await driver.initObjects(objects);
const list: any = await knexInstance.raw('PRAGMA index_list(idx_virtual_obj)');
- const declared = list.filter((i: any) => !String(i.name).startsWith('sqlite_autoindex'));
+ // [#33695] Neither the PK autoindex nor the implicit `(created_at, id)` default-order index is declared.
+ const declared = list.filter((i: any) => !String(i.name).startsWith('sqlite_autoindex') && !String(i.name).endsWith('_created_at_id'));
expect(declared.length).toBe(0);
expect(warnings.some((w) => w.includes('total'))).toBe(true);
});
diff --git a/packages/drivers/driver-turso/src/remote-transport.ts b/packages/drivers/driver-turso/src/remote-transport.ts
index db5f51895ab..c260a83aa25 100644
--- a/packages/drivers/driver-turso/src/remote-transport.ts
+++ b/packages/drivers/driver-turso/src/remote-transport.ts
@@ -80,9 +80,17 @@ import { isComposedReadableIds, type FilterCondition } from '@objectstack/spec/d
// (`normalizeDeclaredIndex`). Until then only the field-level half above was
// imported, so every object-level index — unique or not — had no consumer on
// this face and never reached a remote database at all.
+//
+// [#33695] …and the indexes the sync builds without a declaration (the #31882
+// reference columns, `(created_at, id)`, `owner_id`), through the composition
+// `SqlDriver.syncTableIndexes` and the drift differ read
+// (`implicitReferenceIndexes`). The drift differ runs over the remote face
+// too, so a remote sync that built fewer than it expects reported each one as
+// a `create_index` it never converged on.
import {
uniqueIndexesFromFields,
normalizeDeclaredIndex,
+ implicitReferenceIndexes,
organizationKeyPartSql,
type DeclaredIndexInput,
type ExpectedIndex,
@@ -2660,6 +2668,18 @@ export class RemoteTransport {
const normalized = normalizeDeclaredIndex(tableName, entry, tenantField);
if (normalized) expected.push(normalized);
}
+ // [#33695] The implicit set, after the declared one, as the local face's
+ // `syncTableIndexes` composes it. A key over a column this table lacks is
+ // left out by the composition itself, never reported as a skip below.
+ expected.push(
+ ...implicitReferenceIndexes({
+ table: tableName,
+ fields: objectDef.fields ?? {},
+ tenantField,
+ declaredIndexes: declared,
+ physicalColumns: materializedColumns,
+ }),
+ );
const planned: PlannedIndex[] = [];
const emitted = new Set();
diff --git a/packages/drivers/driver-turso/src/turso-33695-implicit-index-parity.test.ts b/packages/drivers/driver-turso/src/turso-33695-implicit-index-parity.test.ts
new file mode 100644
index 00000000000..7067d6cd223
--- /dev/null
+++ b/packages/drivers/driver-turso/src/turso-33695-implicit-index-parity.test.ts
@@ -0,0 +1,110 @@
+// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
+
+/**
+ * [#33695] The indexes the schema sync builds WITHOUT a declaration land on
+ * the remote face as on the local one: the #31882 reference columns,
+ * `(created_at, id)` (the default list order) and `(owner_id)` (the column a
+ * private-OWD read filters on).
+ *
+ * The local face composes them in `SqlDriver.syncTableIndexes`; the remote
+ * face (`RemoteTransport.buildDeclaredIndexDDL`) composed only the declared
+ * half. The drift differ runs over both faces and expects the whole set, so a
+ * remote sync that built fewer left a `create_index` behind every sync. Each
+ * pin compares what physically landed on the two faces, anchored by names
+ * from the shared `buildIndexName`: two faces that both lost the set would
+ * agree perfectly.
+ */
+
+import { describe, it, expect, afterEach } from 'vitest';
+import { createClient } from '@libsql/client';
+import { buildIndexName } from '@objectstack/driver-sql';
+import { TursoDriver } from './turso-driver.js';
+
+type ObjectDef = { name: string; fields: Record };
+type Row = Record;
+type Query = (sql: string) => Promise;
+
+const OWNED: ObjectDef = {
+ name: 'os33695_deal',
+ fields: {
+ name: { type: 'text' },
+ account: { type: 'lookup', reference: 'os33695_account' },
+ owner_id: { type: 'lookup', reference: 'sys_user' },
+ created_by: { type: 'lookup', reference: 'sys_user' },
+ },
+};
+const UNOWNED: ObjectDef = { name: 'os33695_catalog', fields: { name: { type: 'text' } } };
+
+/** Index name → key columns, the primary-key autoindex included. */
+const EXPECTED: Record> = {
+ [OWNED.name]: {
+ [buildIndexName(OWNED.name, ['account'], false)]: ['account'],
+ [buildIndexName(OWNED.name, ['created_at', 'id'], false)]: ['created_at', 'id'],
+ [buildIndexName(OWNED.name, ['owner_id'], false)]: ['owner_id'],
+ [`sqlite_autoindex_${OWNED.name}_1`]: ['id'],
+ },
+ [UNOWNED.name]: {
+ [buildIndexName(UNOWNED.name, ['created_at', 'id'], false)]: ['created_at', 'id'],
+ [`sqlite_autoindex_${UNOWNED.name}_1`]: ['id'],
+ },
+};
+
+/** A fresh copy per sync: neither face may see a definition the other one mutated. */
+const fresh = (o: ObjectDef): ObjectDef => ({
+ ...o,
+ fields: Object.fromEntries(Object.entries(o.fields).map(([k, v]) => [k, { ...v }])),
+});
+
+async function indexKeys(query: Query, table: string): Promise> {
+ const out: Record = {};
+ for (const row of await query(`PRAGMA index_list("${table}")`)) {
+ const name = String(row.name);
+ out[name] = (await query(`PRAGMA index_info("${name.replace(/"/g, '""')}")`))
+ .sort((a, b) => Number(a.seqno) - Number(b.seqno))
+ .map((k) => String(k.name));
+ }
+ return out;
+}
+
+const cleanups: Array<() => Promise> = [];
+afterEach(async () => {
+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup();
+});
+
+async function localFace(): Promise<{ driver: TursoDriver; query: Query }> {
+ const driver = new TursoDriver({ url: ':memory:' });
+ await driver.connect();
+ expect(driver.transportMode).toBe('local');
+ cleanups.push(() => driver.disconnect());
+ return { driver, query: async (sql) => (await driver.execute(sql, [])) as Row[] };
+}
+
+async function remoteFace(): Promise<{ driver: TursoDriver; query: Query }> {
+ const client = createClient({ url: 'file::memory:' });
+ const driver = new TursoDriver({ url: 'libsql://implicit-index-parity.turso.io', client });
+ await driver.connect();
+ expect(driver.transportMode).toBe('remote');
+ cleanups.push(() => driver.disconnect());
+ return { driver, query: async (sql) => (await client.execute(sql)).rows as unknown as Row[] };
+}
+
+describe('[#33695] the implicit index set lands identically on both TursoDriver faces', () => {
+ it('a fresh database: the same names and key parts on both faces, none on created_by', async () => {
+ const local = await localFace();
+ const remote = await remoteFace();
+ await local.driver.initObjects([fresh(OWNED), fresh(UNOWNED)] as never);
+ await remote.driver.initObjects([fresh(OWNED), fresh(UNOWNED)] as never);
+ for (const name of [OWNED.name, UNOWNED.name]) {
+ const localKeys = await indexKeys(local.query, name);
+ expect(await indexKeys(remote.query, name), name).toEqual(localKeys);
+ expect(localKeys, name).toEqual(EXPECTED[name]);
+ }
+ });
+
+ it('after a remote sync the remote plan proposes no index: no create_index left behind', async () => {
+ const remote = await remoteFace();
+ await remote.driver.initObjects([fresh(OWNED), fresh(UNOWNED)] as never);
+ const plan = await remote.driver.detectManagedDrift([fresh(OWNED), fresh(UNOWNED)] as never);
+ expect(plan.filter((d) => /index/.test(d.op.type)).map((d) => (d.op as { indexName?: string }).indexName)).toEqual([]);
+ });
+});
diff --git a/packages/drivers/driver-turso/src/turso-local-remote-declared-index-parity.test.ts b/packages/drivers/driver-turso/src/turso-local-remote-declared-index-parity.test.ts
index bf20fc638b6..3f77dc0d302 100644
--- a/packages/drivers/driver-turso/src/turso-local-remote-declared-index-parity.test.ts
+++ b/packages/drivers/driver-turso/src/turso-local-remote-declared-index-parity.test.ts
@@ -169,12 +169,16 @@ const EXPECTED_NAMES: Record = {
buildIndexName(DELIVERY.name, ['status', 'claimed_at'], false),
buildIndexName(DELIVERY.name, ['notification_id'], false),
buildIndexName(DELIVERY.name, ['digest_key', 'status', 'next_attempt_at'], false),
+ // [#33695] The default-order key every table carries, declared or not.
+ buildIndexName(DELIVERY.name, ['created_at', 'id'], false),
`sqlite_autoindex_${DELIVERY.name}_1`,
].sort(),
[JOB_QUEUE.name]: [
buildIndexName(JOB_QUEUE.name, ['queue', 'status', 'priority', 'scheduled_for'], false),
buildIndexName(JOB_QUEUE.name, ['idempotency_key', 'queue'], false),
buildIndexName(JOB_QUEUE.name, ['status'], false),
+ // [#33695] The default-order key every table carries, declared or not.
+ buildIndexName(JOB_QUEUE.name, ['created_at', 'id'], false),
`sqlite_autoindex_${JOB_QUEUE.name}_1`,
].sort(),
[SCOPED.name]: [
@@ -184,6 +188,8 @@ const EXPECTED_NAMES: Record = {
buildIndexName(SCOPED.name, ['region', 'slug'], false),
'os17609_scoped_by_region',
'os17609 scoped-by "slug"',
+ // [#33695] The default-order key every table carries, declared or not.
+ buildIndexName(SCOPED.name, ['created_at', 'id'], false),
`sqlite_autoindex_${SCOPED.name}_1`,
].sort(),
};
@@ -408,8 +414,12 @@ describe('[#17609] declared object-level indexes land identically on both TursoD
// The production state: tables the pre-fix remote face provisioned, holding rows.
await remote.driver.initObjects(OBJECTS.map(withoutDeclaredIndexes));
- expect(await indexNames(remote.query, DELIVERY.name)).toEqual([`sqlite_autoindex_${DELIVERY.name}_1`]);
- expect(await indexNames(remote.query, JOB_QUEUE.name)).toEqual([`sqlite_autoindex_${JOB_QUEUE.name}_1`]);
+ // [#33695] …but for the default-order key, which needs no declaration.
+ for (const o of [DELIVERY, JOB_QUEUE]) {
+ expect(await indexNames(remote.query, o.name)).toEqual(
+ [buildIndexName(o.name, ['created_at', 'id'], false), `sqlite_autoindex_${o.name}_1`].sort(),
+ );
+ }
for (let i = 0; i < 3; i++) {
await remote.driver.create(DELIVERY.name, {
notification_id: `n${i}`,
diff --git a/packages/drivers/driver-turso/src/turso-remote-deferred-ddl.test.ts b/packages/drivers/driver-turso/src/turso-remote-deferred-ddl.test.ts
index 713a851c318..3528a9e7a66 100644
--- a/packages/drivers/driver-turso/src/turso-remote-deferred-ddl.test.ts
+++ b/packages/drivers/driver-turso/src/turso-remote-deferred-ddl.test.ts
@@ -230,7 +230,10 @@ describe('lit control — remote ordinary boot sync (deferral NOT armed) still p
expect(rec.ddl()).toEqual([
expect.stringMatching(/^CREATE TABLE "fresh"/),
+ // [#33695] The implicit default-order index, on the new table and the existing one.
+ 'CREATE INDEX IF NOT EXISTS "idx_fresh_created_at_id" ON "fresh" ("created_at", "id")',
'ALTER TABLE "probe" ADD COLUMN "why" TEXT',
+ 'CREATE INDEX IF NOT EXISTS "idx_probe_created_at_id" ON "probe" ("created_at", "id")',
]);
expect(tablesOf(stub)).toEqual(['fresh', 'probe']);
expect(columnsOf(stub, 'probe')).toContain('why');
@@ -244,7 +247,11 @@ describe('lit control — remote ordinary boot sync (deferral NOT armed) still p
await driver.syncSchema('probe', PROBE);
- expect(rec.ddl()).toEqual(['ALTER TABLE "probe" ADD COLUMN "why" TEXT']);
+ expect(rec.ddl()).toEqual([
+ 'ALTER TABLE "probe" ADD COLUMN "why" TEXT',
+ // [#33695] The implicit default-order index the seeded table never had.
+ 'CREATE INDEX IF NOT EXISTS "idx_probe_created_at_id" ON "probe" ("created_at", "id")',
+ ]);
expect(rec.rowWrites().length).toBeGreaterThan(0);
expect(rec.rowWrites().every((s) => /^\s*update "probe" set "at"/i.test(s))).toBe(true);
expect(atOf(stub)).toBe('2025-07-28T00:00:00.000Z');
diff --git a/packages/drivers/driver-turso/src/turso-remote-drift-apply-limit.test.ts b/packages/drivers/driver-turso/src/turso-remote-drift-apply-limit.test.ts
index 845ab8e677a..4a23e9e4946 100644
--- a/packages/drivers/driver-turso/src/turso-remote-drift-apply-limit.test.ts
+++ b/packages/drivers/driver-turso/src/turso-remote-drift-apply-limit.test.ts
@@ -179,6 +179,8 @@ describe('a unique index its rows violate: a limit of the entry, declared on bot
async function seedDuplicates(file: string): Promise {
const setup = createClient({ url: `file:${file}` });
await setup.execute('CREATE TABLE "quote" ("id" TEXT PRIMARY KEY, "created_at" TEXT, "updated_at" TEXT, "code" TEXT)');
+ // [#33695] The implicit default-order index, so the one create_index left is the unique's.
+ await setup.execute('CREATE INDEX "idx_quote_created_at_id" ON "quote" ("created_at", "id")');
await setup.execute(`INSERT INTO "quote" ("id", "code") VALUES ('q1', 'Q-1'), ('q2', 'Q-1')`);
setup.close();
}
diff --git a/packages/drivers/driver-turso/src/turso-remote-migration-entries.test.ts b/packages/drivers/driver-turso/src/turso-remote-migration-entries.test.ts
index 10e98ac3813..fc3fc568252 100644
--- a/packages/drivers/driver-turso/src/turso-remote-migration-entries.test.ts
+++ b/packages/drivers/driver-turso/src/turso-remote-migration-entries.test.ts
@@ -120,13 +120,14 @@ async function withLegacyColumn(): Promise<{ file: string; remote: TursoDriver;
describe('drop_column', () => {
it('drops the column and every index keyed on it, keeping the rows', async () => {
const { file, remote, drop } = await withLegacyColumn();
- expect(Object.keys(await indexesOf(file, 't')).sort()).toEqual(['idx_t_legacy', 'idx_t_name_legacy']);
+ expect(Object.keys(await indexesOf(file, 't')).sort()).toEqual(['idx_t_created_at_id', 'idx_t_legacy', 'idx_t_name_legacy']);
const { applied, skipped } = await remote.applyMigrationEntries([drop], { allowDestructive: true });
expect([applied, skipped]).toEqual([[drop], []]);
expect(await columnsOf(file, 't')).not.toContain('legacy');
- expect(await indexesOf(file, 't')).toEqual({});
+ // [#33695] The implicit default-order index is keyed on no dropped column, so it stays.
+ expect(Object.keys(await indexesOf(file, 't'))).toEqual(['idx_t_created_at_id']);
expect(await secondConnection(file, 'SELECT id, name FROM "t" ORDER BY id')).toEqual([
{ id: 'a', name: 'A' },
{ id: 'b', name: 'B' },
@@ -139,7 +140,7 @@ describe('drop_column', () => {
const { file, remote, drop } = await withLegacyColumn();
expect(await remote.applyMigrationEntries([drop])).toEqual({ applied: [], skipped: [drop] });
expect(await columnsOf(file, 't')).toContain('legacy');
- expect(Object.keys(await indexesOf(file, 't')).sort()).toEqual(['idx_t_legacy', 'idx_t_name_legacy']);
+ expect(Object.keys(await indexesOf(file, 't')).sort()).toEqual(['idx_t_created_at_id', 'idx_t_legacy', 'idx_t_name_legacy']);
});
it('a column SQLite refuses to drop is skipped, and the indexes dropped before it are rolled back', async () => {
@@ -190,7 +191,8 @@ describe('the index entries', () => {
expect(drop).toBeDefined();
expect(await remote.applyMigrationEntries([drop], { allowDestructive: true })).toEqual({ applied: [drop], skipped: [] });
- expect(await indexesOf(file, 'indexed_t')).toEqual({});
+ // [#33695] Only the undeclared index goes; the implicit default-order index stays.
+ expect(Object.keys(await indexesOf(file, 'indexed_t'))).toEqual(['idx_indexed_t_created_at_id']);
expect(await remote.applyMigrationEntries([drop], { allowDestructive: true })).toEqual({ applied: [drop], skipped: [] });
});