diff --git a/docs/python-api.rst b/docs/python-api.rst index d515642a5..a6b7f6602 100644 --- a/docs/python-api.rst +++ b/docs/python-api.rst @@ -2013,6 +2013,8 @@ CHECK constraints A column-level check is removed if its owning column is dropped. Dropping a column referenced by any remaining check raises ``TransformError`` instead of creating an invalid or unexpectedly weakened schema. +A column's ``COLLATE`` clause is preserved as well, so a ``TEXT COLLATE NOCASE`` column keeps comparing case-insensitively. + Comments immediately before or after a column definition are preserved too. They move with that column if it is renamed or reordered, and are removed if the column is dropped. A comment between two column definitions is treated as belonging to the following column. .. _python_api_transform_views: diff --git a/sqlite_utils/create_table_parser.py b/sqlite_utils/create_table_parser.py index 7377f4fd6..6e48ff7ff 100644 --- a/sqlite_utils/create_table_parser.py +++ b/sqlite_utils/create_table_parser.py @@ -610,6 +610,39 @@ def parse_autoincrement(create_sql: str) -> str | None: return None +def parse_column_collations(create_sql: str) -> dict[str, str]: + """Return the ``COLLATE`` name declared on each column of a CREATE TABLE statement.""" + body_info = _table_body(create_sql) + if body_info is None: + return {} + body, _ = body_info + collations: dict[str, str] = {} + for item, _, _ in _split_spans(body, _lex(body)): + item_tokens = _meaningful(_lex(item)) + if not item_tokens: + continue + head = item_tokens[0] + if ( + head.kind == "word" and head.text.upper() in _TABLE_CONSTRAINT_KEYWORDS + ) or head.is_keyword("CONSTRAINT"): + continue + column = _unquote(head.text) + index = 1 + while index < len(item_tokens): + token = item_tokens[index] + if token.text == "(": + index = _matching_paren(item_tokens, index) + 1 + continue + if token.is_keyword("COLLATE"): + if index + 1 >= len(item_tokens): + raise ParseError("COLLATE is missing its name") + collations[column] = _unquote(item_tokens[index + 1].text) + index += 2 + continue + index += 1 + return collations + + _CONFLICT_ACTIONS = frozenset(("ROLLBACK", "ABORT", "FAIL", "IGNORE", "REPLACE")) diff --git a/sqlite_utils/db.py b/sqlite_utils/db.py index c011d9bb0..bad923d05 100644 --- a/sqlite_utils/db.py +++ b/sqlite_utils/db.py @@ -35,6 +35,7 @@ check_references_identifier, parse_autoincrement, parse_checks, + parse_column_collations, parse_column_comments, parse_uniques, rewrite_check_expression, @@ -1444,6 +1445,7 @@ def create_table_sql( _column_comments: Mapping[str, ColumnComments] | None = None, _autoincrement: str | None = None, _uniques: Iterable[Unique] | None = None, + _collations: Mapping[str, str] | None = None, ) -> str: """ Returns the SQL ``CREATE TABLE`` statement for creating the specified table. @@ -1493,6 +1495,10 @@ def create_table_sql( resolve_casing(name, columns): comments for name, comments in (_column_comments or {}).items() } + collations = { + resolve_casing(name, columns): collation + for name, collation in (_collations or {}).items() + } checks = list(_checks or ()) checks_by_column: dict[str, list[Check]] = {} table_checks: list[Check] = [] @@ -1609,6 +1615,10 @@ def sort_key(p): raise ValueError("AUTOINCREMENT requires a single-column primary key") for column_name, column_type in column_items: column_extras = [] + if column_name in collations: + column_extras.append( + f"COLLATE {quote_identifier(collations[column_name])}" + ) if column_name == single_pk: column_extras.append("PRIMARY KEY") if column_name == _autoincrement: @@ -2845,6 +2855,7 @@ def transform_sql( existing_column_comments = parse_column_comments(self.schema) existing_autoincrement = parse_autoincrement(self.schema) existing_uniques = parse_uniques(self.schema) + existing_collations = parse_column_collations(self.schema) except ParseError as ex: raise TransformError( f"Could not parse table schema for table {self.name!r}: {ex}" @@ -2908,6 +2919,12 @@ def transform_sql( if owner not in drop: create_table_column_comments[rename.get(owner) or owner] = comments + create_table_collations: dict[str, str] = {} + for column, collation in existing_collations.items(): + owner = resolve_casing(column, existing_columns) + if owner not in drop: + create_table_collations[rename.get(owner) or owner] = collation + create_table_foreign_keys: list[ForeignKeyIndicator] = [] if foreign_keys is not None: @@ -3088,6 +3105,7 @@ def fk_with_renamed_columns(fk: ForeignKey) -> ForeignKey: _column_comments=create_table_column_comments, _autoincrement=create_table_autoincrement, _uniques=create_table_uniques, + _collations=create_table_collations, ).strip() ) diff --git a/tests/test_create_table_parser.py b/tests/test_create_table_parser.py index 74a089cc0..938c99bb2 100644 --- a/tests/test_create_table_parser.py +++ b/tests/test_create_table_parser.py @@ -12,6 +12,7 @@ UniqueColumn, parse_autoincrement, parse_checks, + parse_column_collations, parse_column_comments, parse_uniques, ) @@ -151,6 +152,34 @@ def test_parse_autoincrement(sql, expected): assert parse_autoincrement(sql) == expected +@pytest.mark.parametrize( + "sql,expected", + [ + ("CREATE TABLE t(id INTEGER PRIMARY KEY, name TEXT)", {}), + ( + "CREATE TABLE t(id INTEGER, name TEXT COLLATE NOCASE NOT NULL)", + {"name": "NOCASE"}, + ), + ('CREATE TABLE t("full name" collate "rtrim", other)', {"full name": "rtrim"}), + ( + "CREATE TABLE t(a TEXT CHECK (a COLLATE NOCASE != ''), b TEXT)", + {}, + ), + ( + "CREATE TABLE t(a TEXT DEFAULT 'COLLATE NOCASE', b TEXT /* COLLATE x */)", + {}, + ), + ( + "CREATE TABLE t(a TEXT, b TEXT, UNIQUE (a COLLATE NOCASE))", + {}, + ), + ], +) +def test_parse_column_collations(sql, expected): + sqlite3.connect(":memory:").execute(sql) + assert parse_column_collations(sql) == expected + + def test_parse_column_and_table_uniques(): sql = """ CREATE TABLE memberships ( diff --git a/tests/test_transform.py b/tests/test_transform.py index 873871308..d541c7317 100644 --- a/tests/test_transform.py +++ b/tests/test_transform.py @@ -1090,6 +1090,35 @@ def test_transform_preserves_column_unique_collation(fresh_db): people.insert({"id": 2, "full_name": "cleo"}) +def test_transform_preserves_column_collation(fresh_db): + fresh_db.execute(""" + CREATE TABLE people ( + id INTEGER PRIMARY KEY, + name TEXT COLLATE NOCASE, + nick TEXT COLLATE RTRIM NOT NULL, + other TEXT COLLATE NOCASE + ) + """) + people = fresh_db.table("people") + people.insert({"id": 1, "name": "Alice", "nick": "Al", "other": "x"}) + + people.transform(rename={"nick": "nickname"}, drop={"other"}) + + assert people.schema == ( + 'CREATE TABLE "people" (\n' + ' "id" INTEGER PRIMARY KEY,\n' + ' "name" TEXT COLLATE "NOCASE",\n' + ' "nickname" TEXT COLLATE "RTRIM" NOT NULL\n' + ")" + ) + assert fresh_db.execute( + "select count(*) from people where name = 'alice'" + ).fetchone() == (1,) + assert fresh_db.execute( + "select count(*) from people where nickname = 'Al '" + ).fetchone() == (1,) + + def test_transform_drops_entire_composite_unique_constraint(fresh_db): fresh_db.execute(""" CREATE TABLE memberships (