dbt-ibm-netezza 1.0.2__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.
- dbt/__init__.py +1 -0
- dbt/adapters/__init__.py +1 -0
- dbt/adapters/netezza/__init__.py +12 -0
- dbt/adapters/netezza/__version__.py +1 -0
- dbt/adapters/netezza/column.py +23 -0
- dbt/adapters/netezza/connections.py +243 -0
- dbt/adapters/netezza/et_options_parser.py +40 -0
- dbt/adapters/netezza/impl.py +300 -0
- dbt/adapters/netezza/relation.py +86 -0
- dbt/include/__init__.py +1 -0
- dbt/include/netezza/__init__.py +2 -0
- dbt/include/netezza/dbt_project.yml +5 -0
- dbt/include/netezza/macros/adapters.sql +147 -0
- dbt/include/netezza/macros/catalog.sql +33 -0
- dbt/include/netezza/macros/grants.sql +62 -0
- dbt/include/netezza/macros/materializations/incremental_strategies.sql +13 -0
- dbt/include/netezza/macros/materializations/merge.sql +50 -0
- dbt/include/netezza/macros/materializations/seed.sql +21 -0
- dbt/include/netezza/macros/materializations/snapshot.sql +34 -0
- dbt/include/netezza/macros/schema.sql +5 -0
- dbt/include/netezza/macros/utils/array_append.sql +3 -0
- dbt/include/netezza/macros/utils/array_concat.sql +3 -0
- dbt/include/netezza/macros/utils/array_construct.sql +25 -0
- dbt/include/netezza/macros/utils/bool_or.sql +3 -0
- dbt/include/netezza/macros/utils/cast_bool_to_text.sql +3 -0
- dbt/include/netezza/macros/utils/concat.sql +3 -0
- dbt/include/netezza/macros/utils/dateadd.sql +3 -0
- dbt/include/netezza/macros/utils/datediff.sql +30 -0
- dbt/include/netezza/macros/utils/hash.sql +12 -0
- dbt/include/netezza/macros/utils/lastday.sql +9 -0
- dbt/include/netezza/macros/utils/listagg.sql +12 -0
- dbt/include/netezza/macros/utils/right.sql +8 -0
- dbt/include/netezza/macros/utils/split_part.sql +3 -0
- dbt/include/netezza/macros/utils/timestamps.sql +8 -0
- dbt/include/netezza/profile_template.yml +23 -0
- dbt_ibm_netezza-1.0.2.dist-info/LICENSE +201 -0
- dbt_ibm_netezza-1.0.2.dist-info/LICENSE copy +24 -0
- dbt_ibm_netezza-1.0.2.dist-info/METADATA +202 -0
- dbt_ibm_netezza-1.0.2.dist-info/RECORD +41 -0
- dbt_ibm_netezza-1.0.2.dist-info/WHEEL +5 -0
- dbt_ibm_netezza-1.0.2.dist-info/top_level.txt +1 -0
dbt/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
|
dbt/adapters/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from dbt.adapters.netezza.connections import NetezzaConnectionManager # noqa
|
|
2
|
+
from dbt.adapters.netezza.connections import NetezzaCredentials
|
|
3
|
+
from dbt.adapters.netezza.impl import NetezzaAdapter
|
|
4
|
+
|
|
5
|
+
from dbt.adapters.base import AdapterPlugin
|
|
6
|
+
from dbt.include import netezza
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
Plugin = AdapterPlugin(
|
|
10
|
+
adapter=NetezzaAdapter,
|
|
11
|
+
credentials=NetezzaCredentials,
|
|
12
|
+
include_path=netezza.PACKAGE_PATH)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
version = "1.5.0"
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from dbt.adapters.base.column import Column
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
@dataclass
|
|
6
|
+
class NetezzaColumn(Column):
|
|
7
|
+
TYPE_LABELS = {
|
|
8
|
+
**Column.TYPE_LABELS,
|
|
9
|
+
"STRING": "varchar(2000)",
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
# Override to ignore data type length
|
|
13
|
+
def is_string(self) -> bool:
|
|
14
|
+
return self.dtype.lower() == "text" or any(
|
|
15
|
+
self.dtype.lower().startswith(dtype)
|
|
16
|
+
for dtype in ["char", "nchar", "varchar", "nvarchar"]
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
# Override to ignore data type precision
|
|
20
|
+
def is_numeric(self) -> bool:
|
|
21
|
+
return any(
|
|
22
|
+
self.dtype.lower().startswith(dtype) for dtype in ["numeric", "decimal"]
|
|
23
|
+
)
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
from contextlib import contextmanager
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from typing import Optional, Tuple, Any
|
|
4
|
+
import time
|
|
5
|
+
import inspect
|
|
6
|
+
|
|
7
|
+
import agate
|
|
8
|
+
from dbt_common.clients import agate_helper
|
|
9
|
+
from dbt_common.exceptions import DbtRuntimeError, DbtDatabaseError
|
|
10
|
+
from dbt.adapters.contracts.connection import Credentials
|
|
11
|
+
from dbt.adapters.sql import SQLConnectionManager as connection_cls
|
|
12
|
+
from dbt.adapters.events.logging import AdapterLogger
|
|
13
|
+
from dbt_common.events.functions import fire_event
|
|
14
|
+
from dbt.adapters.events.types import ConnectionUsed, SQLQuery, SQLQueryStatus
|
|
15
|
+
from dbt.adapters.contracts.connection import Connection, AdapterResponse
|
|
16
|
+
from dbt_common.helper_types import Port
|
|
17
|
+
import nzpy
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
logger = AdapterLogger("Netezza")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class NetezzaCredentials(Credentials):
|
|
25
|
+
"""
|
|
26
|
+
Defines database specific credentials that get added to
|
|
27
|
+
profiles.yml to connect to new adapter
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
dsn: Optional[str] = None
|
|
31
|
+
username: Optional[str] = None
|
|
32
|
+
password: Optional[str] = None
|
|
33
|
+
database: Optional[str] = None
|
|
34
|
+
schema: Optional[str] = None
|
|
35
|
+
host: Optional[str] = None
|
|
36
|
+
port: Port = Port(5480)
|
|
37
|
+
retries: int = 1
|
|
38
|
+
|
|
39
|
+
_ALIASES = {"dbname": "database", "user": "username", "pass": "password"}
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def type(self):
|
|
43
|
+
"""Return name of adapter."""
|
|
44
|
+
return "netezza"
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def unique_field(self):
|
|
48
|
+
"""
|
|
49
|
+
Hashed and included in anonymous telemetry to track adapter adoption.
|
|
50
|
+
Pick a field that can uniquely identify one team/organization building with this adapter
|
|
51
|
+
"""
|
|
52
|
+
return self.host
|
|
53
|
+
|
|
54
|
+
def _connection_keys(self):
|
|
55
|
+
"""
|
|
56
|
+
List of keys to display in the `dbt debug` output.
|
|
57
|
+
"""
|
|
58
|
+
return (
|
|
59
|
+
("dsn", "username")
|
|
60
|
+
if self.dsn
|
|
61
|
+
else ("host", "port", "database", "schema", "username")
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class NetezzaConnectionManager(connection_cls):
|
|
66
|
+
TYPE = "netezza"
|
|
67
|
+
|
|
68
|
+
@contextmanager
|
|
69
|
+
def exception_handler(self, sql):
|
|
70
|
+
"""
|
|
71
|
+
Returns a context manager, that will handle exceptions raised
|
|
72
|
+
from queries, catch, log, and raise dbt exceptions it knows how to handle.
|
|
73
|
+
"""
|
|
74
|
+
try:
|
|
75
|
+
yield
|
|
76
|
+
|
|
77
|
+
except nzpy.core.ProgrammingError as e:
|
|
78
|
+
logger.error("NZ backend responded with: {}", str(e))
|
|
79
|
+
raise DbtRuntimeError(str(e)) from e
|
|
80
|
+
|
|
81
|
+
except nzpy.DatabaseError as e:
|
|
82
|
+
logger.debug("Netezza error: {}", str(e))
|
|
83
|
+
try:
|
|
84
|
+
self.rollback_if_open()
|
|
85
|
+
except nzpy.DatabaseError:
|
|
86
|
+
logger.error("Failed to release connection!")
|
|
87
|
+
|
|
88
|
+
_, error_message = e.args
|
|
89
|
+
raise DbtDatabaseError(error_message) from e
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
except Exception as e:
|
|
93
|
+
logger.debug("Error running SQL: {}", sql)
|
|
94
|
+
logger.debug("Rolling back transaction.")
|
|
95
|
+
self.rollback_if_open()
|
|
96
|
+
if isinstance(e, DbtRuntimeError):
|
|
97
|
+
# during a sql query, an internal to dbt exception was raised.
|
|
98
|
+
# this sounds a lot like a signal handler and probably has
|
|
99
|
+
# useful information, so raise it without modification.
|
|
100
|
+
raise
|
|
101
|
+
|
|
102
|
+
raise DbtRuntimeError(str(e)) from e
|
|
103
|
+
|
|
104
|
+
@classmethod
|
|
105
|
+
def open(cls, connection):
|
|
106
|
+
"""
|
|
107
|
+
Receives a connection object and a Credentials object
|
|
108
|
+
and moves it to the "open" state.
|
|
109
|
+
"""
|
|
110
|
+
if connection.state == "open":
|
|
111
|
+
logger.debug("Connection is already open, skipping open.")
|
|
112
|
+
return connection
|
|
113
|
+
|
|
114
|
+
credentials = cls.get_credentials(connection.credentials)
|
|
115
|
+
|
|
116
|
+
connection_args = {}
|
|
117
|
+
if credentials.dsn:
|
|
118
|
+
connection_args = {"DSN": credentials.dsn}
|
|
119
|
+
else:
|
|
120
|
+
connection_args = {
|
|
121
|
+
"host": credentials.host,
|
|
122
|
+
"port": credentials.port,
|
|
123
|
+
"database": credentials.database,
|
|
124
|
+
"logOptions": nzpy.LogOptions.Disabled
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
def connect():
|
|
128
|
+
handle = nzpy.connect(
|
|
129
|
+
user=credentials.username,
|
|
130
|
+
password=credentials.password,
|
|
131
|
+
**connection_args,
|
|
132
|
+
)
|
|
133
|
+
return handle
|
|
134
|
+
|
|
135
|
+
retryable_exceptions = [
|
|
136
|
+
nzpy.OperationalError,
|
|
137
|
+
]
|
|
138
|
+
|
|
139
|
+
return cls.retry_connection(
|
|
140
|
+
connection,
|
|
141
|
+
connect=connect,
|
|
142
|
+
logger=logger,
|
|
143
|
+
retry_limit=credentials.retries,
|
|
144
|
+
retryable_exceptions=retryable_exceptions,
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
def cancel(self, connection):
|
|
148
|
+
"""
|
|
149
|
+
Gets a connection object and attempts to cancel any ongoing queries.
|
|
150
|
+
"""
|
|
151
|
+
connection.handle.close()
|
|
152
|
+
|
|
153
|
+
@classmethod
|
|
154
|
+
def get_credentials(cls, credentials):
|
|
155
|
+
return credentials
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
@classmethod
|
|
159
|
+
def get_response(cls, cursor) -> AdapterResponse:
|
|
160
|
+
"""
|
|
161
|
+
Gets a cursor object and returns adapter-specific information
|
|
162
|
+
about the last executed command generally a AdapterResponse object
|
|
163
|
+
that has items such as code, rows_affected, etc. can also just be a string ex. "OK"
|
|
164
|
+
if your cursor does not offer rich metadata.
|
|
165
|
+
"""
|
|
166
|
+
return AdapterResponse("OK", rows_affected=cursor.rowcount)
|
|
167
|
+
|
|
168
|
+
# Override to prevent error when calling execute without bindings
|
|
169
|
+
def add_query(
|
|
170
|
+
self,
|
|
171
|
+
sql: str,
|
|
172
|
+
auto_begin: bool = True,
|
|
173
|
+
bindings: Optional[Any] = None,
|
|
174
|
+
abridge_sql_log: bool = False,
|
|
175
|
+
) -> Tuple[Connection, Any]:
|
|
176
|
+
connection = self.get_thread_connection()
|
|
177
|
+
if auto_begin and connection.transaction_open is False:
|
|
178
|
+
self.begin()
|
|
179
|
+
fire_event(ConnectionUsed(conn_type=self.TYPE, conn_name=connection.name))
|
|
180
|
+
|
|
181
|
+
with self.exception_handler(sql):
|
|
182
|
+
if abridge_sql_log:
|
|
183
|
+
log_sql = "{}...".format(sql[:512])
|
|
184
|
+
else:
|
|
185
|
+
log_sql = sql
|
|
186
|
+
|
|
187
|
+
fire_event(SQLQuery(conn_name=connection.name, sql=log_sql))
|
|
188
|
+
pre = time.time()
|
|
189
|
+
|
|
190
|
+
cursor = connection.handle.cursor()
|
|
191
|
+
|
|
192
|
+
# pyodbc cursor will fail if bindings are passed to execute and not needed
|
|
193
|
+
if bindings:
|
|
194
|
+
cursor.execute(sql, bindings)
|
|
195
|
+
else:
|
|
196
|
+
cursor.execute(sql)
|
|
197
|
+
|
|
198
|
+
# Get the result of the first non-empty result set (if any)
|
|
199
|
+
while cursor.description is None:
|
|
200
|
+
# if not cursor.nextset():
|
|
201
|
+
break
|
|
202
|
+
fire_event(
|
|
203
|
+
SQLQueryStatus(
|
|
204
|
+
status=str(self.get_response(cursor)),
|
|
205
|
+
elapsed=round((time.time() - pre), 2),
|
|
206
|
+
)
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
return connection, cursor
|
|
210
|
+
|
|
211
|
+
@classmethod
|
|
212
|
+
def data_type_code_to_name(cls, type_code) -> str:
|
|
213
|
+
name_map = {
|
|
214
|
+
"int": "INTEGER",
|
|
215
|
+
"str": "STRING",
|
|
216
|
+
"date": "DATE",
|
|
217
|
+
"datetime": "DATETIME",
|
|
218
|
+
"bool": "BOOLEAN",
|
|
219
|
+
"float": "FLOAT",
|
|
220
|
+
}
|
|
221
|
+
assert inspect.isclass(type_code)
|
|
222
|
+
return name_map[type_code.__name__]
|
|
223
|
+
|
|
224
|
+
# Override to support multiple queries
|
|
225
|
+
# Source: https://github.com/dbt-msft/dbt-sqlserver/blob/master/dbt/adapters/sqlserver/sql_server_connection_manager.py
|
|
226
|
+
def execute(
|
|
227
|
+
self, sql: str, auto_begin: bool = False, fetch: bool = False, limit: Optional[int] = None
|
|
228
|
+
) -> Tuple[AdapterResponse, agate.Table]:
|
|
229
|
+
sql = self._add_query_comment(sql)
|
|
230
|
+
_, cursor = self.add_query(sql, auto_begin)
|
|
231
|
+
response = self.get_response(cursor)
|
|
232
|
+
if fetch:
|
|
233
|
+
# Get the result of the first non-empty result set (if any)
|
|
234
|
+
while cursor.description is None:
|
|
235
|
+
# if not cursor.nextset():
|
|
236
|
+
break
|
|
237
|
+
table = self.get_result_from_cursor(cursor, limit)
|
|
238
|
+
else:
|
|
239
|
+
table = agate_helper.empty_table()
|
|
240
|
+
# Step through all result sets so we process all errors
|
|
241
|
+
# while cursor.nextset():
|
|
242
|
+
# pass
|
|
243
|
+
return response, table
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import yaml
|
|
3
|
+
from typing import Dict
|
|
4
|
+
|
|
5
|
+
class ETOptions:
|
|
6
|
+
def __init__(self, options: Dict):
|
|
7
|
+
self.options = options
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def et_options_constructor(loader, node):
|
|
11
|
+
"""
|
|
12
|
+
Returns a dict of values written in et_options.yaml file
|
|
13
|
+
in the client/fe project.
|
|
14
|
+
"""
|
|
15
|
+
values = loader.construct_mapping(node)
|
|
16
|
+
et_options_obj: ETOptions = ETOptions(values)
|
|
17
|
+
return et_options_obj
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def etoptions_representer(dumper, data: ETOptions):
|
|
21
|
+
return dumper.represent_mapping('!ETOptions', { k: v for k,v in data.options.items()})
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def parse_et_options_yaml(file_path):
|
|
25
|
+
if not os.path.exists(file_path):
|
|
26
|
+
return {}
|
|
27
|
+
with open(file_path, 'r') as file:
|
|
28
|
+
data = yaml.safe_load(file)
|
|
29
|
+
return data
|
|
30
|
+
|
|
31
|
+
def get_et_options_as_string(user_file_path: str):
|
|
32
|
+
yaml.SafeLoader.add_constructor('!ETOptions', et_options_constructor)
|
|
33
|
+
et_options_data = parse_et_options_yaml(user_file_path)
|
|
34
|
+
if not et_options_data:
|
|
35
|
+
return ""
|
|
36
|
+
to_be_returned = ""
|
|
37
|
+
for k,v in et_options_data[0].options.items():
|
|
38
|
+
to_be_returned += f"{k} {v}\n"
|
|
39
|
+
return to_be_returned
|
|
40
|
+
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
import pytz
|
|
4
|
+
import agate
|
|
5
|
+
from dateutil import parser
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Optional, List, Dict, Tuple, Any, Union
|
|
9
|
+
|
|
10
|
+
from dbt import deprecations
|
|
11
|
+
from dbt.adapters.base.connections import AdapterResponse
|
|
12
|
+
from dbt.adapters.base.meta import available
|
|
13
|
+
from dbt.adapters.base.impl import ConstraintSupport, _utc
|
|
14
|
+
from dbt.adapters.base.relation import BaseRelation
|
|
15
|
+
from dbt.adapters.exceptions.database import UnexpectedDbReferenceError
|
|
16
|
+
from dbt.adapters.netezza import NetezzaConnectionManager
|
|
17
|
+
from dbt.adapters.netezza.column import NetezzaColumn
|
|
18
|
+
from dbt.adapters.netezza.et_options_parser import get_et_options_as_string
|
|
19
|
+
from dbt.adapters.netezza.relation import NetezzaRelation
|
|
20
|
+
from dbt.adapters.protocol import AdapterConfig
|
|
21
|
+
from dbt.adapters.sql.impl import SQLAdapter, LIST_RELATIONS_MACRO_NAME
|
|
22
|
+
from dbt.contracts.graph.manifest import Manifest
|
|
23
|
+
from dbt_common.exceptions import CompilationError, DbtDatabaseError, MacroResultError
|
|
24
|
+
from dbt_common.utils import filter_null_values, AttrDict
|
|
25
|
+
from dbt.contracts.graph.nodes import ConstraintType
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class NetezzaConfig(AdapterConfig):
|
|
29
|
+
dist: Optional[str] = None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
FRESHNESS_MACRO_NAME = "collect_freshness" # Macro used to analyze the freshness of the data imports in tables
|
|
33
|
+
class NetezzaAdapter(SQLAdapter):
|
|
34
|
+
INT_MIN32 = -2147483648
|
|
35
|
+
INT_MAX32 = 2147483648
|
|
36
|
+
|
|
37
|
+
AdapterSpecificConfigs = NetezzaConfig
|
|
38
|
+
ConnectionManager = NetezzaConnectionManager
|
|
39
|
+
Relation = NetezzaRelation
|
|
40
|
+
Column = NetezzaColumn
|
|
41
|
+
|
|
42
|
+
CONSTRAINT_SUPPORT = {
|
|
43
|
+
ConstraintType.check: ConstraintSupport.NOT_ENFORCED,
|
|
44
|
+
ConstraintType.not_null: ConstraintSupport.ENFORCED,
|
|
45
|
+
ConstraintType.unique: ConstraintSupport.NOT_ENFORCED,
|
|
46
|
+
ConstraintType.primary_key: ConstraintSupport.NOT_ENFORCED,
|
|
47
|
+
ConstraintType.foreign_key: ConstraintSupport.NOT_ENFORCED,
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
@classmethod
|
|
51
|
+
def date_function(cls):
|
|
52
|
+
return "now()"
|
|
53
|
+
|
|
54
|
+
# Overriding methods because Netezza uppercases by default
|
|
55
|
+
# and we want to avoid quoting of columns
|
|
56
|
+
# Source: https://github.com/dbt-labs/dbt-snowflake/blob/fda11c2e822519996101d2c456a51570f4ed1c04/dbt/adapters/snowflake/impl.py#L45-L54
|
|
57
|
+
@classmethod
|
|
58
|
+
def _catalog_filter_table(
|
|
59
|
+
cls, table: agate.Table, manifest: Manifest
|
|
60
|
+
) -> agate.Table:
|
|
61
|
+
lowered = table.rename(column_names=[c.lower() for c in table.column_names])
|
|
62
|
+
return super()._catalog_filter_table(lowered, manifest)
|
|
63
|
+
|
|
64
|
+
# Source: https://github.com/dbt-labs/dbt-snowflake/blob/fda11c2e822519996101d2c456a51570f4ed1c04/dbt/adapters/snowflake/impl.py#L56-L69
|
|
65
|
+
def _make_match_kwargs(self, database: str, schema: str, identifier: str):
|
|
66
|
+
quoting = self.config.quoting
|
|
67
|
+
if identifier is not None and quoting["identifier"] is False:
|
|
68
|
+
identifier = identifier.upper()
|
|
69
|
+
|
|
70
|
+
if schema is not None and quoting["schema"] is False:
|
|
71
|
+
schema = schema.upper()
|
|
72
|
+
|
|
73
|
+
if database is not None and quoting["database"] is False:
|
|
74
|
+
database = database.upper()
|
|
75
|
+
|
|
76
|
+
return filter_null_values(
|
|
77
|
+
{"identifier": identifier, "schema": schema, "database": database}
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
# Source: https://github.com/dbt-labs/dbt-snowflake/blob/fda11c2e822519996101d2c456a51570f4ed1c04/dbt/adapters/snowflake/impl.py#L128-L166
|
|
81
|
+
def list_relations_without_caching(
|
|
82
|
+
self, schema_relation: BaseRelation
|
|
83
|
+
) -> List[BaseRelation]:
|
|
84
|
+
kwargs = {"schema_relation": schema_relation}
|
|
85
|
+
try:
|
|
86
|
+
results = self.execute_macro(LIST_RELATIONS_MACRO_NAME, kwargs=kwargs)
|
|
87
|
+
except DbtDatabaseError as exc:
|
|
88
|
+
# if the schema doesn't exist, we just want to return.
|
|
89
|
+
# Alternatively, we could query the list of schemas before we start
|
|
90
|
+
# and skip listing the missing ones, which sounds expensive.
|
|
91
|
+
if "Object does not exist" in str(exc):
|
|
92
|
+
return []
|
|
93
|
+
raise
|
|
94
|
+
|
|
95
|
+
relations: List[BaseRelation] = []
|
|
96
|
+
quote_policy = {"database": True, "schema": True, "identifier": True}
|
|
97
|
+
|
|
98
|
+
columns = ["DATABASE", "SCHEMA", "NAME", "TYPE"]
|
|
99
|
+
for _database, _schema, _identifier, _type in results.select(columns):
|
|
100
|
+
try:
|
|
101
|
+
_type = self.Relation.get_relation_type(_type.lower())
|
|
102
|
+
except ValueError:
|
|
103
|
+
_type = self.Relation.External
|
|
104
|
+
relations.append(
|
|
105
|
+
self.Relation.create(
|
|
106
|
+
database=_database,
|
|
107
|
+
schema=_schema,
|
|
108
|
+
identifier=_identifier,
|
|
109
|
+
quote_policy=quote_policy,
|
|
110
|
+
type=_type,
|
|
111
|
+
)
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
return relations
|
|
115
|
+
|
|
116
|
+
# Override with Redshift implementation because Netezza does not support `text`
|
|
117
|
+
# Source: https://github.com/dbt-labs/dbt-redshift/blob/64f6f7ba4f8fbe11d9c547f7c07faeb9b14deb83/dbt/adapters/redshift/impl.py#L54-L61
|
|
118
|
+
@classmethod
|
|
119
|
+
def convert_text_type(cls, agate_table, col_idx):
|
|
120
|
+
column = agate_table.columns[col_idx]
|
|
121
|
+
# `lens` must be a list, so this can't be a generator expression,
|
|
122
|
+
# because max() raises an exception if its argument has no members.
|
|
123
|
+
# source: https://github.com/fishtown-analytics/dbt/pull/2255/files#diff-39545f1198b754f67de59957630a527b6d1df026aff22cc90de923f5653d5ad8
|
|
124
|
+
lens = [len(d.encode("utf-8")) for d in column.values_without_nulls()]
|
|
125
|
+
max_len = max(lens) if lens else 64
|
|
126
|
+
return f"varchar({max_len})"
|
|
127
|
+
|
|
128
|
+
# Override to remove `without time zone` because Netezza does not support this
|
|
129
|
+
@classmethod
|
|
130
|
+
def convert_datetime_type(cls, agate_table: agate.Table, col_idx: int) -> str:
|
|
131
|
+
return "timestamp"
|
|
132
|
+
|
|
133
|
+
# Override to check if view exists before dropping because Netezza does not support
|
|
134
|
+
# `drop view if exists`
|
|
135
|
+
def drop_relation(self, relation):
|
|
136
|
+
if relation.type == "view":
|
|
137
|
+
identifier = relation.identifier
|
|
138
|
+
relations = self.list_relations_without_caching(relation)
|
|
139
|
+
no_relation_exists = (
|
|
140
|
+
next(
|
|
141
|
+
rel
|
|
142
|
+
for rel in relations
|
|
143
|
+
if rel.type == "view" and rel.identifier == identifier
|
|
144
|
+
)
|
|
145
|
+
is None
|
|
146
|
+
)
|
|
147
|
+
if no_relation_exists:
|
|
148
|
+
return
|
|
149
|
+
|
|
150
|
+
super().drop_relation(relation)
|
|
151
|
+
|
|
152
|
+
# Override to skip the cursor.commit() which causes a ODBC HY010
|
|
153
|
+
# "function sequence error"
|
|
154
|
+
# Source: https://github.com/dbt-labs/dbt-core/blob/c270a77552ae9fc66fdfab359d65a8db1307c3f3/core/dbt/adapters/sql/impl.py#L223-L243
|
|
155
|
+
def run_sql_for_tests(self, sql, fetch, conn):
|
|
156
|
+
cursor = conn.handle.cursor()
|
|
157
|
+
try:
|
|
158
|
+
cursor.execute(sql)
|
|
159
|
+
if hasattr(conn.handle, "commit"):
|
|
160
|
+
# Skip cursor.commit()
|
|
161
|
+
pass
|
|
162
|
+
if fetch == "one":
|
|
163
|
+
return cursor.fetchone()
|
|
164
|
+
elif fetch == "all":
|
|
165
|
+
return cursor.fetchall()
|
|
166
|
+
else:
|
|
167
|
+
return
|
|
168
|
+
except BaseException as e:
|
|
169
|
+
if conn.handle and not getattr(conn.handle, "closed", True):
|
|
170
|
+
conn.handle.rollback()
|
|
171
|
+
print(sql)
|
|
172
|
+
print(e)
|
|
173
|
+
raise
|
|
174
|
+
finally:
|
|
175
|
+
conn.transaction_open = False
|
|
176
|
+
|
|
177
|
+
@available
|
|
178
|
+
def get_seed_file_path(self, model) -> str:
|
|
179
|
+
return os.path.join(model["root_path"], model["original_file_path"])
|
|
180
|
+
|
|
181
|
+
@available
|
|
182
|
+
def verify_database(self, database):
|
|
183
|
+
if database.startswith('"'):
|
|
184
|
+
database = database.strip('"')
|
|
185
|
+
expected = self.config.credentials.database
|
|
186
|
+
if database.lower() != expected.lower():
|
|
187
|
+
raise UnexpectedDbReferenceError(self.type(), database, expected)
|
|
188
|
+
# return an empty string on success so macros can call this
|
|
189
|
+
return ""
|
|
190
|
+
|
|
191
|
+
@available
|
|
192
|
+
def rename_relation(self, from_relation, to_relation):
|
|
193
|
+
self.cache_renamed(from_relation, to_relation)
|
|
194
|
+
|
|
195
|
+
kwargs = {"from_relation": from_relation, "to_relation": to_relation}
|
|
196
|
+
self.execute_macro('rename_relation', kwargs=kwargs)
|
|
197
|
+
|
|
198
|
+
@available
|
|
199
|
+
def get_et_options(self, model) -> str:
|
|
200
|
+
return get_et_options_as_string(os.path.join(model["root_path"], "et_options.yml"))
|
|
201
|
+
|
|
202
|
+
# Override to change the default value of quote_columns to False
|
|
203
|
+
# Source: https://github.com/dbt-labs/dbt-core/blob/7f8d9a7af976f640e376900773a0d793acf3a3ce/core/dbt/adapters/base/impl.py#L812-L828
|
|
204
|
+
@available
|
|
205
|
+
def quote_seed_column(self, column: str, quote_config: Optional[bool]) -> str:
|
|
206
|
+
# Change default value to False
|
|
207
|
+
quote_columns: bool = False
|
|
208
|
+
if isinstance(quote_config, bool):
|
|
209
|
+
quote_columns = quote_config
|
|
210
|
+
elif quote_config is None:
|
|
211
|
+
pass
|
|
212
|
+
else:
|
|
213
|
+
raise CompilationError(
|
|
214
|
+
f'The seed configuration value of "quote_columns" has an '
|
|
215
|
+
f"invalid type {type(quote_config)}"
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
if quote_columns:
|
|
219
|
+
return self.quote(column)
|
|
220
|
+
else:
|
|
221
|
+
return column
|
|
222
|
+
|
|
223
|
+
# Override to search for uppercase keys in grants_table because Netezza always returns
|
|
224
|
+
# uppercase keys and agate.Table.__get_item__ is case-sensitive
|
|
225
|
+
def standardize_grants_dict(self, grants_table: agate.Table) -> dict:
|
|
226
|
+
grants_dict: Dict[str, List[str]] = {}
|
|
227
|
+
for row in grants_table:
|
|
228
|
+
grantee = row["GRANTEE"]
|
|
229
|
+
privilege = row["PRIVILEGE_TYPE"]
|
|
230
|
+
if privilege in grants_dict.keys():
|
|
231
|
+
grants_dict[privilege].append(grantee)
|
|
232
|
+
else:
|
|
233
|
+
grants_dict.update({privilege: [grantee]})
|
|
234
|
+
return grants_dict
|
|
235
|
+
|
|
236
|
+
def valid_incremental_strategies(self):
|
|
237
|
+
"""The set of standard builtin strategies which this adapter supports out-of-the-box.
|
|
238
|
+
Not used to validate custom strategies defined by end users.
|
|
239
|
+
"""
|
|
240
|
+
return ["merge", "delete+insert"]
|
|
241
|
+
|
|
242
|
+
# For checking the freshness , converting the str type object returned from netezza relation to datetime
|
|
243
|
+
def calculate_freshness(
|
|
244
|
+
self,
|
|
245
|
+
source: BaseRelation,
|
|
246
|
+
loaded_at_field: str,
|
|
247
|
+
filter: Optional[str],
|
|
248
|
+
manifest: Optional[Manifest] = None,
|
|
249
|
+
) -> Tuple[Optional[AdapterResponse], Dict[str, Any]]:
|
|
250
|
+
"""Calculate the freshness of sources in dbt, and return it"""
|
|
251
|
+
kwargs: Dict[str, Any] = {
|
|
252
|
+
"source": source,
|
|
253
|
+
"loaded_at_field": loaded_at_field,
|
|
254
|
+
"filter": filter,
|
|
255
|
+
}
|
|
256
|
+
# run the macro
|
|
257
|
+
# in older versions of dbt-core, the 'collect_freshness' macro returned the table of results directly
|
|
258
|
+
# starting in v1.5, by default, we return both the table and the adapter response (metadata about the query)
|
|
259
|
+
result: Union[
|
|
260
|
+
AttrDict, # current: contains AdapterResponse + agate.Table
|
|
261
|
+
agate.Table, # previous: just table
|
|
262
|
+
]
|
|
263
|
+
result = self.execute_macro(FRESHNESS_MACRO_NAME, kwargs=kwargs, manifest=manifest)
|
|
264
|
+
if isinstance(result, agate.Table):
|
|
265
|
+
deprecations.warn("collect-freshness-return-signature")
|
|
266
|
+
adapter_response = None
|
|
267
|
+
table = result
|
|
268
|
+
else:
|
|
269
|
+
adapter_response, table = result.response, result.table # type: ignore[attr-defined]
|
|
270
|
+
# now we have a 1-row table of the maximum `loaded_at_field` value and
|
|
271
|
+
# the current time according to the db.
|
|
272
|
+
if len(table) != 1 or len(table[0]) != 2:
|
|
273
|
+
raise MacroResultError(FRESHNESS_MACRO_NAME, table)
|
|
274
|
+
if table[0][0] is None:
|
|
275
|
+
# no records in the table, so really the max_loaded_at was
|
|
276
|
+
# infinitely long ago. Just call it 0:00 January 1 year UTC
|
|
277
|
+
max_loaded_at = datetime(1, 1, 1, 0, 0, 0, tzinfo=pytz.UTC)
|
|
278
|
+
else:
|
|
279
|
+
max_loaded_at = _utc(parser.parse(table[0][0]), source, loaded_at_field)
|
|
280
|
+
snapshotted_at = _utc(parser.parse(table[0][1]), source, loaded_at_field)
|
|
281
|
+
age = (snapshotted_at - max_loaded_at).total_seconds()
|
|
282
|
+
freshness = {
|
|
283
|
+
"max_loaded_at": max_loaded_at,
|
|
284
|
+
"snapshotted_at": snapshotted_at,
|
|
285
|
+
"age": age,
|
|
286
|
+
}
|
|
287
|
+
return adapter_response, freshness
|
|
288
|
+
|
|
289
|
+
@classmethod
|
|
290
|
+
def convert_number_type(cls, agate_table: agate.Table, col_idx: int) -> str:
|
|
291
|
+
# TODO CT-211
|
|
292
|
+
decimals = agate_table.aggregate(agate.MaxPrecision(col_idx)) # type: ignore[attr-defined]
|
|
293
|
+
if decimals :
|
|
294
|
+
return "float8"
|
|
295
|
+
else :
|
|
296
|
+
clm = max([row[col_idx] for row in agate_table.rows])
|
|
297
|
+
if clm >= cls.INT_MIN32 and clm <= cls.INT_MAX32:
|
|
298
|
+
return "integer"
|
|
299
|
+
elif clm > cls.INT_MAX32:
|
|
300
|
+
return "bigint"
|