Repository navigation
alter() changes and renames attributes on PostgreSQL - #1639
dimitri-yatsenko wants to merge 4 commits into
Conversation
On PostgreSQL, `Table.alter()` could add and drop attributes but not change them. A change of type, nullability or default emitted MySQL's `MODIFY`, a syntax error. A change of comment alone was ignored: PostgreSQL keeps comments out of the column declaration, and the declarations were what alter() compared. alter() now compares the parts of each column (type, nullability, default and comment) instead of the compiled declarations, and a new adapter method, `alter_table_ddl`, turns the differences into statements. MySQL still gets one ALTER TABLE with `MODIFY`, `CHANGE`, `ADD` and `DROP`, and unit tests pin those statements to what master produced. PostgreSQL gets `ALTER COLUMN ... TYPE`, `SET`/`DROP NOT NULL` and `SET`/`DROP DEFAULT`; `RENAME COLUMN`; and `COMMENT ON COLUMN` for each new or changed comment, carrying the core-type marker (`:float64:`) that describe() reads back. A changed table comment becomes `COMMENT ON TABLE` in place of MySQL's `COMMENT=`, which was also a syntax error there. The statements run in one transaction, so a failure in any of them leaves the table as it was. A type change adds a `USING` expression where PostgreSQL has no assignment conversion: strings and enum labels are parsed as the new type, numbers become booleans by comparison with zero, booleans become 0 or 1, and other values become JSON through `to_jsonb`. A conversion with no meaning, such as a date to a number, raises a DataJointError before anything runs. A default is dropped before the type changes and set again after it, because PostgreSQL would otherwise try to convert the default as well. A change to an enum creates the new type first, as adding an enum attribute already did. Renames now work on PostgreSQL as `RENAME COLUMN`. The rename marker is read from the comment as written (#1634, which this builds on); where #1634 refused a rename on PostgreSQL, this carries it out. The MySQL statements are unchanged. describe() on PostgreSQL wrote defaults with the cast the server reports, as `value='1.5'::real` or `label="'abc'::character varying"`. alter() parses describe() for the current definition, so the first made it fail on any table with such a default, and the second reads as a different default. The adapter now reports the value alone, as MySQL does. New integration tests run on both backends. Each alters a table that holds data and checks that the table then describes itself exactly as a table declared from the new definition does, that alter() finds nothing left to change, and that the values survived. They cover a change of type (including to and from strings, booleans and enums), nullability, default, attribute comment and table comment; several changes in one alter; a rename alone and with other changes; a failed change, which leaves the table unchanged; and a refused conversion. Closes #1625.
MilagrosMarin
left a comment
There was a problem hiding this comment.
This reads well. Comparing columns by their parts, and letting the adapter produce the statements, makes the PostgreSQL path straightforward, and pinning the MySQL output to what master produced is reassuring. It needs a rebase now that #1634 has merged (it is CONFLICTING, and the "Stacked on #1634" line is out of date); I'll approve once it is rebased.
On the three points for reviewers:
- Refused conversions: agreed. None of date/timestamp, uuid, or bytea to or from numbers, booleans, or each other has an obvious meaning, and passing unrecognized type pairs to PostgreSQL, with the change rolling back on failure, is a sensible default.
- Booleans and numbers:
<> 0and::integermatch what MySQL stores for a boolean, so both are fine. - Swapping names in one alter: acceptable, but the user gets PostgreSQL's "already exists". Detecting a swap in
_make_attribute_alterand raising a DataJointError that says to rename in two alters would be friendlier, and it would fail before anything runs.
Smaller notes, none blocking:
pre_ddl(CREATE TYPEfor a changed enum) runs before the transaction, so a failure later in the alter rolls back the columns but leaves the new enum type, unused. Harmless, but worth a comment, or moving it inside the transaction.- On PostgreSQL,
alter()now opensself.connection.transaction. What happens when the caller is already inside a transaction (an error on nesting, or joining the outer one)? A test or a line in the docstring would settle it. - The
parse_column_infochange only strips the cast from a whole quoted literal (fullmatch), sonextval(...)and other expressions are left alone. That's the right scope.
# Conflicts: # src/datajoint/table.py
MilagrosMarin
left a comment
There was a problem hiding this comment.
Thanks for updating this, @dimitri-yatsenko. The merge from master resolves the conflict, and the PR's changes are the same as the commit I reviewed. Unit tests pass locally. Once it's out of draft and ready for review, I'll approve.
Two small things, neither blocking:
- Nested transactions: to answer my earlier question, on PostgreSQL
alter()now opensconnection.transaction, so calling it inside a caller's transaction raises "Nested connections are not supported." MySQL doesn't. A line in thealter()docstring would make that clear. - Double quotes in attribute comments (PostgreSQL):
compile_attributewrites"as\", and PostgreSQL keeps the backslash in the stored comment. Sincealter()now compares comments, a table withnote : varchar(8) # say "hi"gets aCOMMENT ON COLUMNevery time, and never reports nothing to alter. The escaping predates this PR, so a follow-up issue is fine.
The PR body still says it's stacked on #1634, which has since merged. Worth updating before it leaves draft.
PostgreSQL renames one column per statement, so names that traded places in one alter() failed with "already exists". Renames now run once their new name is free, and a cycle moves one column to a temporary name first. Document that alter() refuses to run inside a transaction and why the enum pre-DDL runs before alter()'s own transaction.
|
Thanks @MilagrosMarin. I merged the current
The full suite passes locally on both backends. |
Summary
On PostgreSQL,
Table.alter()could add and drop attributes but not change them. A change of type, nullability or default emitted MySQL'sMODIFY, which is a syntax error there. A change of comment alone was ignored: PostgreSQL keeps comments out of the column declaration, and the declarations were whatalter()compared.alter()now makes the same changes on PostgreSQL as on MySQL: type, nullability, default, attribute comment, table comment and renames. The MySQL statements are unchanged.Fixes #1625
Changes
declare.py:alter()compares the parts of each column (type, nullability, default and comment) instead of the compiled declarations.alter_table_ddl, turns the differences into statements.ALTER TABLEwithMODIFY,CHANGE,ADDandDROP. Unit tests pin those statements to what master produced.ALTER COLUMN ... TYPE,SET/DROP NOT NULLandSET/DROP DEFAULT;RENAME COLUMN; andCOMMENT ON COLUMNfor each new or changed comment. The comment carries the core-type marker (such as:float64:) thatdescribe()reads back. A changed table comment becomesCOMMENT ON TABLEin place of MySQL'sCOMMENT=, which was also a syntax error there.table.py: on PostgreSQL the statements run in one transaction, so a failure in any of them leaves the table as it was.alter()already refuses to run inside a caller's transaction; its docstring now says so.USINGexpression is added where PostgreSQL has no assignment conversion. Strings and enum labels are parsed as the new type. Numbers become booleans by comparison with zero, and booleans become 0 or 1. Other values become JSON throughto_jsonb.DataJointErrorbefore anything runs.CREATE TYPEruns before the transaction, because an error inside it (for a type that already exists) would abort the transaction. A type created for an alter that then fails stays in the schema, unused. A comment in the code says so.ALTER TABLEat once. Renames now run in an order where each new name is free. Names that trade places are moved through a temporary name, so swapping two names in onealter()works as it does on MySQL.describe()on PostgreSQL wrote defaults with the cast the server reports, such asvalue='1.5'::real.alter()parsesdescribe()for the current definition, so this made it fail on any table with such a default. The adapter now reports the value alone, as MySQL does. Only a whole quoted literal is stripped of its cast; expressions such asnextval(...)are left alone.datajoint.declare.alter: the optional keywordschema_nameis replaced by the required keywordfull_table_name(the quoted name of the table), and the return value is a 3-tuple(sql, new_stores, pre_ddl)instead of(sql, new_stores, pre_ddl, column_comments).sqlnow holds complete statements to run in order, including anyCOMMENT ONstatements, where it used to hold the clauses of oneALTER TABLE._make_attribute_alterreturns the attributes to drop and the changes instead of SQL.Table.alter()is the public entry point and its signature is unchanged; code that callsdatajoint.declare.alterdirectly must be updated.Behavior change
alter()changes an attribute's type, nullability, default and comment, the table comment, and renames attributes. Before, a change of type, nullability or default failed with a syntax error, a change of comment alone was ignored, and a rename was refused.alter()run in one transaction, so a failure leaves the table as it was. A conversion with no meaning raises aDataJointErrorbefore anything runs.describe()writes a default without the cast the server reports.alter()generates are unchanged.datajoint.declare.alterhas a new internal signature and return value, described under Changes.Tests
tests/unit/test_alter_sql.py: the statementsalter()generates on each backend, for each kind of change. MySQL output matches master. New cases cover the order of renames on PostgreSQL: chains, swaps, a three-way cycle, and two cycles in one alter.tests/integration/test_alter_attributes.py, on MySQL and PostgreSQL: each test alters a table that holds data. It checks that the table then describes itself exactly as a table declared from the new definition does, thatalter()finds nothing left to change, and that the values survived. Covered: a change of type (including to and from strings, booleans and enums), nullability, default, attribute comment and table comment; several changes in one alter; a rename alone and with other changes; names that swap and names that move along a chain; a failed change, which leaves the table unchanged; and a refused conversion.For reviewers to confirm
Follow-up
alter()then emits aCOMMENT ON COLUMNfor such a table every time. The escaping predates this PR.Merge order
original_regexpin_make_attribute_alter, which this PR removes, and addstest_rename_enum_with_colon_keeps_valuestotests/integration/test_alter_rename.py. Whichever of the two merges second must reconcile them: keep this PR's_make_attribute_alter(it reads the rename marker before the:type:marker is added), keep the new test, and change its PostgreSQL branch to expect the rename to keep the values.