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,104 @@
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
+ SQLAlchemy dialect for Google BigQuery
21
+ """
22
+
23
+ import warnings
24
+
25
+ from .version import __version__
26
+
27
+ from .base import BigQueryDialect, dialect
28
+ from ._types import (
29
+ ARRAY,
30
+ BIGNUMERIC,
31
+ BOOL,
32
+ BOOLEAN,
33
+ BYTES,
34
+ DATE,
35
+ DATETIME,
36
+ FLOAT,
37
+ FLOAT64,
38
+ INT64,
39
+ INTEGER,
40
+ NUMERIC,
41
+ RECORD,
42
+ STRING,
43
+ STRUCT,
44
+ TIME,
45
+ TIMESTAMP,
46
+ )
47
+
48
+ from . import _versions_helpers
49
+
50
+ sys_major, sys_minor, sys_micro = _versions_helpers.extract_runtime_version()
51
+ if sys_major == 3 and sys_minor in (7, 8):
52
+ warnings.warn(
53
+ "The python-bigquery library will stop supporting Python 3.7 "
54
+ "and Python 3.8 in a future major release expected in Q4 2024. "
55
+ f"Your Python version is {sys_major}.{sys_minor}.{sys_micro}. We "
56
+ "recommend that you update soon to ensure ongoing support. For "
57
+ "more details, see: [Google Cloud Client Libraries Supported Python Versions policy](https://cloud.google.com/python/docs/supported-python-versions)",
58
+ PendingDeprecationWarning,
59
+ )
60
+
61
+
62
+ __all__ = [
63
+ "__version__",
64
+ "dialect",
65
+ "ARRAY",
66
+ "BIGNUMERIC",
67
+ "BigQueryDialect",
68
+ "BOOL",
69
+ "BOOLEAN",
70
+ "BYTES",
71
+ "DATE",
72
+ "DATETIME",
73
+ "FLOAT",
74
+ "FLOAT64",
75
+ "INT64",
76
+ "INTEGER",
77
+ "NUMERIC",
78
+ "RECORD",
79
+ "STRING",
80
+ "STRUCT",
81
+ "TIME",
82
+ "TIMESTAMP",
83
+ ]
84
+
85
+ try:
86
+ from .geography import GEOGRAPHY, WKB, WKT # noqa
87
+ except ImportError: # pragma: NO COVER
88
+ pass
89
+ else:
90
+ __all__.extend(["GEOGRAPHY", "WKB", "WKT"])
91
+
92
+ try:
93
+ import pybigquery # noqa
94
+ except ImportError:
95
+ pass
96
+ else: # pragma: NO COVER
97
+ import warnings
98
+
99
+ warnings.warn(
100
+ "Obsolete pybigquery is installed, which is likely to\n"
101
+ "interfere with sqlalchemy_bigquery.\n"
102
+ "pybigquery should be uninstalled.",
103
+ stacklevel=2,
104
+ )
@@ -0,0 +1,122 @@
1
+ # Copyright 2021 The sqlalchemy-bigquery Authors
2
+ #
3
+ # Use of this source code is governed by an MIT-style
4
+ # license that can be found in the LICENSE file or at
5
+ # https://opensource.org/licenses/MIT.
6
+
7
+ import functools
8
+ import re
9
+ from typing import Optional
10
+
11
+ from google.api_core import client_info
12
+ import google.auth
13
+ from google.cloud import bigquery
14
+ from google.oauth2 import service_account
15
+ import sqlalchemy
16
+ import base64
17
+ import json
18
+
19
+
20
+ USER_AGENT_TEMPLATE = "sqlalchemy/{}"
21
+ SCOPES = (
22
+ "https://www.googleapis.com/auth/bigquery",
23
+ "https://www.googleapis.com/auth/cloud-platform",
24
+ "https://www.googleapis.com/auth/drive",
25
+ )
26
+
27
+
28
+ def google_client_info(
29
+ user_agent: Optional[str] = None,
30
+ ) -> google.api_core.client_info.ClientInfo:
31
+ """
32
+ Return a client_info object, with an optional user agent
33
+ string. If user_agent is None, use a default value.
34
+ """
35
+
36
+ if user_agent is None:
37
+ user_agent = USER_AGENT_TEMPLATE.format(sqlalchemy.__version__)
38
+ return client_info.ClientInfo(user_agent=user_agent)
39
+
40
+
41
+ def create_bigquery_client(
42
+ credentials_info: Optional[dict] = None,
43
+ credentials_path: Optional[str] = None,
44
+ credentials_base64: Optional[str] = None,
45
+ default_query_job_config: Optional[google.cloud.bigquery.job.QueryJobConfig] = None,
46
+ location: Optional[str] = None,
47
+ project_id: Optional[str] = None,
48
+ user_agent: Optional[google.api_core.client_info.ClientInfo] = None,
49
+ ) -> google.cloud.bigquery.Client:
50
+ """Construct a BigQuery client object.
51
+
52
+ Args:
53
+ credentials_info Optional[dict]:
54
+ credentials_path Optional[str]:
55
+ credentials_base64 Optional[str]:
56
+ default_query_job_config (Optional[google.cloud.bigquery.job.QueryJobConfig]):
57
+ Default ``QueryJobConfig``.
58
+ Will be merged into job configs passed into the ``query`` method.
59
+ location (Optional[str]):
60
+ Default location for jobs / datasets / tables.
61
+ project_id (Optional[str]):
62
+ Project ID for the project which the client acts on behalf of.
63
+ user_agent (Optional[google.api_core.client_info.ClientInfo]):
64
+ The client info used to send a user-agent string along with API
65
+ requests. If ``None``, then default info will be used. Generally,
66
+ you only need to set this if you're developing your own library
67
+ or partner tool.
68
+ """
69
+
70
+ default_project = None
71
+
72
+ if credentials_base64:
73
+ credentials_info = json.loads(base64.b64decode(credentials_base64))
74
+
75
+ if credentials_path:
76
+ credentials = service_account.Credentials.from_service_account_file(
77
+ credentials_path
78
+ )
79
+ credentials = credentials.with_scopes(SCOPES)
80
+ default_project = credentials.project_id
81
+ elif credentials_info:
82
+ credentials = service_account.Credentials.from_service_account_info(
83
+ credentials_info
84
+ )
85
+ credentials = credentials.with_scopes(SCOPES)
86
+ default_project = credentials.project_id
87
+ else:
88
+ credentials, default_project = google.auth.default(scopes=SCOPES)
89
+
90
+ if project_id is None:
91
+ project_id = default_project
92
+
93
+ client_info = google_client_info(user_agent=user_agent)
94
+
95
+ return bigquery.Client(
96
+ client_info=client_info,
97
+ project=project_id,
98
+ credentials=credentials,
99
+ location=location,
100
+ default_query_job_config=default_query_job_config,
101
+ )
102
+
103
+
104
+ def substitute_re_method(r, flags=0, repl=None):
105
+ if repl is None:
106
+ return lambda f: substitute_re_method(r, flags, f)
107
+
108
+ r = re.compile(r, flags)
109
+
110
+ @functools.wraps(repl)
111
+ def sub(self, s, *args, **kw):
112
+ def repl_(m):
113
+ return repl(self, m, *args, **kw)
114
+
115
+ return r.sub(repl_, s)
116
+
117
+ return sub
118
+
119
+
120
+ def substitute_string_re_method(r, *, repl, flags=0):
121
+ r = re.compile(r, flags)
122
+ return lambda self, s: r.sub(repl, s)
@@ -0,0 +1,128 @@
1
+ # Copyright (c) 2021 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 sqlalchemy.sql.default_comparator
21
+ import sqlalchemy.sql.sqltypes
22
+ import sqlalchemy.types
23
+
24
+ from . import base
25
+
26
+ import sqlalchemy.sql.coercions
27
+ import sqlalchemy.sql.roles
28
+
29
+
30
+ def _get_subtype_col_spec(type_):
31
+ global _get_subtype_col_spec
32
+
33
+ type_compiler = base.dialect.type_compiler(base.dialect())
34
+ _get_subtype_col_spec = type_compiler.process
35
+ return _get_subtype_col_spec(type_)
36
+
37
+
38
+ class STRUCT(sqlalchemy.sql.sqltypes.Indexable, sqlalchemy.types.UserDefinedType):
39
+ """
40
+ A type for BigQuery STRUCT/RECORD data
41
+
42
+ See https://googleapis.dev/python/sqlalchemy-bigquery/latest/struct.html
43
+ """
44
+
45
+ # See https://docs.sqlalchemy.org/en/14/core/custom_types.html#creating-new-types
46
+
47
+ def __init__(
48
+ self,
49
+ *fields,
50
+ **kwfields,
51
+ ):
52
+ # Note that because:
53
+ # https://docs.python.org/3/whatsnew/3.6.html#pep-468-preserving-keyword-argument-order
54
+ # We know that `kwfields` preserves order.
55
+ self._STRUCT_fields = tuple(
56
+ (
57
+ name,
58
+ type_ if isinstance(type_, sqlalchemy.types.TypeEngine) else type_(),
59
+ )
60
+ for (name, type_) in (fields + tuple(kwfields.items()))
61
+ )
62
+
63
+ self._STRUCT_byname = {
64
+ name.lower(): type_ for (name, type_) in self._STRUCT_fields
65
+ }
66
+
67
+ def __repr__(self):
68
+ fields = ", ".join(
69
+ f"{name}={repr(type_)}" for name, type_ in self._STRUCT_fields
70
+ )
71
+ return f"STRUCT({fields})"
72
+
73
+ def get_col_spec(self, **kw):
74
+ fields = ", ".join(
75
+ f"{name} {_get_subtype_col_spec(type_)}"
76
+ for name, type_ in self._STRUCT_fields
77
+ )
78
+ return f"STRUCT<{fields}>"
79
+
80
+ def bind_processor(self, dialect):
81
+ return dict
82
+
83
+ class Comparator(sqlalchemy.sql.sqltypes.Indexable.Comparator):
84
+ def _setup_getitem(self, name):
85
+ if not isinstance(name, str):
86
+ raise TypeError(
87
+ f"STRUCT fields can only be accessed with strings field names,"
88
+ f" not {repr(name)}."
89
+ )
90
+ subtype = self.expr.type._STRUCT_byname.get(name.lower())
91
+ if subtype is None:
92
+ raise KeyError(name)
93
+ operator = struct_getitem_op
94
+ index = _field_index(self, name, operator)
95
+ return operator, index, subtype
96
+
97
+ def __getattr__(self, name):
98
+ if name.lower() in self.expr.type._STRUCT_byname:
99
+ return self[name]
100
+ else:
101
+ raise AttributeError(name)
102
+
103
+ comparator_factory = Comparator
104
+
105
+
106
+ def _field_index(self, name, operator):
107
+ return sqlalchemy.sql.coercions.expect(
108
+ sqlalchemy.sql.roles.BinaryElementRole,
109
+ name,
110
+ expr=self.expr,
111
+ operator=operator,
112
+ bindparam_type=sqlalchemy.types.String(),
113
+ )
114
+
115
+
116
+ def struct_getitem_op(a, b):
117
+ raise NotImplementedError()
118
+
119
+
120
+ sqlalchemy.sql.default_comparator.operator_lookup[
121
+ struct_getitem_op.__name__
122
+ ] = sqlalchemy.sql.default_comparator.operator_lookup["json_getitem_op"]
123
+
124
+
125
+ class SQLCompiler:
126
+ def visit_struct_getitem_op_binary(self, binary, operator_, **kw):
127
+ left = self.process(binary.left, **kw)
128
+ return f"{left}.{binary.right.value}"
@@ -0,0 +1,141 @@
1
+ # Copyright (c) 2021 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 sqlalchemy.types
21
+ import sqlalchemy.util
22
+
23
+ from google.cloud.bigquery.schema import SchemaField
24
+
25
+ try:
26
+ from .geography import GEOGRAPHY
27
+ except ImportError: # pragma: NO COVER
28
+ pass
29
+
30
+ from ._struct import STRUCT
31
+
32
+ _type_map = {
33
+ "ARRAY": sqlalchemy.types.ARRAY,
34
+ "BIGNUMERIC": sqlalchemy.types.Numeric,
35
+ "BOOLEAN": sqlalchemy.types.Boolean,
36
+ "BOOL": sqlalchemy.types.Boolean,
37
+ "BYTES": sqlalchemy.types.BINARY,
38
+ "DATETIME": sqlalchemy.types.DATETIME,
39
+ "DATE": sqlalchemy.types.DATE,
40
+ "FLOAT64": sqlalchemy.types.Float,
41
+ "FLOAT": sqlalchemy.types.Float,
42
+ "INT64": sqlalchemy.types.Integer,
43
+ "INTEGER": sqlalchemy.types.Integer,
44
+ "NUMERIC": sqlalchemy.types.Numeric,
45
+ "RECORD": STRUCT,
46
+ "STRING": sqlalchemy.types.String,
47
+ "STRUCT": STRUCT,
48
+ "TIMESTAMP": sqlalchemy.types.TIMESTAMP,
49
+ "TIME": sqlalchemy.types.TIME,
50
+ }
51
+
52
+ # By convention, dialect-provided types are spelled with all upper case.
53
+ ARRAY = _type_map["ARRAY"]
54
+ BIGNUMERIC = _type_map["NUMERIC"]
55
+ BOOLEAN = _type_map["BOOLEAN"]
56
+ BOOL = _type_map["BOOL"]
57
+ BYTES = _type_map["BYTES"]
58
+ DATETIME = _type_map["DATETIME"]
59
+ DATE = _type_map["DATE"]
60
+ FLOAT64 = _type_map["FLOAT64"]
61
+ FLOAT = _type_map["FLOAT"]
62
+ INT64 = _type_map["INT64"]
63
+ INTEGER = _type_map["INTEGER"]
64
+ NUMERIC = _type_map["NUMERIC"]
65
+ RECORD = _type_map["RECORD"]
66
+ STRING = _type_map["STRING"]
67
+ TIMESTAMP = _type_map["TIMESTAMP"]
68
+ TIME = _type_map["TIME"]
69
+
70
+ try:
71
+ _type_map["GEOGRAPHY"] = GEOGRAPHY
72
+ except NameError: # pragma: NO COVER
73
+ pass
74
+
75
+ STRUCT_FIELD_TYPES = "RECORD", "STRUCT"
76
+
77
+
78
+ def _get_transitive_schema_fields(fields):
79
+ """
80
+ Recurse into record type and return all the nested field names.
81
+ As contributed by @sumedhsakdeo on issue #17
82
+ """
83
+ results = []
84
+ for field in fields:
85
+ results += [field]
86
+ if field.field_type in STRUCT_FIELD_TYPES:
87
+ sub_fields = [
88
+ SchemaField.from_api_repr(
89
+ dict(f.to_api_repr(), name=f"{field.name}.{f.name}")
90
+ )
91
+ for f in field.fields
92
+ ]
93
+ results += _get_transitive_schema_fields(sub_fields)
94
+ return results
95
+
96
+
97
+ def _get_sqla_column_type(field):
98
+ try:
99
+ coltype = _type_map[field.field_type]
100
+ except KeyError:
101
+ sqlalchemy.util.warn(
102
+ "Did not recognize type '%s' of column '%s'"
103
+ % (field.field_type, field.name)
104
+ )
105
+ coltype = sqlalchemy.types.NullType
106
+ else:
107
+ if field.field_type.endswith("NUMERIC"):
108
+ coltype = coltype(precision=field.precision, scale=field.scale)
109
+ elif field.field_type == "STRING" or field.field_type == "BYTES":
110
+ coltype = coltype(field.max_length)
111
+ elif field.field_type == "RECORD" or field.field_type == "STRUCT":
112
+ coltype = STRUCT(
113
+ *(
114
+ (subfield.name, _get_sqla_column_type(subfield))
115
+ for subfield in field.fields
116
+ )
117
+ )
118
+ else:
119
+ coltype = coltype()
120
+
121
+ if field.mode == "REPEATED":
122
+ coltype = ARRAY(coltype)
123
+
124
+ return coltype
125
+
126
+
127
+ def get_columns(bq_schema):
128
+ fields = _get_transitive_schema_fields(bq_schema)
129
+ return [
130
+ {
131
+ "name": field.name,
132
+ "type": _get_sqla_column_type(field),
133
+ "nullable": field.mode == "NULLABLE" or field.mode == "REPEATED",
134
+ "comment": field.description,
135
+ "default": None,
136
+ "precision": field.precision,
137
+ "scale": field.scale,
138
+ "max_length": field.max_length,
139
+ }
140
+ for field in fields
141
+ ]
@@ -0,0 +1,32 @@
1
+ # Copyright 2024 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Shared helper functions for verifying versions of installed modules."""
16
+
17
+
18
+ import sys
19
+ from typing import Tuple
20
+
21
+
22
+ def extract_runtime_version() -> Tuple[int, int, int]:
23
+ # Retrieve the version information
24
+ version_info = sys.version_info
25
+
26
+ # Extract the major, minor, and micro components
27
+ major = version_info.major
28
+ minor = version_info.minor
29
+ micro = version_info.micro
30
+
31
+ # Display the version number in a clear format
32
+ return major, minor, micro