def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) try: # django < 1.3 self.features = DatabaseFeatures() except TypeError: # django >= 1.3 self.features = DatabaseFeatures(self) try: self.ops = DatabaseOperations() except TypeError: self.ops = DatabaseOperations(self) self.client = BaseDatabaseClient(self) self.creation = DatabaseCreation(self) self.introspection = DatabaseIntrospection(self) self.validation = BaseDatabaseValidation(self) try: self.command_timeout = int(self.settings_dict.get('COMMAND_TIMEOUT', 30)) except ValueError: self.command_timeout = 30 try: options = self.settings_dict.get('OPTIONS', {}) self.cast_avg_to_float = not bool(options.get('disable_avg_cast', False)) self.autocommit = bool(options.get('autocommit', False)) except ValueError: self.cast_avg_to_float = False
def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) self.features = DatabaseFeatures(self) self.features.uses_autocommit = True #self.settings_dict["OPTIONS"].get('autocommit', False) # if self.features.uses_autocommit: # self._set_isolation_level(extensions.ISOLATION_LEVEL_AUTOCOMMIT) # else: # self._set_isolation_level(extensions.ISOLATION_LEVEL_READ_COMMITTED) self.ops = DatabaseOperations(self) self.client = DatabaseClient(self) self.creation = DatabaseCreation(self) self.introspection = DatabaseIntrospection(self) self.validation = BaseDatabaseValidation(self) self._pg_version = None
def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) self.db_config = args[0] client_class = self.db_config['CLIENT'] client_class = import_string(client_class) self.db_name = self.db_config['NAME'] self.client = client_class(self.db_config) schema_module = self.db_config.get('SCHEMA', None) self.migrations = self.db_config.get('MIGRATIONS', False) if schema_module: self.SchemaEditorClass = import_string(schema_module + '.DatabaseSchemaEditor') self._cache = import_module(self.client.compiler_module) self.ops = DatabaseOperations(self, cache=self._cache) self.creation = DatabaseCreation(self) self.features = DatabaseFeatures(self) self.validation = BaseDatabaseValidation(self) introspection_module = self.db_config.get('INTROSPECTION', None) if introspection_module: self.introspectionClass = import_string(introspection_module + '.DatabaseIntrospection') self.introspection = self.introspectionClass(self) else: self.introspection = DatabaseIntrospection(self) logger.debug( 'Initialized django_any_backend. Compiler is %s. Client is %s.' % (self.client.compiler_module, client_class)) logger.debug('DB_config: %s' % self.db_config)
def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) self.features = DatabaseFeatures(self) self.ops = DatabaseOperations(self) self.client = DatabaseClient(self) self.creation = DatabaseCreation(self) self.introspection = DatabaseIntrospection(self) self.validation = BaseDatabaseValidation(self) self.connection = None
def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) self.features = DatabaseFeatures(self) autocommit = self.settings_dict["OPTIONS"].get('autocommit', False) self.features.uses_autocommit = autocommit self.ops = DatabaseOperations(self) self.client = DatabaseClient(self) self.creation = DatabaseCreation(self) self.introspection = DatabaseIntrospection(self) self.validation = BaseDatabaseValidation(self) self._nuodb_version = None self.Database = Database
def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) self.features = DatabaseFeatures() self.ops = DatabaseOperations() self.client = BaseDatabaseClient(self) self.creation = DatabaseCreation(self) self.introspection = DatabaseIntrospection(self) self.validation = BaseDatabaseValidation(self) try: self.command_timeout = int(self.settings_dict.get('COMMAND_TIMEOUT', 30)) except ValueError: self.command_timeout = 30
def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) self.features = DatabaseFeatures(self) self.features.uses_autocommit = True#self.settings_dict["OPTIONS"].get('autocommit', False) # if self.features.uses_autocommit: # self._set_isolation_level(extensions.ISOLATION_LEVEL_AUTOCOMMIT) # else: # self._set_isolation_level(extensions.ISOLATION_LEVEL_READ_COMMITTED) self.ops = DatabaseOperations(self) self.client = DatabaseClient(self) self.creation = DatabaseCreation(self) self.introspection = DatabaseIntrospection(self) self.validation = BaseDatabaseValidation(self) self._pg_version = None
def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) if "DATABASE_ENGINE" in args: self.settings_dict = args else: self.settings_dict=args[0] if 'DATABASE_OPTIONS' in args: self.MARS_Connection = self.settings_dict['DATABASE_OPTIONS'].get('MARS_Connection', False) self.datefirst = self.settings_dict['DATABASE_OPTIONS'].get('datefirst', 7) self.unicode_results = self.settings_dict['DATABASE_OPTIONS'].get('unicode_results', False) self.features = DatabaseFeatures() self.ops = DatabaseOperations(self.settings_dict) self.client = DatabaseClient(self) self.creation = DatabaseCreation(self) self.introspection = DatabaseIntrospection(self) if _DJANGO_VERSION >= 12: self.validation = BaseDatabaseValidation(self) else: self.validation = BaseDatabaseValidation() self.connection = None
class DatabaseWrapper(BaseDatabaseWrapper): vendor = 'postgresql' operators = { 'exact': '= %s', 'iexact': '= UPPER(%s)', 'contains': 'LIKE %s', 'icontains': 'LIKE UPPER(%s)', 'regex': '~ %s', 'iregex': '~* %s', 'gt': '> %s', 'gte': '>= %s', 'lt': '< %s', 'lte': '<= %s', 'startswith': 'LIKE %s', 'endswith': 'LIKE %s', 'istartswith': 'LIKE UPPER(%s)', 'iendswith': 'LIKE UPPER(%s)', } def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) self.features = DatabaseFeatures(self) self.features.uses_autocommit = True #self.settings_dict["OPTIONS"].get('autocommit', False) # if self.features.uses_autocommit: # self._set_isolation_level(extensions.ISOLATION_LEVEL_AUTOCOMMIT) # else: # self._set_isolation_level(extensions.ISOLATION_LEVEL_READ_COMMITTED) self.ops = DatabaseOperations(self) self.client = DatabaseClient(self) self.creation = DatabaseCreation(self) self.introspection = DatabaseIntrospection(self) self.validation = BaseDatabaseValidation(self) self._pg_version = None def check_constraints(self, table_names=None): """ To check constraints, we set constraints to immediate. Then, when, we're done we must ensure they are returned to deferred. """ self.cursor().execute('SET CONSTRAINTS ALL IMMEDIATE') self.cursor().execute('SET CONSTRAINTS ALL DEFERRED') def close(self): self.validate_thread_sharing() if self.connection is None: return try: self.connection.close() self.connection = None except Database.Error: # In some cases (database restart, network connection lost etc...) # the connection to the database is lost without giving Django a # notification. If we don't set self.connection to None, the error # will occur a every request. self.connection = None logger.warning('pygresql error while closing the connection.', exc_info=sys.exc_info()) raise def _get_pg_version(self): if self._pg_version is None: self._pg_version = get_version(self.connection) return self._pg_version pg_version = property(_get_pg_version) def _cursor(self): settings_dict = self.settings_dict if self.connection is None: if settings_dict['NAME'] == '': from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured( "You need to specify NAME in your Django settings file.") options = settings_dict['OPTIONS'] if 'autocommit' in options: del options['autocommit'] if options: dsn = '::::%s:' % str(options) else: dsn = None conn_params = { 'database': settings_dict['NAME'], } if settings_dict['USER']: conn_params['user'] = settings_dict['USER'] if settings_dict['PASSWORD']: conn_params['password'] = settings_dict['PASSWORD'] if settings_dict['HOST']: conn_params['host'] = settings_dict['HOST'] if settings_dict['PORT'] and int(settings_dict['PORT']) > 0: conn_params['host'] += ":%d" % int(settings_dict['PORT']) # isolation_level = self.isolation_level self.connection = Database.connect(dsn, **conn_params) self.connection.cursor().execute( self.ops.set_client_encoding('UTF8')) tz = 'UTC' if settings.USE_TZ else settings_dict.get('TIME_ZONE') if tz: # Set the time zone in autocommit mode # self._set_isolation_level( # extensions.ISOLATION_LEVEL_AUTOCOMMIT) self.connection.cursor().execute(self.ops.set_time_zone_sql(), [tz]) # self._set_isolation_level(isolation_level) self._get_pg_version() connection_created.send(sender=self.__class__, connection=self) cursor = PyGreSQLCursor(self.connection) # cursor.tzinfo_factory = utc_tzinfo_factory if settings.USE_TZ else None return CursorWrapper(cursor) def _enter_transaction_management(self, managed): """ Switch the isolation level when needing transaction support, so that the same transaction is visible across all the queries. """ # if self.features.uses_autocommit and managed and not self.isolation_level: # self._set_isolation_level(extensions.ISOLATION_LEVEL_READ_COMMITTED) pass def _leave_transaction_management(self, managed): """ If the normal operating mode is "autocommit", switch back to that when leaving transaction management. """ # if self.features.uses_autocommit and not managed and self.isolation_level: # self._set_isolation_level(extensions.ISOLATION_LEVEL_AUTOCOMMIT) pass def _set_isolation_level(self, level): """ Do all the related feature configurations for changing isolation levels. This doesn't touch the uses_autocommit feature, since that controls the movement *between* isolation levels. """ # assert level in range(1,5) # try: # if self.connection is not None: # if level == extensions.ISOLATION_LEVEL_AUTOCOMMIT: # self.connection.cursor.commit() # else: # # self.connection.cursor.autocommit = False # self.connection.cursor.commit() # self.connection.cursor().execute(self.ops.isolation_level_sql(level)) # finally: # self.isolation_level = level # self.features.uses_savepoints = bool(level) pass def _commit(self): if self.connection is not None: try: return self.connection.commit() except Database.IntegrityError, e: raise utils.IntegrityError, utils.IntegrityError( *tuple(e)), sys.exc_info()[2]
class DatabaseWrapper(BaseDatabaseWrapper): vendor = 'postgresql' operators = { 'exact': '= %s', 'iexact': '= UPPER(%s)', 'contains': 'LIKE %s', 'icontains': 'LIKE UPPER(%s)', 'regex': '~ %s', 'iregex': '~* %s', 'gt': '> %s', 'gte': '>= %s', 'lt': '< %s', 'lte': '<= %s', 'startswith': 'LIKE %s', 'endswith': 'LIKE %s', 'istartswith': 'LIKE UPPER(%s)', 'iendswith': 'LIKE UPPER(%s)', } def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) self.features = DatabaseFeatures(self) self.features.uses_autocommit = True#self.settings_dict["OPTIONS"].get('autocommit', False) # if self.features.uses_autocommit: # self._set_isolation_level(extensions.ISOLATION_LEVEL_AUTOCOMMIT) # else: # self._set_isolation_level(extensions.ISOLATION_LEVEL_READ_COMMITTED) self.ops = DatabaseOperations(self) self.client = DatabaseClient(self) self.creation = DatabaseCreation(self) self.introspection = DatabaseIntrospection(self) self.validation = BaseDatabaseValidation(self) self._pg_version = None def check_constraints(self, table_names=None): """ To check constraints, we set constraints to immediate. Then, when, we're done we must ensure they are returned to deferred. """ self.cursor().execute('SET CONSTRAINTS ALL IMMEDIATE') self.cursor().execute('SET CONSTRAINTS ALL DEFERRED') def close(self): self.validate_thread_sharing() if self.connection is None: return try: self.connection.close() self.connection = None except Database.Error: # In some cases (database restart, network connection lost etc...) # the connection to the database is lost without giving Django a # notification. If we don't set self.connection to None, the error # will occur a every request. self.connection = None logger.warning('pygresql error while closing the connection.', exc_info=sys.exc_info() ) raise def _get_pg_version(self): if self._pg_version is None: self._pg_version = get_version(self.connection) return self._pg_version pg_version = property(_get_pg_version) def _cursor(self): settings_dict = self.settings_dict if self.connection is None: if settings_dict['NAME'] == '': from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured("You need to specify NAME in your Django settings file.") options = settings_dict['OPTIONS'] if 'autocommit' in options: del options['autocommit'] if options: dsn = '::::%s:' % str(options) else: dsn = None conn_params = { 'database': settings_dict['NAME'], } if settings_dict['USER']: conn_params['user'] = settings_dict['USER'] if settings_dict['PASSWORD']: conn_params['password'] = settings_dict['PASSWORD'] if settings_dict['HOST']: conn_params['host'] = settings_dict['HOST'] if settings_dict['PORT'] and int(settings_dict['PORT']) > 0: conn_params['host'] += ":%d" % int(settings_dict['PORT']) # isolation_level = self.isolation_level self.connection = Database.connect(dsn, **conn_params) self.connection.cursor().execute(self.ops.set_client_encoding('UTF8')) tz = 'UTC' if settings.USE_TZ else settings_dict.get('TIME_ZONE') if tz: # Set the time zone in autocommit mode # self._set_isolation_level( # extensions.ISOLATION_LEVEL_AUTOCOMMIT) self.connection.cursor().execute( self.ops.set_time_zone_sql(), [tz]) # self._set_isolation_level(isolation_level) self._get_pg_version() connection_created.send(sender=self.__class__, connection=self) cursor = PyGreSQLCursor(self.connection) # cursor.tzinfo_factory = utc_tzinfo_factory if settings.USE_TZ else None return CursorWrapper(cursor) def _enter_transaction_management(self, managed): """ Switch the isolation level when needing transaction support, so that the same transaction is visible across all the queries. """ # if self.features.uses_autocommit and managed and not self.isolation_level: # self._set_isolation_level(extensions.ISOLATION_LEVEL_READ_COMMITTED) pass def _leave_transaction_management(self, managed): """ If the normal operating mode is "autocommit", switch back to that when leaving transaction management. """ # if self.features.uses_autocommit and not managed and self.isolation_level: # self._set_isolation_level(extensions.ISOLATION_LEVEL_AUTOCOMMIT) pass def _set_isolation_level(self, level): """ Do all the related feature configurations for changing isolation levels. This doesn't touch the uses_autocommit feature, since that controls the movement *between* isolation levels. """ # assert level in range(1,5) # try: # if self.connection is not None: # if level == extensions.ISOLATION_LEVEL_AUTOCOMMIT: # self.connection.cursor.commit() # else: # # self.connection.cursor.autocommit = False # self.connection.cursor.commit() # self.connection.cursor().execute(self.ops.isolation_level_sql(level)) # finally: # self.isolation_level = level # self.features.uses_savepoints = bool(level) pass def _commit(self): if self.connection is not None: try: return self.connection.commit() except Database.IntegrityError, e: raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
class DatabaseWrapper(BaseDatabaseWrapper): drv_name = None driver_needs_utf8 = None MARS_Connection = False unicode_results = False datefirst = 7 # Collations: http://msdn2.microsoft.com/en-us/library/ms184391.aspx # http://msdn2.microsoft.com/en-us/library/ms179886.aspx # T-SQL LIKE: http://msdn2.microsoft.com/en-us/library/ms179859.aspx # Full-Text search: http://msdn2.microsoft.com/en-us/library/ms142571.aspx # CONTAINS: http://msdn2.microsoft.com/en-us/library/ms187787.aspx # FREETEXT: http://msdn2.microsoft.com/en-us/library/ms176078.aspx operators = { # Since '=' is used not only for string comparision there is no way # to make it case (in)sensitive. It will simply fallback to the # database collation. 'exact': '= %s', 'iexact': "= UPPER(%s)", 'contains': "LIKE %s ESCAPE '\\' COLLATE " + collation, 'icontains': "LIKE UPPER(%s) ESCAPE '\\' COLLATE "+ collation, 'gt': '> %s', 'gte': '>= %s', 'lt': '< %s', 'lte': '<= %s', 'startswith': "LIKE %s ESCAPE '\\' COLLATE " + collation, 'endswith': "LIKE %s ESCAPE '\\' COLLATE " + collation, 'istartswith': "LIKE UPPER(%s) ESCAPE '\\' COLLATE " + collation, 'iendswith': "LIKE UPPER(%s) ESCAPE '\\' COLLATE " + collation, # TODO: remove, keep native T-SQL LIKE wildcards support # or use a "compatibility layer" and replace '*' with '%' # and '.' with '_' 'regex': 'LIKE %s COLLATE ' + collation, 'iregex': 'LIKE %s COLLATE ' + collation, # TODO: freetext, full-text contains... } def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) if "DATABASE_ENGINE" in args: self.settings_dict = args else: self.settings_dict=args[0] if 'DATABASE_OPTIONS' in args: self.MARS_Connection = self.settings_dict['DATABASE_OPTIONS'].get('MARS_Connection', False) self.datefirst = self.settings_dict['DATABASE_OPTIONS'].get('datefirst', 7) self.unicode_results = self.settings_dict['DATABASE_OPTIONS'].get('unicode_results', False) self.features = DatabaseFeatures() self.ops = DatabaseOperations(self.settings_dict) self.client = DatabaseClient(self) self.creation = DatabaseCreation(self) self.introspection = DatabaseIntrospection(self) if _DJANGO_VERSION >= 12: self.validation = BaseDatabaseValidation(self) else: self.validation = BaseDatabaseValidation() self.connection = None def _cursor(self): new_conn = False settings_dict = self.settings_dict db_str, user_str, passwd_str, port_str = None, None, None, None options = settings_dict['DATABASE_OPTIONS'] if settings_dict['DATABASE_NAME']: db_str = settings_dict['DATABASE_NAME'] if settings_dict['DATABASE_HOST']: host_str = settings_dict['DATABASE_HOST'] else: host_str = 'localhost' if settings_dict['DATABASE_USER']: user_str = settings_dict['DATABASE_USER'] if settings_dict['DATABASE_PASSWORD']: passwd_str = settings_dict['DATABASE_PASSWORD'] if settings_dict['DATABASE_PORT']: port_str = settings_dict['DATABASE_PORT'] if self.connection is None: new_conn = True if not db_str: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured('You need to specify NAME in your Django settings file.') cstr_parts = [] if 'driver' in options: driver = options['driver'] else: if os.name == 'nt': driver = 'SQL Server' else: driver = 'FreeTDS' if 'dsn' in options: cstr_parts.append('DSN=%s' % options['dsn']) else: # Only append DRIVER if DATABASE_ODBC_DSN hasn't been set cstr_parts.append('DRIVER={%s}' % driver) if os.name == 'nt' or driver == 'FreeTDS' and \ options.get('host_is_server', False): if port_str: host_str += ',%s' % port_str cstr_parts.append('SERVER=%s' % host_str) else: cstr_parts.append('SERVERNAME=%s' % host_str) if user_str: cstr_parts.append('UID=%s;PWD=%s' % (user_str, passwd_str)) else: if driver in ('SQL Server', 'SQL Native Client'): cstr_parts.append('Trusted_Connection=yes') else: cstr_parts.append('Integrated Security=SSPI') cstr_parts.append('DATABASE=%s' % db_str) if self.MARS_Connection: cstr_parts.append('MARS_Connection=yes') if 'extra_params' in options: cstr_parts.append(options['extra_params']) connstr = ';'.join(cstr_parts) autocommit = options.get('autocommit', False) if self.unicode_results: self.connection = Database.connect(connstr, autocommit=autocommit, unicode_results='True') else: self.connection = Database.connect(connstr, autocommit=autocommit) connection_created.send(sender=self.__class__) cursor = self.connection.cursor() if new_conn: # Set date format for the connection. Also, make sure Sunday is # considered the first day of the week (to be consistent with the # Django convention for the 'week_day' Django lookup) if the user # hasn't told us otherwise cursor.execute("SET DATEFORMAT ymd; SET DATEFIRST %s" % self.datefirst) if self.ops._get_sql_server_ver(self.connection) < 2005: self.creation.data_types['TextField'] = 'ntext' if self.driver_needs_utf8 is None: self.driver_needs_utf8 = True self.drv_name = self.connection.getinfo(Database.SQL_DRIVER_NAME).upper() if self.drv_name in ('SQLSRV32.DLL', 'SQLNCLI.DLL', 'SQLNCLI10.DLL'): self.driver_needs_utf8 = False # http://msdn.microsoft.com/en-us/library/ms131686.aspx if self.ops._get_sql_server_ver(self.connection) >= 2005 and self.drv_name in ('SQLNCLI.DLL', 'SQLNCLI10.DLL') and self.MARS_Connection: # How to to activate it: Add 'MARS_Connection': True # to the DATABASE_OPTIONS dictionary setting self.features.can_use_chunked_reads = True # FreeTDS can't execute some sql queries like CREATE DATABASE etc. # in multi-statement, so we need to commit the above SQL sentence(s) # to avoid this if self.drv_name.startswith('LIBTDSODBC') and not self.connection.autocommit: self.connection.commit() return CursorWrapper(cursor, self.driver_needs_utf8)