|
| 1 | +"""Operations for template strings (t-strings).""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from itertools import zip_longest |
| 6 | +from typing import TYPE_CHECKING, Protocol |
| 7 | + |
| 8 | +import sqlglot as sg |
| 9 | +import sqlglot.expressions as sge |
| 10 | +from public import public |
| 11 | +from sqlglot.optimizer.annotate_types import annotate_types |
| 12 | +from typing_extensions import runtime_checkable |
| 13 | + |
| 14 | +import ibis.expr.datashape as ds |
| 15 | +import ibis.expr.datatypes as dt |
| 16 | +import ibis.expr.rules as rlz |
| 17 | +from ibis.common.annotations import attribute |
| 18 | +from ibis.common.typing import VarTuple # noqa: TC001 |
| 19 | +from ibis.expr.operations.core import Value |
| 20 | + |
| 21 | +if TYPE_CHECKING: |
| 22 | + from collections.abc import Iterator |
| 23 | + |
| 24 | + from ibis.backends.sql.datatypes import SqlglotType |
| 25 | + from ibis.expr.operations.relations import Relation |
| 26 | + from ibis.expr.types.generic import Value as ExprValue |
| 27 | + |
| 28 | + |
| 29 | +@runtime_checkable |
| 30 | +class IntoInterpolation(Protocol): |
| 31 | + """Protocol for an object that can be interpreted as a PEP 750 t-string Interpolation.""" |
| 32 | + |
| 33 | + value: ExprValue |
| 34 | + expression: str |
| 35 | + |
| 36 | + |
| 37 | +@runtime_checkable |
| 38 | +class IntoTemplate(Protocol): |
| 39 | + """Protocol for an object that can be interpreted as a PEP 750 t-string Template.""" |
| 40 | + |
| 41 | + strings: tuple[str, ...] |
| 42 | + interpolations: tuple[IntoInterpolation, ...] |
| 43 | + |
| 44 | + |
| 45 | +@public |
| 46 | +class TemplateSQL(Value): |
| 47 | + strings: VarTuple[str] |
| 48 | + values: VarTuple[Value] |
| 49 | + dialect: str | None = None |
| 50 | + """The SQL dialect the template was written in. |
| 51 | +
|
| 52 | + eg if t'CAST({val} AS REAL)', you should use 'sqlite', |
| 53 | + since REAL is a sqlite-specific concept. |
| 54 | + """ |
| 55 | + |
| 56 | + def __init__(self, strings, values, dialect: str | None = None): |
| 57 | + super().__init__(strings=strings, values=values, dialect=dialect or "duckdb") |
| 58 | + if self.dtype.is_unknown(): |
| 59 | + raise TypeError( |
| 60 | + f"Could not infer the dtype of the template expression with sql:\n{self.sql_for_inference}" |
| 61 | + ) |
| 62 | + |
| 63 | + @classmethod |
| 64 | + def from_template( |
| 65 | + cls, template: IntoTemplate, /, *, dialect: str | None = None |
| 66 | + ) -> TemplateSQL: |
| 67 | + return cls( |
| 68 | + strings=template.strings, |
| 69 | + values=[interp.value for interp in template.interpolations], |
| 70 | + dialect=dialect, |
| 71 | + ) |
| 72 | + |
| 73 | + @attribute |
| 74 | + def shape(self): |
| 75 | + if not self.values: |
| 76 | + return ds.scalar |
| 77 | + return rlz.highest_precedence_shape(self.values) |
| 78 | + |
| 79 | + @attribute |
| 80 | + def dtype(self) -> dt.DataType: |
| 81 | + parsed = sg.parse_one(self.sql_for_inference, dialect=self.dialect) |
| 82 | + annotated = annotate_types(parsed, dialect=self.dialect) |
| 83 | + sqlglot_type = annotated.type |
| 84 | + return self.type_mapper.to_ibis(sqlglot_type) |
| 85 | + |
| 86 | + @attribute |
| 87 | + def relations(self) -> frozenset[Relation]: |
| 88 | + children = (n.relations for n in self.values) |
| 89 | + return frozenset().union(*children) |
| 90 | + |
| 91 | + @property |
| 92 | + def sql_for_inference(self) -> str: |
| 93 | + parts: list[str] = [] |
| 94 | + for part in self.parts: |
| 95 | + if isinstance(part, str): |
| 96 | + parts.append(part) |
| 97 | + else: |
| 98 | + ibis_type: dt.DataType = part.dtype |
| 99 | + null_sqlglot_value = sge.cast( |
| 100 | + sge.null(), self.type_mapper.from_ibis(ibis_type) |
| 101 | + ) |
| 102 | + parts.append(null_sqlglot_value.sql(self.dialect)) |
| 103 | + return "".join(parts) |
| 104 | + |
| 105 | + @property |
| 106 | + def type_mapper(self) -> SqlglotType: |
| 107 | + return get_type_mapper(self.dialect) |
| 108 | + |
| 109 | + @property |
| 110 | + def parts(self): |
| 111 | + def iter() -> Iterator[str | Value]: |
| 112 | + for s, i in zip_longest(self.strings, self.values): |
| 113 | + if s: |
| 114 | + yield s |
| 115 | + if i: |
| 116 | + yield i |
| 117 | + |
| 118 | + return tuple(iter()) |
| 119 | + |
| 120 | + |
| 121 | +def get_type_mapper(dialect: str | None) -> SqlglotType: |
| 122 | + """Get the type mapper for the given SQL dialect.""" |
| 123 | + import importlib |
| 124 | + |
| 125 | + module = importlib.import_module(f"ibis.backends.sql.compilers.{dialect}") |
| 126 | + compiler_instance = module.compiler |
| 127 | + return compiler_instance.type_mapper |
0 commit comments