From 46b932b792be6779f70e04ea4ee8f64b13d5a253 Mon Sep 17 00:00:00 2001 From: TEJA P C Date: Thu, 26 Nov 2026 01:14:23 +0000 Subject: [PATCH] fix(django-google-spanner): unconditionally quote all identifiers in quote_name quote_name() returned valid unreserved regular ASCII identifiers unquoted, which required tracking SPANNER_RESERVED_KEYWORDS. Remove the fast path so all identifiers are escaped and wrapped in backticks, and update the unit and mockserver SQL expectations accordingly. Fixes #19072 --- .../django_spanner/operations.py | 30 ++----- .../tests/mockserver_tests/test_basics.py | 48 +++++------ .../unit/django_spanner/test_compiler.py | 70 +++++++-------- .../unit/django_spanner/test_expressions.py | 11 +-- .../unit/django_spanner/test_functions.py | 58 ++++++------- .../tests/unit/django_spanner/test_lookups.py | 86 +++++++++---------- .../unit/django_spanner/test_operations.py | 24 +++--- .../tests/unit/django_spanner/test_schema.py | 66 +++++++------- 8 files changed, 192 insertions(+), 201 deletions(-) diff --git a/packages/django-google-spanner/django_spanner/operations.py b/packages/django-google-spanner/django_spanner/operations.py index b19a111958ad..7520e8ef1af8 100644 --- a/packages/django-google-spanner/django_spanner/operations.py +++ b/packages/django-google-spanner/django_spanner/operations.py @@ -17,18 +17,12 @@ from django.db.utils import DatabaseError from django.utils import timezone from django.utils.duration import duration_microseconds -from google.cloud.spanner_dbapi.parse_utils import ( - SPANNER_RESERVED_KEYWORDS, - TYPES_MAP, - DateStr, - TimestampStr, -) +from google.cloud.spanner_dbapi.parse_utils import TYPES_MAP, DateStr, TimestampStr from google.cloud.spanner_v1 import JsonObject, param_types _QUOTED_IDENTIFIER_RE = re.compile( r"\A`(?:\\\\|\\[abfnrtv]|\\x[0-9a-fA-F]{2}|[^`\\\x00-\x1f\x7f])+`\Z" ) -_REGULAR_IDENTIFIER_RE = re.compile(r"\A[A-Za-z_][A-Za-z0-9_]*\Z") _IDENTIFIER_ESCAPE_TABLE = str.maketrans( { **{chr(code): f"\\x{code:02x}" for code in (*range(0x20), 0x7F)}, @@ -129,12 +123,11 @@ def quote_name(self, name: str) -> str: """ Return a quoted version of the given table, index, or column name. - Valid unreserved regular ASCII identifiers are returned unquoted, and - single identifiers already validly quoted using safe GoogleSQL escapes - are returned unchanged. All other identifiers (including reserved - keywords and names containing dots, spaces, hyphens, embedded - backticks, backslashes, or ASCII control characters) are escaped and - wrapped in backticks as a single identifier. + All identifiers are escaped and wrapped in backticks as a single + identifier, including reserved keywords and names containing dots, + spaces, hyphens, embedded backticks, backslashes, or ASCII control + characters. Single identifiers already validly quoted using safe + GoogleSQL escapes are returned unchanged. Spanner does not allow spaces, hyphens, or '>' in table, index, or constraint names, even when quoted. Only when running Django's own @@ -147,7 +140,7 @@ def quote_name(self, name: str) -> str: :rtype: :class:`str` :returns: Quoted identifier, or the identifier unchanged if it is - already quoted or a valid unreserved regular identifier. + already quoted. :raises TypeError: If ``name`` is not a string. """ if not isinstance(name, str): @@ -158,15 +151,6 @@ def quote_name(self, name: str) -> str: name = name.replace(" ", "_").replace("-", "_").replace(">", "_") if _QUOTED_IDENTIFIER_RE.match(name): return name - # TODO(https://github.com/googleapis/google-cloud-python/issues/19072): - # Unconditionally quote all identifiers in a follow-up PR (after fixing - # schema.py check-constraint/trace quoting and updating SQL tests) so - # reserved keyword tracking is no longer required. - if ( - _REGULAR_IDENTIFIER_RE.match(name) - and name.upper() not in SPANNER_RESERVED_KEYWORDS - ): - return name escaped = name.translate(_IDENTIFIER_ESCAPE_TABLE) return f"`{escaped}`" diff --git a/packages/django-google-spanner/tests/mockserver_tests/test_basics.py b/packages/django-google-spanner/tests/mockserver_tests/test_basics.py index 9cae482075db..686a70044575 100644 --- a/packages/django-google-spanner/tests/mockserver_tests/test_basics.py +++ b/packages/django-google-spanner/tests/mockserver_tests/test_basics.py @@ -65,7 +65,7 @@ def test_django_select1(self): def test_django_select_singer(self): add_singer_query_result( - "SELECT tests_singer.id, tests_singer.first_name, tests_singer.last_name FROM tests_singer" + "SELECT `tests_singer`.`id`, `tests_singer`.`first_name`, `tests_singer`.`last_name` FROM `tests_singer`" ) singers = Singer.objects.all() self.assertEqual(len(singers), 2) @@ -77,7 +77,7 @@ def test_django_select_singer(self): def test_django_select_singer_using_other_db(self): add_singer_query_result( - "SELECT tests_singer.id, tests_singer.first_name, tests_singer.last_name FROM tests_singer" + "SELECT `tests_singer`.`id`, `tests_singer`.`first_name`, `tests_singer`.`last_name` FROM `tests_singer`" ) singers = Singer.objects.using("secondary").all() self.assertEqual(len(singers), 2) @@ -89,10 +89,10 @@ def test_django_select_singer_using_other_db(self): def test_insert_singer(self): add_single_result( - "INSERT INTO tests_singer " - "(id, first_name, last_name) " + "INSERT INTO `tests_singer` " + "(`id`, `first_name`, `last_name`) " "VALUES (@a0, @a1, @a2) " - "THEN RETURN id", + "THEN RETURN `id`", "id", TypeCode.INT64, [("1",)], @@ -124,10 +124,10 @@ class LocalSinger(models.Model): try: add_single_result( - "INSERT INTO tests_localsinger " - "(first_name, last_name) " + "INSERT INTO `tests_localsinger` " + "(`first_name`, `last_name`) " "VALUES (@a0, @a1) " - "THEN RETURN id", + "THEN RETURN `id`", "id", TypeCode.INT64, [("1",)], @@ -156,7 +156,7 @@ def test_update_all_without_dbapi_intervention(self): "google.cloud.spanner_dbapi.parse_utils.ensure_where_clause", side_effect=lambda sql: sql, ): - add_update_count("UPDATE tests_singer SET last_name = @a0 WHERE 1=1", 1) + add_update_count("UPDATE `tests_singer` SET `last_name` = @a0 WHERE 1=1", 1) Singer.objects.all().update(last_name="Test") requests = [ @@ -167,7 +167,7 @@ def test_update_all_without_dbapi_intervention(self): self.assertEqual(len(requests), 1) self.assertEqual( requests[0].sql, - "UPDATE tests_singer SET last_name = @a0 WHERE 1=1", + "UPDATE `tests_singer` SET `last_name` = @a0 WHERE 1=1", ) def test_delete_all_without_dbapi_intervention(self): @@ -176,7 +176,7 @@ def test_delete_all_without_dbapi_intervention(self): "google.cloud.spanner_dbapi.parse_utils.ensure_where_clause", side_effect=lambda sql: sql, ): - add_update_count("DELETE FROM tests_singer WHERE 1=1", 1) + add_update_count("DELETE FROM `tests_singer` WHERE 1=1", 1) Singer.objects.all().delete() requests = [ @@ -187,7 +187,7 @@ def test_delete_all_without_dbapi_intervention(self): self.assertEqual(len(requests), 1) self.assertEqual( requests[0].sql, - "DELETE FROM tests_singer WHERE 1=1", + "DELETE FROM `tests_singer` WHERE 1=1", ) def _make_detail_result_set(self, rows): @@ -226,29 +226,29 @@ def _make_detail_result_set(self, rows): def test_insert_and_fetch_json_field(self): add_single_result( - "INSERT INTO tests_detail (id, value) VALUES (@a0, @a1) THEN RETURN id", + "INSERT INTO `tests_detail` (`id`, `value`) VALUES (@a0, @a1) THEN RETURN `id`", "id", TypeCode.INT64, [("1",)], ) add_result( - "INSERT INTO tests_detail (id, value) VALUES (@a0, @a1) THEN RETURN id, value", + "INSERT INTO `tests_detail` (`id`, `value`) VALUES (@a0, @a1) THEN RETURN `id`, `value`", self._make_detail_result_set([("1", "null")]), ) add_single_result( - "INSERT INTO tests_detail (id, value) VALUES (@a0, @a1), (@a2, @a3)", + "INSERT INTO `tests_detail` (`id`, `value`) VALUES (@a0, @a1), (@a2, @a3)", "id", TypeCode.INT64, [("10",), ("11",)], ) add_single_result( - "UPDATE tests_detail SET value = @a0 WHERE tests_detail.id = @a1", + "UPDATE `tests_detail` SET `value` = @a0 WHERE `tests_detail`.`id` = @a1", "id", TypeCode.INT64, [("1",)], ) add_result( - "SELECT tests_detail.id, tests_detail.value FROM tests_detail", + "SELECT `tests_detail`.`id`, `tests_detail`.`value` FROM `tests_detail`", self._make_detail_result_set( [ ("1", '{"age": "26", "name": "Jakob"}'), @@ -263,19 +263,19 @@ def test_insert_and_fetch_json_field(self): ), ) add_result( - "SELECT tests_detail.id, tests_detail.value FROM tests_detail WHERE JSON_QUERY(tests_detail.value, '$.\"name\"') = @a0", + "SELECT `tests_detail`.`id`, `tests_detail`.`value` FROM `tests_detail` WHERE JSON_QUERY(`tests_detail`.`value`, '$.\"name\"') = @a0", self._make_detail_result_set([("1", '{"age": "26", "name": "Jakob"}')]), ) add_result( - "SELECT tests_detail.id, tests_detail.value FROM tests_detail WHERE JSON_QUERY(tests_detail.value, '$.\"name\"') IS NOT NULL", + "SELECT `tests_detail`.`id`, `tests_detail`.`value` FROM `tests_detail` WHERE JSON_QUERY(`tests_detail`.`value`, '$.\"name\"') IS NOT NULL", self._make_detail_result_set([("1", '{"age": "26", "name": "Jakob"}')]), ) add_result( - "SELECT tests_detail.id, tests_detail.value FROM tests_detail WHERE tests_detail.value = @a0", + "SELECT `tests_detail`.`id`, `tests_detail`.`value` FROM `tests_detail` WHERE `tests_detail`.`value` = @a0", self._make_detail_result_set([("8", "null")]), ) add_result( - "SELECT tests_detail.id, tests_detail.value FROM tests_detail WHERE tests_detail.value IS NULL", + "SELECT `tests_detail`.`id`, `tests_detail`.`value` FROM `tests_detail` WHERE `tests_detail`.`value` IS NULL", self._make_detail_result_set([("3", None)]), ) @@ -413,7 +413,7 @@ def test_check_constraint_validate(self): name="first_name_alice", ) sql_non_null = ( - "SELECT @a0 AS _check FROM UNNEST([1]) WHERE COALESCE((@a1 = @a2), @a3)" + "SELECT @a0 AS `_check` FROM UNNEST([1]) WHERE COALESCE((@a1 = @a2), @a3)" ) # Valid instance -> returns 1 row -> passes @@ -427,7 +427,7 @@ def test_check_constraint_validate(self): # Null field -> emits typed CAST(NULL AS STRING) -> returns 1 row -> passes sql_null = ( - "SELECT @a0 AS _check FROM UNNEST([1]) " + "SELECT @a0 AS `_check` FROM UNNEST([1]) " "WHERE COALESCE((CAST(NULL AS STRING) = @a1), @a2)" ) add_single_result(sql_null, "_check", TypeCode.INT64, [("1",)]) @@ -478,7 +478,7 @@ class Meta: name="positive_rating", ) sql_float = ( - "SELECT @a0 AS _check FROM UNNEST([1]) " + "SELECT @a0 AS `_check` FROM UNNEST([1]) " "WHERE COALESCE((CAST(@a1 AS FLOAT64) > @a2), @a3)" ) add_single_result(sql_float, "_check", TypeCode.INT64, [("1",)]) diff --git a/packages/django-google-spanner/tests/unit/django_spanner/test_compiler.py b/packages/django-google-spanner/tests/unit/django_spanner/test_compiler.py index 830f70465b1f..a40b0ef3669e 100644 --- a/packages/django-google-spanner/tests/unit/django_spanner/test_compiler.py +++ b/packages/django-google-spanner/tests/unit/django_spanner/test_compiler.py @@ -49,9 +49,9 @@ def test_get_combinator_sql_all_union_sql_generated(self): self.assertEqual( sql_compiled, [ - "SELECT tests_number.num AS num FROM tests_number WHERE " - + "tests_number.num <= %s UNION ALL SELECT tests_number.num " - + "AS num FROM tests_number WHERE tests_number.num >= %s" + "SELECT `tests_number`.`num` AS `num` FROM `tests_number` WHERE " + + "`tests_number`.`num` <= %s UNION ALL SELECT `tests_number`.`num` " + + "AS `num` FROM `tests_number` WHERE `tests_number`.`num` >= %s" ], ) self.assertEqual(params, [1, 8]) @@ -70,10 +70,10 @@ def test_get_combinator_sql_distinct_union_sql_generated(self): self.assertEqual( sql_compiled, [ - "SELECT tests_number.num AS num FROM tests_number WHERE " - + "tests_number.num <= %s UNION DISTINCT SELECT " - + "tests_number.num AS num FROM tests_number WHERE " - + "tests_number.num >= %s" + "SELECT `tests_number`.`num` AS `num` FROM `tests_number` WHERE " + + "`tests_number`.`num` <= %s UNION DISTINCT SELECT " + + "`tests_number`.`num` AS `num` FROM `tests_number` WHERE " + + "`tests_number`.`num` >= %s" ], ) self.assertEqual(params, [1, 8]) @@ -92,9 +92,9 @@ def test_get_combinator_sql_difference_all_sql_generated(self): self.assertEqual( sql_compiled, [ - "SELECT tests_number.num AS num FROM tests_number WHERE " - + "tests_number.num <= %s EXCEPT ALL SELECT tests_number.num " - + "AS num FROM tests_number WHERE tests_number.num >= %s" + "SELECT `tests_number`.`num` AS `num` FROM `tests_number` WHERE " + + "`tests_number`.`num` <= %s EXCEPT ALL SELECT `tests_number`.`num` " + + "AS `num` FROM `tests_number` WHERE `tests_number`.`num` >= %s" ], ) self.assertEqual(params, [1, 8]) @@ -113,10 +113,10 @@ def test_get_combinator_sql_difference_distinct_sql_generated(self): self.assertEqual( sql_compiled, [ - "SELECT tests_number.num AS num FROM tests_number WHERE " - + "tests_number.num <= %s EXCEPT DISTINCT SELECT " - + "tests_number.num AS num FROM tests_number WHERE " - + "tests_number.num >= %s" + "SELECT `tests_number`.`num` AS `num` FROM `tests_number` WHERE " + + "`tests_number`.`num` <= %s EXCEPT DISTINCT SELECT " + + "`tests_number`.`num` AS `num` FROM `tests_number` WHERE " + + "`tests_number`.`num` >= %s" ], ) self.assertEqual(params, [1, 8]) @@ -135,12 +135,12 @@ def test_get_combinator_sql_union_and_difference_query_together(self): self.assertEqual( sql_compiled, [ - "SELECT tests_number.num AS num FROM tests_number WHERE " - + "tests_number.num <= %s UNION DISTINCT SELECT * FROM (" - + "SELECT tests_number.num AS num FROM tests_number WHERE " - + "tests_number.num >= %s EXCEPT DISTINCT " - + "SELECT tests_number.num AS num FROM tests_number " - + "WHERE tests_number.num = %s)" + "SELECT `tests_number`.`num` AS `num` FROM `tests_number` WHERE " + + "`tests_number`.`num` <= %s UNION DISTINCT SELECT * FROM (" + + "SELECT `tests_number`.`num` AS `num` FROM `tests_number` WHERE " + + "`tests_number`.`num` >= %s EXCEPT DISTINCT " + + "SELECT `tests_number`.`num` AS `num` FROM `tests_number` " + + "WHERE `tests_number`.`num` = %s)" ], ) self.assertEqual(params, [1, 8, 10]) @@ -162,12 +162,12 @@ def test_get_combinator_sql_parentheses_in_compound_not_supported(self): self.assertEqual( sql_compiled, [ - "SELECT tests_number.num AS num FROM tests_number WHERE " - + "tests_number.num <= %s UNION DISTINCT SELECT * FROM (" - + "SELECT tests_number.num AS num FROM tests_number WHERE " - + "tests_number.num >= %s EXCEPT DISTINCT " - + "SELECT tests_number.num AS num FROM tests_number " - + "WHERE tests_number.num = %s)" + "SELECT `tests_number`.`num` AS `num` FROM `tests_number` WHERE " + + "`tests_number`.`num` <= %s UNION DISTINCT SELECT * FROM (" + + "SELECT `tests_number`.`num` AS `num` FROM `tests_number` WHERE " + + "`tests_number`.`num` >= %s EXCEPT DISTINCT " + + "SELECT `tests_number`.`num` AS `num` FROM `tests_number` " + + "WHERE `tests_number`.`num` = %s)" ], ) self.assertEqual(params, [1, 8, 10]) @@ -185,14 +185,16 @@ def test_unqualified_delete_appends_dummy_where(self): delete_query = Number.objects.all().query.chain(DeleteQuery) compiler = SQLDeleteCompiler(delete_query, self.connection, "default") sql, _ = compiler.as_sql() - self.assertEqual(sql, "DELETE FROM tests_number WHERE 1=1") + self.assertEqual(sql, "DELETE FROM `tests_number` WHERE 1=1") def test_qualified_delete_preserves_where(self): """Test that qualified DELETE statements do not append extra WHERE 1=1.""" delete_query = Number.objects.filter(num=1).query.chain(DeleteQuery) compiler = SQLDeleteCompiler(delete_query, self.connection, "default") sql, parameters = compiler.as_sql() - self.assertEqual(sql, "DELETE FROM tests_number WHERE tests_number.num = %s") + self.assertEqual( + sql, "DELETE FROM `tests_number` WHERE `tests_number`.`num` = %s" + ) self.assertEqual(parameters, (1,)) def test_unqualified_update_appends_dummy_where(self): @@ -201,7 +203,7 @@ def test_unqualified_update_appends_dummy_where(self): update_query.add_update_values({"num": 5}) compiler = SQLUpdateCompiler(update_query, self.connection, "default") sql, _ = compiler.as_sql() - self.assertEqual(sql, "UPDATE tests_number SET num = %s WHERE 1=1") + self.assertEqual(sql, "UPDATE `tests_number` SET `num` = %s WHERE 1=1") def test_qualified_update_preserves_where(self): """Test that qualified UPDATE statements do not append extra WHERE 1=1.""" @@ -210,7 +212,7 @@ def test_qualified_update_preserves_where(self): compiler = SQLUpdateCompiler(update_query, self.connection, "default") sql, parameters = compiler.as_sql() self.assertEqual( - sql, "UPDATE tests_number SET num = %s WHERE tests_number.num = %s" + sql, "UPDATE `tests_number` SET `num` = %s WHERE `tests_number`.`num` = %s" ) self.assertEqual(parameters, (5, 1)) @@ -219,7 +221,7 @@ def test_full_result_set_delete_appends_dummy_where(self): delete_query = Number.objects.filter(~Q(num__in=[])).query.chain(DeleteQuery) compiler = SQLDeleteCompiler(delete_query, self.connection, "default") sql, _ = compiler.as_sql() - self.assertEqual(sql, "DELETE FROM tests_number WHERE 1=1") + self.assertEqual(sql, "DELETE FROM `tests_number` WHERE 1=1") def test_full_result_set_update_appends_dummy_where(self): """Test that UPDATE raising FullResultSet automatically appends WHERE 1=1.""" @@ -227,7 +229,7 @@ def test_full_result_set_update_appends_dummy_where(self): update_query.add_update_values({"num": 5}) compiler = SQLUpdateCompiler(update_query, self.connection, "default") sql, _ = compiler.as_sql() - self.assertEqual(sql, "UPDATE tests_number SET num = %s WHERE 1=1") + self.assertEqual(sql, "UPDATE `tests_number` SET `num` = %s WHERE 1=1") def test_joined_delete_does_not_duplicate_where(self): """Test that DELETE with joins/annotations retains single WHERE clause.""" @@ -310,7 +312,7 @@ def test_bare_select_uses_from_unnest(self): query.add_annotation(Value(1), "_check") compiler = SQLCompiler(query, self.connection, "default") sql, parameters = compiler.as_sql() - self.assertEqual(sql, "SELECT %s AS _check FROM UNNEST([1])") + self.assertEqual(sql, "SELECT %s AS `_check` FROM UNNEST([1])") self.assertEqual(parameters, (1,)) query_with_where = Query(None) @@ -323,6 +325,6 @@ def test_bare_select_uses_from_unnest(self): sql, parameters = compiler.as_sql() self.assertEqual( sql, - "SELECT %s AS _check FROM UNNEST([1]) WHERE COALESCE((%s > %s), %s)", + "SELECT %s AS `_check` FROM UNNEST([1]) WHERE COALESCE((%s > %s), %s)", ) self.assertEqual(parameters, (1, 10, 0, True)) diff --git a/packages/django-google-spanner/tests/unit/django_spanner/test_expressions.py b/packages/django-google-spanner/tests/unit/django_spanner/test_expressions.py index 4856c02e41d6..46f4c8ac9afb 100644 --- a/packages/django-google-spanner/tests/unit/django_spanner/test_expressions.py +++ b/packages/django-google-spanner/tests/unit/django_spanner/test_expressions.py @@ -19,8 +19,8 @@ def test_order_by_sql_query_with_order_by_null_last(self): sql_compiled, _ = compiler.as_sql() self.assertEqual( sql_compiled, - "SELECT tests_report.name AS name FROM tests_report ORDER BY " - + "tests_report.name IS NULL, tests_report.name DESC", + "SELECT `tests_report`.`name` AS `name` FROM `tests_report` ORDER BY " + + "`tests_report`.`name` IS NULL, `tests_report`.`name` DESC", ) def test_order_by_sql_query_with_order_by_null_first(self): @@ -29,8 +29,8 @@ def test_order_by_sql_query_with_order_by_null_first(self): sql_compiled, _ = compiler.as_sql() self.assertEqual( sql_compiled, - "SELECT tests_report.name AS name FROM tests_report ORDER BY " - + "tests_report.name IS NOT NULL, tests_report.name DESC", + "SELECT `tests_report`.`name` AS `name` FROM `tests_report` ORDER BY " + + "`tests_report`.`name` IS NOT NULL, `tests_report`.`name` DESC", ) def test_order_by_sql_query_with_order_by_name(self): @@ -39,5 +39,6 @@ def test_order_by_sql_query_with_order_by_name(self): sql_compiled, _ = compiler.as_sql() self.assertEqual( sql_compiled, - "SELECT tests_report.name AS name FROM tests_report ORDER BY " + "1 ASC", + "SELECT `tests_report`.`name` AS `name` FROM `tests_report` ORDER BY " + + "1 ASC", ) diff --git a/packages/django-google-spanner/tests/unit/django_spanner/test_functions.py b/packages/django-google-spanner/tests/unit/django_spanner/test_functions.py index bd6c6ed0f3b9..8ea3319d8f3d 100644 --- a/packages/django-google-spanner/tests/unit/django_spanner/test_functions.py +++ b/packages/django-google-spanner/tests/unit/django_spanner/test_functions.py @@ -38,8 +38,8 @@ def test_cast_with_max_length(self): sql_query, params = compiler.query.as_sql(compiler, self.connection) self.assertEqual( sql_query, - "SELECT tests_author.name AS name, SUBSTR(CAST(tests_author.name AS " - + "STRING), 0, 10) AS name_as_prefix FROM tests_author", + "SELECT `tests_author`.`name` AS `name`, SUBSTR(CAST(`tests_author`.`name` AS " + + "STRING), 0, 10) AS `name_as_prefix` FROM `tests_author`", ) self.assertEqual(params, ()) @@ -54,8 +54,8 @@ def test_cast_without_max_length(self): sql_query, params = compiler.query.as_sql(compiler, self.connection) self.assertEqual( sql_query, - "SELECT tests_author.num AS num, CAST(tests_author.num AS FLOAT64) " - + "AS num_as_float FROM tests_author", + "SELECT `tests_author`.`num` AS `num`, CAST(`tests_author`.`num` AS FLOAT64) " + + "AS `num_as_float` FROM `tests_author`", ) self.assertEqual(params, ()) @@ -70,9 +70,9 @@ def test_concatpair(self): sql_query, params = compiler.query.as_sql(compiler, self.connection) self.assertEqual( sql_query, - "SELECT tests_author.name AS name, CONCAT(IFNULL(tests_author.name, %s), " - + "IFNULL(CONCAT(IFNULL(%s, %s), IFNULL(tests_author.last_name, " - + "%s)), %s)) AS full_name FROM tests_author", + "SELECT `tests_author`.`name` AS `name`, CONCAT(IFNULL(`tests_author`.`name`, %s), " + + "IFNULL(CONCAT(IFNULL(%s, %s), IFNULL(`tests_author`.`last_name`, " + + "%s)), %s)) AS `full_name` FROM `tests_author`", ) self.assertEqual(params, ("", " ", "", "", "")) @@ -87,8 +87,8 @@ def test_cot(self): sql_query, params = compiler.query.as_sql(compiler, self.connection) self.assertEqual( sql_query, - "SELECT tests_author.num AS num, (1 / TAN(tests_author.num)) AS num_cot " - + "FROM tests_author", + "SELECT `tests_author`.`num` AS `num`, (1 / TAN(`tests_author`.`num`)) AS `num_cot` " + + "FROM `tests_author`", ) self.assertEqual(params, ()) @@ -103,8 +103,8 @@ def test_degrees(self): sql_query, params = compiler.query.as_sql(compiler, self.connection) self.assertEqual( sql_query, - "SELECT tests_author.num AS num, ((tests_author.num) * 180 / " - + "3.141592653589793) AS num_degrees FROM tests_author", + "SELECT `tests_author`.`num` AS `num`, ((`tests_author`.`num`) * 180 / " + + "3.141592653589793) AS `num_degrees` FROM `tests_author`", ) self.assertEqual(params, ()) @@ -119,8 +119,8 @@ def test_left(self): sql_query, params = compiler.query.as_sql(compiler, self.connection) self.assertEqual( sql_query, - "SELECT tests_author.num AS num, SUBSTR(tests_author.name, %s, %s) AS " - + "first_initial FROM tests_author", + "SELECT `tests_author`.`num` AS `num`, SUBSTR(`tests_author`.`name`, %s, %s) AS " + + "`first_initial` FROM `tests_author`", ) self.assertEqual(params, (1, 1)) @@ -135,8 +135,8 @@ def test_right(self): sql_query, params = compiler.query.as_sql(compiler, self.connection) self.assertEqual( sql_query, - "SELECT tests_author.num AS num, SUBSTR(tests_author.name, (%s * %s), %s) " - + "AS last_letter FROM tests_author", + "SELECT `tests_author`.`num` AS `num`, SUBSTR(`tests_author`.`name`, (%s * %s), %s) " + + "AS `last_letter` FROM `tests_author`", ) self.assertEqual(params, (1, -1, 1)) @@ -150,8 +150,8 @@ def test_log(self): sql_query, params = compiler.query.as_sql(compiler, self.connection) self.assertEqual( sql_query, - "SELECT tests_author.num AS num, LOG(%s, tests_author.num) AS log FROM " - + "tests_author", + "SELECT `tests_author`.`num` AS `num`, LOG(%s, `tests_author`.`num`) AS `log` FROM " + + "`tests_author`", ) self.assertEqual(params, (10,)) @@ -165,8 +165,8 @@ def test_ord(self): sql_query, params = compiler.query.as_sql(compiler, self.connection) self.assertEqual( sql_query, - "SELECT tests_author.name AS name, TO_CODE_POINTS(tests_author.name)" - + "[OFFSET(0)] AS name_code_point FROM tests_author", + "SELECT `tests_author`.`name` AS `name`, TO_CODE_POINTS(`tests_author`.`name`)" + + "[OFFSET(0)] AS `name_code_point` FROM `tests_author`", ) self.assertEqual(params, ()) @@ -179,7 +179,7 @@ def test_pi(self): compiler = SQLCompiler(q1.query, self.connection, "default") sql_query, params = compiler.query.as_sql(compiler, self.connection) expected_sql = ( - "SELECT tests_author.num AS num FROM tests_author WHERE tests_author.num " + "SELECT `tests_author`.`num` AS `num` FROM `tests_author` WHERE `tests_author`.`num` " + "= (3.141592653589793)" ) self.assertEqual( @@ -198,8 +198,8 @@ def test_radians(self): sql_query, params = compiler.query.as_sql(compiler, self.connection) self.assertEqual( sql_query, - "SELECT tests_author.num AS num, ((tests_author.num) * 3.141592653589793 " - "/ 180) AS num_radians FROM tests_author", + "SELECT `tests_author`.`num` AS `num`, ((`tests_author`.`num`) * 3.141592653589793 " + "/ 180) AS `num_radians` FROM `tests_author`", ) self.assertEqual(params, ()) @@ -215,8 +215,8 @@ def test_strindex(self): sql_query, params = compiler.query.as_sql(compiler, self.connection) self.assertEqual( sql_query, - "SELECT tests_author.name AS name, STRPOS(tests_author.name, %s) AS " - + "smith_index FROM tests_author", + "SELECT `tests_author`.`name` AS `name`, STRPOS(`tests_author`.`name`, %s) AS " + + "`smith_index` FROM `tests_author`", ) self.assertEqual(params, ("Smith",)) @@ -230,8 +230,8 @@ def test_substr(self): sql_query, params = compiler.query.as_sql(compiler, self.connection) self.assertEqual( sql_query, - "SELECT tests_author.name AS name, SUBSTR(tests_author.name, %s, %s) AS " - + "name_prefix FROM tests_author", + "SELECT `tests_author`.`name` AS `name`, SUBSTR(`tests_author`.`name`, %s, %s) AS " + + "`name_prefix` FROM `tests_author`", ) self.assertEqual(params, (1, 5)) @@ -360,7 +360,7 @@ def get_placeholder(self, value, compiler, connection): query_sql, query_params = SQLCompiler( queryset.query, self.connection, "default" ).as_sql() - self.assertIn("CAST(NULL AS STRING) AS null_text", query_sql) - self.assertIn("COALESCE(CAST(NULL AS STRING), %s) AS coalesced", query_sql) - self.assertIn("ELSE CAST(NULL AS STRING) END AS cased", query_sql) + self.assertIn("CAST(NULL AS STRING) AS `null_text`", query_sql) + self.assertIn("COALESCE(CAST(NULL AS STRING), %s) AS `coalesced`", query_sql) + self.assertIn("ELSE CAST(NULL AS STRING) END AS `cased`", query_sql) self.assertEqual(query_params, ("fallback", 0, "ok")) diff --git a/packages/django-google-spanner/tests/unit/django_spanner/test_lookups.py b/packages/django-google-spanner/tests/unit/django_spanner/test_lookups.py index 3d53acc0dcc7..cd0bb1ee3505 100644 --- a/packages/django-google-spanner/tests/unit/django_spanner/test_lookups.py +++ b/packages/django-google-spanner/tests/unit/django_spanner/test_lookups.py @@ -24,8 +24,8 @@ def test_cast_param_to_float_lte_sql_query(self): sql_compiled, params = compiler.as_sql() self.assertEqual( sql_compiled, - "SELECT tests_number.decimal_num AS decimal_num FROM tests_number WHERE " - + "tests_number.decimal_num <= %s", + "SELECT `tests_number`.`decimal_num` AS `decimal_num` FROM `tests_number` WHERE " + + "`tests_number`.`decimal_num` <= %s", ) self.assertEqual(params, (Decimal("1.1"),)) @@ -36,8 +36,8 @@ def test_cast_param_to_float_for_int_field_query(self): sql_compiled, params = compiler.as_sql() self.assertEqual( sql_compiled, - "SELECT tests_number.num AS num FROM tests_number WHERE " - + "tests_number.num <= %s", + "SELECT `tests_number`.`num` AS `num` FROM `tests_number` WHERE " + + "`tests_number`.`num` <= %s", ) self.assertEqual(params, (1,)) @@ -47,8 +47,8 @@ def test_cast_param_to_float_for_foreign_key_field_query(self): sql_compiled, params = compiler.as_sql() self.assertEqual( sql_compiled, - "SELECT tests_number.num AS num FROM tests_number WHERE " - + "tests_number.item_id = %s", + "SELECT `tests_number`.`num` AS `num` FROM `tests_number` WHERE " + + "`tests_number`.`item_id` = %s", ) self.assertEqual(params, (10,)) @@ -57,8 +57,8 @@ def test_cast_param_to_float_with_no_params_query(self): compiler = SQLCompiler(qs1.query, self.connection, "default") sql_compiled, params = compiler.as_sql() expected_sql = ( - "SELECT tests_number.num AS num FROM tests_number WHERE " - + "tests_number.item_id = (tests_number.num)" + "SELECT `tests_number`.`num` AS `num` FROM `tests_number` WHERE " + + "`tests_number`.`item_id` = (`tests_number`.`num`)" ) self.assertEqual(sql_compiled, expected_sql) self.assertEqual(params, ()) @@ -69,8 +69,8 @@ def test_startswith_endswith_sql_query_with_startswith(self): sql_compiled, params = compiler.as_sql() self.assertEqual( sql_compiled, - "SELECT tests_author.num AS num FROM tests_author WHERE " - + "REGEXP_CONTAINS(CAST(tests_author.name AS STRING), %s)", + "SELECT `tests_author`.`num` AS `num` FROM `tests_author` WHERE " + + "REGEXP_CONTAINS(CAST(`tests_author`.`name` AS STRING), %s)", ) self.assertEqual(params, ("^abc",)) @@ -80,8 +80,8 @@ def test_startswith_endswith_sql_query_with_endswith(self): sql_compiled, params = compiler.as_sql() self.assertEqual( sql_compiled, - "SELECT tests_author.num AS num FROM tests_author WHERE " - + "REGEXP_CONTAINS(CAST(tests_author.name AS STRING), %s)", + "SELECT `tests_author`.`num` AS `num` FROM `tests_author` WHERE " + + "REGEXP_CONTAINS(CAST(`tests_author`.`name` AS STRING), %s)", ) self.assertEqual(params, ("abc$",)) @@ -91,8 +91,8 @@ def test_startswith_endswith_sql_query_case_insensitive(self): sql_compiled, params = compiler.as_sql() self.assertEqual( sql_compiled, - "SELECT tests_author.num AS num FROM tests_author WHERE " - + "REGEXP_CONTAINS(CAST(tests_author.name AS STRING), %s)", + "SELECT `tests_author`.`num` AS `num` FROM `tests_author` WHERE " + + "REGEXP_CONTAINS(CAST(`tests_author`.`name` AS STRING), %s)", ) self.assertEqual(params, ("(?i)^abc",)) @@ -102,8 +102,8 @@ def test_startswith_endswith_sql_query_with_bileteral_transform(self): compiler = SQLCompiler(qs1.query, self.connection, "default") sql_compiled, params = compiler.as_sql() expected_sql = ( - "SELECT tests_author.name AS name FROM tests_author WHERE " - + "REGEXP_CONTAINS(CAST(UPPER(tests_author.name) AS STRING), " + "SELECT `tests_author`.`name` AS `name` FROM `tests_author` WHERE " + + "REGEXP_CONTAINS(CAST(UPPER(`tests_author`.`name`) AS STRING), " + "REPLACE(REPLACE(REPLACE(CONCAT('^', (UPPER(%s))), " + '"\\\\", "\\\\\\\\"), "%%", r"\\%%"), "_", r"\\_"))' ) @@ -116,8 +116,8 @@ def test_startswith_endswith_case_insensitive_transform_sql_query(self): compiler = SQLCompiler(qs1.query, self.connection, "default") sql_compiled, params = compiler.as_sql() expected_sql = ( - "SELECT tests_author.name AS name FROM tests_author WHERE " - + "REGEXP_CONTAINS(CAST(UPPER(tests_author.name) AS STRING), " + "SELECT `tests_author`.`name` AS `name` FROM `tests_author` WHERE " + + "REGEXP_CONTAINS(CAST(UPPER(`tests_author`.`name`) AS STRING), " + "REPLACE(REPLACE(REPLACE(CONCAT('^(?i)', (UPPER(%s))), " + '"\\\\", "\\\\\\\\"), "%%", r"\\%%"), "_", r"\\_"))' ) @@ -131,8 +131,8 @@ def test_startswith_endswith_endswith_sql_query_with_transform(self): sql_compiled, params = compiler.as_sql() expected_sql = ( - "SELECT tests_author.name AS name FROM tests_author WHERE " - + "REGEXP_CONTAINS(CAST(UPPER(tests_author.name) AS STRING), " + "SELECT `tests_author`.`name` AS `name` FROM `tests_author` WHERE " + + "REGEXP_CONTAINS(CAST(UPPER(`tests_author`.`name`) AS STRING), " + "REPLACE(REPLACE(REPLACE(CONCAT('', (UPPER(%s)), '$'), " + '"\\\\", "\\\\\\\\"), "%%", r"\\%%"), "_", r"\\_"))' ) @@ -145,8 +145,8 @@ def test_regex_sql_query_case_sensitive(self): sql_compiled, params = compiler.as_sql() self.assertEqual( sql_compiled, - "SELECT tests_author.num AS num FROM tests_author WHERE " - "REGEXP_CONTAINS(CAST(tests_author.name AS STRING), %s)", + "SELECT `tests_author`.`num` AS `num` FROM `tests_author` WHERE " + "REGEXP_CONTAINS(CAST(`tests_author`.`name` AS STRING), %s)", ) self.assertEqual(params, ("abc",)) @@ -156,8 +156,8 @@ def test_regex_sql_query_case_insensitive(self): sql_compiled, params = compiler.as_sql() self.assertEqual( sql_compiled, - "SELECT tests_author.num AS num FROM tests_author WHERE " - "REGEXP_CONTAINS(CAST(tests_author.name AS STRING), %s)", + "SELECT `tests_author`.`num` AS `num` FROM `tests_author` WHERE " + "REGEXP_CONTAINS(CAST(`tests_author`.`name` AS STRING), %s)", ) self.assertEqual(params, ("(?i)abc",)) @@ -167,8 +167,8 @@ def test_regex_sql_query_case_sensitive_with_transform(self): sql_compiled, params = compiler.as_sql() expected_sql = ( - "SELECT tests_author.num AS num FROM tests_author WHERE " - + "REGEXP_CONTAINS(CAST(UPPER(tests_author.name) AS STRING), " + "SELECT `tests_author`.`num` AS `num` FROM `tests_author` WHERE " + + "REGEXP_CONTAINS(CAST(UPPER(`tests_author`.`name`) AS STRING), " + "(UPPER(%s)))" ) self.assertEqual(sql_compiled, expected_sql) @@ -180,8 +180,8 @@ def test_regex_sql_query_case_insensitive_with_transform(self): sql_compiled, params = compiler.as_sql() expected_sql = ( - "SELECT tests_author.num AS num FROM tests_author WHERE " - + "REGEXP_CONTAINS(CAST(UPPER(tests_author.name) AS STRING), " + "SELECT `tests_author`.`num` AS `num` FROM `tests_author` WHERE " + + "REGEXP_CONTAINS(CAST(UPPER(`tests_author`.`name`) AS STRING), " + "CONCAT('(?i)', (UPPER(%s))))" ) self.assertEqual(sql_compiled, expected_sql) @@ -193,8 +193,8 @@ def test_contains_sql_query_case_insensitive(self): sql_compiled, params = compiler.as_sql() self.assertEqual( sql_compiled, - "SELECT tests_author.num AS num FROM tests_author WHERE " - + "REGEXP_CONTAINS(CAST(tests_author.name AS STRING), %s)", + "SELECT `tests_author`.`num` AS `num` FROM `tests_author` WHERE " + + "REGEXP_CONTAINS(CAST(`tests_author`.`name` AS STRING), %s)", ) self.assertEqual(params, ("(?i)abc",)) @@ -204,8 +204,8 @@ def test_contains_sql_query_case_sensitive(self): sql_compiled, params = compiler.as_sql() self.assertEqual( sql_compiled, - "SELECT tests_author.num AS num FROM tests_author WHERE " - + "REGEXP_CONTAINS(CAST(tests_author.name AS STRING), %s)", + "SELECT `tests_author`.`num` AS `num` FROM `tests_author` WHERE " + + "REGEXP_CONTAINS(CAST(`tests_author`.`name` AS STRING), %s)", ) self.assertEqual(params, ("abc",)) @@ -214,8 +214,8 @@ def test_contains_sql_query_case_insensitive_transform(self): compiler = SQLCompiler(qs1.query, self.connection, "default") sql_compiled, params = compiler.as_sql() expected_sql = ( - "SELECT tests_author.name AS name FROM tests_author WHERE " - + "REGEXP_CONTAINS(CAST(UPPER(tests_author.name) AS STRING), " + "SELECT `tests_author`.`name` AS `name` FROM `tests_author` WHERE " + + "REGEXP_CONTAINS(CAST(UPPER(`tests_author`.`name`) AS STRING), " + "REPLACE(REPLACE(REPLACE(CONCAT('(?i)', (UPPER(%s))), " + '"\\\\", "\\\\\\\\"), "%%", r"\\%%"), "_", r"\\_"))' ) @@ -227,8 +227,8 @@ def test_contains_sql_query_case_sensitive_transform(self): compiler = SQLCompiler(qs1.query, self.connection, "default") sql_compiled, params = compiler.as_sql() expected_sql = ( - "SELECT tests_author.name AS name FROM tests_author WHERE " - + "REGEXP_CONTAINS(CAST(UPPER(tests_author.name) AS STRING), " + "SELECT `tests_author`.`name` AS `name` FROM `tests_author` WHERE " + + "REGEXP_CONTAINS(CAST(UPPER(`tests_author`.`name`) AS STRING), " + 'REPLACE(REPLACE(REPLACE((UPPER(%s)), "\\\\", "\\\\\\\\"), ' + '"%%", r"\\%%"), "_", r"\\_"))' ) @@ -242,8 +242,8 @@ def test_iexact_sql_query_case_insensitive(self): self.assertEqual( sql_compiled, - "SELECT tests_author.num AS num FROM tests_author WHERE " - + "REGEXP_CONTAINS(CAST(tests_author.name AS STRING), %s)", + "SELECT `tests_author`.`num` AS `num` FROM `tests_author` WHERE " + + "REGEXP_CONTAINS(CAST(`tests_author`.`name` AS STRING), %s)", ) self.assertEqual(params, ("^(?i)abc$",)) @@ -253,9 +253,9 @@ def test_iexact_sql_query_case_insensitive_function_transform(self): sql_compiled, params = compiler.as_sql() expected_sql = ( - "SELECT tests_author.name AS name FROM tests_author WHERE " - + "REGEXP_CONTAINS((UPPER(tests_author.last_name)), " - + "CONCAT('^(?i)', CAST(UPPER(tests_author.name) AS STRING), '$'))" + "SELECT `tests_author`.`name` AS `name` FROM `tests_author` WHERE " + + "REGEXP_CONTAINS((UPPER(`tests_author`.`last_name`)), " + + "CONCAT('^(?i)', CAST(UPPER(`tests_author`.`name`) AS STRING), '$'))" ) self.assertEqual(sql_compiled, expected_sql) self.assertEqual(params, ()) @@ -266,9 +266,9 @@ def test_iexact_sql_query_case_insensitive_value_match(self): sql_compiled, params = compiler.as_sql() expected_sql = ( - "SELECT tests_author.name AS name FROM tests_author WHERE " + "SELECT `tests_author`.`name` AS `name` FROM `tests_author` WHERE " + "REGEXP_CONTAINS((UPPER(CONCAT('^(?i)', " - + "CAST(UPPER(tests_author.name) AS STRING), '$'))), %s)" + + "CAST(UPPER(`tests_author`.`name`) AS STRING), '$'))), %s)" ) self.assertEqual(sql_compiled, expected_sql) self.assertEqual(params, ("abc",)) diff --git a/packages/django-google-spanner/tests/unit/django_spanner/test_operations.py b/packages/django-google-spanner/tests/unit/django_spanner/test_operations.py index ee71c56b8ad2..74457f7e460a 100644 --- a/packages/django-google-spanner/tests/unit/django_spanner/test_operations.py +++ b/packages/django-google-spanner/tests/unit/django_spanner/test_operations.py @@ -31,7 +31,7 @@ def test_max_name_length(self): def test_quote_name(self): quoted_name = self.db_operations.quote_name("abc") - self.assertEqual(quoted_name, "abc") + self.assertEqual(quoted_name, "`abc`") def test_quote_name_empty_string(self): self.assertEqual(self.db_operations.quote_name(""), "") @@ -39,7 +39,9 @@ def test_quote_name_empty_string(self): def test_quote_name_regular_identifiers(self): for identifier in ("_", "_col_1", "TestsAuthor", "col123", "table", "value"): with self.subTest(identifier=identifier): - self.assertEqual(self.db_operations.quote_name(identifier), identifier) + self.assertEqual( + self.db_operations.quote_name(identifier), f"`{identifier}`" + ) def test_quote_name_spanner_reserved_keyword_escaped(self): quoted_name = self.db_operations.quote_name("ALL") @@ -265,14 +267,14 @@ def test_quote_name_running_spanner_backend_tests(self): {"RUNNING_SPANNER_BACKEND_TESTS": "1"}, ): self.assertEqual( - self.db_operations.quote_name("my col-name"), "my_col_name" + self.db_operations.quote_name("my col-name"), "`my_col_name`" ) self.assertEqual(self.db_operations.quote_name("SELECT"), "`SELECT`") self.assertEqual( self.db_operations.quote_name("my-col.name"), "`my_col.name`" ) - self.assertEqual(self.db_operations.quote_name("my-select"), "my_select") - self.assertEqual(self.db_operations.quote_name("ALL "), "ALL_") + self.assertEqual(self.db_operations.quote_name("my-select"), "`my_select`") + self.assertEqual(self.db_operations.quote_name("ALL "), "`ALL_`") self.assertEqual( self.db_operations.quote_name("my col`; DROP TABLE t"), r"`my_col\x60;_DROP_TABLE_t`", @@ -281,10 +283,10 @@ def test_quote_name_running_spanner_backend_tests(self): self.assertEqual(self.db_operations.quote_name("a b\nc"), r"`a_b\nc`") self.assertEqual(self.db_operations.quote_name("`already`"), "`already`") self.assertEqual(self.db_operations.quote_name(""), "") - self.assertEqual(self.db_operations.quote_name(" "), "___") + self.assertEqual(self.db_operations.quote_name(" "), "`___`") self.assertEqual( self.db_operations.quote_name("Generated model check constraint a > 0"), - "Generated_model_check_constraint_a___0", + "`Generated_model_check_constraint_a___0`", ) for sample in ("my col-name", "SELECT", "`a b-c`", "a b\nc"): once = self.db_operations.quote_name(sample) @@ -316,7 +318,7 @@ def test_bulk_batch_size(self): def test_sql_flush(self): self.assertEqual( self.db_operations.sql_flush(style=no_style(), tables=["Table1", "Table2"]), - ["DELETE FROM Table1 WHERE 1=1", "DELETE FROM Table2 WHERE 1=1"], + ["DELETE FROM `Table1` WHERE 1=1", "DELETE FROM `Table2` WHERE 1=1"], ) def test_sql_flush_empty_table_list(self): @@ -684,12 +686,12 @@ def test_returning_columns(self): field1 = mock.MagicMock(column="id") field2 = mock.MagicMock(column="name") sql, params = self.db_operations.returning_columns([field1, field2]) - self.assertEqual(sql, "THEN RETURN id, name") + self.assertEqual(sql, "THEN RETURN `id`, `name`") self.assertEqual(params, ()) def test_returning_columns_with_strings(self): sql, params = self.db_operations.returning_columns(["id", "created_at"]) - self.assertEqual(sql, "THEN RETURN id, created_at") + self.assertEqual(sql, "THEN RETURN `id`, `created_at`") self.assertEqual(params, ()) def test_returning_columns_empty(self): @@ -700,7 +702,7 @@ def test_returning_columns_empty(self): def test_return_insert_columns_alias(self): field = mock.MagicMock(column="id") sql, params = self.db_operations.return_insert_columns([field]) - self.assertEqual(sql, "THEN RETURN id") + self.assertEqual(sql, "THEN RETURN `id`") self.assertEqual(params, ()) def test_savepoint_sql(self): diff --git a/packages/django-google-spanner/tests/unit/django_spanner/test_schema.py b/packages/django-google-spanner/tests/unit/django_spanner/test_schema.py index c8ccc88803b8..dada1d7336e2 100644 --- a/packages/django-google-spanner/tests/unit/django_spanner/test_schema.py +++ b/packages/django-google-spanner/tests/unit/django_spanner/test_schema.py @@ -64,10 +64,10 @@ def test_create_model(self): schema_editor.create_model(Author) schema_editor.execute.assert_called_once_with( - "CREATE TABLE tests_author (id INT64 NOT NULL, name STRING(40) " - + "NOT NULL, last_name STRING(40) NOT NULL, num INT64 NOT " - + "NULL, created TIMESTAMP NOT NULL, modified TIMESTAMP) " - + "PRIMARY KEY(id)", + "CREATE TABLE `tests_author` (`id` INT64 NOT NULL, `name` STRING(40) " + + "NOT NULL, `last_name` STRING(40) NOT NULL, `num` INT64 NOT " + + "NULL, `created` TIMESTAMP NOT NULL, `modified` TIMESTAMP) " + + "PRIMARY KEY(`id`)", None, ) if HAS_OPENTELEMETRY_INSTALLED: @@ -89,7 +89,7 @@ def test_delete_model(self): schema_editor.delete_model(Author) schema_editor.execute.assert_called_once_with( - "DROP TABLE tests_author", + "DROP TABLE `tests_author`", ) if HAS_OPENTELEMETRY_INSTALLED: @@ -121,7 +121,7 @@ def constraint_names(*args, **kwargs): calls = [ mock.call("DROP INDEX num_unique"), - mock.call("DROP TABLE tests_author"), + mock.call("DROP TABLE `tests_author`"), ] schema_editor.execute.assert_has_calls(calls) @@ -159,7 +159,7 @@ def test_add_field(self): schema_editor.add_field(Author, new_field) schema_editor.execute.assert_called_once_with( - "ALTER TABLE tests_author ADD COLUMN age INT64", [] + "ALTER TABLE `tests_author` ADD COLUMN `age` INT64", [] ) def test_add_field_with_default(self): @@ -172,7 +172,7 @@ def test_add_field_with_default(self): schema_editor.add_field(Author, new_field) schema_editor.execute.assert_any_call( - "UPDATE tests_author SET age=%s WHERE 1=1", + "UPDATE `tests_author` SET `age`=%s WHERE 1=1", (42,), ) @@ -189,7 +189,7 @@ def test_remove_field(self): schema_editor.remove_field(Author, remove_field) schema_editor.execute.assert_called_once_with( - "ALTER TABLE tests_author DROP COLUMN num" + "ALTER TABLE `tests_author` DROP COLUMN `num`" ) if HAS_OPENTELEMETRY_INSTALLED: @@ -229,7 +229,7 @@ def constraint_names(*args, **kwargs): calls = [ mock.call("DROP INDEX num_unique"), - mock.call("ALTER TABLE tests_author DROP COLUMN num"), + mock.call("ALTER TABLE `tests_author` DROP COLUMN `num`"), ] schema_editor.execute.assert_has_calls(calls) @@ -293,7 +293,7 @@ def test_column_add_index(self): name, args, kwargs = schema_editor.execute.mock_calls[0] self.assertEqual( str(args[0]), - "CREATE INDEX test_author_index_num ON tests_author (num)", + "CREATE INDEX `test_author_index_num` ON `tests_author` (`num`)", ) self.assertEqual(kwargs["params"], None) self.assertEqual(name, "") @@ -325,7 +325,7 @@ def test_alter_field(self): schema_editor.alter_field(Author, old_field, new_field) schema_editor.execute.assert_called_once_with( - "ALTER TABLE tests_author RENAME COLUMN num TO author_num" + "ALTER TABLE `tests_author` RENAME COLUMN `num` TO `author_num`" ) def test_alter_field_change_null_with_single_index(self): @@ -359,9 +359,11 @@ def constraint_names(*args, **kwargs): calls = [ mock.call("DROP INDEX num_unique"), - mock.call("ALTER TABLE tests_author RENAME COLUMN num TO author_num"), mock.call( - "ALTER TABLE tests_author ALTER COLUMN author_num INT64 NOT NULL", + "ALTER TABLE `tests_author` RENAME COLUMN `num` TO `author_num`" + ), + mock.call( + "ALTER TABLE `tests_author` ALTER COLUMN `author_num` INT64 NOT NULL", [], ), mock.call("CREATE INDEX tests_author ON tests_author (author_num)"), @@ -491,20 +493,20 @@ def test_index_include_sql(self): """Tests _index_include_sql with normal fields.""" schema_editor = DatabaseSchemaEditor(self.connection) sql = schema_editor._index_include_sql(Author, ["name", "last_name"]) - self.assertEqual(sql, " STORING (name, last_name)") + self.assertEqual(sql, " STORING (`name`, `last_name`)") def test_index_include_sql_with_field_objects(self): """Tests _index_include_sql with Field instances possessing a .column attribute.""" schema_editor = DatabaseSchemaEditor(self.connection) field_mock = mock.MagicMock(column="custom_col") sql = schema_editor._index_include_sql(Author, [field_mock]) - self.assertEqual(sql, " STORING (custom_col)") + self.assertEqual(sql, " STORING (`custom_col`)") def test_index_include_sql_includes_all_fields(self): """Tests _index_include_sql formats all included columns directly.""" schema_editor = DatabaseSchemaEditor(self.connection) sql = schema_editor._index_include_sql(Author, ["id", "name"]) - self.assertEqual(sql, " STORING (id, name)") + self.assertEqual(sql, " STORING (`id`, `name`)") def test_index_include_sql_empty(self): """Tests _index_include_sql returns empty string when include is empty.""" @@ -542,10 +544,10 @@ class Meta: schema_editor.create_model(QuotedModel) schema_editor.execute.assert_called_once_with( - "CREATE TABLE `my-table` (id INT64 NOT NULL, " + "CREATE TABLE `my-table` (`id` INT64 NOT NULL, " "`order` INT64 NOT NULL, " "CONSTRAINT `my-table_order_61957483_check` " - "CHECK (`order` >= 0)) PRIMARY KEY(id)", + "CHECK (`order` >= 0)) PRIMARY KEY(`id`)", None, ) @@ -619,10 +621,10 @@ class Meta: schema_editor.create_model(CustomColumnModel) schema_editor.execute.assert_called_once_with( - "CREATE TABLE `my-table` (id INT64 NOT NULL, " + "CREATE TABLE `my-table` (`id` INT64 NOT NULL, " "`order` INT64 NOT NULL, " "CONSTRAINT `my-table_order_61957483_check` " - "CHECK (`order` >= 0)) PRIMARY KEY(id)", + "CHECK (`order` >= 0)) PRIMARY KEY(`id`)", None, ) @@ -725,7 +727,7 @@ def test_check_sql(self): schema_editor = DatabaseSchemaEditor(self.connection) self.assertEqual( schema_editor._check_sql("check_age", "age >= 0"), - "CONSTRAINT check_age CHECK (age >= 0)", + "CONSTRAINT `check_age` CHECK (age >= 0)", ) # Keep the inline CheckedModel out of Django's global app registry. @@ -751,9 +753,9 @@ class Meta: schema_editor.create_model(CheckedModel) schema_editor.execute.assert_called_once_with( - "CREATE TABLE tests_checked_model (id INT64 NOT NULL, " - "num INT64 NOT NULL, CONSTRAINT num_gte_0 CHECK (num >= 0)) " - "PRIMARY KEY(id)", + "CREATE TABLE `tests_checked_model` (`id` INT64 NOT NULL, " + "`num` INT64 NOT NULL, CONSTRAINT `num_gte_0` CHECK (`num` >= 0)) " + "PRIMARY KEY(`id`)", None, ) @@ -778,8 +780,8 @@ def test_alter_field_add_check_constraint(self): self.assertIsNotNone(statement) self.assertEqual( str(statement), - "ALTER TABLE tests_author ADD CONSTRAINT " - "tests_author_num_f8282a0e_check CHECK (num >= 0)", + "ALTER TABLE `tests_author` ADD CONSTRAINT " + "`tests_author_num_f8282a0e_check` CHECK (`num` >= 0)", ) def _assert_recorded_spans( @@ -860,7 +862,7 @@ def _assert_unquoted_model_name_across_operations( remove_field.model = Author schema_editor.remove_field(Author, remove_field) self.assertIn( - f"ALTER TABLE {expected_sql_table} DROP COLUMN num", + f"ALTER TABLE {expected_sql_table} DROP COLUMN `num`", str(schema_editor.execute.call_args_list[1].args[0]), ) self._assert_recorded_spans( @@ -888,7 +890,7 @@ def _assert_unquoted_model_name_across_operations( schema_editor.add_index(Author, index) self.assertEqual( str(schema_editor.execute.call_args_list[0].args[0]), - f"CREATE INDEX test_order_index_num ON {expected_sql_table} (num)", + f"CREATE INDEX `test_order_index_num` ON {expected_sql_table} (`num`)", ) self._assert_recorded_spans( [ @@ -913,11 +915,11 @@ def _assert_unquoted_model_name_across_operations( new_field.model = Author schema_editor.alter_field(Author, old_field, new_field) self.assertIn( - f"ALTER TABLE {expected_sql_table} RENAME COLUMN num TO author_num", + f"ALTER TABLE {expected_sql_table} RENAME COLUMN `num` TO `author_num`", str(schema_editor.execute.call_args_list[1].args[0]), ) self.assertIn( - f"ON {expected_sql_table} (author_num)", + f"ON {expected_sql_table} (`author_num`)", str(schema_editor.execute.call_args_list[3].args[0]), ) self._assert_recorded_spans( @@ -961,7 +963,7 @@ def test_trace_model_name_unquoted(self) -> None: {"RUNNING_SPANNER_BACKEND_TESTS": "1"}, ): self._assert_unquoted_model_name_across_operations( - "my-table name", "my_table_name" + "my-table name", "`my_table_name`" ) def test_trace_model_name_unquoted_empty_and_multiple_indexes(self) -> None: