|
| 1 | +from peewee import Database, ImproperlyConfigured, OP, QueryCompiler, CompoundSelect, SQL, Clause, CommaClause |
| 2 | +from playhouse.db_url import register_database |
| 3 | + |
| 4 | +try: |
| 5 | + import pymssql |
| 6 | +except ImportError: |
| 7 | + pymssql = None |
| 8 | + |
| 9 | +try: |
| 10 | + from playhouse.pool import PooledDatabase |
| 11 | +except ImportError: |
| 12 | + PooledDatabase = None |
| 13 | + |
| 14 | +__version__ = '0.1.0' |
| 15 | + |
| 16 | +class MssqlQueryCompiler(QueryCompiler): |
| 17 | + # TODO: implement limit and offset properly, we can use: |
| 18 | + # SELECT * |
| 19 | + # FROM (SELECT ROW_NUMBER() OVER(ORDER BY id) RowNr, id FROM tbl) t |
| 20 | + # WHERE RowNr BETWEEN 10 AND 20 |
| 21 | + |
| 22 | + def generate_select(self, query, alias_map=None): |
| 23 | + model = query.model_class |
| 24 | + db = model._meta.database |
| 25 | + |
| 26 | + alias_map = self.calculate_alias_map(query, alias_map) |
| 27 | + |
| 28 | + if isinstance(query, CompoundSelect): |
| 29 | + clauses = [_StripParens(query)] |
| 30 | + else: |
| 31 | + if not query._distinct: |
| 32 | + clauses = [SQL('SELECT')] |
| 33 | + else: |
| 34 | + clauses = [SQL('SELECT DISTINCT')] |
| 35 | + if query._distinct not in (True, False): |
| 36 | + clauses += [SQL('ON'), EnclosedClause(*query._distinct)] |
| 37 | + |
| 38 | + # basic support for query limit |
| 39 | + if query._limit is not None or (query._offset and db.limit_max): |
| 40 | + limit = query._limit if query._limit is not None else db.limit_max |
| 41 | + clauses.append(SQL('TOP %s' % limit)) |
| 42 | + |
| 43 | + select_clause = Clause(*query._select) |
| 44 | + select_clause.glue = ', ' |
| 45 | + |
| 46 | + clauses.extend((select_clause, SQL('FROM'))) |
| 47 | + if query._from is None: |
| 48 | + clauses.append(model.as_entity().alias(alias_map[model])) |
| 49 | + else: |
| 50 | + clauses.append(CommaClause(*query._from)) |
| 51 | + |
| 52 | + if query._windows is not None: |
| 53 | + clauses.append(SQL('WINDOW')) |
| 54 | + clauses.append(CommaClause(*[ |
| 55 | + Clause( |
| 56 | + SQL(window._alias), |
| 57 | + SQL('AS'), |
| 58 | + window.__sql__()) |
| 59 | + for window in query._windows])) |
| 60 | + |
| 61 | + join_clauses = self.generate_joins(query._joins, model, alias_map) |
| 62 | + if join_clauses: |
| 63 | + clauses.extend(join_clauses) |
| 64 | + |
| 65 | + if query._where is not None: |
| 66 | + clauses.extend([SQL('WHERE'), query._where]) |
| 67 | + |
| 68 | + if query._group_by: |
| 69 | + clauses.extend([SQL('GROUP BY'), CommaClause(*query._group_by)]) |
| 70 | + |
| 71 | + if query._having: |
| 72 | + clauses.extend([SQL('HAVING'), query._having]) |
| 73 | + |
| 74 | + if query._order_by: |
| 75 | + clauses.extend([SQL('ORDER BY'), CommaClause(*query._order_by)]) |
| 76 | + |
| 77 | + # NO OFFSET SUPPORT |
| 78 | + |
| 79 | + for_update, no_wait = query._for_update |
| 80 | + if for_update: |
| 81 | + stmt = 'FOR UPDATE NOWAIT' if no_wait else 'FOR UPDATE' |
| 82 | + clauses.append(SQL(stmt)) |
| 83 | + |
| 84 | + return self.build_query(clauses, alias_map) |
| 85 | + |
| 86 | +class MssqlDatabase(Database): |
| 87 | + compiler_class = MssqlQueryCompiler |
| 88 | + commit_select = False |
| 89 | + interpolation = '%s' |
| 90 | + quote_char = '"' |
| 91 | + |
| 92 | + field_overrides = { |
| 93 | + 'bool': 'tinyint', |
| 94 | + 'double': 'float(53)', |
| 95 | + 'float': 'float', |
| 96 | + 'int': 'int', |
| 97 | + 'string': 'nvarchar', |
| 98 | + 'fixed_char': 'nchar', |
| 99 | + 'text': 'nvarchar(max)', |
| 100 | + 'blob': 'varbinary', |
| 101 | + 'uuid': 'nchar(40)', |
| 102 | + 'primary_key': 'int identity', |
| 103 | + 'datetime': 'datetime2', |
| 104 | + 'date': 'date', |
| 105 | + 'time': 'time', |
| 106 | + } |
| 107 | + |
| 108 | + op_overrides = { |
| 109 | + OP.LIKE: 'LIKE BINARY', |
| 110 | + OP.ILIKE: 'LIKE', |
| 111 | + } |
| 112 | + |
| 113 | + def _connect(self, database, **kwargs): |
| 114 | + if not pymssql: |
| 115 | + raise ImproperlyConfigured('pymssql must be installed') |
| 116 | + |
| 117 | + if kwargs.pop('use_legacy_datetime', False): |
| 118 | + self.field_overrides['datetime'] = 'datetime' |
| 119 | + self.field_overrides['date'] = 'nvarchar(15)' |
| 120 | + self.field_overrides['time'] = 'nvarchar(10)' |
| 121 | + |
| 122 | + return pymssql.connect(database=database, **kwargs) |
| 123 | + |
| 124 | + def get_tables(self, schema=None): |
| 125 | + # should I not be using sys.tables? |
| 126 | + if schema: |
| 127 | + query = ('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE ' |
| 128 | + 'TABLE_SCHEMA = %s AND TABLE_TYPE = %s ORDER BY TABLE_NAME') |
| 129 | + cursor = self.execute_sql(query, (schema, 'BASE TABLE',), |
| 130 | + require_commit=False) |
| 131 | + else: |
| 132 | + query = ('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE ' |
| 133 | + 'TABLE_TYPE = %s ORDER BY TABLE_NAME') |
| 134 | + cursor = self.execute_sql(query, ('BASE TABLE',), |
| 135 | + require_commit=False) |
| 136 | + |
| 137 | + return [row[0] for row in cursor.fetchall()] |
| 138 | + |
| 139 | + def execute_sql(self, sql, params, *args, **kwargs): |
| 140 | + # convert params to tuple |
| 141 | + params = tuple(params) |
| 142 | + |
| 143 | + return super(MssqlDatabase, self).execute_sql(sql, params, *args, **kwargs) |
| 144 | + |
| 145 | +register_database(MssqlDatabase, 'mssql') |
| 146 | + |
| 147 | +if PooledDatabase: |
| 148 | + class PooledMssqlDatabase(PooledDatabase, MssqlDatabase): |
| 149 | + pass # TODO: implement _is_closed() |
| 150 | + |
| 151 | + register_database(PooledMssqlDatabase, 'mssql+pool') |
0 commit comments