def _cursor(self): if not self._valid_connection(): kwargs = {"conv": django_conversions, "charset": "utf8", "use_unicode": True} settings_dict = self.settings_dict if settings_dict["USER"]: kwargs["user"] = settings_dict["USER"] if settings_dict["NAME"]: kwargs["db"] = settings_dict["NAME"] if settings_dict["PASSWORD"]: kwargs["passwd"] = settings_dict["PASSWORD"] if settings_dict["HOST"].startswith("/"): kwargs["unix_socket"] = settings_dict["HOST"] elif settings_dict["HOST"]: kwargs["host"] = settings_dict["HOST"] if settings_dict["PORT"]: kwargs["port"] = int(settings_dict["PORT"]) # We need the number of potentially affected rows after an # "UPDATE", not the number of changed rows. kwargs["client_flag"] = CLIENT.FOUND_ROWS kwargs.update(settings_dict["OPTIONS"]) self.connection = Database.connect(**kwargs) self.connection.encoders[SafeUnicode] = self.connection.encoders[unicode] self.connection.encoders[SafeString] = self.connection.encoders[str] connection_created.send(sender=self.__class__, connection=self) cursor = CursorWrapper(self.connection.cursor()) return cursor
def _cursor(self): if self.connection is None: settings_dict = self.settings_dict if settings_dict['NAME'] == '': from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured( "settings.DATABASES is improperly configured. " "Please supply the NAME value.") conn_params = {'charset': 'UTF8'} conn_params['dsn'] = settings_dict['NAME'] if settings_dict['HOST']: conn_params['dsn'] = ('%s:%s') % (settings_dict['HOST'], conn_params['dsn']) if settings_dict['PORT']: conn_params['port'] = settings_dict['PORT'] if settings_dict['USER']: conn_params['user'] = settings_dict['USER'] if settings_dict['PASSWORD']: conn_params['password'] = settings_dict['PASSWORD'] options = settings_dict['OPTIONS'].copy() conn_params.update(options) self._db_charset = conn_params.get('charset') self.encoding = charset_map.get(self._db_charset, 'utf_8') self.connection = Database.connect(**conn_params) connection_created.send(sender=self.__class__) return FirebirdCursorWrapper(self.connection.cursor(), self.encoding)
def _cursor(self): if not self.pool: kwargs = { 'conv': django_conversions, 'charset': 'utf8', 'use_unicode': True, } settings_dict = self.settings_dict if settings_dict['USER']: kwargs['user'] = settings_dict['USER'] if settings_dict['NAME']: kwargs['db'] = settings_dict['NAME'] if settings_dict['PASSWORD']: kwargs['passwd'] = settings_dict['PASSWORD'] if settings_dict['HOST'].startswith('/'): kwargs['unix_socket'] = settings_dict['HOST'] elif settings_dict['HOST']: kwargs['host'] = settings_dict['HOST'] if settings_dict['PORT']: kwargs['port'] = int(settings_dict['PORT']) kwargs['client_flag'] = CLIENT.FOUND_ROWS kwargs.update(settings_dict['OPTIONS']) self.pool = eventlet.db_pool.TpooledConnectionPool(MySQLdb, min_size=1, max_size=16, **kwargs) if not self._valid_connection(): self.connection = self.pool.get() connection_created.send(sender=self.__class__) cursor = mysqldb_base.CursorWrapper(self.connection.cursor()) return cursor
def _cursor(self): if self.connection is None: self.connection = self.pool.getconn() self.connection.set_client_encoding('UTF8') tz = 'UTC' if settings.USE_TZ else self.settings_dict.get( 'TIME_ZONE') if tz: try: get_parameter_status = self.connection.get_parameter_status except AttributeError: # psycopg2 < 2.0.12 doesn't have get_parameter_status conn_tz = None else: conn_tz = get_parameter_status('TimeZone') if conn_tz != tz: # Set the time zone in autocommit mode (see #17062) self.connection.set_isolation_level( psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) self.connection.cursor().execute( self.ops.set_time_zone_sql(), [tz]) self.connection.set_isolation_level(self.isolation_level) self._get_pg_version() connection_created.send(sender=self.__class__, connection=self) cursor = self.connection.cursor() cursor.tzinfo_factory = utc_tzinfo_factory if settings.USE_TZ else None return CursorWrapper(cursor)
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.") conn_params = { 'database': settings_dict['NAME'], } conn_params.update(settings_dict['OPTIONS']) if 'autocommit' in conn_params: del conn_params['autocommit'] 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']: conn_params['port'] = settings_dict['PORT'] self.connection = Database.connect(**conn_params) self.connection.set_client_encoding('UTF8') # Set the time zone in autocommit mode (see #17062) tz = 'UTC' if settings.USE_TZ else settings_dict.get('TIME_ZONE') if tz: self.connection.set_isolation_level( psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) self.connection.cursor().execute("SET TIME ZONE %s", [tz]) self.connection.set_isolation_level(self.isolation_level) self._get_pg_version() connection_created.send(sender=self.__class__, connection=self) cursor = self.connection.cursor() cursor.tzinfo_factory = utc_tzinfo_factory if settings.USE_TZ else None return CursorWrapper(cursor)
def _cursor(self): set_tz = False settings_dict = self.settings_dict if self.connection is None: set_tz = True if settings_dict['NAME'] == '': from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured( "You need to specify NAME in your Django settings file.") conn_string = "dbname=%s" % settings_dict['NAME'] if settings_dict['USER']: conn_string = "user=%s %s" % (settings_dict['USER'], conn_string) if settings_dict['PASSWORD']: conn_string += " password='******'" % settings_dict['PASSWORD'] if settings_dict['HOST']: conn_string += " host=%s" % settings_dict['HOST'] if settings_dict['PORT']: conn_string += " port=%s" % settings_dict['PORT'] self.connection = Database.connect(conn_string, **settings_dict['OPTIONS']) self.connection.set_isolation_level( 1) # make transactions transparent to all cursors connection_created.send(sender=self.__class__) cursor = self.connection.cursor() if set_tz: cursor.execute("SET TIME ZONE %s", [settings_dict['TIME_ZONE']]) if not hasattr(self, '_version'): self.__class__._version = get_version(cursor) if self._version[0:2] < (8, 0): # No savepoint support for earlier version of PostgreSQL. self.features.uses_savepoints = False cursor.execute("SET client_encoding to 'UNICODE'") cursor = UnicodeCursorWrapper(cursor, 'utf-8') return cursor
def _cursor(self): if not self._valid_connection(): kwargs = { #'conv': django_conversions, 'charset': 'utf8', 'use_unicode': True, } settings_dict = self.settings_dict if settings_dict['DATABASE_USER']: kwargs['user'] = settings_dict['DATABASE_USER'] if settings_dict['DATABASE_NAME']: kwargs['db'] = settings_dict['DATABASE_NAME'] if settings_dict['DATABASE_PASSWORD']: kwargs['passwd'] = settings_dict['DATABASE_PASSWORD'] if settings_dict['DATABASE_HOST'].startswith('/'): kwargs['unix_socket'] = settings_dict['DATABASE_HOST'] elif settings_dict['DATABASE_HOST']: kwargs['host'] = settings_dict['DATABASE_HOST'] if settings_dict['DATABASE_PORT']: kwargs['port'] = int(settings_dict['DATABASE_PORT']) kwargs.update(settings_dict['DATABASE_OPTIONS']) self.connection = eventlet.db_pool.ConnectionPool.connect(MySQLdb, 15, **kwargs) connection_created.send(sender=self.__class__) cursor = mysqldb_base.CursorWrapper(self.connection.cursor()) return cursor
def _cursor(self): cursor = None if not self._valid_connection(): conn_string = convert_unicode(self._connect_string()) self.connection = Database.connect(conn_string, **self.settings_dict['OPTIONS']) cursor = FormatStylePlaceholderCursor(self.connection) # Set oracle date to ansi date format. This only needs to execute # once when we create a new connection. We also set the Territory # to 'AMERICA' which forces Sunday to evaluate to a '1' in TO_CHAR(). cursor.execute("ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS' " "NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF' " "NLS_TERRITORY = 'AMERICA'") try: self.oracle_version = int(self.connection.version.split('.')[0]) # There's no way for the DatabaseOperations class to know the # currently active Oracle version, so we do some setups here. # TODO: Multi-db support will need a better solution (a way to # communicate the current version). if self.oracle_version <= 9: self.ops.regex_lookup = self.ops.regex_lookup_9 else: self.ops.regex_lookup = self.ops.regex_lookup_10 except ValueError: pass try: self.connection.stmtcachesize = 20 except: # Django docs specify cx_Oracle version 4.3.1 or higher, but # stmtcachesize is available only in 4.3.2 and up. pass connection_created.send(sender=self.__class__) if not cursor: cursor = FormatStylePlaceholderCursor(self.connection) return cursor
def _cursor(self): cursor = None if not self._valid_connection(): conn_string = convert_unicode(self._connect_string()) self.connection = Database.connect(conn_string, **self.settings_dict['OPTIONS']) cursor = FormatStylePlaceholderCursor(self.connection) # Set oracle date to ansi date format. This only needs to execute # once when we create a new connection. We also set the Territory # to 'AMERICA' which forces Sunday to evaluate to a '1' in TO_CHAR(). cursor.execute("ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS' " "NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF' " "NLS_TERRITORY = 'AMERICA'") try: self.oracle_version = int(self.connection.version.split('.')[0]) # There's no way for the DatabaseOperations class to know the # currently active Oracle version, so we do some setups here. # TODO: Multi-db support will need a better solution (a way to # communicate the current version). if self.oracle_version <= 9: self.ops.regex_lookup = self.ops.regex_lookup_9 else: self.ops.regex_lookup = self.ops.regex_lookup_10 except ValueError: pass try: self.connection.stmtcachesize = 20 except: # Django docs specify cx_Oracle version 4.3.1 or higher, but # stmtcachesize is available only in 4.3.2 and up. pass connection_created.send(sender=self.__class__, connection=self) if not cursor: cursor = FormatStylePlaceholderCursor(self.connection) return cursor
def _cursor(self): cursor = None if not self._valid_connection(): conn_string = convert_unicode(self._connect_string()) conn_params = self.settings_dict['OPTIONS'].copy() if 'use_returning_into' in conn_params: del conn_params['use_returning_into'] self.connection = Database.connect(conn_string, **conn_params) cursor = FormatStylePlaceholderCursor(self.connection) # Set the territory first. The territory overrides NLS_DATE_FORMAT # and NLS_TIMESTAMP_FORMAT to the territory default. When all of # these are set in single statement it isn't clear what is supposed # to happen. cursor.execute("ALTER SESSION SET NLS_TERRITORY = 'AMERICA'") # Set oracle date to ansi date format. This only needs to execute # once when we create a new connection. We also set the Territory # to 'AMERICA' which forces Sunday to evaluate to a '1' in # TO_CHAR(). cursor.execute( "ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'" " NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF'" + (" TIME_ZONE = 'UTC'" if settings.USE_TZ else '')) if 'operators' not in self.__dict__: # Ticket #14149: Check whether our LIKE implementation will # work for this connection or we need to fall back on LIKEC. # This check is performed only once per DatabaseWrapper # instance per thread, since subsequent connections will use # the same settings. try: cursor.execute("SELECT 1 FROM DUAL WHERE DUMMY %s" % self._standard_operators['contains'], ['X']) except utils.DatabaseError: self.operators = self._likec_operators else: self.operators = self._standard_operators try: self.oracle_version = int(self.connection.version.split('.')[0]) # There's no way for the DatabaseOperations class to know the # currently active Oracle version, so we do some setups here. # TODO: Multi-db support will need a better solution (a way to # communicate the current version). if self.oracle_version <= 9: self.ops.regex_lookup = self.ops.regex_lookup_9 else: self.ops.regex_lookup = self.ops.regex_lookup_10 except ValueError: pass try: self.connection.stmtcachesize = 20 except: # Django docs specify cx_Oracle version 4.3.1 or higher, but # stmtcachesize is available only in 4.3.2 and up. pass connection_created.send(sender=self.__class__, connection=self) if not cursor: cursor = FormatStylePlaceholderCursor(self.connection) return cursor
def _cursor(self): if not self._valid_connection(): conn_params = self.get_connection_params() self.connection = self.get_new_connection(conn_params) self.init_connection_state() connection_created.send(sender=self.__class__, connection=self) return self.create_cursor(self.connection)
def _cursor(self): if not self._valid_connection(): kwargs = { 'charset': 'utf8', 'use_unicode': True, } settings_dict = self.settings_dict if settings_dict['USER']: kwargs['user'] = settings_dict['USER'] if settings_dict['NAME']: kwargs['db'] = settings_dict['NAME'] if settings_dict['PASSWORD']: kwargs['passwd'] = settings_dict['PASSWORD'] if settings_dict['HOST'].startswith('/'): kwargs['unix_socket'] = settings_dict['HOST'] elif settings_dict['HOST']: kwargs['host'] = settings_dict['HOST'] if settings_dict['PORT']: kwargs['port'] = int(settings_dict['PORT']) opts = settings_dict['OPTIONS'] if 'autoreconnect' in opts: kwargs['autoreconnect'] = opts['autoreconnect'] # We need the number of potentially affected rows after an # "UPDATE", not the number of changed rows. kwargs['found_rows'] = True # TODO: support for 'init_command' kwargs.update(settings_dict['OPTIONS']) self.connection = Database.connect(**kwargs) # XXX: oursql does not have encoders like mysqldb -- unknown if this is still needed # self.connection.encoders[SafeUnicode] = self.connection.encoders[unicode] # self.connection.encoders[SafeString] = self.connection.encoders[str] connection_created.send(sender=self.__class__) cursor = CursorWrapper(self.connection.cursor()) return cursor
def create_cursor(self): if not self._valid_connection(): self.connection = self.get_new_connection(None) connection_created.send(sender=self.__class__, connection=self) cursor = CursorWrapper(self.connection.cursor()) return cursor
def connect(self): """Connect to the database. Assume that the connection is closed.""" # Check for invalid configurations. self.check_settings() # In case the previous connection was closed while in an atomic block self.in_atomic_block = False self.savepoint_ids = [] self.atomic_blocks = [] self.needs_rollback = False # Reset parameters defining when to close/health-check the connection. self.health_check_enabled = self.settings_dict["CONN_HEALTH_CHECKS"] max_age = self.settings_dict["CONN_MAX_AGE"] self.close_at = None if max_age is None else time.monotonic() + max_age self.closed_in_transaction = False self.errors_occurred = False # New connections are healthy. self.health_check_done = True # Establish the connection conn_params = self.get_connection_params() self.connection = self.get_new_connection(conn_params) self.set_autocommit(self.settings_dict["AUTOCOMMIT"]) self.init_connection_state() connection_created.send(sender=self.__class__, connection=self) self.run_on_commit = []
def connect(self): """Connect to the database. Assume that the connection is closed.""" # self 是「数据库包装对象」 # Check for invalid configurations. self.check_settings() # In case the previous connection was closed while in an atomic block self.in_atomic_block = False self.savepoint_ids = [] self.needs_rollback = False # Reset parameters defining when to close the connection max_age = self.settings_dict['CONN_MAX_AGE'] self.close_at = None if max_age is None else time.monotonic() + max_age self.closed_in_transaction = False self.errors_occurred = False # Establish the connection conn_params = self.get_connection_params() # 下面这个方法定义在子类 django.db.backends.mysql.base.DatabaseWrapper 类中 # 参数 conn_params 是连接数据库所需的各种信息组成的字典对象 # 此处创建「数据库连接对象」,也就是 MySQLdb.connections.Connection 类的实例 self.connection = self.get_new_connection(conn_params) self.set_autocommit(self.settings_dict['AUTOCOMMIT']) self.init_connection_state() connection_created.send(sender=self.__class__, connection=self) self.run_on_commit = []
def _sqlite_create_connection(self): settings_dict = self.settings_dict if not settings_dict["NAME"]: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured("settings.DATABASES is improperly configured. " "Please supply the NAME value.") kwargs = {"database": settings_dict["NAME"], "detect_types": Database.PARSE_DECLTYPES | Database.PARSE_COLNAMES} kwargs.update(settings_dict["OPTIONS"]) # Always allow the underlying SQLite connection to be shareable # between multiple threads. The safe-guarding will be handled at a # higher level by the `BaseDatabaseWrapper.allow_thread_sharing` # property. This is necessary as the shareability is disabled by # default in pysqlite and it cannot be changed once a connection is # opened. if "check_same_thread" in kwargs and kwargs["check_same_thread"]: warnings.warn( "The `check_same_thread` option was provided and set to " "True. It will be overriden with False. Use the " "`DatabaseWrapper.allow_thread_sharing` property instead " "for controlling thread shareability.", RuntimeWarning, ) kwargs.update({"check_same_thread": False}) self.connection = Database.connect(**kwargs) # Register extract, date_trunc, and regexp functions. self.connection.create_function("django_extract", 2, _sqlite_extract) self.connection.create_function("django_date_trunc", 2, _sqlite_date_trunc) self.connection.create_function("regexp", 2, _sqlite_regexp) self.connection.create_function("django_format_dtdelta", 5, _sqlite_format_dtdelta) connection_created.send(sender=self.__class__, connection=self)
def connect(self): """Connects to the database. Assumes that the connection is closed.""" # Check for invalid configurations. self.check_settings() # In case the previous connection was closed while in an atomic block self.in_atomic_block = False self.savepoint_ids = [] self.needs_rollback = False # Reset parameters defining when to close the connection max_age = self.settings_dict['CONN_MAX_AGE'] self.close_at = None if max_age is None else time.time() + max_age self.closed_in_transaction = False self.errors_occurred = False # Establish the connection conn_params = self.get_connection_params() # 创建connection self.connection = self.get_new_connection(conn_params) # 设置: AUTOCOMMIT 状态 self.set_autocommit(self.settings_dict['AUTOCOMMIT']) self.init_connection_state() # 发出: connection_created的信号 connection_created.send(sender=self.__class__, connection=self) self.run_on_commit = []
def _sqlite_create_connection(self): settings_dict = self.settings_dict if not settings_dict['NAME']: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured( "settings.DATABASES is improperly configured. " "Please supply the NAME value.") kwargs = { 'database': settings_dict['NAME'], 'detect_types': Database.PARSE_DECLTYPES | Database.PARSE_COLNAMES, } kwargs.update(settings_dict['OPTIONS']) # Always allow the underlying SQLite connection to be shareable # between multiple threads. The safe-guarding will be handled at a # higher level by the `BaseDatabaseWrapper.allow_thread_sharing` # property. This is necessary as the shareability is disabled by # default in pysqlite and it cannot be changed once a connection is # opened. if 'check_same_thread' in kwargs and kwargs['check_same_thread']: warnings.warn( 'The `check_same_thread` option was provided and set to ' 'True. It will be overriden with False. Use the ' '`DatabaseWrapper.allow_thread_sharing` property instead ' 'for controlling thread shareability.', RuntimeWarning) kwargs.update({'check_same_thread': False}) self.connection = Database.connect(**kwargs) # Register extract, date_trunc, and regexp functions. self.connection.create_function("django_extract", 2, _sqlite_extract) self.connection.create_function("django_date_trunc", 2, _sqlite_date_trunc) self.connection.create_function("regexp", 2, _sqlite_regexp) self.connection.create_function("django_format_dtdelta", 5, _sqlite_format_dtdelta) connection_created.send(sender=self.__class__, connection=self)
def _cursor(self): new_connection = False set_tz = False settings_dict = self.settings_dict if self.connection is None: new_connection = True set_tz = settings_dict.get("TIME_ZONE") if settings_dict["NAME"] == "": from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured("You need to specify NAME in your Django settings file.") conn_params = {"database": settings_dict["NAME"]} conn_params.update(settings_dict["OPTIONS"]) if "autocommit" in conn_params: del conn_params["autocommit"] 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"]: conn_params["port"] = settings_dict["PORT"] self.connection = Database.connect(**conn_params) self.connection.set_client_encoding("UTF8") self.connection.set_isolation_level(self.isolation_level) connection_created.send(sender=self.__class__, connection=self) cursor = self.connection.cursor() cursor.tzinfo_factory = None if new_connection: if set_tz: cursor.execute("SET TIME ZONE %s", [settings_dict["TIME_ZONE"]]) self._get_pg_version() return CursorWrapper(cursor)
def _cursor(self): if self.connection is None: conn_params = self.get_connection_params() self.connection = self.get_new_connection(conn_params) self.init_connection_state() connection_created.send(sender=self.__class__, connection=self) return self.create_cursor()
def _cursor(self): new_connection = False set_tz = False settings_dict = self.settings_dict if self.connection is None: new_connection = True set_tz = settings_dict.get('TIME_ZONE') if settings_dict['NAME'] == '': from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured("You need to specify NAME in your Django settings file.") conn_string = "dbname=%s" % settings_dict['NAME'] if settings_dict['USER']: conn_string = "user=%s %s" % (settings_dict['USER'], conn_string) if settings_dict['PASSWORD']: conn_string += " password='******'" % settings_dict['PASSWORD'] if settings_dict['HOST']: conn_string += " host=%s" % settings_dict['HOST'] if settings_dict['PORT']: conn_string += " port=%s" % settings_dict['PORT'] self.connection = Database.connect(conn_string, **settings_dict['OPTIONS']) self.connection.set_isolation_level(1) # make transactions transparent to all cursors connection_created.send(sender=self.__class__) cursor = self.connection.cursor() if new_connection: if set_tz: cursor.execute("SET TIME ZONE %s", [settings_dict['TIME_ZONE']]) if not hasattr(self, '_version'): self.__class__._version = get_version(cursor) if self._version[0:2] < (8, 0): # No savepoint support for earlier version of PostgreSQL. self.features.uses_savepoints = False cursor.execute("SET client_encoding to 'UNICODE'") cursor = UnicodeCursorWrapper(cursor, 'utf-8') return cursor
def _cursor(self): if not self._valid_connection(): kwargs = { 'conv': django_conversions, 'charset': 'utf8', 'use_unicode': True, } settings_dict = self.settings_dict if settings_dict['USER']: kwargs['user'] = settings_dict['USER'] if settings_dict['NAME']: kwargs['db'] = settings_dict['NAME'] if settings_dict['PASSWORD']: kwargs['passwd'] = settings_dict['PASSWORD'] if settings_dict['HOST'].startswith('/'): kwargs['unix_socket'] = settings_dict['HOST'] elif settings_dict['HOST']: kwargs['host'] = settings_dict['HOST'] if settings_dict['PORT']: kwargs['port'] = int(settings_dict['PORT']) # We need the number of potentially affected rows after an # "UPDATE", not the number of changed rows. kwargs['client_flag'] = CLIENT.FOUND_ROWS kwargs.update(settings_dict['OPTIONS']) self.connection = Database.connect(**kwargs) self.connection.encoders[SafeUnicode] = self.connection.encoders[unicode] self.connection.encoders[SafeString] = self.connection.encoders[str] connection_created.send(sender=self.__class__, connection=self) cursor = CursorWrapper(self.connection.cursor()) return cursor
def _cursor(self): if not self._valid_connection(): kwargs = { 'conv': django_conversions, 'charset': 'utf8', 'use_unicode': True, } settings_dict = self.settings_dict if settings_dict['USER']: kwargs['user'] = settings_dict['USER'] if settings_dict['NAME']: kwargs['db'] = settings_dict['NAME'] if settings_dict['PASSWORD']: kwargs['passwd'] = settings_dict['PASSWORD'] if settings_dict['HOST'].startswith('/'): kwargs['unix_socket'] = settings_dict['HOST'] elif settings_dict['HOST']: kwargs['host'] = settings_dict['HOST'] if settings_dict['PORT']: kwargs['port'] = int(settings_dict['PORT']) # We need the number of potentially affected rows after an # "UPDATE", not the number of changed rows. kwargs['client_flag'] = CLIENT.FOUND_ROWS kwargs.update(settings_dict['OPTIONS']) self.connection = Database.connect(**kwargs) self.connection.encoders[SafeUnicode] = self.connection.encoders[ unicode] self.connection.encoders[SafeString] = self.connection.encoders[ str] connection_created.send(sender=self.__class__, connection=self) cursor = CursorWrapper(self.connection.cursor()) return cursor
def _cursor(self): if self.connection is None: settings_dict = self.settings_dict if settings_dict['NAME'] == '': from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured("You need to specify DATABASE_NAME in your Django settings file.") conn_params = { 'charset': 'UNICODE_FSS' } conn_params['dsn'] = settings_dict['NAME'] if settings_dict['HOST']: conn_params['dsn'] = ('%s:%s') % (settings_dict['HOST'], conn_params['dsn']) if settings_dict['PORT']: conn_params['port'] = settings_dict['PORT'] if settings_dict['USER']: conn_params['user'] = settings_dict['USER'] if settings_dict['PASSWORD']: conn_params['password'] = settings_dict['PASSWORD'] options = settings_dict['OPTIONS'].copy() # Normalization for databases with 'NONE', 'OCTETS' or 'ASCII' charset. encoding = options.pop('encoding', 'utf_8') conn_params.update(options) self.connection = Database.connect(**conn_params) self._type_translator.set_charset(self.connection.charset, encoding) connection_created.send(sender=self.__class__) if self.ops.firebird_version[0] >= 2: self.features.can_return_id_from_insert = True return FirebirdCursorWrapper(self.connection.cursor(), self._type_translator)
def _cursor(self): if settings.TEST_CONNECTION_QUEUE is None: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured("Please fill out the TEST_CONNECTION_QUEUE in the settings module before using this database. It should look like \nif 'test' in sys.argv:\n\tfrom Queue import Queue\n\tTEST_CONNECTION_QUEUE=Queue()") if settings.TEST_CONNECTION_QUEUE.empty(): #if self.connection is None: settings_dict = self.settings_dict if not settings_dict['NAME']: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured("Please fill out the database NAME in the settings module before using the database.") kwargs = { 'database': settings_dict['NAME'], 'detect_types': Database.PARSE_DECLTYPES | Database.PARSE_COLNAMES, } kwargs.update(settings_dict['OPTIONS']) self.connection = Database.connect(**kwargs) # Register extract, date_trunc, and regexp functions. self.connection.create_function("django_extract", 2, _sqlite_extract) self.connection.create_function("django_date_trunc", 2, _sqlite_date_trunc) self.connection.create_function("regexp", 2, _sqlite_regexp) self.connection.create_function("django_format_dtdelta", 5, _sqlite_format_dtdelta) connection_created.send(sender=self.__class__, connection=self) settings.TEST_CONNECTION_QUEUE.put(self.connection) else: self.connection = settings.TEST_CONNECTION_QUEUE.get() settings.TEST_CONNECTION_QUEUE.put(self.connection) return self.connection.cursor(factory=SQLiteCursorWrapper)
def _cursor(self): new_connection = False if not self._valid_connection(): new_connection = True kwargs = {"conv": django_conversions, "charset": "utf8", "use_unicode": True} settings_dict = self.settings_dict if settings_dict["USER"]: kwargs["user"] = settings_dict["USER"] if settings_dict["NAME"]: kwargs["db"] = settings_dict["NAME"] if settings_dict["PASSWORD"]: kwargs["passwd"] = force_str(settings_dict["PASSWORD"]) if settings_dict["HOST"].startswith("/"): kwargs["unix_socket"] = settings_dict["HOST"] elif settings_dict["HOST"]: kwargs["host"] = settings_dict["HOST"] if settings_dict["PORT"]: kwargs["port"] = int(settings_dict["PORT"]) # We need the number of potentially affected rows after an # "UPDATE", not the number of changed rows. kwargs["client_flag"] = CLIENT.FOUND_ROWS kwargs.update(settings_dict["OPTIONS"]) self.connection = Database.connect(**kwargs) self.connection.encoders[SafeText] = self.connection.encoders[six.text_type] self.connection.encoders[SafeBytes] = self.connection.encoders[bytes] connection_created.send(sender=self.__class__, connection=self) cursor = self.connection.cursor() if new_connection: # SQL_AUTO_IS_NULL in MySQL controls whether an AUTO_INCREMENT column # on a recently-inserted row will return when the field is tested for # NULL. Disabling this value brings this aspect of MySQL in line with # SQL standards. cursor.execute("SET SQL_AUTO_IS_NULL = 0") return CursorWrapper(cursor)
def _cursor(self): new_connection = False set_tz = False settings_dict = self.settings_dict if self.connection is None: new_connection = True set_tz = settings_dict.get('TIME_ZONE') if settings_dict['NAME'] == '': from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured("You need to specify NAME in your Django settings file.") conn_params = { 'database': settings_dict['NAME'], } conn_params.update(settings_dict['OPTIONS']) if 'autocommit' in conn_params: del conn_params['autocommit'] 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']: conn_params['port'] = settings_dict['PORT'] self.connection = Database.connect(**conn_params) self.connection.set_client_encoding('UTF8') self.connection.set_isolation_level(self.isolation_level) connection_created.send(sender=self.__class__, connection=self) cursor = self.connection.cursor() cursor.tzinfo_factory = None if new_connection: if set_tz: cursor.execute("SET TIME ZONE %s", [settings_dict['TIME_ZONE']]) self._get_pg_version() return CursorWrapper(cursor)
def _cursor(self): settings_dict = self.settings_dict if self.connection is None: self.connection = self.pool.get() self.connection.set_client_encoding('UTF8') tz = 'UTC' if settings.USE_TZ else settings_dict.get('TIME_ZONE') if tz: try: get_parameter_status = self.connection.get_parameter_status except AttributeError: # psycopg2 < 2.0.12 doesn't have get_parameter_status conn_tz = None else: conn_tz = get_parameter_status('TimeZone') if conn_tz != tz: # Set the time zone in autocommit mode (see #17062) self.connection.set_isolation_level( psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) self.connection.cursor().execute( self.ops.set_time_zone_sql(), [tz]) self.connection.set_isolation_level(self.isolation_level) self._get_pg_version() connection_created.send(sender=self.__class__, connection=self) cursor = self.connection.cursor() cursor.tzinfo_factory = utc_tzinfo_factory if settings.USE_TZ else None return CursorWrapper(cursor)
def _sqlite_create_connection(self): settings_dict = self.settings_dict if not settings_dict['NAME']: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured("Please fill out the database NAME in the settings module before using the database.") kwargs = { 'database': settings_dict['NAME'], 'detect_types': Database.PARSE_DECLTYPES | Database.PARSE_COLNAMES, } kwargs.update(settings_dict['OPTIONS']) # Always allow the underlying SQLite connection to be shareable # between multiple threads. The safe-guarding will be handled at a # higher level by the `BaseDatabaseWrapper.allow_thread_sharing` # property. This is necessary as the shareability is disabled by # default in pysqlite and it cannot be changed once a connection is # opened. if 'check_same_thread' in kwargs and kwargs['check_same_thread']: warnings.warn( 'The `check_same_thread` option was provided and set to ' 'True. It will be overriden with False. Use the ' '`DatabaseWrapper.allow_thread_sharing` property instead ' 'for controlling thread shareability.', RuntimeWarning ) kwargs.update({'check_same_thread': False}) self.connection = Database.connect(**kwargs) # Register extract, date_trunc, and regexp functions. self.connection.create_function("django_extract", 2, _sqlite_extract) self.connection.create_function("django_date_trunc", 2, _sqlite_date_trunc) self.connection.create_function("regexp", 2, _sqlite_regexp) self.connection.create_function("django_format_dtdelta", 5, _sqlite_format_dtdelta) connection_created.send(sender=self.__class__, connection=self)
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.") conn_params = { 'database': settings_dict['NAME'], } conn_params.update(settings_dict['OPTIONS']) if 'autocommit' in conn_params: del conn_params['autocommit'] 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']: conn_params['port'] = settings_dict['PORT'] self.connection = Database.connect(**conn_params) self.connection.set_client_encoding('UTF8') # Set the time zone in autocommit mode (see #17062) tz = 'UTC' if settings.USE_TZ else settings_dict.get('TIME_ZONE') if tz: self.connection.set_isolation_level( psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) self.connection.cursor().execute("SET TIME ZONE %s", [tz]) self.connection.set_isolation_level(self.isolation_level) self._get_pg_version() connection_created.send(sender=self.__class__, connection=self) cursor = self.connection.cursor() cursor.tzinfo_factory = utc_tzinfo_factory if settings.USE_TZ else None return CursorWrapper(cursor)
def _cursor(self): if self.connection is None: settings_dict = self.settings_dict if not settings_dict['NAME']: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured( "Please fill out the database NAME in the settings module before using the database." ) kwargs = { 'database': settings_dict['NAME'], 'detect_types': Database.PARSE_DECLTYPES | Database.PARSE_COLNAMES, } kwargs.update(settings_dict['OPTIONS']) self.connection = Database.connect(**kwargs) # Register extract, date_trunc, and regexp functions. self.connection.create_function("django_extract", 2, _sqlite_extract) self.connection.create_function("django_date_trunc", 2, _sqlite_date_trunc) self.connection.create_function("regexp", 2, _sqlite_regexp) self.connection.create_function("django_format_dtdelta", 5, _sqlite_format_dtdelta) connection_created.send(sender=self.__class__, connection=self) return self.connection.cursor(factory=SQLiteCursorWrapper)
def _cursor(self): if not self._valid_connection(): settings_dict = self.settings_dict # Connection to CUBRID database is made through connect() method. # Syntax: # connect (url[,user[password]]) # url - CUBRID:host:port:db_name:db_user:db_password # user - Authorized username. # password - Password associated with the username. url = "CUBRID" if settings_dict['HOST'].startswith('/'): url += ':' + settings_dict['HOST'] elif settings_dict['HOST']: url += ':' + settings_dict['HOST'] else: url += ':localhost' if settings_dict['PORT']: url += ':' + settings_dict['PORT'] if settings_dict['NAME']: url += ':' + settings_dict['NAME'] if settings_dict['USER']: url += ':' + settings_dict['USER'] if settings_dict['PASSWORD']: url += ':' + settings_dict['PASSWORD'] self.connection = Database.connect(url) connection_created.send(sender=self.__class__, connection=self) cursor = CursorWrapper(self.connection.cursor()) return cursor
def _cursor(self): settings_dict = self.settings_dict if self.connection is None or connection_pools[ self.alias]['settings'] != settings_dict: # Is this the initial use of the global connection_pools dictionary for # this python interpreter? Build a ThreadedConnectionPool instance and # add it to the dictionary if so. if self.alias not in connection_pools or connection_pools[ self.alias]['settings'] != settings_dict: if not settings_dict['NAME']: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured( "settings.DATABASES is improperly configured. " "Please supply the NAME value.") conn_params = { 'database': settings_dict['NAME'], } conn_params.update(settings_dict['OPTIONS']) for extra in ['autocommit'] + pool_config_defaults.keys(): if extra in conn_params: del conn_params[extra] if settings_dict['USER']: conn_params['user'] = settings_dict['USER'] if settings_dict['PASSWORD']: conn_params['password'] = force_str( settings_dict['PASSWORD']) if settings_dict['HOST']: conn_params['host'] = settings_dict['HOST'] if settings_dict['PORT']: conn_params['port'] = settings_dict['PORT'] self.create_connection_pool(conn_params) self.connection = PooledConnection( connection_pools[self.alias]['pool'], test_query=self._test_on_borrow_query) self.connection.set_client_encoding('UTF8') tz = 'UTC' if settings.USE_TZ else settings_dict.get('TIME_ZONE') if tz: try: get_parameter_status = self.connection.get_parameter_status except AttributeError: # psycopg2 < 2.0.12 doesn't have get_parameter_status conn_tz = None else: conn_tz = get_parameter_status('TimeZone') if conn_tz != tz: # Set the time zone in autocommit mode (see #17062) self.connection.set_isolation_level( psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) self.connection.cursor().execute( self.ops.set_time_zone_sql(), [tz]) self.connection.set_isolation_level(self.isolation_level) self._get_pg_version() connection_created.send(sender=self.__class__, connection=self) cursor = self.connection.cursor() cursor.tzinfo_factory = utc_tzinfo_factory if settings.USE_TZ else None return CursorWrapper(cursor)
def _cursor(self): cursor = None if not self._valid_connection(): kwargs = {} links = {} settings_dict = self.settings_dict if settings_dict['USER']: kwargs['uid'] = settings_dict['USER'] if settings_dict['NAME']: kwargs['dbn'] = settings_dict['NAME'] if settings_dict['PASSWORD']: kwargs['pwd'] = settings_dict['PASSWORD'] root = Database.Root('PYTHON') try: vers = root.api.sqlany_client_version() ret = True except: length = 1000 buffer = ctypes.create_string_buffer(length) ret = root.api.sqlany_client_version( ctypes.byref(buffer), length) vers = buffer.value if ret: vers = int(vers.split('.')[0]) else: vers = 11 # assume old host = settings_dict['HOST'] if host == '': host = 'localhost' # "Set to empty string for localhost" if host and vers > 11: kwargs['host'] = host try: port = str(settings_dict['PORT']) except: port = None if port: kwargs['host'] += ':%s' % port else: if host: links['host'] = host if settings_dict['PORT']: links['port'] = str(settings_dict['PORT']) if len(links) > 0: kwargs['links'] = 'tcpip(' + ','.join( k + '=' + v for k, v in links.items()) + ')' kwargs.update(settings_dict['OPTIONS']) self.connection = Database.connect(**kwargs) cursor = CursorWrapper(self.connection.cursor()) cursor.execute("SET OPTION PUBLIC.reserved_keywords='LIMIT'") cursor.execute( "SET TEMPORARY OPTION TIMESTAMP_FORMAT='YYYY-MM-DD HH:NN:SS.SSSSSS'" ) connection_created.send(sender=self.__class__, connection=self) if not cursor: cursor = CursorWrapper(self.connection.cursor()) return cursor
def get_new_connection(self, conn_params): # Django 1.6 cnx = mysql.connector.connect(**conn_params) self.server_version = cnx.get_server_version() cnx.set_converter_class(DjangoMySQLConverter) connection_created.send(sender=self.__class__, connection=self) return cnx
def __connect(self): """Connect to the database""" self.connection = Database.connect( make_connection_string(self.settings_dict), self.command_timeout ) connection_created.send(sender=self.__class__) return self.connection
def _cursor(self): if not self._valid_connection(): conn_params = self.get_connection_params() self.connection = self.get_new_connection(conn_params) self.init_connection_state() connection_created.send(sender=self.__class__, connection=self) cursor = self.connection.cursor() return CursorWrapper(cursor)
def _cursor(self): if self.connection is None: conn_params = self.get_connection_params() self.connection = self.get_new_connection(conn_params) self.init_connection_state() connection_created.send(sender=self.__class__, connection=self) return self.connection.cursor(factory=SQLiteCursorWrapper)
def _cursor(self): if self.connection is None: self.connection = self.get_new_connection() # JAMI: shouldn't we send the signal from within get_new_connection() ? connection_created.send(sender=self.__class__, connection=self) cursor = self.connection.cursor() return CursorWrapper(cursor, self.encoding)
def _connect(self): settings = self.settings_dict.copy() def pop(name, default=None): return settings.pop(name) or default db_name = pop('NAME') host = pop('HOST') port = pop('PORT') user = pop('USER') password = pop('PASSWORD') options = pop('OPTIONS', {}) if port: try: port = int(port) except ValueError: raise ImproperlyConfigured("If set, PORT must be an integer " "(got %r instead)" % port) self.operation_flags = options.pop('OPERATIONS', {}) if not any(k in ['save', 'delete', 'update'] for k in self.operation_flags): # flags apply to all operations flags = self.operation_flags self.operation_flags = { 'save': flags, 'delete': flags, 'update': flags } # Compatibility to version < 0.4 if 'SAFE_INSERTS' in settings: _warn_deprecated('SAFE_INSERTS') self.operation_flags['save']['safe'] = settings['SAFE_INSERTS'] if 'WAIT_FOR_SLAVES' in settings: _warn_deprecated('WAIT_FOR_SLAVES') self.operation_flags['save']['w'] = settings['WAIT_FOR_SLAVES'] # lower-case all remaining OPTIONS for key, value in options.items(): options[key.lower()] = options.pop(key) try: self.connection = Connection(host=host, port=port, **options) self.database = self.connection[db_name] except TypeError: import sys exc_info = sys.exc_info() raise ImproperlyConfigured, exc_info[1], exc_info[2] if user and password: if not self.database.authenticate(user, password): raise ImproperlyConfigured("Invalid username or password") self._add_serializer() self.connected = True connection_created.send(sender=self.__class__, connection=self)
def _cursor(self): new_connection = False if not self._valid_connection(): new_connection = True kwargs = { 'conv': django_conversions, 'charset': 'utf8', 'use_unicode': True, } settings_dict = self.settings_dict if settings_dict['USER']: kwargs['user'] = settings_dict['USER'] if settings_dict['NAME']: kwargs['db'] = settings_dict['NAME'] if settings_dict['PASSWORD']: kwargs['passwd'] = force_str(settings_dict['PASSWORD']) if settings_dict['HOST'].startswith('/'): kwargs['unix_socket'] = settings_dict['HOST'] elif settings_dict['HOST']: kwargs['host'] = settings_dict['HOST'] if settings_dict['PORT']: kwargs['port'] = int(settings_dict['PORT']) # We need the number of potentially affected rows after an # "UPDATE", not the number of changed rows. kwargs['client_flag'] = CLIENT.FOUND_ROWS kwargs.update(settings_dict['OPTIONS']) # 此处设置 connection, 已经有 MySQL 内部实现 self.connection = Database.connect(**kwargs) self.connection.encoders[SafeText] = self.connection.encoders[six.text_type] self.connection.encoders[SafeBytes] = self.connection.encoders[bytes] connection_created.send(sender=self.__class__, connection=self) cursor = self.connection.cursor() 获取游标 if new_connection: """ 另外还可以用"WHERE auto_col IS NULL"条件选择出新插入的行,即在INSERT后马上用: SELECT * FROM t WHERE a IS NULL; 选 择出来的将是新插入的行,而非真正的满足"a IS NULL"条件的行。但你要是再执行一次上述查询,则返回的又变成了真正的满足"a IS NULL"条件的行,由于a是主键,因此肯定会返回空集。这看上去很诡异是吗,不过MySQL也不想这么干,但ODBC标准里曾有这种用法,为了支持 ODBC,MySQL也是没办法啊。不过可以将SQL_AUTO_IS_NULL设为0来禁止这一用法。 """ # SQL_AUTO_IS_NULL in MySQL controls whether an AUTO_INCREMENT column # on a recently-inserted row will return when the field is tested for # NULL. Disabling this value brings this aspect of MySQL in line with # SQL standards. cursor.execute('SET SQL_AUTO_IS_NULL = 0') return CursorWrapper(cursor)
def __init__(self, conn, query=None): """ Connect to the Salesforce API. """ connection_created.send(sender=self.__class__, connection=self) self.settings_dict = conn.settings_dict self.query = query self.results = iter([]) self.rowcount = None
def _cursor(self): if self.connection is None: self.connection = Database.connect( make_connection_string(self.settings_dict), self.command_timeout ) connection_created.send(sender=self.__class__) return Database.Cursor(self.connection)
def __init__(self, conn, query=None): """ Connect to the Salesforce API. """ connection_created.send(sender=self.__class__, connection=self) self.settings_dict = conn.settings_dict self.query = query self.results = [] self.rowcount = None
def _cursor(self): if self.connection is None: conn_params = self.get_connection_params() self.connection = self.get_new_connection(conn_params) self.init_connection_state() connection_created.send(sender=self.__class__, connection=self) cursor = self.connection.cursor() cursor.tzinfo_factory = utc_tzinfo_factory if settings.USE_TZ else None return CursorWrapper(cursor)
def _cursor(self): new_connection = False set_tz = False settings_dict = self.settings_dict if self.connection is None: new_connection = True set_tz = settings_dict.get('TIME_ZONE') if settings_dict['DATABASE_NAME'] == '': from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured( "You need to specify DATABASE_NAME in your Django settings file." ) conn_params = { 'database': settings_dict['DATABASE_NAME'], } conn_params.update(settings_dict['DATABASE_OPTIONS']) if 'autocommit' in conn_params: del conn_params['autocommit'] if settings_dict['DATABASE_USER']: conn_params['user'] = settings_dict['DATABASE_USER'] if settings_dict['DATABASE_PASSWORD']: conn_params['password'] = settings_dict['DATABASE_PASSWORD'] if settings_dict['DATABASE_HOST']: conn_params['host'] = settings_dict['DATABASE_HOST'] if settings_dict['DATABASE_PORT']: conn_params['port'] = settings_dict['DATABASE_PORT'] self.connection = Database.connect(**conn_params) self.connection.set_client_encoding('UTF8') self.connection.set_isolation_level(self.isolation_level) connection_created.send(sender=self.__class__) cursor = self.connection.cursor() cursor.tzinfo_factory = None if new_connection: if set_tz: cursor.execute("SET TIME ZONE %s", [settings_dict['TIME_ZONE']]) if not hasattr(self, '_version'): self.__class__._version = get_version(cursor) if self._version[0:2] < (8, 0): # No savepoint support for earlier version of PostgreSQL. self.features.uses_savepoints = False if self.features.uses_autocommit: if self._version[0:2] < (8, 2): # FIXME: Needs extra code to do reliable model insert # handling, so we forbid it for now. from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured( "You cannot use autocommit=True with PostgreSQL prior to 8.2 at the moment." ) else: # FIXME: Eventually we're enable this by default for # versions that support it, but, right now, that's hard to # do without breaking other things (#10509). self.features.can_return_id_from_insert = True return cursor
def cursor(self, query=None): """ Return a fake cursor for accessing the Salesforce API with SOQL. """ from salesforce.backend.query import CursorWrapper cursor = CursorWrapper(self, query) # prior to 1.6 you were expected to send this signal # just after the cursor was constructed if not DJANGO_16_PLUS: connection_created.send(self.__class__, connection=self) return cursor
def create_cursor( self ): cursor = None if not self._valid_connection(): kwargs = self.get_connection_params() self.connection = self.get_new_connection(kwargs) cursor = CursorWrapper(self.connection.cursor()) if djangoVersion[:2] < (1, 2): cursor.execute("SET TEMPORARY OPTION PUBLIC.reserved_keywords='LIMIT'") cursor.execute("SET TEMPORARY OPTION TIMESTAMP_FORMAT='YYYY-MM-DD HH:NN:SS.SSSSSS'") connection_created.send(sender=self.__class__, connection=self) if not cursor: cursor = CursorWrapper(self.connection.cursor()) return cursor
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.") conn_params = { 'database': settings_dict['NAME'], } conn_params.update(settings_dict['OPTIONS']) if 'autocommit' in conn_params: del conn_params['autocommit'] 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']: conn_params['port'] = settings_dict['PORT'] self.connection = Database.connect(**conn_params) self.connection.set_client_encoding('UTF8') tz = 'UTC' if settings.USE_TZ else settings_dict.get('TIME_ZONE') if tz: try: get_parameter_status = self.connection.get_parameter_status except AttributeError: # psycopg2 < 2.0.12 doesn't have get_parameter_status conn_tz = None else: conn_tz = get_parameter_status('TimeZone') if conn_tz != tz: # Set the time zone in autocommit mode (see #17062) self.connection.set_isolation_level( psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) self.connection.cursor().execute( self.ops.set_time_zone_sql(), [tz]) self.connection.set_isolation_level(self.isolation_level) self._get_pg_version() connection_created.send(sender=self.__class__, connection=self) #here uses a server side cursor cursor = self.connection.cursor(name='cur%s' % str(uuid.uuid4()).replace('-', ''), scrollable=True, withhold=True) cursor.tzinfo_factory = utc_tzinfo_factory if settings.USE_TZ else None return pgServerSideCursorWrapper(cursor, self)
def _cursor( self, settings = None ): if not self.__is_connection(): if ( djangoVersion[0:2] <= ( 1, 0 ) ): self.settings = settings self.connection = self.get_new_connection(self.get_connection_params()) cursor = self.databaseWrapper._cursor(self.connection) if( djangoVersion[0:3] <= ( 1, 2, 2 ) ): connection_created.send( sender = self.__class__ ) else: connection_created.send( sender = self.__class__, connection = self ) else: cursor = self.databaseWrapper._cursor( self.connection ) return cursor
def connect(self): """Connects to the database. Assumes that the connection is closed.""" # In case the previous connection was closed while in an atomic block self.in_atomic_block = False self.savepoint_ids = [] # Reset parameters defining when to close the connection max_age = self.settings_dict['CONN_MAX_AGE'] self.close_at = None if max_age is None else time.time() + max_age self.errors_occurred = False # Establish the connection conn_params = self.get_connection_params() self.connection = self.get_new_connection(conn_params) self.init_connection_state() if self.settings_dict['AUTOCOMMIT']: self.set_autocommit(True) connection_created.send(sender=self.__class__, connection=self)
def _cursor(self): settings_dict = self.settings_dict if self.connection is None: if not settings_dict['NAME']: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured( "settings.DATABASES is improperly configured. " "Please supply the NAME value.") conn_params = { 'database': settings_dict['NAME'], } conn_params.update(settings_dict['OPTIONS']) if 'autocommit' in conn_params: del conn_params['autocommit'] if settings_dict.has_key('SCHEMA'): options = { "schema": settings_dict.get('SCHEMA', 'user') or 'user' } else: options = {"schema": "user"} if settings_dict['DBA_USER']: conn_params['user'] = settings_dict['DBA_USER'] if settings_dict['DBA_PASSWORD']: conn_params['password'] = force_str( settings_dict['DBA_PASSWORD']) if settings_dict['HOST']: conn_params['host'] = settings_dict['HOST'] if settings_dict['PORT']: options['port'] = settings_dict['PORT'] tz = 'UTC' if settings.USE_TZ else settings_dict.get('TIME_ZONE') # options['timezone'] = tz conn_params['options'] = options self.connection = Database.connect(**conn_params) if tz: try: get_parameter_status = self.connection.get_parameter_status except AttributeError: conn_tz = None else: conn_tz = get_parameter_status('TimeZone') self._get_nuodb_version() connection_created.send(sender=self.__class__, connection=self) cursor = self.connection.cursor() cursor.tzinfo_factory = utc_tzinfo_factory if settings.USE_TZ else None return CursorWrapper(cursor)