Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/python-api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
33 changes: 33 additions & 0 deletions sqlite_utils/create_table_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"))


Expand Down
18 changes: 18 additions & 0 deletions sqlite_utils/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
check_references_identifier,
parse_autoincrement,
parse_checks,
parse_column_collations,
parse_column_comments,
parse_uniques,
rewrite_check_expression,
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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] = []
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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}"
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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()
)

Expand Down
29 changes: 29 additions & 0 deletions tests/test_create_table_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
UniqueColumn,
parse_autoincrement,
parse_checks,
parse_column_collations,
parse_column_comments,
parse_uniques,
)
Expand Down Expand Up @@ -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 (
Expand Down
29 changes: 29 additions & 0 deletions tests/test_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
Loading