Repository URL to install this package:
|
Version:
3.0.0.dev3 ▾
|
import re
import typing as t
from snsql.sql.reader.base import NameCompare
# all known identifiers quotes
KNOWN_IDENTIFIERS_QUOTE = ['"', "`", "["]
def escape_quotes(name: str) -> str:
name_parts = split_quote(name)
name_compare = NameCompare()
if len(name_parts) == 1:
return str(
name_compare.strip_escapes(name)
if name_compare.is_escaped(name)
else name.lower()
)
return escape_quotes(name_parts[-1])
def is_quoted(name: str) -> bool:
return any([name.startswith(quote) for quote in KNOWN_IDENTIFIERS_QUOTE])
def split_quote(
name: str, ident_quote: t.Optional[str] = None
) -> t.Tuple[str, ...]:
"""Extract qualified column or table names.
It supports names containing dots or special characters.
If ident_quote is provided it will quote all the name parts accordinly
otherwise it will leave names as they are.
If an empty string is provided it will unquote
Args:
name (str):
ident_quote (str): the quote identifier
Returns:
Tuple[str, ...]:
"""
regex = re.compile(r"""((?:[^."\[\]]|"[^"]*"|\[[^\[]*\])+)""")
parts = [
sub_name for sub_name in regex.split(name) if sub_name not in [".", ""]
]
if ident_quote is not None:
parts = [
f"{ident_quote}{part[1:-1]}{ident_quote}"
if is_quoted(part)
else f"{ident_quote}{part}{ident_quote}"
for part in parts
]
return tuple(parts)
def expand_fully_qualified_name(
fully_qualified_name: t.Tuple[str, ...],
) -> t.List[t.Tuple[str, ...]]:
"""Expands fully qualified table names in all possible suffixes.
e.g: (a, b, c, d,) -> [(a, b, c, d,), (b, c, d,), (c, d,), (d,)]
"""
all_qualified_names = []
for idx in range(len(fully_qualified_name)):
all_qualified_names.append(fully_qualified_name[idx:])
return all_qualified_names