Skip to content
Open
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
29 changes: 25 additions & 4 deletions src/datajoint/adapters/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
"""
Expand Down Expand Up @@ -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
-------
Expand All @@ -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
-------
Expand All @@ -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
-------
Expand All @@ -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
-------
Expand Down
35 changes: 33 additions & 2 deletions src/datajoint/adapters/mysql.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand Down
42 changes: 35 additions & 7 deletions src/datajoint/adapters/postgres.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
"""
Expand All @@ -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:
"""
Expand Down
4 changes: 1 addition & 3 deletions src/datajoint/declare.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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))

Expand Down
12 changes: 9 additions & 3 deletions src/datajoint/heading.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading