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
Original file line number Diff line number Diff line change
Expand Up @@ -384,15 +384,25 @@ def ensure_where_clause(sql):

def escape_name(name):
"""
Apply backticks to the name that either contain '-' or
' ', or is a Cloud Spanner's reserved keyword.
Apply backticks to the name if it is not a valid regular ASCII identifier,
or if it is a Cloud Spanner's reserved keyword.

:type name: str
:param name: Name to escape.

:rtype: str
:returns: Name escaped if it has to be escaped.
"""
if "-" in name or " " in name or name.upper() in SPANNER_RESERVED_KEYWORDS:
return "`" + name + "`"
if not name:
return name

is_valid_regular_identifier = (
(name[0].isalpha() or name[0] == "_")
and all(c.isalnum() or c == "_" for c in name)
and name.isascii()
)

if not is_valid_regular_identifier or name.upper() in SPANNER_RESERVED_KEYWORDS:
return "`" + name.replace("`", "``") + "`"

return name
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,13 @@ def test_escape_name(self):
("with space", "`with space`"),
("name", "name"),
("", ""),
("col`; DROP TABLE t; -- x", "`col``; DROP TABLE t; -- x`"),
("table`name", "`table``name`"),
("`", "````"),
("col/*comment*/name", "`col/*comment*/name`"),
("123column", "`123column`"),
("col;select", "`col;select`"),
("col\nname", "`col\nname`"),
)
for name, want in cases:
with self.subTest(name=name):
Expand Down
Loading