-
Notifications
You must be signed in to change notification settings - Fork 8
Changes to support MSSQL #33
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ifMatt
wants to merge
6
commits into
erezsh:master
Choose a base branch
from
ifMatt:Add-MsSQL
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
965fd55
Initial Changes to support MSSQL
ifMatt 1b2d04b
Formatting changes to better conform to origin
ifMatt 3b7ea6f
Fixes based on pull request feedback.
ifMatt f726838
2nd wave of PR feedback. Also fix for foreign key column type.
ifMatt f429f22
Added in MSSQL support for three part ids. Updated test to cover new …
ifMatt 632924c
Changes to test MSSQL Connection details
ifMatt File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,25 +1,217 @@ | ||
# class MsSQL(ThreadedDatabase): | ||
# "AKA sql-server" | ||
from typing import List | ||
from datetime import datetime | ||
from ..abcs.database_types import ( | ||
DbPath, | ||
Timestamp, | ||
TimestampTZ, | ||
Float, | ||
Decimal, | ||
Integer, | ||
TemporalType, | ||
Text, | ||
FractionalType, | ||
Boolean, | ||
Date, | ||
) | ||
from typing import Dict | ||
from ..abcs.mixins import AbstractMixin_MD5, AbstractMixin_NormalizeValue, AbstractMixin_Schema | ||
from .base import BaseDialect, ThreadedDatabase, import_helper, ConnectError, Mixin_Schema | ||
from ..abcs import Compilable | ||
from ..queries import this, table, Select, SKIP | ||
from ..queries.ast_classes import ForeignKey, TablePath | ||
from .base import TIMESTAMP_PRECISION_POS, Mixin_RandomSample | ||
|
||
# def __init__(self, host, port, user, password, *, database, thread_count, **kw): | ||
# args = dict(server=host, port=port, database=database, user=user, password=password, **kw) | ||
# self._args = {k: v for k, v in args.items() if v is not None} | ||
SESSION_TIME_ZONE = None # Changed by the tests | ||
|
||
# super().__init__(thread_count=thread_count) | ||
|
||
# def create_connection(self): | ||
# mssql = import_mssql() | ||
# try: | ||
# return mssql.connect(**self._args) | ||
# except mssql.Error as e: | ||
# raise ConnectError(*e.args) from e | ||
@import_helper("mssql") | ||
def import_mssql(): | ||
import pymssql | ||
|
||
# def quote(self, s: str): | ||
# return f"[{s}]" | ||
return pymssql | ||
|
||
# def md5_as_int(self, s: str) -> str: | ||
# return f"CONVERT(decimal(38,0), CONVERT(bigint, HashBytes('MD5', {s}), 2))" | ||
# # return f"CONVERT(bigint, (CHECKSUM({s})))" | ||
|
||
# def to_string(self, s: str): | ||
# return f"CONVERT(varchar, {s})" | ||
class Mixin_MD5(AbstractMixin_MD5): | ||
def md5_as_int(self, s: str) -> str: | ||
return f"CONVERT(decimal(38,0), CONVERT(bigint, HashBytes('MD5', {s}), 2))" | ||
|
||
class Mixin_NormalizeValue(AbstractMixin_NormalizeValue): | ||
def normalize_timestamp(self, value: str, coltype: TemporalType) -> str: | ||
timestamp = f"convert(varchar(26), {value} AT TIME ZONE 'UTC', 25)" | ||
return ( | ||
f"LEFT({timestamp} + REPLICATE(' ', {coltype.precision}), {TIMESTAMP_PRECISION_POS+6})" | ||
) | ||
|
||
def normalize_number(self, value: str, coltype: FractionalType) -> str: | ||
return self.to_string(f"convert(varchar, convert(decimal(38, {coltype.precision}), {value}))") | ||
|
||
def normalize_boolean(self, value: str, _coltype: Boolean) -> str: | ||
return self.to_string(f"convert(varchar, {value})") | ||
|
||
class Mixin_Schema(AbstractMixin_Schema): | ||
def table_information(self) -> TablePath: | ||
return table("information_schema", "tables") | ||
|
||
def list_tables(self, table_schema: str, like: Compilable = None) -> Select: | ||
return ( | ||
self.table_information() | ||
.where( | ||
this.table_schema == table_schema if table_schema is not None else SKIP, | ||
this.table_name.like(like) if like is not None else SKIP, | ||
this.table_type == "BASE TABLE", | ||
) | ||
.select(this.table_name) | ||
) | ||
|
||
|
||
class MsSQLDialect(BaseDialect, Mixin_Schema): | ||
name = "MsSQL" | ||
ROUNDS_ON_PREC_LOSS = True | ||
SUPPORTS_PRIMARY_KEY = True | ||
SUPPORTS_INDEXES = True | ||
MIXINS = {Mixin_Schema, Mixin_MD5, Mixin_NormalizeValue, Mixin_RandomSample} | ||
AT_TIMEZONE = False | ||
|
||
TYPE_CLASSES = { | ||
# Numbers | ||
"tinyint": Integer, | ||
"smallint": Integer, | ||
"int": Integer, | ||
"bigint": Integer, | ||
"decimal": Decimal, | ||
"numeric": Decimal, | ||
"money": Decimal, | ||
"smallmoney": Decimal, | ||
"float": Float, | ||
"real": Float, | ||
# Timestamps | ||
"date": Date, | ||
"time": Timestamp, | ||
"datetime2": Timestamp, | ||
"datetimeoffset": TimestampTZ, | ||
"datetime": Timestamp, | ||
"smalldatetime": Date, | ||
# Text | ||
"char": Text, | ||
"varchar": Text, | ||
"text": Text, | ||
"nchar": Text, | ||
"nvarchar": Text, | ||
"ntext": Text, | ||
# Boolean | ||
"BIT": Boolean, | ||
} | ||
|
||
# TSQL has EXPLAIN for Azure SQL Data warehouse | ||
# But not yet included for the regular RDBMS SQL Server | ||
def explain_as_text(self, query: str) -> str: | ||
return f"""SET SHOWPLAN_ALL ON; | ||
GO | ||
{query} | ||
GO | ||
SET SHOWPLAN_ALL ON; | ||
GO""" | ||
|
||
def quote(self, s: str): | ||
return f'"{s}"' | ||
|
||
def to_string(self, s: str): | ||
return f"CONVERT(VARCHAR(MAX), {s})" | ||
|
||
def concat(self, items: List[str]) -> str: | ||
joined_exprs = ", ".join(items) | ||
return f"CONCAT({joined_exprs})" | ||
|
||
def _convert_db_precision_to_digits(self, p: int) -> int: | ||
return super()._convert_db_precision_to_digits(p) - 2 | ||
|
||
# Datetime is stored as UTC by default in MsSQL | ||
# There is no current way to enforce a timezone for a session | ||
def set_timezone_to_utc(self) -> str: | ||
return "" | ||
|
||
def current_timestamp(self) -> str: | ||
return "SYSUTCDATETIME()" | ||
|
||
def type_repr(self, t) -> str: | ||
if isinstance(t, TimestampTZ): | ||
return f"datetimeoffset" | ||
elif isinstance(t, ForeignKey): | ||
return self.type_repr(t.type) | ||
elif isinstance(t, type): | ||
try: | ||
return { | ||
str: "NVARCHAR(MAX)", | ||
bool: "BIT", | ||
datetime: "datetime2", | ||
}[t] | ||
except KeyError: | ||
return super().type_repr(t) | ||
|
||
super().type_repr(t) | ||
|
||
class MsSQL(ThreadedDatabase): | ||
"AKA sql-server" | ||
dialect = MsSQLDialect() | ||
SUPPORTS_ALPHANUMS = False | ||
SUPPORTS_UNIQUE_CONSTAINT = True | ||
CONNECT_URI_HELP = "pymssql://<user>:<password>@<host>:<port>/<database>" | ||
CONNECT_URI_PARAMS = ["database"] | ||
|
||
def __init__(self, host, port, user, password, *, database, thread_count, **kw): | ||
args = dict(server=host, port=port, database=database, user=user, password=password, conn_properties=['SET QUOTED_IDENTIFIER ON;'], **kw) | ||
self._args = {k: v for k, v in args.items() if v is not None} | ||
|
||
super().__init__(thread_count=thread_count) | ||
|
||
def create_connection(self): | ||
self.mssql = import_mssql() | ||
try: | ||
return self.mssql.connect(**self._args) | ||
except self.mssql.Error as e: | ||
raise ConnectError(*e.args) from e | ||
|
||
def _normalize_table_path(self, path: DbPath) -> DbPath: | ||
if len(path) == 1: | ||
return None, self.default_schema, path[0] | ||
elif len(path) == 2: | ||
return None, path[0], path[1] | ||
elif len(path) == 3: | ||
return path | ||
|
||
raise ValueError( | ||
f"{self.name}: Bad table path for {self}: '{'.'.join(path)}'. Expected format: table, schema.table, or database.schema.table" | ||
) | ||
|
||
def select_table_schema(self, path: DbPath) -> str: | ||
"""Provide SQL for selecting the table schema as (name, type, date_prec, num_prec)""" | ||
|
||
database, schema, name = self._normalize_table_path(path) | ||
|
||
info_schema_path = ["information_schema", "COLUMNS"] | ||
if database: | ||
info_schema_path.insert(0, database) | ||
|
||
if schema == None: | ||
sql_code = ( | ||
"SELECT column_name, data_type, datetime_precision, numeric_precision, numeric_scale " | ||
f"FROM {'.'.join(info_schema_path)} " | ||
f"WHERE table_name = '{name}'" | ||
) | ||
else: | ||
sql_code = ( | ||
"SELECT column_name, data_type, datetime_precision, numeric_precision, numeric_scale " | ||
f"FROM {'.'.join(info_schema_path)} " | ||
f"WHERE table_name = '{name}' AND table_schema = '{schema}'" | ||
) | ||
|
||
return sql_code | ||
|
||
def query_table_schema(self, path: DbPath) -> Dict[str, tuple]: | ||
rows = self.query(self.select_table_schema(path), list) | ||
if not rows: | ||
raise RuntimeError(f"{self.name}: Table '{'.'.join(path)}' does not exist, or has no columns") | ||
|
||
d = {r[0]: r for r in rows} | ||
assert len(d) == len(rows) | ||
return d |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is it always UTC? If so, worth documenting.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It is, I have added code commentary. Is there an additional location that this should be documented?