From a7d814ada9b7721e60dac40fc4ab7da95cb7a214 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Mon, 23 Nov 2026 17:02:33 -0600 Subject: [PATCH 1/6] Store comments with quotes and backslashes as declared on both backends compile_attribute wrote each double quote in an attribute comment as \", which MySQL reads as a quote but PostgreSQL stores with the backslash. The escaping moves into the adapters through a new quote_comment(): - MySQL keeps the double-quoted COMMENT "..." form and escapes the comment like quote_string, doubling a double quote so the literal stays closed under NO_BACKSLASH_ESCAPES. Table comments, which were written unescaped, use it too, including in alter(). - PostgreSQL writes a comment containing a backslash as an E'...' literal, which reads the same under either standard_conforming_strings setting. --- src/datajoint/adapters/base.py | 27 +++- src/datajoint/adapters/mysql.py | 31 +++- src/datajoint/adapters/postgres.py | 42 +++++- src/datajoint/declare.py | 4 +- tests/integration/test_comment_quoting.py | 165 ++++++++++++++++++++++ tests/unit/test_comment_quoting.py | 148 +++++++++++++++++++ 6 files changed, 401 insertions(+), 16 deletions(-) create mode 100644 tests/integration/test_comment_quoting.py create mode 100644 tests/unit/test_comment_quoting.py diff --git a/src/datajoint/adapters/base.py b/src/datajoint/adapters/base.py index 1aa12f52f..403028c2d 100644 --- a/src/datajoint/adapters/base.py +++ b/src/datajoint/adapters/base.py @@ -207,6 +207,25 @@ 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. + + 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 +1248,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 +1270,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 +1294,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 +1320,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..fcbeff4e4 100644 --- a/src/datajoint/adapters/mysql.py +++ b/src/datajoint/adapters/mysql.py @@ -289,6 +289,33 @@ 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. The comment is escaped like ``quote_string``: a double quote is + doubled rather than escaped with a backslash, so the literal stays closed + even under NO_BACKSLASH_ESCAPES. + + 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 = client.converters.escape_string(comment).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 +1057,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 +1073,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/tests/integration/test_comment_quoting.py b/tests/integration/test_comment_quoting.py new file mode 100644 index 000000000..eed2fc7fa --- /dev/null +++ b/tests/integration/test_comment_quoting.py @@ -0,0 +1,165 @@ +""" +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. +""" + +import pytest + +import datajoint as dj + +TABLE_COMMENT = r"""a "quoted" table, it's at C:\new\table \" , x""" + +DEFINITION = rf""" +# {TABLE_COMMENT} +item_id : int32 # key "quoted", it's \ +--- +double_quotes : varchar(16) # say "hi" +single_quote : varchar(16) # it's a test +backslash : varchar(16) # back\slash +escape_sequences : varchar(16) # C:\new\table\0 +escaped_quotes : varchar(16) # a \" b \' c +doubled_quotes : varchar(16) # a '' b "" c +breakout_double : varchar(16) # x\" , injected int NOT NULL COMMENT " +breakout_single : varchar(16) # x\'; SELECT 1; -- +trailing_backslash : varchar(16) # ends with a 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 Item.heading.names == list(COMMENTS) + 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, each comment still ends where it should.""" + 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,)) + assert Item.heading.names == list(COMMENTS) + assert stored_comments(Item)["double_quotes"] == COMMENTS["double_quotes"] + + +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..bbc251c17 --- /dev/null +++ b/tests/unit/test_comment_quoting.py @@ -0,0 +1,148 @@ +""" +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. +""" + +import pytest + +from datajoint.adapters import get_adapter +from datajoint.declare import compile_attribute + +COMMENTS = [ + 'say "hi"', + "it's a test", + "back\\slash", + "C:\\new\\table\\0", + "a \\\" b \\' c", + "a '' b \"\" c", + 'x\\" , injected int NOT NULL COMMENT "', + "x\\'; SELECT 1; --", + "ends with a 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 + read_mysql(sql, prefix, backslash_escapes=False) + + +@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 + read_mysql(sql, prefix, backslash_escapes=False) + + +def test_mysql_comment_without_backslash_reads_the_same_under_no_backslash_escapes(mysql): + sql = mysql.format_column_definition("note", "varchar(16)", comment='a "b" c') + assert sql == '`note` varchar(16) NOT NULL COMMENT "a ""b"" c"' + assert read_mysql(sql, "`note` varchar(16) NOT NULL COMMENT ", backslash_escapes=False) == 'a "b" c' + + +@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 From 74ab0ef2a86f4443e598087a721f9f39dfd3abff Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Mon, 23 Nov 2026 17:10:16 -0600 Subject: [PATCH 2/6] Escape only backslashes and double quotes in MySQL comments Single quotes need no escape inside a double-quoted literal, and the type marker of an enum attribute contains them. Leaving them as they are keeps the SQL of those columns unchanged and stores them exactly under NO_BACKSLASH_ESCAPES. --- src/datajoint/adapters/mysql.py | 10 ++++++---- tests/integration/test_comment_quoting.py | 6 +++++- tests/unit/test_comment_quoting.py | 18 ++++++++++++------ 3 files changed, 23 insertions(+), 11 deletions(-) diff --git a/src/datajoint/adapters/mysql.py b/src/datajoint/adapters/mysql.py index fcbeff4e4..e5d4b4d16 100644 --- a/src/datajoint/adapters/mysql.py +++ b/src/datajoint/adapters/mysql.py @@ -294,9 +294,11 @@ 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. The comment is escaped like ``quote_string``: a double quote is - doubled rather than escaped with a backslash, so the literal stays closed - even under NO_BACKSLASH_ESCAPES. + them. Only two characters are escaped: a backslash is doubled, and a + double quote is doubled (``""``) rather than escaped with a backslash, so + the literal stays closed even under NO_BACKSLASH_ESCAPES. Single quotes, + which the ``:type:`` marker of an enum attribute contains, are left as + they are. Parameters ---------- @@ -313,7 +315,7 @@ def quote_comment(self, comment: str) -> str: >>> adapter.quote_comment('a "b" c') '"a ""b"" c"' """ - escaped = client.converters.escape_string(comment).replace('\\"', '""') + escaped = comment.replace("\\", "\\\\").replace('"', '""') return f'"{escaped}"' def get_master_table_name(self, part_table: str) -> str | None: diff --git a/tests/integration/test_comment_quoting.py b/tests/integration/test_comment_quoting.py index eed2fc7fa..24c980c99 100644 --- a/tests/integration/test_comment_quoting.py +++ b/tests/integration/test_comment_quoting.py @@ -143,7 +143,11 @@ class Item(dj.Manual): finally: connection.query("SET SESSION sql_mode = %s", (sql_mode,)) assert Item.heading.names == list(COMMENTS) - assert stored_comments(Item)["double_quotes"] == COMMENTS["double_quotes"] + # Without backslash escapes a backslash is stored doubled; every other character as declared + stored = stored_comments(Item) + assert {name: stored[name] for name, comment in COMMENTS.items() if "\\" not in comment} == { + name: comment for name, comment in COMMENTS.items() if "\\" not in comment + } def test_postgresql_comments_without_standard_conforming_strings(schema, backend): diff --git a/tests/unit/test_comment_quoting.py b/tests/unit/test_comment_quoting.py index bbc251c17..264da309a 100644 --- a/tests/unit/test_comment_quoting.py +++ b/tests/unit/test_comment_quoting.py @@ -95,7 +95,9 @@ 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 - read_mysql(sql, prefix, backslash_escapes=False) + text = read_mysql(sql, prefix, backslash_escapes=False) + if "\\" not in comment: + assert text == comment @pytest.mark.parametrize("comment", COMMENTS) @@ -103,13 +105,17 @@ def test_mysql_table_comment(mysql, comment): sql = mysql.table_options_clause(comment) prefix = "ENGINE=InnoDB, COMMENT " assert read_mysql(sql, prefix) == comment - read_mysql(sql, prefix, backslash_escapes=False) + text = read_mysql(sql, prefix, backslash_escapes=False) + if "\\" not in comment: + assert text == comment -def test_mysql_comment_without_backslash_reads_the_same_under_no_backslash_escapes(mysql): - sql = mysql.format_column_definition("note", "varchar(16)", comment='a "b" c') - assert sql == '`note` varchar(16) NOT NULL COMMENT "a ""b"" c"' - assert read_mysql(sql, "`note` varchar(16) NOT NULL COMMENT ", backslash_escapes=False) == 'a "b" c' +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"]) From 898f6dd679e837cd5d82b971bf189b6366ed1edc Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Mon, 23 Nov 2026 17:38:13 -0600 Subject: [PATCH 3/6] Quote the comment in Attribute.sql through the MySQL adapter Attribute.sql wrote COMMENT "{comment}" without escaping. It now uses MySQLAdapter.quote_identifier and quote_comment, so a comment with a double quote or a backslash reads back as declared. Comments without either produce the same SQL as before. --- src/datajoint/heading.py | 12 +++++++++--- tests/unit/test_comment_quoting.py | 21 +++++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) 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/unit/test_comment_quoting.py b/tests/unit/test_comment_quoting.py index 264da309a..9a3d35e8d 100644 --- a/tests/unit/test_comment_quoting.py +++ b/tests/unit/test_comment_quoting.py @@ -12,6 +12,7 @@ from datajoint.adapters import get_adapter from datajoint.declare import compile_attribute +from datajoint.heading import Attribute, default_attribute_properties COMMENTS = [ 'say "hi"', @@ -152,3 +153,23 @@ def test_compile_attribute_keeps_the_declared_comment(backend): 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"' From 837e30e68fc75e39f01201e2f3f88c2fca12b562 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Mon, 23 Nov 2026 18:11:09 -0600 Subject: [PATCH 4/6] Use ordinary comment text in the comment quoting tests The test comments now read as ordinary notes with double quotes, single quotes, commas, semicolons, dashes and backslashes. They still cover each case: a quote of either kind after a backslash followed by more text, a trailing backslash, backslash sequences, doubled quotes, and both quoting settings. The NO_BACKSLASH_ESCAPES test now checks every stored comment, including that each backslash is stored doubled. --- tests/integration/test_comment_quoting.py | 35 +++++++++++------------ tests/unit/test_comment_quoting.py | 19 ++++++------ 2 files changed, 26 insertions(+), 28 deletions(-) diff --git a/tests/integration/test_comment_quoting.py b/tests/integration/test_comment_quoting.py index 24c980c99..f938fe41e 100644 --- a/tests/integration/test_comment_quoting.py +++ b/tests/integration/test_comment_quoting.py @@ -11,21 +11,22 @@ import datajoint as dj -TABLE_COMMENT = r"""a "quoted" table, it's at C:\new\table \" , x""" +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 # key "quoted", it's \ +item_id : int32 # the item's "number", with a trailing backslash \ --- -double_quotes : varchar(16) # say "hi" -single_quote : varchar(16) # it's a test -backslash : varchar(16) # back\slash -escape_sequences : varchar(16) # C:\new\table\0 -escaped_quotes : varchar(16) # a \" b \' c -doubled_quotes : varchar(16) # a '' b "" c -breakout_double : varchar(16) # x\" , injected int NOT NULL COMMENT " -breakout_single : varchar(16) # x\'; SELECT 1; -- -trailing_backslash : varchar(16) # ends with a 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 \ """ @@ -57,7 +58,6 @@ def test_comments_stored_as_declared(schema): class Item(dj.Manual): definition = DEFINITION - assert Item.heading.names == list(COMMENTS) assert stored_comments(Item) == COMMENTS assert Item.heading.table_status["comment"] == TABLE_COMMENT @@ -128,7 +128,7 @@ class Item(dj.Manual): def test_mysql_comments_without_backslash_escapes(schema, backend): - """With NO_BACKSLASH_ESCAPES, each comment still ends where it should.""" + """With NO_BACKSLASH_ESCAPES, comments are stored as declared, with each backslash doubled.""" if backend != "mysql": pytest.skip("sql_mode is MySQL-specific") connection = schema.connection @@ -142,12 +142,9 @@ class Item(dj.Manual): finally: connection.query("SET SESSION sql_mode = %s", (sql_mode,)) - assert Item.heading.names == list(COMMENTS) - # Without backslash escapes a backslash is stored doubled; every other character as declared - stored = stored_comments(Item) - assert {name: stored[name] for name, comment in COMMENTS.items() if "\\" not in comment} == { - name: comment for name, comment in COMMENTS.items() if "\\" not in comment - } + # 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): diff --git a/tests/unit/test_comment_quoting.py b/tests/unit/test_comment_quoting.py index 9a3d35e8d..530da1b22 100644 --- a/tests/unit/test_comment_quoting.py +++ b/tests/unit/test_comment_quoting.py @@ -15,15 +15,16 @@ from datajoint.heading import Attribute, default_attribute_properties COMMENTS = [ - 'say "hi"', - "it's a test", - "back\\slash", - "C:\\new\\table\\0", - "a \\\" b \\' c", - "a '' b \"\" c", - 'x\\" , injected int NOT NULL COMMENT "', - "x\\'; SELECT 1; --", - "ends with a backslash \\", + '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 \\', "\\", '"', "'", From 8b6db06902d42f62f059960d5f7f97955ab1a48b Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Mon, 23 Nov 2026 18:52:04 -0600 Subject: [PATCH 5/6] Describe how MySQL stores a comment backslash under NO_BACKSLASH_ESCAPES --- src/datajoint/adapters/mysql.py | 8 +++++--- tests/integration/test_comment_quoting.py | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/datajoint/adapters/mysql.py b/src/datajoint/adapters/mysql.py index e5d4b4d16..2dc7bbfaa 100644 --- a/src/datajoint/adapters/mysql.py +++ b/src/datajoint/adapters/mysql.py @@ -296,9 +296,11 @@ def quote_comment(self, comment: str) -> str: 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 literal stays closed even under NO_BACKSLASH_ESCAPES. Single quotes, - which the ``:type:`` marker of an enum attribute contains, are left as - they are. + 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 ---------- diff --git a/tests/integration/test_comment_quoting.py b/tests/integration/test_comment_quoting.py index f938fe41e..5d3a8fc27 100644 --- a/tests/integration/test_comment_quoting.py +++ b/tests/integration/test_comment_quoting.py @@ -128,7 +128,7 @@ class Item(dj.Manual): def test_mysql_comments_without_backslash_escapes(schema, backend): - """With NO_BACKSLASH_ESCAPES, comments are stored as declared, with each backslash doubled.""" + """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 From 1f8ee35d1cf2c1606d2f833b1586b14fac5b5bd8 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Mon, 23 Nov 2026 19:13:04 -0600 Subject: [PATCH 6/6] Note the NO_BACKSLASH_ESCAPES exception in comment-quoting docstrings --- src/datajoint/adapters/base.py | 4 +++- tests/integration/test_comment_quoting.py | 3 ++- tests/unit/test_comment_quoting.py | 4 +++- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/datajoint/adapters/base.py b/src/datajoint/adapters/base.py index 403028c2d..3ab79b3c9 100644 --- a/src/datajoint/adapters/base.py +++ b/src/datajoint/adapters/base.py @@ -212,7 +212,9 @@ 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. + 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 ---------- diff --git a/tests/integration/test_comment_quoting.py b/tests/integration/test_comment_quoting.py index 5d3a8fc27..18874b190 100644 --- a/tests/integration/test_comment_quoting.py +++ b/tests/integration/test_comment_quoting.py @@ -4,7 +4,8 @@ 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. +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 diff --git a/tests/unit/test_comment_quoting.py b/tests/unit/test_comment_quoting.py index 530da1b22..8efc3ad55 100644 --- a/tests/unit/test_comment_quoting.py +++ b/tests/unit/test_comment_quoting.py @@ -5,7 +5,9 @@ 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. +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