| | 1 | """ |
|---|
| | 2 | Firebird database backend for Django. |
|---|
| | 3 | |
|---|
| | 4 | Requires KInterbasDB 3.2: http://kinterbasdb.sourceforge.net/ |
|---|
| | 5 | The egenix mx (mx.DateTime) is NOT required |
|---|
| | 6 | |
|---|
| | 7 | Database charset should be UNICODE_FSS or UTF8 (FireBird 2.0+) |
|---|
| | 8 | To use UTF8 encoding add FIREBIRD_CHARSET = 'UTF8' to your settings.py |
|---|
| | 9 | UNICODE_FSS works with all versions and uses less memory |
|---|
| | 10 | """ |
|---|
| | 11 | |
|---|
| | 12 | from django.db.backends import BaseDatabaseWrapper, BaseDatabaseFeatures, BaseDatabaseOperations, util |
|---|
| | 13 | import sys |
|---|
| | 14 | try: |
|---|
| | 15 | import decimal |
|---|
| | 16 | except ImportError: |
|---|
| | 17 | from django.utils import _decimal as decimal # for Python 2.3 |
|---|
| | 18 | |
|---|
| | 19 | try: |
|---|
| | 20 | import kinterbasdb as Database |
|---|
| | 21 | except ImportError, e: |
|---|
| | 22 | from django.core.exceptions import ImproperlyConfigured |
|---|
| | 23 | raise ImproperlyConfigured, "Error loading KInterbasDB module: %s" % e |
|---|
| | 24 | |
|---|
| | 25 | DatabaseError = Database.DatabaseError |
|---|
| | 26 | IntegrityError = Database.IntegrityError |
|---|
| | 27 | |
|---|
| | 28 | class DatabaseFeatures(BaseDatabaseFeatures): |
|---|
| | 29 | inline_fk_references = False |
|---|
| | 30 | needs_datetime_string_cast = False |
|---|
| | 31 | needs_upper_for_iops = True |
|---|
| | 32 | quote_autofields = True |
|---|
| | 33 | uses_custom_field = True |
|---|
| | 34 | uses_custom_queryset = True |
|---|
| | 35 | |
|---|
| | 36 | ################################################################################ |
|---|
| | 37 | # Database operations (db.connection.ops) |
|---|
| | 38 | class DatabaseOperations(BaseDatabaseOperations): |
|---|
| | 39 | """ |
|---|
| | 40 | This class encapsulates all backend-specific differences, such as the way |
|---|
| | 41 | a backend performs ordering or calculates the ID of a recently-inserted |
|---|
| | 42 | row. |
|---|
| | 43 | """ |
|---|
| | 44 | # Utility ops: names, version, page size etc.: |
|---|
| | 45 | _max_name_length = 31 |
|---|
| | 46 | def __init__(self): |
|---|
| | 47 | self._firebird_version = None |
|---|
| | 48 | self._page_size = None |
|---|
| | 49 | |
|---|
| | 50 | def get_generator_name(self, name): |
|---|
| | 51 | return '%s$G' % util.truncate_name(name.strip('"'), self._max_name_length-2).upper() |
|---|
| | 52 | |
|---|
| | 53 | def get_trigger_name(self, name): |
|---|
| | 54 | return '%s$T' % util.truncate_name(name.strip('"'), self._max_name_length-2).upper() |
|---|
| | 55 | |
|---|
| | 56 | def _get_firebird_version(self): |
|---|
| | 57 | if self._firebird_version is None: |
|---|
| | 58 | from django.db import connection |
|---|
| | 59 | self._firebird_version = [int(val) for val in connection.server_version.split()[-1].split('.')] |
|---|
| | 60 | return self._firebird_version |
|---|
| | 61 | firebird_version = property(_get_firebird_version) |
|---|
| | 62 | |
|---|
| | 63 | def reference_name(self, r_col, col, r_table, table): |
|---|
| | 64 | base_name = util.truncate_name('%s$%s' % (r_col, col), self._max_name_length-5) |
|---|
| | 65 | return ('%s$%x' % (base_name, abs(hash((r_table, table))))).upper() |
|---|
| | 66 | |
|---|
| | 67 | def _get_page_size(self): |
|---|
| | 68 | if self._page_size is None: |
|---|
| | 69 | from django.db import connection |
|---|
| | 70 | self._page_size = connection.database_info(Database.isc_info_page_size, 'i') |
|---|
| | 71 | return self._page_size |
|---|
| | 72 | page_size = property(_get_page_size) |
|---|
| | 73 | |
|---|
| | 74 | def _get_index_limit(self): |
|---|
| | 75 | if self.firebird_version[0] < 2: |
|---|
| | 76 | self._index_limit = 252 |
|---|
| | 77 | else: |
|---|
| | 78 | page_size = self._get_page_size() |
|---|
| | 79 | self._index_limit = page_size/4 |
|---|
| | 80 | return self._index_limit |
|---|
| | 81 | index_limit = property(_get_index_limit) |
|---|
| | 82 | |
|---|
| | 83 | def max_name_length(self): |
|---|
| | 84 | return self._max_name_length |
|---|
| | 85 | |
|---|
| | 86 | def quote_name(self, name): |
|---|
| | 87 | name = '"%s"' % util.truncate_name(name.strip('"'), self._max_name_length) |
|---|
| | 88 | return name |
|---|
| | 89 | |
|---|
| | 90 | def quote_id_plus_number(self, name): |
|---|
| | 91 | try: |
|---|
| | 92 | return '"%s" + %s' % tuple(s.strip() for s in name.strip('"').split('+')) |
|---|
| | 93 | except: |
|---|
| | 94 | return self.quote_name(name) |
|---|
| | 95 | |
|---|
| | 96 | def field_cast_sql(self, db_type): |
|---|
| | 97 | return '%s' |
|---|
| | 98 | |
|---|
| | 99 | ############################################################################ |
|---|
| | 100 | # Basic SQL ops: |
|---|
| | 101 | def last_insert_id(self, cursor, table_name, pk_name=None): |
|---|
| | 102 | generator_name = self.get_generator_name(table_name) |
|---|
| | 103 | cursor.execute('SELECT GEN_ID(%s, 0) from RDB$DATABASE' % generator_name) |
|---|
| | 104 | return cursor.fetchone()[0] |
|---|
| | 105 | |
|---|
| | 106 | def date_extract_sql(self, lookup_type, column_name): |
|---|
| | 107 | # lookup_type is 'year', 'month', 'day' |
|---|
| | 108 | return "EXTRACT(%s FROM %s)" % (lookup_type, column_name) |
|---|
| | 109 | |
|---|
| | 110 | def date_trunc_sql(self, lookup_type, column_name): |
|---|
| | 111 | if lookup_type == 'year': |
|---|
| | 112 | sql = "EXTRACT(year FROM %s)||'-01-01 00:00:00'" % column_name |
|---|
| | 113 | elif lookup_type == 'month': |
|---|
| | 114 | sql = "EXTRACT(year FROM %s)||'-'||EXTRACT(month FROM %s)||'-01 00:00:00'" % (column_name, column_name) |
|---|
| | 115 | elif lookup_type == 'day': |
|---|
| | 116 | sql = "EXTRACT(year FROM %s)||'-'||EXTRACT(month FROM %s)||'-'||EXTRACT(day FROM %s)||' 00:00:00'" % (column_name, column_name, column_name) |
|---|
| | 117 | return "CAST(%s AS TIMESTAMP)" % sql |
|---|
| | 118 | |
|---|
| | 119 | def datetime_cast_sql(self): |
|---|
| | 120 | return None |
|---|
| | 121 | |
|---|
| | 122 | def drop_sequence_sql(self, table): |
|---|
| | 123 | return "DROP GENERATOR %s;" % self.get_generator_name(table) |
|---|
| | 124 | |
|---|
| | 125 | def drop_foreignkey_sql(self): |
|---|
| | 126 | return "DROP CONSTRAINT" |
|---|
| | 127 | |
|---|
| | 128 | def limit_offset_sql(self, limit, offset=None): |
|---|
| | 129 | # limits are handled in custom FirebirdQuerySet |
|---|
| | 130 | assert False, 'Limits are handled in a different way in Firebird' |
|---|
| | 131 | return "" |
|---|
| | 132 | |
|---|
| | 133 | def random_function_sql(self): |
|---|
| | 134 | return "rand()" |
|---|
| | 135 | |
|---|
| | 136 | def pk_default_value(self): |
|---|
| | 137 | """ |
|---|
| | 138 | Returns the value to use during an INSERT statement to specify that |
|---|
| | 139 | the field should use its default value. |
|---|
| | 140 | """ |
|---|
| | 141 | return 'NULL' |
|---|
| | 142 | |
|---|
| | 143 | def start_transaction_sql(self): |
|---|
| | 144 | return "" |
|---|
| | 145 | |
|---|
| | 146 | def fulltext_search_sql(self, field_name): |
|---|
| | 147 | # We use varchar for TextFields so this is possible |
|---|
| | 148 | # Look at http://www.volny.cz/iprenosil/interbase/ip_ib_strings.htm |
|---|
| | 149 | return '%%s CONTAINING %s' % self.quote_name(field_name) |
|---|
| | 150 | |
|---|
| | 151 | ############################################################################ |
|---|
| | 152 | # Advanced SQL ops: |
|---|
| | 153 | def autoinc_sql(self, style, table_name, column_name): |
|---|
| | 154 | """ |
|---|
| | 155 | To simulate auto-incrementing primary keys in Firebird, we have to |
|---|
| | 156 | create a generator and a trigger. |
|---|
| | 157 | |
|---|
| | 158 | Create the generators and triggers names based only on table name |
|---|
| | 159 | since django only support one auto field per model |
|---|
| | 160 | """ |
|---|
| | 161 | |
|---|
| | 162 | generator_name = self.get_generator_name(table_name) |
|---|
| | 163 | trigger_name = self.get_trigger_name(table_name) |
|---|
| | 164 | column_name = self.quote_name(column_name) |
|---|
| | 165 | table_name = self.quote_name(table_name) |
|---|
| | 166 | |
|---|
| | 167 | generator_sql = "%s %s;" % ( style.SQL_KEYWORD('CREATE GENERATOR'), |
|---|
| | 168 | generator_name) |
|---|
| | 169 | trigger_sql = "\n".join([ |
|---|
| | 170 | "%s %s %s %s" % ( \ |
|---|
| | 171 | style.SQL_KEYWORD('CREATE TRIGGER'), trigger_name, style.SQL_KEYWORD('FOR'), |
|---|
| | 172 | style.SQL_TABLE(table_name)), |
|---|
| | 173 | "%s 0 %s" % (style.SQL_KEYWORD('ACTIVE BEFORE INSERT POSITION'), style.SQL_KEYWORD('AS')), |
|---|
| | 174 | style.SQL_KEYWORD('BEGIN'), |
|---|
| | 175 | " %s ((%s.%s %s) %s (%s.%s = 0)) %s" % ( \ |
|---|
| | 176 | style.SQL_KEYWORD('IF'), |
|---|
| | 177 | style.SQL_KEYWORD('NEW'), style.SQL_FIELD(column_name), style.SQL_KEYWORD('IS NULL'), |
|---|
| | 178 | style.SQL_KEYWORD('OR'), style.SQL_KEYWORD('NEW'), style.SQL_FIELD(column_name), |
|---|
| | 179 | style.SQL_KEYWORD('THEN') |
|---|
| | 180 | ), |
|---|
| | 181 | " %s" % style.SQL_KEYWORD('BEGIN'), |
|---|
| | 182 | " %s.%s = %s(%s, 1);" % ( \ |
|---|
| | 183 | style.SQL_KEYWORD('NEW'), style.SQL_FIELD(column_name), |
|---|
| | 184 | style.SQL_KEYWORD('GEN_ID'), generator_name |
|---|
| | 185 | ), |
|---|
| | 186 | " %s" % style.SQL_KEYWORD('END'), |
|---|
| | 187 | "%s;" % style.SQL_KEYWORD('END')]) |
|---|
| | 188 | return (generator_sql, trigger_sql) |
|---|
| | 189 | |
|---|
| | 190 | def sequence_reset_sql(self, style, model_list): |
|---|
| | 191 | from django.db import models |
|---|
| | 192 | output = [] |
|---|
| | 193 | sql = ['%s %s %s' % (style.SQL_KEYWORD('CREATE OR ALTER PROCEDURE'), |
|---|
| | 194 | style.SQL_TABLE('"GENERATOR_RESET"'), |
|---|
| | 195 | style.SQL_KEYWORD('AS'))] |
|---|
| | 196 | sql.append('%s %s' % (style.SQL_KEYWORD('DECLARE VARIABLE'), style.SQL_COLTYPE('start_val integer;'))) |
|---|
| | 197 | sql.append('%s %s' % (style.SQL_KEYWORD('DECLARE VARIABLE'), style.SQL_COLTYPE('gen_val integer;'))) |
|---|
| | 198 | sql.append('\t%s' % style.SQL_KEYWORD('BEGIN')) |
|---|
| | 199 | sql.append('\t\t%s %s %s %s %s %s;' % (style.SQL_KEYWORD('SELECT MAX'), style.SQL_FIELD('(%(col)s)'), |
|---|
| | 200 | style.SQL_KEYWORD('FROM'), style.SQL_TABLE('%(table)s'), |
|---|
| | 201 | style.SQL_KEYWORD('INTO'), style.SQL_COLTYPE(':start_val'))) |
|---|
| | 202 | sql.append('\t\t%s (%s %s) %s' % (style.SQL_KEYWORD('IF'), style.SQL_COLTYPE('start_val'), |
|---|
| | 203 | style.SQL_KEYWORD('IS NULL'), style.SQL_KEYWORD('THEN'))) |
|---|
| | 204 | sql.append('\t\t\t%s = %s(%s, 1 - %s(%s, 0));' %\ |
|---|
| | 205 | (style.SQL_COLTYPE('gen_val'), style.SQL_KEYWORD('GEN_ID'), style.SQL_TABLE('%(gen)s'), |
|---|
| | 206 | style.SQL_KEYWORD('GEN_ID'), style.SQL_TABLE('%(gen)s'))) |
|---|
| | 207 | sql.append('\t\t%s' % style.SQL_KEYWORD('ELSE')) |
|---|
| | 208 | sql.append('\t\t\t%s = %s(%s, %s - %s(%s, 0));' %\ |
|---|
| | 209 | (style.SQL_COLTYPE('gen_val'), style.SQL_KEYWORD('GEN_ID'), |
|---|
| | 210 | style.SQL_TABLE('%(gen)s'), style.SQL_COLTYPE('start_val'), style.SQL_KEYWORD('GEN_ID'), |
|---|
| | 211 | style.SQL_TABLE('%(gen)s'))) |
|---|
| | 212 | sql.append('\t\t%s;' % style.SQL_KEYWORD('EXIT')) |
|---|
| | 213 | sql.append('%s;' % style.SQL_KEYWORD('END')) |
|---|
| | 214 | sql ="\n".join(sql) |
|---|
| | 215 | for model in model_list: |
|---|
| | 216 | for f in model._meta.fields: |
|---|
| | 217 | if isinstance(f, models.AutoField): |
|---|
| | 218 | generator_name = self.get_generator_name(model._meta.db_table) |
|---|
| | 219 | column_name = self.quote_name(f.db_column or f.name) |
|---|
| | 220 | table_name = self.quote_name(model._meta.db_table) |
|---|
| | 221 | output.append(sql % {'col' : column_name, 'table' : table_name, 'gen' : generator_name}) |
|---|
| | 222 | output.append('%s %s;' % (style.SQL_KEYWORD('EXECUTE PROCEDURE'), |
|---|
| | 223 | style.SQL_TABLE('"GENERATOR_RESET"'))) |
|---|
| | 224 | break # Only one AutoField is allowed per model, so don't bother continuing. |
|---|
| | 225 | for f in model._meta.many_to_many: |
|---|
| | 226 | generator_name = self.get_generator_name(f.m2m_db_table()) |
|---|
| | 227 | table_name = self.quote_name(f.m2m_db_table()) |
|---|
| | 228 | column_name = '"id"' |
|---|
| | 229 | output.append(sql % {'col' : column_name, 'table' : table_name, 'gen' : generator_name}) |
|---|
| | 230 | output.append('%s %s;' % (style.SQL_KEYWORD('EXECUTE PROCEDURE'), |
|---|
| | 231 | style.SQL_TABLE('"GENERATOR_RESET"'))) |
|---|
| | 232 | return output |
|---|
| | 233 | |
|---|
| | 234 | def sql_flush(self, style, tables, sequences): |
|---|
| | 235 | if tables: |
|---|
| | 236 | sql = ['%s %s %s;' % \ |
|---|
| | 237 | (style.SQL_KEYWORD('DELETE'), |
|---|
| | 238 | style.SQL_KEYWORD('FROM'), |
|---|
| | 239 | style.SQL_TABLE(self.quote_name(table)) |
|---|
| | 240 | ) for table in tables] |
|---|
| | 241 | for generator_info in sequences: |
|---|
| | 242 | table_name = generator_info['table'] |
|---|
| | 243 | query = "%s %s %s 0;" % (style.SQL_KEYWORD('SET GENERATOR'), |
|---|
| | 244 | self.get_generator_name(table_name), style.SQL_KEYWORD('TO')) |
|---|
| | 245 | sql.append(query) |
|---|
| | 246 | return sql |
|---|
| | 247 | else: |
|---|
| | 248 | return [] |
|---|
| | 249 | |
|---|
| | 250 | ############################################################################ |
|---|
| | 251 | # Custom classes |
|---|
| | 252 | def field_class(this, DefaultField): |
|---|
| | 253 | from django.db import connection |
|---|
| | 254 | from django.db.models.fields import prep_for_like_query |
|---|
| | 255 | class FirebirdField(DefaultField): |
|---|
| | 256 | def get_db_prep_lookup(self, lookup_type, value): |
|---|
| | 257 | "Returns field's value prepared for database lookup." |
|---|
| | 258 | if lookup_type in ('exact', 'regex', 'iregex', 'gt', 'gte', 'lt', |
|---|
| | 259 | 'lte', 'month', 'day', 'search', 'icontains', |
|---|
| | 260 | 'startswith', 'istartswith'): |
|---|
| | 261 | return [value] |
|---|
| | 262 | elif lookup_type in ('range', 'in'): |
|---|
| | 263 | return value |
|---|
| | 264 | elif lookup_type in ('contains',): |
|---|
| | 265 | return ["%%%s%%" % prep_for_like_query(value)] |
|---|
| | 266 | elif lookup_type == 'iexact': |
|---|
| | 267 | return [prep_for_like_query(value)] |
|---|
| | 268 | elif lookup_type in ('endswith', 'iendswith'): |
|---|
| | 269 | return ["%%%s" % prep_for_like_query(value)] |
|---|
| | 270 | elif lookup_type == 'isnull': |
|---|
| | 271 | return [] |
|---|
| | 272 | elif lookup_type == 'year': |
|---|
| | 273 | try: |
|---|
| | 274 | value = int(value) |
|---|
| | 275 | except ValueError: |
|---|
| | 276 | raise ValueError("The __year lookup type requires an integer argument") |
|---|
| | 277 | return ['%s-01-01 00:00:00' % value, '%s-12-31 23:59:59.999999' % value] |
|---|
| | 278 | raise TypeError("Field has invalid lookup: %s" % lookup_type) |
|---|
| | 279 | return FirebirdField |
|---|
| | 280 | |
|---|
| | 281 | def query_set_class(this, DefaultQuerySet): |
|---|
| | 282 | from django.db import connection |
|---|
| | 283 | from django.db.models.query import EmptyResultSet, GET_ITERATOR_CHUNK_SIZE |
|---|
| | 284 | class FirebirdQuerySet(DefaultQuerySet): |
|---|
| | 285 | def _get_sql_clause(self): |
|---|
| | 286 | from django.db.models.query import SortedDict, handle_legacy_orderlist, orderfield2column, fill_table_cache |
|---|
| | 287 | qn = this.quote_name |
|---|
| | 288 | opts = self.model._meta |
|---|
| | 289 | |
|---|
| | 290 | # Construct the fundamental parts of the query: SELECT X FROM Y WHERE Z. |
|---|
| | 291 | select = ["%s.%s" % (qn(opts.db_table), qn(f.column)) for f in opts.fields] |
|---|
| | 292 | tables = [qn(t) for t in self._tables] |
|---|
| | 293 | joins = SortedDict() |
|---|
| | 294 | where = self._where[:] |
|---|
| | 295 | params = self._params[:] |
|---|
| | 296 | |
|---|
| | 297 | # Convert self._filters into SQL. |
|---|
| | 298 | joins2, where2, params2 = self._filters.get_sql(opts) |
|---|
| | 299 | joins.update(joins2) |
|---|
| | 300 | where.extend(where2) |
|---|
| | 301 | params.extend(params2) |
|---|
| | 302 | |
|---|
| | 303 | # Add additional tables and WHERE clauses based on select_related. |
|---|
| | 304 | if self._select_related: |
|---|
| | 305 | fill_table_cache(opts, select, tables, where, |
|---|
| | 306 | old_prefix=opts.db_table, |
|---|
| | 307 | cache_tables_seen=[opts.db_table], |
|---|
| | 308 | max_depth=self._max_related_depth) |
|---|
| | 309 | |
|---|
| | 310 | # Add any additional SELECTs. |
|---|
| | 311 | if self._select: |
|---|
| | 312 | select.extend([('(%s AS %s') % (qn(s[1]), qn(s[0])) for s in self._select.items()]) |
|---|
| | 313 | |
|---|
| | 314 | # Start composing the body of the SQL statement. |
|---|
| | 315 | sql = [" FROM", qn(opts.db_table)] |
|---|
| | 316 | |
|---|
| | 317 | # Compose the join dictionary into SQL describing the joins. |
|---|
| | 318 | if joins: |
|---|
| | 319 | sql.append(" ".join(["%s %s %s ON %s" % (join_type, table, alias, condition) |
|---|
| | 320 | for (alias, (table, join_type, condition)) in joins.items()])) |
|---|
| | 321 | |
|---|
| | 322 | # Compose the tables clause into SQL. |
|---|
| | 323 | if tables: |
|---|
| | 324 | sql.append(", " + ", ".join(tables)) |
|---|
| | 325 | |
|---|
| | 326 | # Compose the where clause into SQL. |
|---|
| | 327 | if where: |
|---|
| | 328 | sql.append(where and "WHERE " + " AND ".join(where)) |
|---|
| | 329 | |
|---|
| | 330 | # ORDER BY clause |
|---|
| | 331 | order_by = [] |
|---|
| | 332 | if self._order_by is not None: |
|---|
| | 333 | ordering_to_use = self._order_by |
|---|
| | 334 | else: |
|---|
| | 335 | ordering_to_use = opts.ordering |
|---|
| | 336 | for f in handle_legacy_orderlist(ordering_to_use): |
|---|
| | 337 | if f == '?': # Special case. |
|---|
| | 338 | order_by.append(connection.ops.random_function_sql()) |
|---|
| | 339 | else: |
|---|
| | 340 | if f.startswith('-'): |
|---|
| | 341 | col_name = f[1:] |
|---|
| | 342 | order = "DESC" |
|---|
| | 343 | else: |
|---|
| | 344 | col_name = f |
|---|
| | 345 | order = "ASC" |
|---|
| | 346 | if "." in col_name: |
|---|
| | 347 | table_prefix, col_name = col_name.split('.', 1) |
|---|
| | 348 | table_prefix = qn(table_prefix) + '.' |
|---|
| | 349 | else: |
|---|
| | 350 | # Use the database table as a column prefix if it wasn't given, |
|---|
| | 351 | # and if the requested column isn't a custom SELECT. |
|---|
| | 352 | if "." not in col_name and col_name not in (self._select or ()): |
|---|
| | 353 | table_prefix = qn(opts.db_table) + '.' |
|---|
| | 354 | else: |
|---|
| | 355 | table_prefix = '' |
|---|
| | 356 | order_by.append('%s%s %s' % \ |
|---|
| | 357 | (table_prefix, qn(orderfield2column(col_name, opts)), order)) |
|---|
| | 358 | if order_by: |
|---|
| | 359 | sql.append("ORDER BY " + ", ".join(order_by)) |
|---|
| | 360 | |
|---|
| | 361 | return select, " ".join(sql), params |
|---|
| | 362 | |
|---|
| | 363 | def iterator(self): |
|---|
| | 364 | "Performs the SELECT database lookup of this QuerySet." |
|---|
| | 365 | from django.db.models.query import get_cached_row |
|---|
| | 366 | try: |
|---|
| | 367 | select, sql, params = self._get_sql_clause() |
|---|
| | 368 | except EmptyResultSet: |
|---|
| | 369 | raise StopIteration |
|---|
| | 370 | |
|---|
| | 371 | # self._select is a dictionary, and dictionaries' key order is |
|---|
| | 372 | # undefined, so we convert it to a list of tuples. |
|---|
| | 373 | extra_select = self._select.items() |
|---|
| | 374 | |
|---|
| | 375 | cursor = connection.cursor() |
|---|
| | 376 | limit_offset_before = "" |
|---|
| | 377 | if self._limit is not None: |
|---|
| | 378 | limit_offset_before += "FIRST %s " % self._limit |
|---|
| | 379 | if self._offset: |
|---|
| | 380 | limit_offset_before += "SKIP %s " % self._offset |
|---|
| | 381 | else: |
|---|
| | 382 | assert self._offset is None, "'offset' is not allowed without 'limit'" |
|---|
| | 383 | cursor.execute("SELECT " + limit_offset_before + (self._distinct and "DISTINCT " or "") + ",".join(select) + sql, params) |
|---|
| | 384 | fill_cache = self._select_related |
|---|
| | 385 | fields = self.model._meta.fields |
|---|
| | 386 | index_end = len(fields) |
|---|
| | 387 | while 1: |
|---|
| | 388 | rows = cursor.fetchmany(GET_ITERATOR_CHUNK_SIZE) |
|---|
| | 389 | if not rows: |
|---|
| | 390 | raise StopIteration |
|---|
| | 391 | for row in rows: |
|---|
| | 392 | row = self.resolve_columns(row, fields) |
|---|
| | 393 | if fill_cache: |
|---|
| | 394 | obj, index_end = get_cached_row(klass=self.model, row=row, |
|---|
| | 395 | index_start=0, max_depth=self._max_related_depth) |
|---|
| | 396 | else: |
|---|
| | 397 | obj = self.model(*row[:index_end]) |
|---|
| | 398 | for i, k in enumerate(extra_select): |
|---|
| | 399 | setattr(obj, k[0], row[index_end+i]) |
|---|
| | 400 | yield obj |
|---|
| | 401 | |
|---|
| | 402 | def resolve_columns(self, row, fields=()): |
|---|
| | 403 | from django.db.models.fields import DateField, DateTimeField, \ |
|---|
| | 404 | TimeField, BooleanField, NullBooleanField, DecimalField, Field |
|---|
| | 405 | values = [] |
|---|
| | 406 | for value, field in map(None, row, fields): |
|---|
| | 407 | # Convert 1 or 0 to True or False |
|---|
| | 408 | if value in (1, 0) and isinstance(field, (BooleanField, NullBooleanField)): |
|---|
| | 409 | value = bool(value) |
|---|
| | 410 | |
|---|
| | 411 | values.append(value) |
|---|
| | 412 | return values |
|---|
| | 413 | |
|---|
| | 414 | def extra(self, select=None, where=None, params=None, tables=None): |
|---|
| | 415 | assert self._limit is None and self._offset is None, \ |
|---|
| | 416 | "Cannot change a query once a slice has been taken" |
|---|
| | 417 | clone = self._clone() |
|---|
| | 418 | qn = this.quote_name |
|---|
| | 419 | if select: clone._select.update(select) |
|---|
| | 420 | if where: |
|---|
| | 421 | qn_where = [] |
|---|
| | 422 | for where_item in where: |
|---|
| | 423 | try: |
|---|
| | 424 | table, col_exact = where_item.split(".") |
|---|
| | 425 | col, value = col_exact.split("=") |
|---|
| | 426 | where_item = "%s.%s = %s" % (qn(table.strip()), |
|---|
| | 427 | qn(col.strip()), value.strip()) |
|---|
| | 428 | except: |
|---|
| | 429 | try: |
|---|
| | 430 | table, value = where_item.split("=") |
|---|
| | 431 | where_item = "%s = %s" % (qn(table.strip()), qn(value.strip())) |
|---|
| | 432 | except: |
|---|
| | 433 | raise TypeError, "Can't understand extra WHERE clause: %s" % where |
|---|
| | 434 | qn_where.append(where_item) |
|---|
| | 435 | clone._where.extend(qn_where) |
|---|
| | 436 | if params: clone._params.extend(params) |
|---|
| | 437 | if tables: clone._tables.extend(tables) |
|---|
| | 438 | return clone |
|---|
| | 439 | |
|---|
| | 440 | return FirebirdQuerySet |
|---|
| | 441 | |
|---|
| | 442 | ################################################################################ |
|---|
| | 443 | # Cursor wrapper |
|---|
| | 444 | class FirebirdCursorWrapper(object): |
|---|
| | 445 | """ |
|---|
| | 446 | Django uses "format" ('%s') style placeholders, but firebird uses "qmark" ('?') style. |
|---|
| | 447 | This fixes it -- but note that if you want to use a literal "%s" in a query, |
|---|
| | 448 | you'll need to use "%%s". |
|---|
| | 449 | |
|---|
| | 450 | We also do all automatic type conversions here. |
|---|
| | 451 | """ |
|---|
| | 452 | import kinterbasdb.typeconv_datetime_stdlib as tc_dt |
|---|
| | 453 | import kinterbasdb.typeconv_fixed_decimal as tc_fd |
|---|
| | 454 | import kinterbasdb.typeconv_text_unicode as tc_tu |
|---|
| | 455 | import django.utils.encoding as dj_ue |
|---|
| | 456 | |
|---|
| | 457 | def ascii_conv_in(self, text): |
|---|
| | 458 | if text is not None: |
|---|
| | 459 | return self.dj_ue.smart_str(text, 'ascii') |
|---|
| | 460 | |
|---|
| | 461 | def ascii_conv_out(self, text): |
|---|
| | 462 | if text is not None: |
|---|
| | 463 | return self.dj_ue.smart_unicode(text) |
|---|
| | 464 | |
|---|
| | 465 | def blob_conv_in(self, text): |
|---|
| | 466 | return self.tc_tu.unicode_conv_in((self.dj_ue.smart_unicode(text), self.FB_CHARSET_CODE)) |
|---|
| | 467 | |
|---|
| | 468 | def blob_conv_out(self, text): |
|---|
| | 469 | return self.tc_tu.unicode_conv_out((text, self.FB_CHARSET_CODE)) |
|---|
| | 470 | |
|---|
| | 471 | def fixed_conv_in(self, (val, scale)): |
|---|
| | 472 | if val is not None: |
|---|
| | 473 | if isinstance(val, basestring): |
|---|
| | 474 | val = decimal.Decimal(val) |
|---|
| | 475 | return self.tc_fd.fixed_conv_in_precise((val, scale)) |
|---|
| | 476 | |
|---|
| | 477 | def timestamp_conv_in(self, timestamp): |
|---|
| | 478 | if isinstance(timestamp, basestring): |
|---|
| | 479 | #Replaces 6 digits microseconds to 4 digits allowed in Firebird |
|---|
| | 480 | timestamp = timestamp[:24] |
|---|
| | 481 | return self.tc_dt.timestamp_conv_in(timestamp) |
|---|
| | 482 | |
|---|
| | 483 | def time_conv_in(self, value): |
|---|
| | 484 | import datetime |
|---|
| | 485 | if isinstance(value, datetime.datetime): |
|---|
| | 486 | value = datetime.time(value.hour, value.minute, value.second, value.microsecond) |
|---|
| | 487 | |
|---|
| | 488 | def unicode_conv_in(self, text): |
|---|
| | 489 | if text[0] is not None: |
|---|
| | 490 | return self.tc_tu.unicode_conv_in((self.dj_ue.smart_unicode(text[0]), self.FB_CHARSET_CODE)) |
|---|
| | 491 | |
|---|
| | 492 | def __init__(self, cursor, connection): |
|---|
| | 493 | self.cursor = cursor |
|---|
| | 494 | self._connection = connection |
|---|
| | 495 | self._statement = None #prepared statement |
|---|
| | 496 | self.FB_CHARSET_CODE = 3 #UNICODE_FSS |
|---|
| | 497 | if connection.charset == 'UTF8': |
|---|
| | 498 | self.FB_CHARSET_CODE = 4 # UTF-8 with Firebird 2.0+ |
|---|
| | 499 | self.cursor.set_type_trans_in({ |
|---|
| | 500 | 'DATE': self.tc_dt.date_conv_in, |
|---|
| | 501 | 'TIME': self.time_conv_in, |
|---|
| | 502 | 'TIMESTAMP': self.timestamp_conv_in, |
|---|
| | 503 | 'FIXED': self.fixed_conv_in, |
|---|
| | 504 | 'TEXT': self.ascii_conv_in, |
|---|
| | 505 | 'TEXT_UNICODE': self.unicode_conv_in, |
|---|
| | 506 | 'BLOB': self.blob_conv_in |
|---|
| | 507 | }) |
|---|
| | 508 | self.cursor.set_ty |
|---|