Skip to content

Commit b2abae9

Browse files
committed
lots of fixes
1 parent 0ca9562 commit b2abae9

File tree

23 files changed

+450
-126
lines changed

23 files changed

+450
-126
lines changed

dbt/adapters/iris/column.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from dataclasses import dataclass
22
from typing import TypeVar, Optional, ClassVar, Dict, Any
3-
3+
from dbt_common.exceptions import DbtRuntimeError
44
from dbt.adapters.base.column import Column
55

66
Self = TypeVar("Self", bound="IRISColumn")
@@ -9,10 +9,8 @@
99
@dataclass
1010
class IRISColumn(Column):
1111
TYPE_LABELS: ClassVar[Dict[str, str]] = {
12-
"STRING": "VARCHAR('')",
13-
"TIMESTAMP": "TIMESTAMP",
14-
"FLOAT": "FLOAT",
15-
"INTEGER": "INTEGER",
12+
"STRING": "VARCHAR(65535)",
13+
"FLOAT": "DOUBLE",
1614
"BOOLEAN": "BIT",
1715
}
1816

@@ -30,3 +28,17 @@ def quoted(self) -> str:
3028

3129
def __repr__(self) -> str:
3230
return "<IRISColumn {} ({})>".format(self.name, self.data_type)
31+
32+
# def string_size(self) -> int:
33+
# if not self.is_string():
34+
# raise DbtRuntimeError("Called string_size() on non-string field!")
35+
36+
# if self.dtype == "text" or not self.char_size:
37+
# return 65535
38+
# else:
39+
# return int(self.char_size)
40+
41+
# @property
42+
# def data_type(self):
43+
# print("!!!! data_type", self.dtype, self.char_size)
44+
# return super().data_type

dbt/adapters/iris/connections.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import time
2-
from typing import Optional, Tuple, Any, Type
2+
from typing import Optional, Tuple, Any, Type, Union
33
from contextlib import contextmanager
44
from dataclasses import dataclass
55
from dbt.exceptions import DbtRuntimeError
@@ -11,6 +11,7 @@
1111
from dbt_common.events.functions import fire_event
1212
from dbt.adapters.events.types import ConnectionUsed, SQLQuery, SQLQueryStatus
1313
import intersystems_iris.dbapi._DBAPI as dbapi
14+
from intersystems_iris.dbapi._SQLType import SQLType
1415
from dbt_common.helper_types import Port
1516
from mashumaro.jsonschema.annotations import Maximum, Minimum
1617
from typing_extensions import Annotated
@@ -183,3 +184,9 @@ def add_query(
183184
)
184185

185186
return connection, cursor
187+
188+
@classmethod
189+
def data_type_code_to_name(cls, type_code: Union[int, str]) -> str:
190+
if isinstance(type_code, int):
191+
return SQLType(type_code).name
192+
return f"unknown type_code {type_code}"

dbt/adapters/iris/impl.py

Lines changed: 40 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,11 @@ def date_function(cls):
3636

3737
@classmethod
3838
def convert_text_type(cls, agate_table, col_idx):
39+
min_length = 65535
3940
column = agate_table.columns[col_idx]
4041
lengths = [len(d.encode("utf-8")) for d in column.values_without_nulls()]
41-
max_len = max(lengths) if lengths else 64
42-
length = max_len if max_len > 16 else 16
42+
max_len = max(lengths) if lengths else min_length
43+
length = max_len if max_len > min_length else min_length
4344
return "varchar({})".format(length)
4445

4546
@classmethod
@@ -55,7 +56,9 @@ def convert_number_type(cls, agate_table, col_idx):
5556
def convert_datetime_type(cls, agate_table: agate.Table, col_idx: int) -> str:
5657
return "datetime"
5758

58-
def timestamp_add_sql(self, add_to: str, number: int = 1, interval: str = "hour") -> str:
59+
def timestamp_add_sql(
60+
self, add_to: str, number: int = 1, interval: str = "hour"
61+
) -> str:
5962
return f"dateadd('{interval}', {number}, {add_to})"
6063

6164
def create_schema(self, schema_relation: BaseRelation) -> None:
@@ -72,7 +75,9 @@ def drop_schema(self, schema_relation) -> None:
7275
raise
7376

7477
def check_schema_exists(self, database, schema):
75-
results = self.execute_macro(LIST_SCHEMAS_MACRO_NAME, kwargs={"database": database})
78+
results = self.execute_macro(
79+
LIST_SCHEMAS_MACRO_NAME, kwargs={"database": database}
80+
)
7681

7782
exists = True if schema in [row[0] for row in results] else False
7883
return exists
@@ -140,12 +145,16 @@ def get_missing_columns(
140145
col.name.lower(): col for col in self.get_columns_in_relation(from_relation)
141146
}
142147

143-
to_columns = {col.name.lower(): col for col in self.get_columns_in_relation(to_relation)}
148+
to_columns = {
149+
col.name.lower(): col for col in self.get_columns_in_relation(to_relation)
150+
}
144151

145152
missing_columns = set(from_columns.keys()) - set(to_columns.keys())
146153

