sqlalchemy-bigquery 1.14.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,295 @@
1
+ # Copyright (c) 2021 The PyBigQuery Authors
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining a copy of
4
+ # this software and associated documentation files (the "Software"), to deal in
5
+ # the Software without restriction, including without limitation the rights to
6
+ # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
7
+ # the Software, and to permit persons to whom the Software is furnished to do so,
8
+ # subject to the following conditions:
9
+ #
10
+ # The above copyright notice and this permission notice shall be included in all
11
+ # copies or substantial portions of the Software.
12
+ #
13
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
15
+ # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
16
+ # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
17
+ # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18
+ # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19
+
20
+ import geoalchemy2
21
+ from geoalchemy2.shape import to_shape
22
+ import geoalchemy2.functions
23
+ from shapely import wkb, wkt
24
+ import sqlalchemy.ext.compiler
25
+ from sqlalchemy.sql.elements import BindParameter
26
+
27
+ SRID = 4326 # WGS84, https://spatialreference.org/ref/epsg/wgs-84/
28
+
29
+
30
+ class WKB(geoalchemy2.WKBElement):
31
+ """
32
+ Well-Known-Binary data wrapper.
33
+
34
+ WKB objects hold geographic data in a binary format known as
35
+ "Well-Known Binary",
36
+ <https://en.wikipedia.org/wiki/Well-known_text_representation_of_geometry>.
37
+ These objects are returned from queries and can be used in insert
38
+ and queries.
39
+
40
+ The WKB class is a subclass of the Geoalchemy2 WKBElement class
41
+ customized for working with BigQuery.
42
+ """
43
+
44
+ geom_from_extended_version = "ST_GeogFromWKB"
45
+
46
+ def __init__(self, data):
47
+ super().__init__(data, SRID, True)
48
+
49
+ @property
50
+ def wkt(self):
51
+ """
52
+ Return the WKB object as a WKT object.
53
+ """
54
+ return WKT(to_shape(self).wkt)
55
+
56
+
57
+ class WKT(geoalchemy2.WKTElement):
58
+ """
59
+ Well-Known-Text data wrapper.
60
+
61
+ WKT objects hold geographic data in a text format known as
62
+ "Well-Known Text",
63
+ <https://en.wikipedia.org/wiki/Well-known_text_representation_of_geometry>.
64
+
65
+ You generally shouldn't need to create WKT objects directly, as
66
+ text arguments to geographic functions and inserts to GEOGRAPHY
67
+ columns are automatically coerced to geographic data.
68
+
69
+ The WKT class is a subclass of the Geoalchemy2 WKTElement class
70
+ customized for working with BigQuery.
71
+ """
72
+
73
+ geom_from_extended_version = "ST_GeogFromText"
74
+
75
+ def __init__(self, data):
76
+ super().__init__(data, SRID, True)
77
+
78
+ @property
79
+ def wkb(self):
80
+ """
81
+ Return the WKT object as a WKB object.
82
+ """
83
+ return WKB(wkb.dumps(wkt.loads(self.data)))
84
+
85
+
86
+ class GEOGRAPHY(geoalchemy2.Geography):
87
+ """
88
+ GEOGRAPHY type
89
+
90
+ Use this to define BigQuery GEOGRAPHY columns::
91
+
92
+ class Lake(Base):
93
+ __tablename__ = 'lakes'
94
+
95
+ name = Column(String)
96
+ geog = column(GEOGRAPHY)
97
+
98
+ See https://googleapis.dev/python/sqlalchemy-bigquery/latest/geography.html
99
+ """
100
+
101
+ def __init__(self):
102
+ super().__init__(
103
+ geometry_type=None,
104
+ spatial_index=False,
105
+ srid=SRID,
106
+ )
107
+ self.extended = True
108
+
109
+ # Un-inherit the bind function that adds an ST_GeogFromText.
110
+ # It's unnecessary and causes BigQuery to error.
111
+ #
112
+ # Some things to note about this:
113
+ #
114
+ # 1. bind_expression can't always know the value. When multiple
115
+ # rows are being inserted, the values may be different in each
116
+ # row. As a consequence, we have to treat all the values as WKT.
117
+ #
118
+ # 2. This applies equally to explicitly converting with
119
+ # st_geogfromtext, or implicitly with the geography parameter
120
+ # conversion.
121
+ #
122
+ # 3. We handle different types using bind_processor, below.
123
+ #
124
+ bind_expression = sqlalchemy.sql.type_api.TypeEngine.bind_expression
125
+
126
+ def bind_processor(self, dialect):
127
+ """
128
+ SqlAlchemy plugin that controls how values are converted to parameters
129
+
130
+ When we bind values, we always bind as text. We have to do
131
+ this because when we decide how to bind, we don't always know
132
+ what the values will be.
133
+
134
+ This is not a user-facing method.
135
+ """
136
+
137
+ def process(bindvalue):
138
+ if isinstance(bindvalue, WKT):
139
+ return bindvalue.data
140
+ elif isinstance(bindvalue, WKB):
141
+ return bindvalue.wkt.data
142
+ else:
143
+ return bindvalue
144
+
145
+ return process
146
+
147
+ @staticmethod
148
+ def ElementType(data, srid=SRID, extended=True):
149
+ """
150
+ Plugin for the Geoalchemy2 framework for constructing WKB objects.
151
+
152
+ The framework wants a callable, which it assumes is a class
153
+ (this the name), for constructing a geographic element.
154
+
155
+ We don't want `WKB` to accept extra arguments that it checks
156
+ and ignores, so we do that in this wrapper.
157
+
158
+ This is not a user-facing method.
159
+ """
160
+ if srid != SRID:
161
+ raise AssertionError("Bad srid", srid)
162
+ if not extended:
163
+ raise AssertionError("Extended must be True.")
164
+ return WKB(data)
165
+
166
+
167
+ @sqlalchemy.ext.compiler.compiles(geoalchemy2.functions.GenericFunction, "bigquery")
168
+ def _fixup_st_arguments(element, compiler, **kw):
169
+ """
170
+ Compiler-plugin for the BigQuery that overrides how geographic functions are handled
171
+
172
+ Geographic function (ST_...) get turned into
173
+ `geoalchemy2.functions.GenericFunction` objects by
174
+ Geoalchemy2. The code here overrides how they're handeled.
175
+
176
+ We want arguments passed to have the GEOGRAPHY type associated
177
+ with them, when appropriate, where "when appropriate" is
178
+ determined by the `function documentation
179
+ <https://cloud.google.com/bigquery/docs/reference/standard-sql/geography_functions>`_..
180
+
181
+ This is not a user-facing function.
182
+ """
183
+ argument_types = _argument_types.get(element.name.lower())
184
+ if argument_types:
185
+ for argument_type, argument in zip(argument_types, element.clauses.clauses):
186
+ if isinstance(argument, BindParameter) and (
187
+ argument.type is not argument_type
188
+ or not isinstance(argument.type, argument_type)
189
+ ):
190
+ argument.type = argument_type()
191
+
192
+ return compiler.visit_function(element, **kw)
193
+
194
+
195
+ _argument_types = dict(
196
+ st_area=(GEOGRAPHY,),
197
+ st_asbinary=(GEOGRAPHY,),
198
+ st_asgeojson=(GEOGRAPHY,),
199
+ st_astext=(GEOGRAPHY,),
200
+ st_boundary=(GEOGRAPHY,),
201
+ st_centroid=(GEOGRAPHY,),
202
+ st_centroid_agg=(GEOGRAPHY,),
203
+ st_closestpoint=(
204
+ GEOGRAPHY,
205
+ GEOGRAPHY,
206
+ ),
207
+ st_clusterdbscan=(GEOGRAPHY,),
208
+ st_contains=(
209
+ GEOGRAPHY,
210
+ GEOGRAPHY,
211
+ ),
212
+ st_convexhull=(GEOGRAPHY,),
213
+ st_coveredby=(
214
+ GEOGRAPHY,
215
+ GEOGRAPHY,
216
+ ),
217
+ st_covers=(
218
+ GEOGRAPHY,
219
+ GEOGRAPHY,
220
+ ),
221
+ st_difference=(
222
+ GEOGRAPHY,
223
+ GEOGRAPHY,
224
+ ),
225
+ st_dimension=(GEOGRAPHY,),
226
+ st_disjoint=(
227
+ GEOGRAPHY,
228
+ GEOGRAPHY,
229
+ ),
230
+ st_distance=(
231
+ GEOGRAPHY,
232
+ GEOGRAPHY,
233
+ ),
234
+ st_dump=(GEOGRAPHY,),
235
+ st_dwithin=(
236
+ GEOGRAPHY,
237
+ GEOGRAPHY,
238
+ ),
239
+ st_endpoint=(GEOGRAPHY,),
240
+ st_equals=(
241
+ GEOGRAPHY,
242
+ GEOGRAPHY,
243
+ ),
244
+ st_exteriorring=(GEOGRAPHY,),
245
+ st_geohash=(GEOGRAPHY,),
246
+ st_intersection=(
247
+ GEOGRAPHY,
248
+ GEOGRAPHY,
249
+ ),
250
+ st_intersects=(
251
+ GEOGRAPHY,
252
+ GEOGRAPHY,
253
+ ),
254
+ st_intersectsbox=(GEOGRAPHY,),
255
+ st_iscollection=(GEOGRAPHY,),
256
+ st_isempty=(GEOGRAPHY,),
257
+ st_length=(GEOGRAPHY,),
258
+ st_makeline=(
259
+ GEOGRAPHY,
260
+ GEOGRAPHY,
261
+ ),
262
+ st_makepolygon=(
263
+ GEOGRAPHY,
264
+ GEOGRAPHY,
265
+ ),
266
+ st_makepolygonoriented=(GEOGRAPHY,),
267
+ st_maxdistance=(
268
+ GEOGRAPHY,
269
+ GEOGRAPHY,
270
+ ),
271
+ st_npoints=(GEOGRAPHY,),
272
+ st_numpoints=(GEOGRAPHY,),
273
+ st_perimeter=(GEOGRAPHY,),
274
+ st_pointn=(GEOGRAPHY,),
275
+ st_simplify=(GEOGRAPHY,),
276
+ st_snaptogrid=(GEOGRAPHY,),
277
+ st_startpoint=(GEOGRAPHY,),
278
+ st_touches=(
279
+ GEOGRAPHY,
280
+ GEOGRAPHY,
281
+ ),
282
+ st_union=(
283
+ GEOGRAPHY,
284
+ GEOGRAPHY,
285
+ ),
286
+ st_union_agg=(GEOGRAPHY,),
287
+ st_within=(
288
+ GEOGRAPHY,
289
+ GEOGRAPHY,
290
+ ),
291
+ st_x=(GEOGRAPHY,),
292
+ st_y=(GEOGRAPHY,),
293
+ )
294
+
295
+ __all__ = ["GEOGRAPHY", "WKB", "WKT"]
@@ -0,0 +1,286 @@
1
+ # Copyright (c) 2017 The sqlalchemy-bigquery Authors
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining a copy of
4
+ # this software and associated documentation files (the "Software"), to deal in
5
+ # the Software without restriction, including without limitation the rights to
6
+ # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
7
+ # the Software, and to permit persons to whom the Software is furnished to do so,
8
+ # subject to the following conditions:
9
+ #
10
+ # The above copyright notice and this permission notice shall be included in all
11
+ # copies or substantial portions of the Software.
12
+ #
13
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
15
+ # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
16
+ # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
17
+ # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18
+ # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19
+
20
+ import re
21
+
22
+ from google.cloud.bigquery import QueryJobConfig
23
+ from google.cloud.bigquery.dataset import DatasetReference
24
+ from google.cloud.bigquery.job import (
25
+ CreateDisposition,
26
+ WriteDisposition,
27
+ QueryPriority,
28
+ SchemaUpdateOption,
29
+ )
30
+ from google.cloud.bigquery.table import EncryptionConfiguration, TableReference
31
+
32
+ GROUP_DELIMITER = re.compile(r"\s*\,\s*")
33
+ KEY_VALUE_DELIMITER = re.compile(r"\s*\:\s*")
34
+
35
+
36
+ def parse_boolean(bool_string):
37
+ bool_string = bool_string.lower()
38
+ if bool_string == "true":
39
+ return True
40
+ elif bool_string == "false":
41
+ return False
42
+ else:
43
+ raise ValueError()
44
+
45
+
46
+ def parse_url(url): # noqa: C901
47
+ query = dict(url.query) # need mutable query.
48
+
49
+ # use_legacy_sql (legacy)
50
+ if "use_legacy_sql" in query:
51
+ raise ValueError("legacy sql is not supported by this dialect")
52
+ # allow_large_results (legacy)
53
+ if "allow_large_results" in query:
54
+ raise ValueError(
55
+ "allow_large_results is only allowed for legacy sql, which is not supported by this dialect"
56
+ )
57
+ # flatten_results (legacy)
58
+ if "flatten_results" in query:
59
+ raise ValueError(
60
+ "flatten_results is only allowed for legacy sql, which is not supported by this dialect"
61
+ )
62
+ # maximum_billing_tier (deprecated)
63
+ if "maximum_billing_tier" in query:
64
+ raise ValueError("maximum_billing_tier is a deprecated argument")
65
+
66
+ project_id = url.host
67
+ location = None
68
+ dataset_id = url.database or None
69
+ arraysize = None
70
+ credentials_path = None
71
+ credentials_base64 = None
72
+ list_tables_page_size = None
73
+ user_supplied_client = False
74
+
75
+ # location
76
+ if "location" in query:
77
+ location = query.pop("location")
78
+
79
+ # credentials_path
80
+ if "credentials_path" in query:
81
+ credentials_path = query.pop("credentials_path")
82
+
83
+ # credentials_base64
84
+ if "credentials_base64" in query:
85
+ credentials_base64 = query.pop("credentials_base64")
86
+
87
+ # arraysize
88
+ if "arraysize" in query:
89
+ str_arraysize = query.pop("arraysize")
90
+ try:
91
+ arraysize = int(str_arraysize)
92
+ except ValueError:
93
+ raise ValueError("invalid int in url query arraysize: " + str_arraysize)
94
+
95
+ if "list_tables_page_size" in query:
96
+ str_list_tables_page_size = query.pop("list_tables_page_size")
97
+ try:
98
+ list_tables_page_size = int(str_list_tables_page_size)
99
+ except ValueError:
100
+ raise ValueError(
101
+ "invalid int in url query list_tables_page_size: "
102
+ + str_list_tables_page_size
103
+ )
104
+
105
+ # user_supplied_client
106
+ if "user_supplied_client" in query:
107
+ user_supplied_client = query.pop("user_supplied_client").lower() == "true"
108
+
109
+ # if only these "non-config" values were present, the dict will now be empty
110
+ if not query:
111
+ # if a dataset_id exists, we need to return a job_config that isn't None
112
+ # so it can be updated with a dataset reference from the client
113
+ if dataset_id:
114
+ return (
115
+ project_id,
116
+ location,
117
+ dataset_id,
118
+ arraysize,
119
+ credentials_path,
120
+ credentials_base64,
121
+ QueryJobConfig(),
122
+ list_tables_page_size,
123
+ user_supplied_client,
124
+ )
125
+ else:
126
+ return (
127
+ project_id,
128
+ location,
129
+ dataset_id,
130
+ arraysize,
131
+ credentials_path,
132
+ credentials_base64,
133
+ None,
134
+ list_tables_page_size,
135
+ user_supplied_client,
136
+ )
137
+
138
+ job_config = QueryJobConfig()
139
+
140
+ # clustering_fields list(str)
141
+ if "clustering_fields" in query:
142
+ clustering_fields = GROUP_DELIMITER.split(query["clustering_fields"])
143
+ job_config.clustering_fields = list(clustering_fields)
144
+
145
+ # create_disposition
146
+ if "create_disposition" in query:
147
+ create_disposition = query["create_disposition"]
148
+ try:
149
+ job_config.create_disposition = getattr(
150
+ CreateDisposition, create_disposition
151
+ )
152
+ except AttributeError:
153
+ raise ValueError(
154
+ "invalid create_disposition in url query: " + create_disposition
155
+ )
156
+
157
+ # default_dataset
158
+ if "default_dataset" in query or "dataset_id" in query or "project_id" in query:
159
+ raise ValueError(
160
+ "don't pass default_dataset, dataset_id, project_id in url query, instead use the url host and database"
161
+ )
162
+
163
+ # destination
164
+ if "destination" in query:
165
+ dest_project = None
166
+ dest_dataset = None
167
+ dest_table = None
168
+
169
+ try:
170
+ dest_project, dest_dataset, dest_table = query["destination"].split(".")
171
+ except ValueError:
172
+ raise ValueError(
173
+ "url query destination parameter should be fully qualified with project, dataset, and table"
174
+ )
175
+
176
+ job_config.destination = TableReference(
177
+ DatasetReference(dest_project, dest_dataset), dest_table
178
+ )
179
+
180
+ # destination_encryption_configuration
181
+ if "destination_encryption_configuration" in query:
182
+ job_config.destination_encryption_configuration = EncryptionConfiguration(
183
+ query["destination_encryption_configuration"]
184
+ )
185
+
186
+ # dry_run
187
+ if "dry_run" in query:
188
+ try:
189
+ job_config.dry_run = parse_boolean(query["dry_run"])
190
+ except ValueError:
191
+ raise ValueError(
192
+ "invalid boolean in url query for dry_run: " + query["dry_run"]
193
+ )
194
+
195
+ # labels
196
+ if "labels" in query:
197
+ label_groups = GROUP_DELIMITER.split(query["labels"])
198
+ labels = {}
199
+ for label_group in label_groups:
200
+ try:
201
+ key, value = KEY_VALUE_DELIMITER.split(label_group)
202
+ except ValueError:
203
+ raise ValueError("malformed url query in labels: " + label_group)
204
+ labels[key] = value
205
+
206
+ job_config.labels = labels
207
+
208
+ # maximum_bytes_billed
209
+ if "maximum_bytes_billed" in query:
210
+ try:
211
+ job_config.maximum_bytes_billed = int(query["maximum_bytes_billed"])
212
+ except ValueError:
213
+ raise ValueError(
214
+ "invalid int in url query maximum_bytes_billed: "
215
+ + query["maximum_bytes_billed"]
216
+ )
217
+
218
+ # priority
219
+ if "priority" in query:
220
+ try:
221
+ job_config.priority = getattr(QueryPriority, query["priority"])
222
+ except AttributeError:
223
+ raise ValueError("invalid priority in url query: " + query["priority"])
224
+
225
+ # query_parameters
226
+ if "query_parameters" in query:
227
+ raise NotImplementedError("url query query_parameters not implemented")
228
+
229
+ # schema_update_options
230
+ if "schema_update_options" in query:
231
+ schema_update_options = GROUP_DELIMITER.split(query["schema_update_options"])
232
+ try:
233
+ job_config.schema_update_options = [
234
+ getattr(SchemaUpdateOption, schema_update_option)
235
+ for schema_update_option in schema_update_options
236
+ ]
237
+ except AttributeError:
238
+ raise ValueError(
239
+ "invalid schema_update_options in url query: "
240
+ + query["schema_update_options"]
241
+ )
242
+
243
+ # table_definitions
244
+ if "table_definitions" in query:
245
+ raise NotImplementedError("url query table_definitions not implemented")
246
+
247
+ # time_partitioning
248
+ if "time_partitioning" in query:
249
+ raise NotImplementedError("url query time_partitioning not implemented")
250
+
251
+ # udf_resources
252
+ if "udf_resources" in query:
253
+ raise NotImplementedError("url query udf_resources not implemented")
254
+
255
+ # use_query_cache
256
+ if "use_query_cache" in query:
257
+ try:
258
+ job_config.use_query_cache = parse_boolean(query["use_query_cache"])
259
+ except ValueError:
260
+ raise ValueError(
261
+ "invalid boolean in url query for use_query_cache: "
262
+ + query["use_query_cache"]
263
+ )
264
+
265
+ # write_disposition
266
+ if "write_disposition" in query:
267
+ try:
268
+ job_config.write_disposition = getattr(
269
+ WriteDisposition, query["write_disposition"]
270
+ )
271
+ except AttributeError:
272
+ raise ValueError(
273
+ "invalid write_disposition in url query: " + query["write_disposition"]
274
+ )
275
+
276
+ return (
277
+ project_id,
278
+ location,
279
+ dataset_id,
280
+ arraysize,
281
+ credentials_path,
282
+ credentials_base64,
283
+ job_config,
284
+ list_tables_page_size,
285
+ user_supplied_client,
286
+ )