Skip to content

feat(export)!: write a table's indexes into the SQL export, after its rows - #2651

Merged
datlechin merged 6 commits into
mainfrom
feat/sql-export-indexes
Sep 6, 2026
Merged

datlechin merged 6 commits into
mainfrom
feat/sql-export-indexes

Conversation

@datlechin

Copy link
Copy Markdown
Member

Fixes #2492.

The problem

The SQL export had no index phase, and no protocol requirement asked a driver for a table's CREATE INDEX text. Whether indexes reached a dump was an accident of each driver's fetchTableDDL:

  • PostgreSQL and PGlite appended pg_indexes.indexdef
  • MySQL, MariaDB, ClickHouse, Trino, Teradata, CockroachDB and Redshift got them inline from the engine's own SHOW CREATE
  • DuckDB re-synthesised them from a regex
  • SQLite, LibSQL, Cloudflare D1, SQL Server, Oracle, Dameng and Cassandra dropped them silently

And the engines that did include them put them before the data, so every INSERT maintained every index.

The rest of #2492, views, sequences, triggers, routines, materialized views, types, events and grants as selectable kinds with per-row Structure/Drop/Data and a dependency-ordered dump, shipped in #2621 after the issue was filed.

The fix

One new PluginDatabaseDriver requirement, mirrored on PluginExportDataSource:

func fetchIndexDDL(table: String, schema: String?) async throws -> [String]

Default []. The contract is "statements fetchTableDDL does not already declare", so a driver whose CREATE TABLE carries its indexes inline returns nothing and its output is unchanged. No companion tableDDLIncludesIndexes flag: the driver renders, so it can just return nothing, and a second hand-maintained list that has to agree with each driver's DDL is the pattern CLAUDE.md warns about.

The export writes them in writeIndexPhase, after the data and after the deferred foreign keys, which is pg_dump's own order. Indexes ride the table's existing Structure checkbox, which is what the issue asked for. No UI change.

No new object kind. SSMS, pgAdmin, DataGrip, DBeaver, TablePlus, Sequel Ace and Postico were all checked: none models an index as a selectable object, and a ticked index under an unticked table is meaningless.

Why DDL text and not PluginIndexInfo

Measured against PostgreSQL 17.11 by running PostgreSQLPluginDriver.fetchIndexes' own query over four test indexes:

  • CREATE INDEX idx_expr ON t (lower(b) text_pattern_ops) INCLUDE (d) WITH (fillfactor=70) came back as columns={d}. The expression key is invisible and the INCLUDE column was promoted to a key column.
  • CREATE INDEX idx_gin ON t USING gin (to_tsvector('english', b)) disappeared entirely: four indexes in, three rows out.
  • idx_bc's DESC NULLS LAST was lost.

Rendering from that struct would have created different indexes, or none. pg_indexes.indexdef, sqlite_master.sql and duckdb_indexes().sql all round-trip verbatim.

Per engine

Engine Source Verified
PostgreSQL, PGlite pg_get_indexdef, constraint indexes excluded by conindid Measured against PostgreSQL 17.11
SQLite, LibSQL, Cloudflare D1 sqlite_master WHERE type='index' AND sql IS NOT NULL Measured against sqlite3 3.54.0
DuckDB duckdb_indexes().sql Measured against DuckDB 1.5.4
SQL Server, Oracle, Dameng, Cassandra catalog queries, rendered by a pure function Rendering unit-tested; the catalog queries are not run against a live server
MySQL, MariaDB, ClickHouse, Trino, Teradata, CockroachDB, Redshift, Snowflake, BigQuery, SurrealDB unchanged, default [] Output is bit-identical

The four synthesis engines have no test server here. Each one's row-to-SQL rendering is a pure function with unit tests, so what is unverified is the catalog query, not the SQL it produces. A wrong statement is contained to that engine and reported through the export's own warning path rather than failing the dump.

PluginKit 21 to 22

A new requirement, even a defaulted one, is only safe old-plugin-in-new-host. Measured with nm -u on a built SQLiteDriver: a conformer emits three undefined references per defaulted requirement it does not implement, including the default implementation's own symbol, so a plugin rebuilt against PluginKit 22 cannot load in a 21 host.

method descriptor for TableProPluginKit.PluginDatabaseDriver.fetchEventDDL(...)
(extension in TableProPluginKit):TableProPluginKit.PluginDatabaseDriver.fetchEventDDL(...)
async function pointer to (extension in TableProPluginKit):...fetchEventDDL(...)

scripts/check-pluginkit-abi.sh reports the diff as purely additive (4 additions, 0 removals), which is correct in the direction it describes. The bump is for the other direction. minimumCompatiblePluginKitVersion stays at 19.

Two accepted costs:

  • scripts/release-all-plugins.sh 22 must run before or with the app release, re-releasing all registry plugins including ones that did not change.
  • The script skips bundled: true plugins, so SQLite's index fix reaches users with the app release rather than out-of-band through the registry.

Collateral fixed here