147154
return [
148-
col for (col_name, col) in from_columns.items() if col_name.lower() in missing_columns
155+
col
156+
for (col_name, col) in from_columns.items()
157+
if col_name.lower() in missing_columns
149158
]
150159

151160
def submit_python_job(self, parsed_model: dict, compiled_code: str):
@@ -166,9 +175,32 @@ def submit_python_job(self, parsed_model: dict, compiled_code: str):
166175
"""
167176

168177
response, _ = self.execute(create_procedure, auto_begin=False, fetch=False)
169-
response, _ = self.execute(f"SELECT {proc_name}()", auto_begin=False, fetch=True)
170-
self.execute(f"drop procedure if exists {proc_name}", auto_begin=False, fetch=False)
178+
response, _ = self.execute(
179+
f"SELECT {proc_name}()", auto_begin=False, fetch=True
180+
)
181+
self.execute(
182+
f"drop procedure if exists {proc_name}", auto_begin=False, fetch=False
183+
)
171184
return response
172185

173186
def valid_incremental_strategies(self) -> List[str]:
174187
return ["append", "merge", "delete+insert"]
188+
189+
def drop_relation(self, relation: BaseRelation):
190+
# if relation.type == "table":
191+
# print("!!!! Dropping table with temporary property", relation)
192+
# tmp_prop = "__dbt_tmp"
193+
# try:
194+
# self.execute(
195+
# f'alter table {relation} add "{tmp_prop}" bit calculated',
196+
# auto_begin=False,
197+
# fetch=False,
198+
# )
199+
# except Exception as ex:
200+
# print(
201+
# "!!!! Failed to add temporary property, continuing anyway",
202+
# relation,
203+
# ex,
204+
# )
205+
206+
super().drop_relation(relation)

dbt/adapters/iris/relation.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ class IRISRelation(BaseRelation):
2828
default_factory=lambda: frozenset(
2929
{
3030
RelationType.Table,
31+
RelationType.View,
3132
}
3233
)
3334
)
@@ -43,6 +44,9 @@ class IRISRelation(BaseRelation):
4344
quote_policy: Policy = field(default_factory=lambda: IRISQuotePolicy())
4445
include_policy: Policy = field(default_factory=lambda: IRISIncludePolicy())
4546

47+
def __repr__(self) -> str:
48+
return "<{} {} {}>".format(self.__class__.__name__, self.type, self.render())
49+
4650
def matches(
4751
self,
4852
database: Optional[str] = None,

dbt/include/iris/macros/adapters.sql

Lines changed: 51 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,6 @@ dbt docs: https://docs.getdbt.com/docs/contributing/building-a-new-adapter
77
{{ return('?') }}
88
{% endmacro %}
99

10-
{% macro iris__current_timestamp() -%}
11-
current_timestamp
12-
{%- endmacro %}
13-
1410
{% macro iris__list_schemas(database) -%}
1511
{% call statement('list_schemas', fetch_result=True, auto_begin=False) -%}
1612
select schema_name
@@ -95,7 +91,7 @@ dbt docs: https://docs.getdbt.com/docs/contributing/building-a-new-adapter
9591
select
9692
column_name,
9793
data_type,
98-
character_maximum_length,
94+
NULLIF(CAST(character_maximum_length as INT),0) character_maximum_length,
9995
numeric_precision,
10096
numeric_scale
10197
from information_schema.columns
@@ -108,18 +104,6 @@ dbt docs: https://docs.getdbt.com/docs/contributing/building-a-new-adapter
108104
{{ return(sql_convert_columns_in_relation(table)) }}
109105
{% endmacro %}
110106

111-
112-
{% macro iris__create_view_as(relation, sql) -%}
113-
{%- set sql_header = config.get('sql_header', none) -%}
114-
115-
{{ sql_header if sql_header is not none }}
116-
/* create_view_as */
117-
{# create or replace view {{ relation }} #}
118-
create table {{ relation }}
119-
as {{ sql }}
120-
121-
{%- endmacro %}
122-
123107
{% macro iris__create_table_as(temporary, relation, compiled_code, language='sql') -%}
124108
{%- if language == 'sql' -%}
125109
{%- set sql_header = config.get('sql_header', none) -%}
@@ -130,11 +114,7 @@ dbt docs: https://docs.getdbt.com/docs/contributing/building-a-new-adapter
130114
{%- endif %}
131115
/* create_table_as */
132116
{{ sql_header if sql_header is not none }}
133-
create
134-
/* {% if temporary: -%}global temporary{%- endif %} */
135-
table
136-
{{ relation }}
137-
as
117+
create {% if temporary: -%}global temporary{%- endif %} table {{ relation }} as
138118
{{ compiled_code }}
139119
{%- elif language == 'python' -%}
140120
{{ py_write_table(compiled_code=compiled_code, target_relation=relation, temporary=temporary) }}
@@ -144,11 +124,56 @@ dbt docs: https://docs.getdbt.com/docs/contributing/building-a-new-adapter
144124
{%- endmacro %}
145125

146126
{% macro iris__rename_relation(from_relation, to_relation) -%}
147-
{% set target_name = adapter.quote_as_configured(to_relation.identifier, 'identifier') %}
148127
{% call statement('drop_relation') %}
149-
drop table if exists {{ to_relation }} cascade
128+
drop {{ to_relation.type }} if exists {{ to_relation }} cascade
129+
{% endcall %}
130+
{% if not from_relation.type %}
131+
{% do exceptions.raise_database_error("Cannot rename a relation with a blank type: " ~ from_relation.identifier) %}
132+
{% elif from_relation.type == 'table' %}
133+
{% set target_name = adapter.quote_as_configured(to_relation.identifier, 'identifier') %}
134+
{% do drop_related_view(from_relation) %}
135+
{%- set target_name = adapter.quote_as_configured(to_relation.identifier, 'identifier') %}
136+
{% call statement('rename_relation') -%}
137+
alter {{ from_relation.type }} {{ from_relation }} rename {{ target_name }}
138+
{%- endcall %}
139+
{%- elif from_relation.type == 'view' -%}
140+
{% do adapter.dispatch('rename_view')(from_relation, to_relation) %}
141+
{% else -%}
142+
{% do exceptions.raise_database_error("Unknown type '" ~ from_relation.type ~ "' for relation: " ~ from_relation.identifier) %}
143+
{% endif %}
144+
145+
{% endmacro %}
146+
147+
{% macro drop_related_view(relation) %}
148+
149+
{% set to_drop = get_related_views(relation) %}
150+
151+
{% if to_drop is not none and to_drop|length > 0 %}
152+
{% for view in to_drop %}
153+
{% set view_relation = api.Relation.create(
154+
identifier=view['VIEW_NAME'],
155+
schema=view['VIEW_SCHEMA'],
156+
database=relation.database,
157+
type='view') %}
158+
{{ drop_relation_if_exists(view_relation) }}
159+
{% endfor %}
160+
{% endif %}
161+
162+
{% endmacro %}
163+
164+
{% macro get_related_views(relation) %}
165+
{% call statement('list_tables', fetch_result=True) %}
166+
SELECT VIEW_SCHEMA,VIEW_NAME
167+
FROM INFORMATION_SCHEMA.VIEW_TABLE_USAGE
168+
WHERE TABLE_SCHEMA='{{ relation.schema }}' AND TABLE_NAME='{{ relation.identifier }}'
150169
{% endcall %}
170+
{{ return(load_result('list_tables').table) }}
171+
{% endmacro %}
172+
173+
{# {% macro iris__rename_relation(from_relation, to_relation) -%}
174+
{% set target_name = adapter.quote_as_configured(to_relation.identifier, 'identifier') %}
175+
{{ print("!!!! rename_relation: " ~ from_relation.type ~ ":" ~ from_relation.identifier ~ " to " ~ to_relation.type ~ ":" ~ to_relation) }}
151176
{% call statement('rename_relation') -%}
152-
alter table {{ from_relation }} rename {{ target_name }}
177+
alter table {{ from_relation.render() }} rename {{ target_name }}
153178
{%- endcall %}
154-
{% endmacro %}
179+
{% endmacro %} #}

dbt/include/iris/macros/adapters/columns.sql

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,40 @@
88

99
{{ return(load_result('get_columns_in_query').table.columns | map(attribute='name') | list) }}
1010
{% endmacro %}
11+
12+
{% macro iris__get_empty_subquery_sql(select_sql, select_sql_header=none) %}
13+
{%- if select_sql_header is not none -%}
14+
{{ select_sql_header }}
15+
{%- endif -%}
16+
select * from (
17+
{{ select_sql }}
18+
) as __dbt_sbq
19+
where 1=0
20+
limit 0
21+
{% endmacro %}
22+
23+
{% macro iris__alter_relation_add_remove_columns(relation, add_columns, remove_columns) %}
24+
25+
{% if add_columns %}
26+
27+
{% for column in add_columns %}
28+
{% set sql -%}
29+
alter {{ relation.type }} {{ relation }} add column {{ column.name }} {{ column.data_type }}
30+
{% endset %}
31+
{% do run_query(sql) %}
32+
{% endfor %}
33+
34+
{% endif %}
35+
36+
{% if remove_columns %}
37+
38+
{% for column in remove_columns %}
39+
{% set sql -%}
40+
alter {{ relation.type }} {{ relation }} drop column {{ column.name }}
41+
{% endset %}
42+
{% do run_query(sql) %}
43+
{% endfor %}
44+
45+
{% endif %}
46+
47+
{% endmacro %}
Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,11 @@
1-
{%- macro iris__type_string() -%}
2-
VARCHAR('')
1+
{%- macro iris__type_float() -%}
2+
DOUBLE
3+
{%- endmacro -%}
4+
5+
{%- macro iris__type_numeric() -%}
6+
NUMERIC
7+
{%- endmacro -%}
8+
9+
{%- macro iris__type_int() -%}
10+
INTEGER
311
{%- endmacro -%}

0 commit comments

Comments
 (0)