| | 1 | """ |
| | 2 | Alpha Multi-plataform MSSQL database backend for Django. |
| | 3 | |
| | 4 | Requires pymssql >= v0.8.0: http://pymssql.sourceforge.net/ |
| | 5 | """ |
| | 6 | |
| | 7 | import datetime |
| | 8 | from django.db.backends import BaseDatabaseWrapper, BaseDatabaseFeatures, BaseDatabaseOperations, util |
| | 9 | from django.core.exceptions import ImproperlyConfigured |
| | 10 | from django.utils.datastructures import SortedDict |
| | 11 | |
| | 12 | try: |
| | 13 | import pymssql as Database |
| | 14 | except ImportError, e: |
| | 15 | raise ImproperlyConfigured("Error loading pymssql module: %s" % e) |
| | 16 | |
| | 17 | try: |
| | 18 | import mx |
| | 19 | except ImportError: |
| | 20 | mx = None |
| | 21 | |
| | 22 | try: |
| | 23 | # Only exists in Python 2.4+ |
| | 24 | from threading import local |
| | 25 | except ImportError: |
| | 26 | # Import copy of _thread_local.py from Python 2.4 |
| | 27 | from django.utils._threading_local import local |
| | 28 | |
| | 29 | DatabaseError = Database.DatabaseError |
| | 30 | IntegrityError = Database.IntegrityError |
| | 31 | |
| | 32 | class DatabaseFeatures(BaseDatabaseFeatures): |
| | 33 | pass |
| | 34 | |
| | 35 | class DatabaseOperations(BaseDatabaseOperations): |
| | 36 | def last_insert_id(self, cursor, table_name, pk_name): |
| | 37 | cursor.execute("SELECT %s FROM %s WHERE %s = IDENT_CURRENT('%s')" % (pk_name, table_name, pk_name,table_name)) |
| | 38 | return cursor.fetchone()[0] |
| | 39 | |
| | 40 | def query_set_class(self, DefaultQuerySet): |
| | 41 | "Create a custom QuerySet class for SqlServer." |
| | 42 | |
| | 43 | from django.db import connection |
| | 44 | from django.db.models.query import EmptyResultSet, GET_ITERATOR_CHUNK_SIZE, quote_only_if_word |
| | 45 | |
| | 46 | class SqlServerQuerySet(DefaultQuerySet): |
| | 47 | |
| | 48 | def iterator(self): |
| | 49 | "Performs the SELECT database lookup of this QuerySet." |
| | 50 | |
| | 51 | from django.db.models.query import get_cached_row |
| | 52 | |
| | 53 | # self._select is a dictionary, and dictionaries' key order is |
| | 54 | # undefined, so we convert it to a list of tuples. |
| | 55 | extra_select = self._select.items() |
| | 56 | |
| | 57 | full_query = None |
| | 58 | |
| | 59 | try: |
| | 60 | try: |
| | 61 | select, sql, params, full_query = self._get_sql_clause(get_full_query=True) |
| | 62 | except TypeError: |
| | 63 | select, sql, params = self._get_sql_clause() |
| | 64 | except EmptyResultSet: |
| | 65 | raise StopIteration |
| | 66 | if not full_query: |
| | 67 | full_query = "SELECT %s%s\n%s" % \ |
| | 68 | ((self._distinct and "DISTINCT " or ""), |
| | 69 | ', '.join(select), sql) |
| | 70 | |
| | 71 | cursor = connection.cursor() |
| | 72 | cursor.execute(full_query, params) |
| | 73 | |
| | 74 | fill_cache = self._select_related |
| | 75 | fields = self.model._meta.fields |
| | 76 | index_end = len(fields) |
| | 77 | |
| | 78 | # so here's the logic; |
| | 79 | # 1. retrieve each row in turn |
| | 80 | # 2. convert NCLOBs |
| | 81 | |
| | 82 | while 1: |
| | 83 | rows = cursor.fetchmany(GET_ITERATOR_CHUNK_SIZE) |
| | 84 | if not rows: |
| | 85 | raise StopIteration |
| | 86 | for row in rows: |
| | 87 | row = self.resolve_columns(row, fields) |
| | 88 | if fill_cache: |
| | 89 | obj, index_end = get_cached_row(klass=self.model, row=row, |
| | 90 | index_start=0, max_depth=self._max_related_depth) |
| | 91 | else: |
| | 92 | obj = self.model(*row[:index_end]) |
| | 93 | for i, k in enumerate(extra_select): |
| | 94 | setattr(obj, k[0], row[index_end+i]) |
| | 95 | yield obj |
| | 96 | |
| | 97 | |
| | 98 | def _get_sql_clause(self, get_full_query=False): |
| | 99 | from django.db.models.query import fill_table_cache, \ |
| | 100 | handle_legacy_orderlist, orderfield2column |
| | 101 | |
| | 102 | opts = self.model._meta |
| | 103 | qn = connection.ops.quote_name |
| | 104 | |
| | 105 | # Construct the fundamental parts of the query: SELECT X FROM Y WHERE Z. |
| | 106 | select = ["%s.%s" % (qn(opts.db_table), qn(f.column)) for f in opts.fields] |
| | 107 | tables = [quote_only_if_word(t) for t in self._tables] |
| | 108 | joins = SortedDict() |
| | 109 | where = self._where[:] |
| | 110 | params = self._params[:] |
| | 111 | |
| | 112 | # Convert self._filters into SQL. |
| | 113 | joins2, where2, params2 = self._filters.get_sql(opts) |
| | 114 | joins.update(joins2) |
| | 115 | where.extend(where2) |
| | 116 | params.extend(params2) |
| | 117 | |
| | 118 | # Add additional tables and WHERE clauses based on select_related. |
| | 119 | if self._select_related: |
| | 120 | fill_table_cache(opts, select, tables, where, opts.db_table, [opts.db_table]) |
| | 121 | |
| | 122 | # Add any additional SELECTs. |
| | 123 | if self._select: |
| | 124 | select.extend(['(%s) AS %s' % (quote_only_if_word(s[1]), qn(s[0])) for s in self._select.items()]) |
| | 125 | |
| | 126 | # Start composing the body of the SQL statement. |
| | 127 | sql = [" FROM", qn(opts.db_table)] |
| | 128 | |
| | 129 | # Compose the join dictionary into SQL describing the joins. |
| | 130 | if joins: |
| | 131 | sql.append(" ".join(["%s %s %s ON %s" % (join_type, table, alias, condition) |
| | 132 | for (alias, (table, join_type, condition)) in joins.items()])) |
| | 133 | |
| | 134 | # Compose the tables clause into SQL. |
| | 135 | if tables: |
| | 136 | sql.append(", " + ", ".join(tables)) |
| | 137 | |
| | 138 | # Compose the where clause into SQL. |
| | 139 | if where: |
| | 140 | sql.append(where and "WHERE " + " AND ".join(where)) |
| | 141 | |
| | 142 | #copy a version suitable for LIMIT |
| | 143 | sql2=[] |
| | 144 | [sql2.append(x) for x in sql] |
| | 145 | # ORDER BY clause |
| | 146 | order_by = [] |
| | 147 | if self._order_by is not None: |
| | 148 | ordering_to_use = self._order_by |
| | 149 | else: |
| | 150 | ordering_to_use = opts.ordering |
| | 151 | for f in handle_legacy_orderlist(ordering_to_use): |
| | 152 | if f == '?': # Special case. |
| | 153 | order_by.append(connection.ops.get_random_function_sql()) |
| | 154 | else: |
| | 155 | if f.startswith('-'): |
| | 156 | col_name = f[1:] |
| | 157 | order = "DESC" |
| | 158 | else: |
| | 159 | col_name = f |
| | 160 | order = "ASC" |
| | 161 | if "." in col_name: |
| | 162 | table_prefix, col_name = col_name.split('.', 1) |
| | 163 | table_prefix = qn(table_prefix) + '.' |
| | 164 | else: |
| | 165 | # Use the database table as a column prefix if it wasn't given, |
| | 166 | # and if the requested column isn't a custom SELECT. |
| | 167 | if "." not in col_name and col_name not in (self._select or ()): |
| | 168 | table_prefix = qn(opts.db_table) + '.' |
| | 169 | else: |
| | 170 | table_prefix = '' |
| | 171 | order_by.append('%s%s %s' % (table_prefix, qn(orderfield2column(col_name, opts)), order)) |
| | 172 | if order_by: |
| | 173 | sql.append("ORDER BY " + ", ".join(order_by)) |
| | 174 | |
| | 175 | # Look for column name collisions in the select elements |
| | 176 | # and fix them with an AS alias. This allows us to do a |
| | 177 | # SELECT * later in the paging query. |
| | 178 | cols = [clause.split('.')[-1] for clause in select] |
| | 179 | for index, col in enumerate(cols): |
| | 180 | if cols.count(col) > 1: |
| | 181 | col = '%s%d' % (col.replace('[', '').replace(']',''), index) |
| | 182 | cols[index] = qn(col) |
| | 183 | select[index] = '%s AS %s' % (select[index], qn(col)) |
| | 184 | |
| | 185 | # LIMIT and OFFSET clauses |
| | 186 | # To support limits and offsets, SqlServer requires some funky rewriting of an otherwise normal looking query. |
| | 187 | select_clause = ",".join(select) |
| | 188 | distinct = (self._distinct and "DISTINCT " or "") |
| | 189 | full_query = None |
| | 190 | |
| | 191 | if self._limit is None: |
| | 192 | assert self._offset is None, "'offset' is not allowed without 'limit'" |
| | 193 | |
| | 194 | if self._offset is not None: |
| | 195 | offset = int(self._offset) |
| | 196 | else: |
| | 197 | offset = 0 |
| | 198 | |
| | 199 | if self._limit is not None: |
| | 200 | limit = int(self._limit) |
| | 201 | else: |
| | 202 | limit = None |
| | 203 | |
| | 204 | limit_and_offset_clause = '' |
| | 205 | |
| | 206 | if limit is not None: |
| | 207 | limit_and_offset_clause = True |
| | 208 | elif offset: |
| | 209 | limit_and_offset_clause = True |
| | 210 | |
| | 211 | if limit_and_offset_clause: |
| | 212 | #Django give: |
| | 213 | # Offset : Start row |
| | 214 | # Limit : How much aditional rows fetch |
| | 215 | |
| | 216 | # This must be transformed to Sql2005 to: |
| | 217 | # Offset : First Row |
| | 218 | # Limit : EndRow |
| | 219 | StartRow = offset + 1 |
| | 220 | EndRow = StartRow + limit - 1 |
| | 221 | # and for Sql2000 |
| | 222 | # Offset : Top rows |
| | 223 | # Limit: From where |
| | 224 | limit = limit + offset |
| | 225 | if offset==0: |
| | 226 | offset = limit |
| | 227 | else: |
| | 228 | offset = offset + 1 |
| | 229 | #Must use a order. If not specified, use Id. |
| | 230 | if len(order_by)==0: |
| | 231 | order_by.append('%s.%s ASC' % |
| | 232 | (qn(opts.db_table), |
| | 233 | qn(opts.fields[0].db_column or opts.fields[0].column) |
| | 234 | ) |
| | 235 | ) |
| | 236 | |
| | 237 | order_by_clause = ", ".join(order_by) |
| | 238 | order_by_clauseReverse = "" |
| | 239 | |
| | 240 | #For Sql2005+ use native implementation... |
| | 241 | if version()>8: |
| | 242 | fmt = \ |
| | 243 | """ |
| | 244 | SELECT * |
| | 245 | FROM ( |
| | 246 | SELECT %(distinc)s TOP %(EndRow)s |
| | 247 | %(fields)s, ROW_NUMBER() |
| | 248 | OVER( |
| | 249 | ORDER BY %(orderby)s |
| | 250 | ) AS row |
| | 251 | %(sql)s ORDER BY %(orderby)s |
| | 252 | ) AS x |
| | 253 | WHERE x.row BETWEEN %(StartRow)s AND %(EndRow)s |
| | 254 | """ |
| | 255 | else: |
| | 256 | #Is necesary reverse all the second order by for the trick to work... |
| | 257 | order_by_clauseReverse= ", ".join(self.change_order_direction(order_by)) |
| | 258 | |
| | 259 | fmt = \ |
| | 260 | """ |
| | 261 | SELECT * FROM ( |
| | 262 | SELECT TOP %(offset)s * FROM ( |
| | 263 | SELECT TOP %(limit)s %(distinc)s%(fields)s |
| | 264 | %(sql)s |
| | 265 | ORDER BY %(orderby)s |
| | 266 | ) AS %(table)s |
| | 267 | ORDER BY %(orderbyReverse)s) AS %(table)s |
| | 268 | ORDER BY %(orderby)s |
| | 269 | """ |
| | 270 | |
| | 271 | full_query = fmt % {'distinc':distinct, 'fields':select_clause, |
| | 272 | 'sql':" ".join(sql2),'orderby':order_by_clause, |
| | 273 | 'orderbyReverse':order_by_clauseReverse, |
| | 274 | 'table':qn(opts.db_table), |
| | 275 | 'offset':offset,'limit':limit, |
| | 276 | 'StartRow':StartRow,'EndRow':EndRow} |
| | 277 | |
| | 278 | print full_query |
| | 279 | if get_full_query: |
| | 280 | return select, " ".join(sql), params, full_query |
| | 281 | else: |
| | 282 | return select, " ".join(sql), params |
| | 283 | |
| | 284 | |
| | 285 | def change_order_direction(self,order_by): |
| | 286 | newOrder=[] |
| | 287 | |
| | 288 | for order in order_by: |
| | 289 | if order.find(' ASC'): |
| | 290 | newOrder.append(order.replace(' ASC',' DESC')) |
| | 291 | else: |
| | 292 | newOrder.append(order.replace(' DESC',' ASC')) |
| | 293 | |
| | 294 | return newOrder |
| | 295 | |
| | 296 | def resolve_columns(self, row, fields=()): |
| | 297 | from django.db.models.fields import DateField, DateTimeField, \ |
| | 298 | TimeField, BooleanField, NullBooleanField, DecimalField, Field |
| | 299 | values = [] |
| | 300 | for value, field in map(None, row, fields): |
| | 301 | # Convert 1 or 0 to True or False |
| | 302 | if value in (1, 0) and isinstance(field, (BooleanField, NullBooleanField)): |
| | 303 | value = bool(value) |
| | 304 | # Convert floats to decimals |
| | 305 | elif value is not None and isinstance(field, DecimalField): |
| | 306 | value = util.typecast_decimal(field.format_number(value)) |
| | 307 | values.append(value) |
| | 308 | return values |
| | 309 | |
| | 310 | return SqlServerQuerySet |
| | 311 | |
| | 312 | def date_extract_sql(self, lookup_type, field_name): |
| | 313 | # lookup_type is 'year', 'month', 'day' |
| | 314 | return "DATEPART(%s, %s)" % (lookup_type, table_name) |
| | 315 | |
| | 316 | def date_trunc_sql(self, lookup_type, field_name): |
| | 317 | # lookup_type is 'year', 'month', 'day' |
| | 318 | if lookup_type=='year': |
| | 319 | return "Convert(datetime, Convert(varchar, DATEPART(year, %s)) + '/01/01')" % field_name |
| | 320 | if lookup_type=='month': |
| | 321 | return "Convert(datetime, Convert(varchar, DATEPART(year, %s)) + '/' + Convert(varchar, DATEPART(month, %s)) + '/01')" % (field_name, field_name) |
| | 322 | if lookup_type=='day': |
| | 323 | return "Convert(datetime, Convert(varchar(12), %s))" % field_name |
| | 324 | |
| | 325 | def limit_offset_sql(self, limit, offset=None): |
| | 326 | # Limits and offset are too complicated to be handled here. |
| | 327 | # Look for a implementation similar to SqlServer backend |
| | 328 | return "" |
| | 329 | |
| | 330 | def quote_name(self, name): |
| | 331 | if name.startswith('[') and name.endswith(']'): |
| | 332 | return name # Quoting once is enough. |
| | 333 | return '[%s]' % name |
| | 334 | |
| | 335 | def random_function_sql(self): |
| | 336 | return "RAND()" |
| | 337 | |
| | 338 | def tablespace_sql(self, tablespace, inline=False): |
| | 339 | return "ON %s" % quote_name(tablespace) |
| | 340 | |
| | 341 | def sql_flush(self, style, tables, sequences): |
| | 342 | """Return a list of SQL statements required to remove all data from |
| | 343 | all tables in the database (without actually removing the tables |
| | 344 | themselves) and put the database in an empty 'initial' state |
| | 345 | """ |
| | 346 | # Cannot use TRUNCATE on tables that are referenced by a FOREIGN KEY |
| | 347 | # So must use the much slower DELETE |
| | 348 | sql_list = ['%s %s %s;' % \ |
| | 349 | (style.SQL_KEYWORD('DELETE'), |
| | 350 | style.SQL_KEYWORD('FROM'), |
| | 351 | style.SQL_FIELD(self.quote_name(table)) |
| | 352 | ) for table in tables] |
| | 353 | #The reset the counters on each table. |
| | 354 | sql_list.extend(['%s %s %s %s %s %s %s;' % ( |
| | 355 | style.SQL_KEYWORD('DBCC'), |
| | 356 | style.SQL_KEYWORD('CHECKIDENT'), |
| | 357 | style.SQL_FIELD(self.quote_name(seq["table"])), |
| | 358 | style.SQL_KEYWORD('RESEED'), |
| | 359 | style.SQL_FIELD('1'), |
| | 360 | style.SQL_KEYWORD('WITH'), |
| | 361 | style.SQL_KEYWORD('NO_INFOMSGS'), |
| | 362 | ) for seq in sequences]) |
| | 363 | |
| | 364 | return sql_list |
| | 365 | |
| | 366 | |
| | 367 | |
| | 368 | def complain(*args, **kwargs): |
| | 369 | raise ImproperlyConfigured("You haven't set the DATABASE_ENGINE setting yet.") |
| | 370 | |
| | 371 | def ignore(*args, **kwargs): |
| | 372 | pass |
| | 373 | |
| | 374 | class DatabaseError(Exception): |
| | 375 | pass |
| | 376 | |
| | 377 | class IntegrityError(DatabaseError): |
| | 378 | pass |
| | 379 | |
| | 380 | class DatabaseWrapper(BaseDatabaseWrapper): |
| | 381 | features = DatabaseFeatures() |
| | 382 | ops = DatabaseOperations() |
| | 383 | operators = { |
| | 384 | 'exact': '= %s', |
| | 385 | 'iexact': 'LIKE %s', |
| | 386 | 'contains': 'LIKE %s', |
| | 387 | 'icontains': 'LIKE %s', |
| | 388 | 'gt': '> %s', |
| | 389 | 'gte': '>= %s', |
| | 390 | 'lt': '< %s', |
| | 391 | 'lte': '<= %s', |
| | 392 | 'startswith': 'LIKE %s', |
| | 393 | 'endswith': 'LIKE %s', |
| | 394 | 'istartswith': 'LIKE %s', |
| | 395 | 'iendswith': 'LIKE %s', |
| | 396 | } |
| | 397 | def __init__(self, **kwargs): |
| | 398 | self.connection = None |
| | 399 | self.queries = [] |
| | 400 | |
| | 401 | def cursor(self): |
| | 402 | from django.conf import settings |
| | 403 | if self.connection is None: |
| | 404 | if settings.DATABASE_NAME == '' or settings.DATABASE_USER == '': |
| | 405 | raise ImproperlyConfigured("You need to specify both DATABASE_NAME and DATABASE_USER in your Django settings file.") |
| | 406 | if not settings.DATABASE_HOST: |
| | 407 | settings.DATABASE_HOST = "127.0.0.1" |
| | 408 | |
| | 409 | if settings.DATABASE_PORT: |
| | 410 | hostStr = '%s:%s' % ( settings.DATABASE_HOST ,settings.DATABASE_PORT) |
| | 411 | else: |
| | 412 | hostStr = settings.DATABASE_HOST |
| | 413 | |
| | 414 | self.connection = Database.connect(host=hostStr,user=settings.DATABASE_USER,password=settings.DATABASE_PASSWORD,database=settings.DATABASE_NAME) |
| | 415 | |
| | 416 | self.connection.cursor().execute("SET DATEFORMAT ymd\nGO") |
| | 417 | |
| | 418 | cursor = self.connection.cursor() |
| | 419 | if settings.DEBUG: |
| | 420 | return util.CursorDebugWrapper(cursor, self) |
| | 421 | return cursor |
| | 422 | |
| | 423 | def _commit(self): |
| | 424 | if self.connection is not None: |
| | 425 | return self.connection.commit() |
| | 426 | |
| | 427 | def _rollback(self): |
| | 428 | if self.connection is not None: |
| | 429 | return self.connection.rollback() |
| | 430 | |
| | 431 | def close(self): |
| | 432 | if self.connection is not None: |
| | 433 | self.connection.close() |
| | 434 | self.connection = None |
| | 435 | |
| | 436 | ''' |
| | 437 | Return the major version of the server. 7=Sql 7,8=Sql2000,9=Sql2005 |
| | 438 | ''' |
| | 439 | def version(): |
| | 440 | cur = DatabaseWrapper().cursor() |
| | 441 | cur.execute("SELECT SERVERPROPERTY('ProductVersion')") |
| | 442 | |
| | 443 | return int(cur.fetchone()[0].split('.')[0]) |
| | 444 | |
| | 445 | |
| | 446 | if __name__ == '__main__': |
| | 447 | from mysite.polls.models import Poll, Choice |
| | 448 | from datetime import datetime |
| | 449 | |
| | 450 | #Poll.objects.all().delete() |
| | 451 | #i =0 |
| | 452 | #for i in range(i,150): |
| | 453 | # p = Poll(question="%s" % i, pub_date=datetime.now()) |
| | 454 | # p.save() |
| | 455 | |
| | 456 | for poll in Poll.objects.all()[:10]: |
| | 457 | print poll |
| | 458 | Pas de fin de ligne |