Found while investigating, each one in code this change already touches:

  • DuckDB expression indexes. extractIndexColumns' regex stopped at the first ), so CREATE INDEX idx_low ON t((lower(email))) was emitted as ("(lower(email"). Replaced with a balanced-paren scan; coalesce(a, b) now stays one key.
  • DuckDB "primary" name heuristic. name.lowercased().contains("primary") marked idx_primary_contact as the primary key, so it was skipped from the DDL and shown as the table's primary key in the Structure tab. duckdb_indexes() never lists constraint-backed indexes, so nothing there is a primary key.
  • PostgreSQL index vs check constraint name collision. The constraint exclusion matched index name against pg_constraint.conname, so an index sharing a name with a CHECK constraint on the same table was dropped from the dump. Measured: CREATE INDEX ck_dup ON ck(a) plus CONSTRAINT ck_dup CHECK (a>0) produced nothing where pg_dump produced the index. Now excluded by conindid, which is what pg_dump does.
  • PostgreSQL materialized views exported as CREATE TABLE. fetchViewDefinition read pg_views, which excludes matviews, so it threw and the export adapter fell back to fetchTableDDL, which succeeds on a matview. The dump carried DROP MATERIALIZED VIEW followed by a table definition and reported success. fetchViewDefinition now falls through to pg_matviews and the laundering fallback is gone.
  • DROP TYPE/DROP SEQUENCE with Drop unticked. writeDependentTypesAndSequences wrote them unconditionally, so a dump meant to be appended to a live database opened with DROP TYPE ... CASCADE, taking the enum column out of every other table using that type. Now gated on the per-table Drop column.
  • Oracle and ClickHouse views as a bare SELECT. ALL_VIEWS.TEXT_VC and system.tables.as_select are the view body alone. The dump ran a query and created nothing. Both now return a CREATE VIEW header.
  • A bare ; for an unreadable definition. Five drivers answer "" rather than throwing, so a SQL Server view created WITH ENCRYPTION produced a comment banner and a lone ; with no warning. Both write phases now treat an empty definition as a failure the summary names.
  • SQL Server reporting every index as clustered. fetchIndexes hardcoded type: "CLUSTERED"; it now reads sys.indexes.type_desc. A table holds one clustered index, so scripting them all that way makes the server reject the second.
  • Unique constraints lost on SQL Server, Oracle and Dameng. Each new index query first excluded constraint-backed indexes, on the premise that CREATE TABLE declares them. That premise is false on these three: SQL Server's fetchTableDDL writes the primary key and foreign keys but never a UNIQUE constraint, Dameng's writes the primary key only, and Oracle's writes column definitions and nothing else. CREATE TABLE t (a INT UNIQUE) round-tripped with no uniqueness at all. Each exclusion now matches what that driver's CREATE TABLE actually declares, and Oracle excludes nothing.
  • ClickHouse materialized views. Removing the .materializedView fallback in the export adapter left ClickHouse routing them through fetchViewDefinition, whose new header is CREATE VIEW, so a restore would have built an ordinary view and lost the target table and engine clause. fetchViewDefinition now reads system.tables.engine and answers a materialized view with SHOW CREATE TABLE.
  • Cassandra index target injection. target(fromOptions:) stripped the CQL quotes off the indexed column and the statement spliced it raw, so a column name holding ) and ; could add statements to the dump the user later replays. Every identifier is quoted now, with keys(...), values(...), entries(...) and full(...) kept as the keyword they are and only the column inside them quoted. Found by the security review; regression tests cover it.

Materialized views carry their own indexes, and PostgreSQL needs a unique one before REFRESH MATERIALIZED VIEW CONCURRENTLY will run, so they get their own index pass after the phase that creates them.

Verification

Step Result
generate PASS
build PASS
test (9 suites) PASS, 75 cases
Individual plugin schemes PASS for all 12 changed plugins except OracleDriver
abi Diff is purely additive: 4 additions, 0 removals
swiftlint --strict Clean on every touched path

OracleDriver does not compile on this machine: the pinned oracle-nio fork's @TaskLocal macro expands to unknown attribute 'usableFromInlinenonisolated' under the local toolchain. The failure is entirely inside oracle-nio's own sources and is pre-existing; CI compiles it. OracleIndexStatements is in the test target and did compile and run there.

The AllPlugins aggregate fails locally for the same reason and no other: no error in the log names any changed file.

Review

Codex was out of credits (You've hit your usage limit ... try again at Sep 7th), so the second-model pass fell back to Skill(code-review) at high effort plus Skill(security-review). Between them they found seven real defects, all fixed above: the three constraint-exclusion mismatches, the ClickHouse materialized view regression, the Cassandra target injection, a dead LocalizedError string that the dump's warning line never printed because it interpolates the error value rather than its description, and a vacuous test that would have passed with the whole index phase deleted.

That last one is replaced by IndexDDLOwnershipTests, a source scan asserting no driver both answers fetchIndexDDL and writes CREATE INDEX into its table DDL. Nothing at runtime can see that contradiction, because fetchTableDDL hands back opaque text, so a scan is the only place the invariant can live.

Not done

A UI automation test was not added because this change has no UI. The export dialog is untouched.

ExportDataSourceAdapter.exportSchema() discards the container name on every .byDatabase engine (TablePro/Core/Plugins/ExportDataSourceAdapter.swift:294). Exporting analytics.users while connected to app runs SHOW CREATE TABLE users in app, so the dump can carry one database's structure with another's rows. The new fetchIndexDDL goes through the same helper and is exactly as affected as fetchTableDDL already was, so this change neither causes nor worsens it. Fixing it properly means making MySQL and ClickHouse honour a schema: they currently ignore, or taking a per-group lease, which is a feature-sized change across engines with no test server here. Left out deliberately rather than half-done.

https://claude.ai/code/session_019LfyVSSD2BuoBYS8VwWKki

@mintlify

mintlify Bot commented Sep 6, 2026 •

Copy link
Copy Markdown

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
TablePro 🟢 Ready View Preview Sep 6, 2026, 6:06 AM

💡 Tip: Enable Automations to automatically generate PRs for you.

@datlechin
datlechin merged commit 7bc6802 into main Sep 6, 2026
4 checks passed
@datlechin
datlechin deleted the feat/sql-export-indexes branch September 6, 2026 08:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Include views and indexes in the SQL export

1 participant