diff --git a/src/datajoint/adapters/base.py b/src/datajoint/adapters/base.py index 1aa12f52f..3ab79b3c9 100644 --- a/src/datajoint/adapters/base.py +++ b/src/datajoint/adapters/base.py @@ -207,6 +207,27 @@ def quote_string(self, value: str) -> str: """ ... + def quote_comment(self, comment: str) -> str: + """ + Quote a table or column comment as a string literal for this backend. + + The comment is stored exactly as given: quotes and backslashes in it are + part of the comment and cannot end the literal. One exception: on MySQL + with NO_BACKSLASH_ESCAPES set, each backslash is stored doubled (see + ``MySQLAdapter.quote_comment``). + + Parameters + ---------- + comment : str + Comment text as declared, including any ``:type:`` marker. + + Returns + ------- + str + Quoted string literal. + """ + return self.quote_string(comment) + @abstractmethod def get_master_table_name(self, part_table: str) -> str | None: """ @@ -1229,7 +1250,7 @@ def format_column_definition( default : str | None, optional Default value expression (e.g., 'NULL', '"value"', 'CURRENT_TIMESTAMP'). comment : str | None, optional - Column comment. + Column comment as declared; quoted with ``quote_comment``. Returns ------- @@ -1251,7 +1272,7 @@ def table_options_clause(self, comment: str | None = None) -> str: Parameters ---------- comment : str | None, optional - Table-level comment. + Table-level comment as declared; quoted with ``quote_comment``. Returns ------- @@ -1275,7 +1296,7 @@ def table_comment_ddl(self, full_table_name: str, comment: str) -> str | None: full_table_name : str Fully qualified table name (quoted). comment : str - Table comment. + Table comment as declared; quoted with ``quote_comment``. Returns ------- @@ -1301,7 +1322,7 @@ def column_comment_ddl(self, full_table_name: str, column_name: str, comment: st column_name : str Column name (unquoted). comment : str - Column comment. + Column comment as declared; quoted with ``quote_comment``. Returns ------- diff --git a/src/datajoint/adapters/mysql.py b/src/datajoint/adapters/mysql.py index e55425254..2dc7bbfaa 100644 --- a/src/datajoint/adapters/mysql.py +++ b/src/datajoint/adapters/mysql.py @@ -289,6 +289,37 @@ def quote_string(self, value: str) -> str: escaped = client.converters.escape_string(value).replace("\\'", "''") return f"'{escaped}'" + def quote_comment(self, comment: str) -> str: + """ + Quote a table or column comment as a double-quoted MySQL string literal. + + Comments are written in double quotes, as DataJoint has always written + them. Only two characters are escaped: a backslash is doubled, and a + double quote is doubled (``""``) rather than escaped with a backslash, so + the comment is stored as written. Under NO_BACKSLASH_ESCAPES, MySQL reads + a backslash literally, so a comment with a backslash is stored with each + backslash doubled; every other character is still stored as written. + Single quotes, which the ``:type:`` marker of an enum attribute contains, + are left as they are. + + Parameters + ---------- + comment : str + Comment text as declared. + + Returns + ------- + str + Quoted and escaped string literal. + + Examples + -------- + >>> adapter.quote_comment('a "b" c') + '"a ""b"" c"' + """ + escaped = comment.replace("\\", "\\\\").replace('"', '""') + return f'"{escaped}"' + def get_master_table_name(self, part_table: str) -> str | None: """Extract master table name from part table (MySQL backtick format).""" import re @@ -1030,7 +1061,7 @@ def format_column_definition( elif not nullable: parts.append("NOT NULL") if comment: - parts.append(f'COMMENT "{comment}"') + parts.append(f"COMMENT {self.quote_comment(comment)}") return " ".join(parts) def table_options_clause(self, comment: str | None = None) -> str: @@ -1046,7 +1077,7 @@ def table_options_clause(self, comment: str | None = None) -> str: """ clause = "ENGINE=InnoDB" if comment: - clause += f', COMMENT "{comment}"' + clause += f", COMMENT {self.quote_comment(comment)}" return clause def table_comment_ddl(self, full_table_name: str, comment: str) -> str | None: diff --git a/src/datajoint/adapters/postgres.py b/src/datajoint/adapters/postgres.py index 52686763f..f75060e17 100644 --- a/src/datajoint/adapters/postgres.py +++ b/src/datajoint/adapters/postgres.py @@ -345,6 +345,38 @@ def quote_string(self, value: str) -> str: escaped = value.replace("'", "''") return f"'{escaped}'" + def quote_comment(self, comment: str) -> str: + """ + Quote a table or column comment as a PostgreSQL string literal. + + A comment without a backslash is quoted with ``quote_string``. A comment + with a backslash is written as an ``E'...'`` literal with each backslash + doubled. That form reads the same whether or not + ``standard_conforming_strings`` is on, so the stored comment is the + declared text under either setting. + + Parameters + ---------- + comment : str + Comment text as declared. + + Returns + ------- + str + Quoted and escaped string literal. + + Examples + -------- + >>> adapter.quote_comment("it's") + "'it''s'" + >>> adapter.quote_comment("a\\\\b") + "E'a\\\\\\\\b'" + """ + if "\\" not in comment: + return self.quote_string(comment) + escaped = comment.replace("\\", "\\\\").replace("'", "''") + return f"E'{escaped}'" + def get_master_table_name(self, part_table: str) -> str | None: """Extract master table name from part table (PostgreSQL double-quote format).""" import re @@ -665,7 +697,7 @@ def add_comment_sql( COMMENT ON statement. """ comment_type = object_type.upper() - return f"COMMENT ON {comment_type} {object_name} IS {self.quote_string(comment)}" + return f"COMMENT ON {comment_type} {object_name} IS {self.quote_comment(comment)}" # ========================================================================= # DML Generation @@ -1355,9 +1387,7 @@ def table_comment_ddl(self, full_table_name: str, comment: str) -> str | None: >>> adapter.table_comment_ddl('"schema"."table"', 'test comment') 'COMMENT ON TABLE "schema"."table" IS \\'test comment\\'' """ - # Escape single quotes by doubling them - escaped_comment = comment.replace("'", "''") - return f"COMMENT ON TABLE {full_table_name} IS '{escaped_comment}'" + return f"COMMENT ON TABLE {full_table_name} IS {self.quote_comment(comment)}" def column_comment_ddl(self, full_table_name: str, column_name: str, comment: str) -> str | None: """ @@ -1369,9 +1399,7 @@ def column_comment_ddl(self, full_table_name: str, column_name: str, comment: st 'COMMENT ON COLUMN "schema"."table"."column" IS \\'test comment\\'' """ quoted_col = self.quote_identifier(column_name) - # Escape single quotes by doubling them (PostgreSQL string literal syntax) - escaped_comment = comment.replace("'", "''") - return f"COMMENT ON COLUMN {full_table_name}.{quoted_col} IS '{escaped_comment}'" + return f"COMMENT ON COLUMN {full_table_name}.{quoted_col} IS {self.quote_comment(comment)}" def enum_type_ddl(self, type_name: str, values: list[str]) -> str | None: """ diff --git a/src/datajoint/declare.py b/src/datajoint/declare.py index 87cef4619..14a6f818a 100644 --- a/src/datajoint/declare.py +++ b/src/datajoint/declare.py @@ -1053,7 +1053,7 @@ def alter( # For MySQL: COMMENT="new comment" # For PostgreSQL: would need COMMENT ON TABLE, but that's not an ALTER TABLE clause # Keep MySQL syntax for now (ALTER TABLE ... COMMENT="...") - sql.append(f'COMMENT="{table_comment}"') + sql.append(f"COMMENT={adapter.quote_comment(table_comment)}") return sql, [e for e in external_stores if e not in external_stores_], pre_ddl, column_comments @@ -1264,8 +1264,6 @@ def compile_attribute( else: match["default"] = "NOT NULL" - match["comment"] = match["comment"].replace('"', '\\"') # escape double quotes in comment - if match["comment"].startswith(":"): raise DataJointError('An attribute comment must not start with a colon in comment "{comment}"'.format(**match)) diff --git a/src/datajoint/heading.py b/src/datajoint/heading.py index a841bf970..441eafe57 100644 --- a/src/datajoint/heading.py +++ b/src/datajoint/heading.py @@ -151,15 +151,21 @@ def sql(self) -> str: Generate SQL clause for this attribute in CREATE TABLE. Used for declaring foreign keys in referencing tables. - Default values are not included. + Default values are not included. The clause uses MySQL syntax, and the + comment is quoted with ``MySQLAdapter.quote_comment``. Returns ------- str SQL attribute declaration. """ - return '`{name}` {type} NOT NULL COMMENT "{comment}"'.format( - name=self.name, type=self.sql_type, comment=self.sql_comment + from .adapters import get_adapter + + adapter = get_adapter("mysql") + return "{name} {type} NOT NULL COMMENT {comment}".format( + name=adapter.quote_identifier(self.name), + type=self.sql_type, + comment=adapter.quote_comment(self.sql_comment), ) @property diff --git a/tests/integration/test_comment_quoting.py b/tests/integration/test_comment_quoting.py new file mode 100644 index 000000000..18874b190 --- /dev/null +++ b/tests/integration/test_comment_quoting.py @@ -0,0 +1,167 @@ +""" +Comments with quotes and backslashes are stored as declared, on both backends. + +Each backend writes a comment as a string literal of its own syntax. A double +quote, a single quote or a backslash in the comment is part of the comment: it is +stored and read back as written, ``describe()`` writes it back unchanged, and it +never ends the literal early. One exception: on MySQL with NO_BACKSLASH_ESCAPES +set, each backslash is stored doubled (see ``MySQLAdapter.quote_comment``). +""" + +import pytest + +import datajoint as dj + +TABLE_COMMENT = r"""a table note with "double quotes", it's at C:\new\table, a backslash and a quote \" , and more""" + +DEFINITION = rf""" +# {TABLE_COMMENT} +item_id : int32 # the item's "number", with a trailing backslash \ +--- +quote_double : varchar(16) # a note with "double quotes" +quote_single : varchar(16) # it's a single-quoted note +backslash : varchar(16) # a path like back\slash +backslash_pair : varchar(16) # two backslashes \\ in a row +backslash_sequences : varchar(16) # a path like C:\new\table\0 +backslash_quotes : varchar(16) # a backslash before quotes \" and \' +doubled_quotes : varchar(16) # doubled quotes '' and "" +backslash_double_comma : varchar(16) # a backslash and a double quote \", then a comma +backslash_single_semicolon : varchar(16) # a backslash and a single quote \'; with a semicolon -- and dashes +trailing_backslash : varchar(16) # a note with "double quotes", a comma, and a trailing backslash \ +""" + + +def declared_comments(definition): + """The comment of each attribute line in a definition, as written.""" + return { + line.split(":", 1)[0].strip(): line.split("#", 1)[1].strip() + for line in definition.strip().splitlines()[1:] + if "#" in line + } + + +COMMENTS = declared_comments(DEFINITION) + + +@pytest.fixture +def schema(connection_by_backend, backend, prefix): + schema = dj.Schema(f"{prefix}_comment_quoting_{backend}", connection=connection_by_backend) + yield schema + schema.drop(prompt=False) + + +def stored_comments(table): + return {name: attr.comment for name, attr in table.heading.attributes.items()} + + +def test_comments_stored_as_declared(schema): + @schema + class Item(dj.Manual): + definition = DEFINITION + + assert stored_comments(Item) == COMMENTS + assert Item.heading.table_status["comment"] == TABLE_COMMENT + + +def test_describe_round_trip(schema): + """A table declared from describe() has the same comments and the same describe().""" + + @schema + class Item(dj.Manual): + definition = DEFINITION + + described = Item().describe() + + @schema + class Copy(dj.Manual): + definition = described + + assert stored_comments(Copy) == COMMENTS + assert Copy.heading.table_status["comment"] == TABLE_COMMENT + assert Copy().describe() == described + + +def test_alter_finds_nothing_to_alter(schema, monkeypatch): + @schema + class Item(dj.Manual): + definition = DEFINITION + + def changes_proposed(message): + raise AssertionError(f"alter() proposed changes to an unchanged table:\n{message}") + + monkeypatch.setattr(dj.table, "user_choice", changes_proposed) + Item.alter(prompt=True) + + +def test_foreign_key_copies_comment(schema): + @schema + class Item(dj.Manual): + definition = DEFINITION + + @schema + class Child(dj.Manual): + definition = """ + -> Item + child_id : int32 + """ + + assert Child.heading["item_id"].comment == COMMENTS["item_id"] + assert Child.heading["item_id"].type == Item.heading["item_id"].type + + +def test_alter_writes_comments_as_declared(schema, backend): + if backend == "postgresql": + pytest.skip("alter() changes comments on PostgreSQL from PR 1639") + + # alter() leaves the primary key as it is, so it starts with the key comment + @schema + class Item(dj.Manual): + definition = f""" + item_id : int32 # {COMMENTS['item_id']} + --- + note : varchar(16) + """ + + Item.definition = DEFINITION + Item.alter(prompt=False) + assert stored_comments(Item) == COMMENTS + assert Item.heading.table_status["comment"] == TABLE_COMMENT + + +def test_mysql_comments_without_backslash_escapes(schema, backend): + """With NO_BACKSLASH_ESCAPES, comments are stored as declared except that each backslash is doubled.""" + if backend != "mysql": + pytest.skip("sql_mode is MySQL-specific") + connection = schema.connection + sql_mode = connection.query("SELECT @@SESSION.sql_mode").fetchone()[0] + try: + connection.query("SET SESSION sql_mode = %s", (",".join(filter(None, [sql_mode, "NO_BACKSLASH_ESCAPES"])),)) + + @schema + class Item(dj.Manual): + definition = DEFINITION + + finally: + connection.query("SET SESSION sql_mode = %s", (sql_mode,)) + # Without backslash escapes, MySQL reads each written backslash literally, so a + # backslash is stored doubled and every other character as declared + assert stored_comments(Item) == {name: comment.replace("\\", "\\\\") for name, comment in COMMENTS.items()} + + +def test_postgresql_comments_without_standard_conforming_strings(schema, backend): + """With standard_conforming_strings off, comments are still stored as declared.""" + if backend != "postgresql": + pytest.skip("standard_conforming_strings is PostgreSQL-specific") + connection = schema.connection + setting = connection.query("SHOW standard_conforming_strings").fetchone()[0] + try: + connection.query("SET standard_conforming_strings = off") + + @schema + class Item(dj.Manual): + definition = DEFINITION + + finally: + connection.query(f"SET standard_conforming_strings = {setting}") + assert stored_comments(Item) == COMMENTS + assert Item.heading.table_status["comment"] == TABLE_COMMENT diff --git a/tests/unit/test_comment_quoting.py b/tests/unit/test_comment_quoting.py new file mode 100644 index 000000000..8efc3ad55 --- /dev/null +++ b/tests/unit/test_comment_quoting.py @@ -0,0 +1,178 @@ +""" +Comments are written as string literals that hold exactly the declared text. + +``read_literal`` reads a string literal the way the server does. It checks that +the literal written for a comment ends where the statement ends and reads back as +the comment. MySQL's NO_BACKSLASH_ESCAPES and PostgreSQL's +standard_conforming_strings change how a backslash is read, so both settings are +checked. On MySQL with NO_BACKSLASH_ESCAPES, each backslash is stored doubled +(see ``MySQLAdapter.quote_comment``), so there a comment with a backslash is only +checked to end where the statement ends. +""" + +import pytest + +from datajoint.adapters import get_adapter +from datajoint.declare import compile_attribute +from datajoint.heading import Attribute, default_attribute_properties + +COMMENTS = [ + 'a note with "double quotes"', + "it's a single-quoted note", + "a path like back\\slash", + "two backslashes \\\\ in a row", + "a path like C:\\new\\table\\0", + "a backslash before quotes \\\" and \\'", + "doubled quotes '' and \"\"", + 'a backslash and a double quote \\", then a comma', + "a backslash and a single quote \\'; with a semicolon -- and dashes", + 'a note with "double quotes", a comma, and a trailing backslash \\', + "\\", + '"', + "'", +] + +# Backslash sequences that MySQL and PostgreSQL E'' literals read as one character +ESCAPES = {"0": "\0", "b": "\b", "n": "\n", "r": "\r", "t": "\t", "Z": "\x1a"} + + +def read_literal(sql, *, backslash_escapes): + """ + Read the string literal at the start of ``sql``. + + A quote character written twice stands for one. With ``backslash_escapes``, + a backslash and the character after it stand for one character. + + Returns + ------- + tuple + The text of the literal and the SQL that follows it. + """ + quote = sql[0] + text, i = [], 1 + while i < len(sql): + char = sql[i] + if char == "\\" and backslash_escapes and i + 1 < len(sql): + text.append(ESCAPES.get(sql[i + 1], sql[i + 1])) + i += 2 + elif char == quote and sql[i + 1 : i + 2] == quote: + text.append(quote) + i += 2 + elif char == quote: + return "".join(text), sql[i + 1 :] + else: + text.append(char) + i += 1 + raise AssertionError(f"The literal is not closed: {sql}") + + +@pytest.fixture +def mysql(): + return get_adapter("mysql") + + +@pytest.fixture +def postgres(): + pytest.importorskip("psycopg2") + return get_adapter("postgresql") + + +def read_mysql(sql, prefix, backslash_escapes=True): + assert sql.startswith(prefix) + text, rest = read_literal(sql[len(prefix) :], backslash_escapes=backslash_escapes) + assert rest == "", f"The comment literal ended early: {sql}" + return text + + +def read_postgres(sql, prefix, standard_conforming_strings=True): + assert sql.startswith(prefix) + literal = sql[len(prefix) :] + # An E'' literal reads backslash escapes under either setting + escapes = literal.startswith("E'") or not standard_conforming_strings + text, rest = read_literal(literal.removeprefix("E"), backslash_escapes=escapes) + assert rest == "", f"The comment literal ended early: {sql}" + return text + + +@pytest.mark.parametrize("comment", COMMENTS) +def test_mysql_column_comment(mysql, comment): + sql = mysql.format_column_definition("note", "varchar(16)", comment=comment) + prefix = "`note` varchar(16) NOT NULL COMMENT " + assert read_mysql(sql, prefix) == comment + text = read_mysql(sql, prefix, backslash_escapes=False) + if "\\" not in comment: + assert text == comment + + +@pytest.mark.parametrize("comment", COMMENTS) +def test_mysql_table_comment(mysql, comment): + sql = mysql.table_options_clause(comment) + prefix = "ENGINE=InnoDB, COMMENT " + assert read_mysql(sql, prefix) == comment + text = read_mysql(sql, prefix, backslash_escapes=False) + if "\\" not in comment: + assert text == comment + + +def test_mysql_comment_sql(mysql): + """Only backslashes and double quotes are escaped; other comments are written as before.""" + assert mysql.quote_comment('a "b" c') == '"a ""b"" c"' + assert mysql.quote_comment("a\\b") == '"a\\\\b"' + sql = mysql.format_column_definition("status", "enum('active', 'retired')", comment=":enum('active', 'retired'):status") + assert sql == "`status` enum('active', 'retired') NOT NULL COMMENT \":enum('active', 'retired'):status\"" + + +@pytest.mark.parametrize("standard_conforming_strings", [True, False], ids=["standard", "backslash_escapes"]) +@pytest.mark.parametrize("comment", COMMENTS) +def test_postgres_column_comment(postgres, comment, standard_conforming_strings): + sql = postgres.column_comment_ddl('"schema"."table"', "note", comment) + prefix = 'COMMENT ON COLUMN "schema"."table"."note" IS ' + assert read_postgres(sql, prefix, standard_conforming_strings) == comment + + +@pytest.mark.parametrize("standard_conforming_strings", [True, False], ids=["standard", "backslash_escapes"]) +@pytest.mark.parametrize("comment", COMMENTS) +def test_postgres_table_comment(postgres, comment, standard_conforming_strings): + sql = postgres.table_comment_ddl('"schema"."table"', comment) + prefix = 'COMMENT ON TABLE "schema"."table" IS ' + assert read_postgres(sql, prefix, standard_conforming_strings) == comment + + +def test_postgres_comment_without_backslash_is_a_plain_literal(postgres): + assert postgres.quote_comment('say "hi", it\'s') == "'say \"hi\", it''s'" + assert postgres.quote_comment("a\\b") == "E'a\\\\b'" + + +@pytest.mark.parametrize("backend", ["mysql", "postgresql"]) +def test_compile_attribute_keeps_the_declared_comment(backend): + """The comment returned for COMMENT ON is the declared text, with no escaping added.""" + if backend == "postgresql": + pytest.importorskip("psycopg2") + adapter = get_adapter(backend) + for comment in COMMENTS: + line = f"note : varchar(16) # {comment}" + name, sql, _store, stored = compile_attribute(line, in_key=False, foreign_key_sql=[], context={}, adapter=adapter) + assert name == "note" + assert stored == f":varchar(16):{comment}" + if backend == "mysql": + assert read_mysql(sql, "`note` varchar(16) NOT NULL COMMENT ") == stored + + +def make_attribute(comment): + properties = dict(default_attribute_properties, name="note", type="varchar(16)", original_type="varchar(16)") + return Attribute(**dict(properties, comment=comment)) + + +@pytest.mark.parametrize("comment", COMMENTS) +def test_attribute_sql_quotes_the_comment(comment): + """Attribute.sql writes the comment through the MySQL adapter's quoting.""" + sql = make_attribute(comment).sql + prefix = "`note` varchar(16) NOT NULL COMMENT " + assert read_mysql(sql, prefix) == f":varchar(16):{comment}" + text = read_mysql(sql, prefix, backslash_escapes=False) + if "\\" not in comment: + assert text == f":varchar(16):{comment}" + + +def test_attribute_sql_without_quotes_is_unchanged(): + assert make_attribute("plain").sql == '`note` varchar(16) NOT NULL COMMENT ":varchar(16):plain"'