2025-02-13 14:52:26 +01:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2025-02-13 14:37:25 +01:00
|
|
|
import inspect
|
2025-02-13 06:15:54 +01:00
|
|
|
import logging
|
|
|
|
import re
|
2025-02-13 14:37:25 +01:00
|
|
|
import sys
|
2025-02-13 14:47:39 +01:00
|
|
|
import typing as t
|
2025-02-13 14:52:26 +01:00
|
|
|
from collections.abc import Collection
|
2025-02-13 06:15:54 +01:00
|
|
|
from contextlib import contextmanager
|
2025-02-13 14:47:39 +01:00
|
|
|
from copy import copy
|
2025-02-13 06:15:54 +01:00
|
|
|
from enum import Enum
|
|
|
|
|
2025-02-13 14:52:26 +01:00
|
|
|
if t.TYPE_CHECKING:
|
|
|
|
from sqlglot.expressions import Expression, Table
|
|
|
|
|
|
|
|
T = t.TypeVar("T")
|
|
|
|
E = t.TypeVar("E", bound=Expression)
|
|
|
|
|
2025-02-13 06:15:54 +01:00
|
|
|
CAMEL_CASE_PATTERN = re.compile("(?<!^)(?=[A-Z])")
|
2025-02-13 14:52:26 +01:00
|
|
|
PYTHON_VERSION = sys.version_info[:2]
|
2025-02-13 06:15:54 +01:00
|
|
|
logger = logging.getLogger("sqlglot")
|
|
|
|
|
|
|
|
|
|
|
|
class AutoName(Enum):
|
2025-02-13 14:52:26 +01:00
|
|
|
"""This is used for creating enum classes where `auto()` is the string form of the corresponding value's name."""
|
|
|
|
|
|
|
|
def _generate_next_value_(name, _start, _count, _last_values): # type: ignore
|
2025-02-13 06:15:54 +01:00
|
|
|
return name
|
|
|
|
|
|
|
|
|
2025-02-13 14:52:26 +01:00
|
|
|
def seq_get(seq: t.Sequence[T], index: int) -> t.Optional[T]:
|
|
|
|
"""Returns the value in `seq` at position `index`, or `None` if `index` is out of bounds."""
|
2025-02-13 06:15:54 +01:00
|
|
|
try:
|
2025-02-13 14:52:26 +01:00
|
|
|
return seq[index]
|
2025-02-13 06:15:54 +01:00
|
|
|
except IndexError:
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
2025-02-13 14:52:26 +01:00
|
|
|
@t.overload
|
|
|
|
def ensure_list(value: t.Collection[T]) -> t.List[T]:
|
|
|
|
...
|
|
|
|
|
|
|
|
|
|
|
|
@t.overload
|
|
|
|
def ensure_list(value: T) -> t.List[T]:
|
|
|
|
...
|
|
|
|
|
|
|
|
|
2025-02-13 06:15:54 +01:00
|
|
|
def ensure_list(value):
|
2025-02-13 14:52:26 +01:00
|
|
|
"""
|
|
|
|
Ensures that a value is a list, otherwise casts or wraps it into one.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
value: the value of interest.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The value cast as a list if it's a list or a tuple, or else the value wrapped in a list.
|
|
|
|
"""
|
2025-02-13 06:15:54 +01:00
|
|
|
if value is None:
|
|
|
|
return []
|
2025-02-13 14:52:26 +01:00
|
|
|
elif isinstance(value, (list, tuple)):
|
|
|
|
return list(value)
|
|
|
|
|
|
|
|
return [value]
|
|
|
|
|
|
|
|
|
|
|
|
@t.overload
|
|
|
|
def ensure_collection(value: t.Collection[T]) -> t.Collection[T]:
|
|
|
|
...
|
2025-02-13 06:15:54 +01:00
|
|
|
|
|
|
|
|
2025-02-13 14:52:26 +01:00
|
|
|
@t.overload
|
|
|
|
def ensure_collection(value: T) -> t.Collection[T]:
|
|
|
|
...
|
|
|
|
|
|
|
|
|
|
|
|
def ensure_collection(value):
|
|
|
|
"""
|
|
|
|
Ensures that a value is a collection (excluding `str` and `bytes`), otherwise wraps it into a list.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
value: the value of interest.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The value if it's a collection, or else the value wrapped in a list.
|
|
|
|
"""
|
|
|
|
if value is None:
|
|
|
|
return []
|
|
|
|
return (
|
|
|
|
value if isinstance(value, Collection) and not isinstance(value, (str, bytes)) else [value]
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
def csv(*args, sep: str = ", ") -> str:
|
|
|
|
"""
|
|
|
|
Formats any number of string arguments as CSV.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
args: the string arguments to format.
|
|
|
|
sep: the argument separator.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The arguments formatted as a CSV string.
|
|
|
|
"""
|
2025-02-13 06:15:54 +01:00
|
|
|
return sep.join(arg for arg in args if arg)
|
|
|
|
|
|
|
|
|
2025-02-13 14:52:26 +01:00
|
|
|
def subclasses(
|
|
|
|
module_name: str,
|
|
|
|
classes: t.Type | t.Tuple[t.Type, ...],
|
|
|
|
exclude: t.Type | t.Tuple[t.Type, ...] = (),
|
|
|
|
) -> t.List[t.Type]:
|
2025-02-13 14:37:25 +01:00
|
|
|
"""
|
2025-02-13 14:52:26 +01:00
|
|
|
Returns all subclasses for a collection of classes, possibly excluding some of them.
|
2025-02-13 14:37:25 +01:00
|
|
|
|
|
|
|
Args:
|
2025-02-13 14:52:26 +01:00
|
|
|
module_name: the name of the module to search for subclasses in.
|
|
|
|
classes: class(es) we want to find the subclasses of.
|
|
|
|
exclude: class(es) we want to exclude from the returned list.
|
|
|
|
|
2025-02-13 14:37:25 +01:00
|
|
|
Returns:
|
2025-02-13 14:52:26 +01:00
|
|
|
The target subclasses.
|
2025-02-13 14:37:25 +01:00
|
|
|
"""
|
|
|
|
return [
|
|
|
|
obj
|
|
|
|
for _, obj in inspect.getmembers(
|
|
|
|
sys.modules[module_name],
|
|
|
|
lambda obj: inspect.isclass(obj) and issubclass(obj, classes) and obj not in exclude,
|
|
|
|
)
|
|
|
|
]
|
|
|
|
|
|
|
|
|
2025-02-13 14:52:26 +01:00
|
|
|
def apply_index_offset(expressions: t.List[E], offset: int) -> t.List[E]:
|
|
|
|
"""
|
|
|
|
Applies an offset to a given integer literal expression.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
expressions: the expression the offset will be applied to, wrapped in a list.
|
|
|
|
offset: the offset that will be applied.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The original expression with the offset applied to it, wrapped in a list. If the provided
|
|
|
|
`expressions` argument contains more than one expressions, it's returned unaffected.
|
|
|
|
"""
|
2025-02-13 06:15:54 +01:00
|
|
|
if not offset or len(expressions) != 1:
|
|
|
|
return expressions
|
|
|
|
|
|
|
|
expression = expressions[0]
|
|
|
|
|
|
|
|
if expression.is_int:
|
|
|
|
expression = expression.copy()
|
|
|
|
logger.warning("Applying array index offset (%s)", offset)
|
|
|
|
expression.args["this"] = str(int(expression.args["this"]) + offset)
|
|
|
|
return [expression]
|
2025-02-13 14:52:26 +01:00
|
|
|
|
2025-02-13 06:15:54 +01:00
|
|
|
return expressions
|
|
|
|
|
|
|
|
|
2025-02-13 14:52:26 +01:00
|
|
|
def camel_to_snake_case(name: str) -> str:
|
|
|
|
"""Converts `name` from camelCase to snake_case and returns the result."""
|
2025-02-13 06:15:54 +01:00
|
|
|
return CAMEL_CASE_PATTERN.sub("_", name).upper()
|
|
|
|
|
|
|
|
|
2025-02-13 14:52:26 +01:00
|
|
|
def while_changing(
|
|
|
|
expression: t.Optional[Expression], func: t.Callable[[t.Optional[Expression]], E]
|
|
|
|
) -> E:
|
|
|
|
"""
|
|
|
|
Applies a transformation to a given expression until a fix point is reached.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
expression: the expression to be transformed.
|
|
|
|
func: the transformation to be applied.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The transformed expression.
|
|
|
|
"""
|
2025-02-13 06:15:54 +01:00
|
|
|
while True:
|
|
|
|
start = hash(expression)
|
|
|
|
expression = func(expression)
|
|
|
|
if start == hash(expression):
|
|
|
|
break
|
|
|
|
return expression
|
|
|
|
|
|
|
|
|
2025-02-13 14:52:26 +01:00
|
|
|
def tsort(dag: t.Dict[T, t.List[T]]) -> t.List[T]:
|
|
|
|
"""
|
|
|
|
Sorts a given directed acyclic graph in topological order.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
dag: the graph to be sorted.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
A list that contains all of the graph's nodes in topological order.
|
|
|
|
"""
|
2025-02-13 06:15:54 +01:00
|
|
|
result = []
|
|
|
|
|
2025-02-13 14:52:26 +01:00
|
|
|
def visit(node: T, visited: t.Set[T]) -> None:
|
2025-02-13 06:15:54 +01:00
|
|
|
if node in result:
|
|
|
|
return
|
|
|
|
if node in visited:
|
|
|
|
raise ValueError("Cycle error")
|
|
|
|
|
|
|
|
visited.add(node)
|
|
|
|
|
|
|
|
for dep in dag.get(node, []):
|
|
|
|
visit(dep, visited)
|
|
|
|
|
|
|
|
visited.remove(node)
|
|
|
|
result.append(node)
|
|
|
|
|
|
|
|
for node in dag:
|
|
|
|
visit(node, set())
|
|
|
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
2025-02-13 14:52:26 +01:00
|
|
|
def open_file(file_name: str) -> t.TextIO:
|
|
|
|
"""Open a file that may be compressed as gzip and return it in universal newline mode."""
|
2025-02-13 06:15:54 +01:00
|
|
|
with open(file_name, "rb") as f:
|
|
|
|
gzipped = f.read(2) == b"\x1f\x8b"
|
|
|
|
|
|
|
|
if gzipped:
|
|
|
|
import gzip
|
|
|
|
|
|
|
|
return gzip.open(file_name, "rt", newline="")
|
|
|
|
|
|
|
|
return open(file_name, "rt", encoding="utf-8", newline="")
|
|
|
|
|
|
|
|
|
|
|
|
@contextmanager
|
2025-02-13 14:52:26 +01:00
|
|
|
def csv_reader(table: Table) -> t.Any:
|
2025-02-13 06:15:54 +01:00
|
|
|
"""
|
2025-02-13 14:52:26 +01:00
|
|
|
Returns a csv reader given the expression `READ_CSV(name, ['delimiter', '|', ...])`.
|
2025-02-13 06:15:54 +01:00
|
|
|
|
|
|
|
Args:
|
2025-02-13 14:52:26 +01:00
|
|
|
table: a `Table` expression with an anonymous function `READ_CSV` in it.
|
2025-02-13 06:15:54 +01:00
|
|
|
|
2025-02-13 14:52:26 +01:00
|
|
|
Yields:
|
2025-02-13 06:15:54 +01:00
|
|
|
A python csv reader.
|
|
|
|
"""
|
|
|
|
file, *args = table.this.expressions
|
|
|
|
file = file.name
|
|
|
|
file = open_file(file)
|
|
|
|
|
|
|
|
delimiter = ","
|
|
|
|
args = iter(arg.name for arg in args)
|
|
|
|
for k, v in zip(args, args):
|
|
|
|
if k == "delimiter":
|
|
|
|
delimiter = v
|
|
|
|
|
|
|
|
try:
|
|
|
|
import csv as csv_
|
|
|
|
|
|
|
|
yield csv_.reader(file, delimiter=delimiter)
|
|
|
|
finally:
|
|
|
|
file.close()
|
2025-02-13 14:37:25 +01:00
|
|
|
|
|
|
|
|
2025-02-13 14:52:26 +01:00
|
|
|
def find_new_name(taken: t.Sequence[str], base: str) -> str:
|
2025-02-13 14:37:25 +01:00
|
|
|
"""
|
|
|
|
Searches for a new name.
|
|
|
|
|
|
|
|
Args:
|
2025-02-13 14:52:26 +01:00
|
|
|
taken: a collection of taken names.
|
|
|
|
base: base name to alter.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The new, available name.
|
2025-02-13 14:37:25 +01:00
|
|
|
"""
|
|
|
|
if base not in taken:
|
|
|
|
return base
|
|
|
|
|
|
|
|
i = 2
|
|
|
|
new = f"{base}_{i}"
|
|
|
|
while new in taken:
|
|
|
|
i += 1
|
|
|
|
new = f"{base}_{i}"
|
2025-02-13 14:52:26 +01:00
|
|
|
|
2025-02-13 14:37:25 +01:00
|
|
|
return new
|
2025-02-13 14:47:39 +01:00
|
|
|
|
|
|
|
|
2025-02-13 14:52:26 +01:00
|
|
|
def object_to_dict(obj: t.Any, **kwargs) -> t.Dict:
|
|
|
|
"""Returns a dictionary created from an object's attributes."""
|
2025-02-13 14:47:39 +01:00
|
|
|
return {**{k: copy(v) for k, v in vars(obj).copy().items()}, **kwargs}
|
|
|
|
|
|
|
|
|
2025-02-13 14:52:26 +01:00
|
|
|
def split_num_words(
|
|
|
|
value: str, sep: str, min_num_words: int, fill_from_start: bool = True
|
|
|
|
) -> t.List[t.Optional[str]]:
|
2025-02-13 14:47:39 +01:00
|
|
|
"""
|
2025-02-13 14:52:26 +01:00
|
|
|
Perform a split on a value and return N words as a result with `None` used for words that don't exist.
|
2025-02-13 14:47:39 +01:00
|
|
|
|
|
|
|
Args:
|
2025-02-13 14:52:26 +01:00
|
|
|
value: the value to be split.
|
|
|
|
sep: the value to use to split on.
|
|
|
|
min_num_words: the minimum number of words that are going to be in the result.
|
|
|
|
fill_from_start: indicates that if `None` values should be inserted at the start or end of the list.
|
2025-02-13 14:47:39 +01:00
|
|
|
|
|
|
|
Examples:
|
|
|
|
>>> split_num_words("db.table", ".", 3)
|
|
|
|
[None, 'db', 'table']
|
|
|
|
>>> split_num_words("db.table", ".", 3, fill_from_start=False)
|
|
|
|
['db', 'table', None]
|
|
|
|
>>> split_num_words("db.table", ".", 1)
|
|
|
|
['db', 'table']
|
2025-02-13 14:52:26 +01:00
|
|
|
|
|
|
|
Returns:
|
|
|
|
The list of words returned by `split`, possibly augmented by a number of `None` values.
|
2025-02-13 14:47:39 +01:00
|
|
|
"""
|
|
|
|
words = value.split(sep)
|
|
|
|
if fill_from_start:
|
|
|
|
return [None] * (min_num_words - len(words)) + words
|
|
|
|
return words + [None] * (min_num_words - len(words))
|
|
|
|
|
|
|
|
|
2025-02-13 14:49:58 +01:00
|
|
|
def is_iterable(value: t.Any) -> bool:
|
|
|
|
"""
|
2025-02-13 14:52:26 +01:00
|
|
|
Checks if the value is an iterable, excluding the types `str` and `bytes`.
|
2025-02-13 14:49:58 +01:00
|
|
|
|
|
|
|
Examples:
|
|
|
|
>>> is_iterable([1,2])
|
|
|
|
True
|
|
|
|
>>> is_iterable("test")
|
|
|
|
False
|
|
|
|
|
|
|
|
Args:
|
2025-02-13 14:52:26 +01:00
|
|
|
value: the value to check if it is an iterable.
|
2025-02-13 14:49:58 +01:00
|
|
|
|
2025-02-13 14:52:26 +01:00
|
|
|
Returns:
|
|
|
|
A `bool` value indicating if it is an iterable.
|
2025-02-13 14:49:58 +01:00
|
|
|
"""
|
|
|
|
return hasattr(value, "__iter__") and not isinstance(value, (str, bytes))
|
|
|
|
|
|
|
|
|
2025-02-13 14:52:26 +01:00
|
|
|
def flatten(values: t.Iterable[t.Iterable[t.Any] | t.Any]) -> t.Generator[t.Any, None, None]:
|
2025-02-13 14:47:39 +01:00
|
|
|
"""
|
2025-02-13 14:52:26 +01:00
|
|
|
Flattens an iterable that can contain both iterable and non-iterable elements. Objects of
|
|
|
|
type `str` and `bytes` are not regarded as iterables.
|
2025-02-13 14:47:39 +01:00
|
|
|
|
|
|
|
Examples:
|
2025-02-13 14:52:26 +01:00
|
|
|
>>> list(flatten([[1, 2], 3, {4}, (5, "bla")]))
|
|
|
|
[1, 2, 3, 4, 5, 'bla']
|
2025-02-13 14:47:39 +01:00
|
|
|
>>> list(flatten([1, 2, 3]))
|
|
|
|
[1, 2, 3]
|
|
|
|
|
|
|
|
Args:
|
2025-02-13 14:52:26 +01:00
|
|
|
values: the value to be flattened.
|
2025-02-13 14:47:39 +01:00
|
|
|
|
2025-02-13 14:52:26 +01:00
|
|
|
Yields:
|
|
|
|
Non-iterable elements in `values`.
|
2025-02-13 14:47:39 +01:00
|
|
|
"""
|
|
|
|
for value in values:
|
2025-02-13 14:49:58 +01:00
|
|
|
if is_iterable(value):
|
2025-02-13 14:47:39 +01:00
|
|
|
yield from flatten(value)
|
|
|
|
else:
|
|
|
|
yield value
|