forked from googleapis/python-bigquery-sqlalchemy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_struct.py
148 lines (115 loc) · 4.91 KB
/
_struct.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# Copyright (c) 2021 The sqlalchemy-bigquery Authors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
from typing import Mapping, Tuple
import packaging.version
import sqlalchemy.sql.default_comparator
import sqlalchemy.sql.sqltypes
import sqlalchemy.types
from . import base
sqlalchemy_1_4_or_more = packaging.version.parse(
sqlalchemy.__version__
) >= packaging.version.parse("1.4")
if sqlalchemy_1_4_or_more:
import sqlalchemy.sql.coercions
import sqlalchemy.sql.roles
def _get_subtype_col_spec(type_):
global _get_subtype_col_spec
type_compiler = base.dialect.type_compiler(base.dialect())
_get_subtype_col_spec = type_compiler.process
return _get_subtype_col_spec(type_)
class STRUCT(sqlalchemy.sql.sqltypes.Indexable, sqlalchemy.types.UserDefinedType):
"""
A type for BigQuery STRUCT/RECORD data
See https://googleapis.dev/python/sqlalchemy-bigquery/latest/struct.html
"""
# See https://docs.sqlalchemy.org/en/14/core/custom_types.html#creating-new-types
def __init__(
self,
*fields: Tuple[str, sqlalchemy.types.TypeEngine],
**kwfields: Mapping[str, sqlalchemy.types.TypeEngine],
):
# Note that because:
# https://docs.python.org/3/whatsnew/3.6.html#pep-468-preserving-keyword-argument-order
# We know that `kwfields` preserves order.
self._STRUCT_fields = tuple(
(
name,
type_ if isinstance(type_, sqlalchemy.types.TypeEngine) else type_(),
)
for (name, type_) in (fields + tuple(kwfields.items()))
)
self._STRUCT_byname = {
name.lower(): type_ for (name, type_) in self._STRUCT_fields
}
def __repr__(self):
fields = ", ".join(
f"{name}={repr(type_)}" for name, type_ in self._STRUCT_fields
)
return f"STRUCT({fields})"
def get_col_spec(self, **kw):
fields = ", ".join(
f"{name} {_get_subtype_col_spec(type_)}"
for name, type_ in self._STRUCT_fields
)
return f"STRUCT<{fields}>"
def bind_processor(self, dialect):
return dict
class Comparator(sqlalchemy.sql.sqltypes.Indexable.Comparator):
def _setup_getitem(self, name):
if not isinstance(name, str):
raise TypeError(
f"STRUCT fields can only be accessed with strings field names,"
f" not {repr(name)}."
)
subtype = self.expr.type._STRUCT_byname.get(name.lower())
if subtype is None:
raise KeyError(name)
operator = struct_getitem_op
index = _field_index(self, name, operator)
return operator, index, subtype
def __getattr__(self, name):
if name.lower() in self.expr.type._STRUCT_byname:
return self[name]
comparator_factory = Comparator
# In the implementations of _field_index below, we're stealing from
# the JSON type implementation, but the code to steal changed in
# 1.4. :/
if sqlalchemy_1_4_or_more:
def _field_index(self, name, operator):
return sqlalchemy.sql.coercions.expect(
sqlalchemy.sql.roles.BinaryElementRole,
name,
expr=self.expr,
operator=operator,
bindparam_type=sqlalchemy.types.String(),
)
else:
def _field_index(self, name, operator):
return sqlalchemy.sql.default_comparator._check_literal(
self.expr, operator, name, bindparam_type=sqlalchemy.types.String(),
)
def struct_getitem_op(a, b):
raise NotImplementedError()
sqlalchemy.sql.default_comparator.operator_lookup[
struct_getitem_op.__name__
] = sqlalchemy.sql.default_comparator.operator_lookup["json_getitem_op"]
class SQLCompiler:
def visit_struct_getitem_op_binary(self, binary, operator_, **kw):
left = self.process(binary.left, **kw)
return f"{left}.{binary.right.value}"