Repository navigation
feat(export)!: write a table's indexes into the SQL export, after its rows - #2651
Merged
Merged
Conversation
|
Preview deployment for your docs. Learn more about Mintlify Previews.
💡 Tip: Enable Automations to automatically generate PRs for you. |
Signed-off-by: Ngô Quốc Đạt <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #2492.
The problem
The SQL export had no index phase, and no protocol requirement asked a driver for a table's
CREATE INDEXtext. Whether indexes reached a dump was an accident of each driver'sfetchTableDDL:pg_indexes.indexdefSHOW CREATEAnd the engines that did include them put them before the data, so every
INSERTmaintained 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
PluginDatabaseDriverrequirement, mirrored onPluginExportDataSource:Default
[]. The contract is "statementsfetchTableDDLdoes not already declare", so a driver whoseCREATE TABLEcarries its indexes inline returns nothing and its output is unchanged. No companiontableDDLIncludesIndexesflag: 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 patternCLAUDE.mdwarns about.The export writes them in
writeIndexPhase, after the data and after the deferred foreign keys, which ispg_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
PluginIndexInfoMeasured 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 ascolumns={d}. The expression key is invisible and theINCLUDEcolumn 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'sDESC NULLS LASTwas lost.Rendering from that struct would have created different indexes, or none.
pg_indexes.indexdef,sqlite_master.sqlandduckdb_indexes().sqlall round-trip verbatim.Per engine
pg_get_indexdef, constraint indexes excluded byconindidsqlite_master WHERE type='index' AND sql IS NOT NULLduckdb_indexes().sql[]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 -uon a builtSQLiteDriver: 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.scripts/check-pluginkit-abi.shreports the diff as purely additive (4 additions, 0 removals), which is correct in the direction it describes. The bump is for the other direction.minimumCompatiblePluginKitVersionstays at 19.Two accepted costs:
scripts/release-all-plugins.sh 22must run before or with the app release, re-releasing all registry plugins including ones that did not change.bundled: trueplugins, 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:
extractIndexColumns' regex stopped at the first), soCREATE 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.name.lowercased().contains("primary")markedidx_primary_contactas 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.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)plusCONSTRAINT ck_dup CHECK (a>0)produced nothing wherepg_dumpproduced the index. Now excluded byconindid, which is whatpg_dumpdoes.CREATE TABLE.fetchViewDefinitionreadpg_views, which excludes matviews, so it threw and the export adapter fell back tofetchTableDDL, which succeeds on a matview. The dump carriedDROP MATERIALIZED VIEWfollowed by a table definition and reported success.fetchViewDefinitionnow falls through topg_matviewsand the laundering fallback is gone.DROP TYPE/DROP SEQUENCEwith Drop unticked.writeDependentTypesAndSequenceswrote them unconditionally, so a dump meant to be appended to a live database opened withDROP TYPE ... CASCADE, taking the enum column out of every other table using that type. Now gated on the per-table Drop column.SELECT.ALL_VIEWS.TEXT_VCandsystem.tables.as_selectare the view body alone. The dump ran a query and created nothing. Both now return aCREATE VIEWheader.;for an unreadable definition. Five drivers answer""rather than throwing, so a SQL Server view createdWITH ENCRYPTIONproduced a comment banner and a lone;with no warning. Both write phases now treat an empty definition as a failure the summary names.fetchIndexeshardcodedtype: "CLUSTERED"; it now readssys.indexes.type_desc. A table holds one clustered index, so scripting them all that way makes the server reject the second.CREATE TABLEdeclares them. That premise is false on these three: SQL Server'sfetchTableDDLwrites the primary key and foreign keys but never aUNIQUEconstraint, 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'sCREATE TABLEactually declares, and Oracle excludes nothing..materializedViewfallback in the export adapter left ClickHouse routing them throughfetchViewDefinition, whose new header isCREATE VIEW, so a restore would have built an ordinary view and lost the target table and engine clause.fetchViewDefinitionnow readssystem.tables.engineand answers a materialized view withSHOW CREATE TABLE.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, withkeys(...),values(...),entries(...)andfull(...)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 CONCURRENTLYwill run, so they get their own index pass after the phase that creates them.Verification
generatebuildtest(9 suites)abiswiftlint --strictOracleDriverdoes not compile on this machine: the pinnedoracle-niofork's@TaskLocalmacro expands tounknown attribute 'usableFromInlinenonisolated'under the local toolchain. The failure is entirely insideoracle-nio's own sources and is pre-existing; CI compiles it.OracleIndexStatementsis in the test target and did compile and run there.The
AllPluginsaggregate 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 toSkill(code-review)at high effort plusSkill(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 deadLocalizedErrorstring 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 answersfetchIndexDDLand writesCREATE INDEXinto its table DDL. Nothing at runtime can see that contradiction, becausefetchTableDDLhands 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.byDatabaseengine (TablePro/Core/Plugins/ExportDataSourceAdapter.swift:294). Exportinganalytics.userswhile connected toapprunsSHOW CREATE TABLE usersinapp, so the dump can carry one database's structure with another's rows. The newfetchIndexDDLgoes through the same helper and is exactly as affected asfetchTableDDLalready was, so this change neither causes nor worsens it. Fixing it properly means making MySQL and ClickHouse honour aschema: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