Esempio n. 1
0
    def test_version_detection(self):
        """Test PostgreSQL version detection"""

        # Helper mocks
        class CursorMock(object):
            "Very simple mock of DB-API cursor"
            def execute(self, arg):
                pass

            def fetchone(self):
                return ["PostgreSQL 9.3"]

            def __enter__(self):
                return self

            def __exit__(self, type, value, traceback):
                pass

        class OlderConnectionMock(object):
            "Mock of psycopg2 (< 2.0.12) connection"
            def cursor(self):
                return CursorMock()

        # psycopg2 < 2.0.12 code path
        conn = OlderConnectionMock()
        self.assertEqual(pg_version.get_version(conn), 90300)
Esempio n. 2
0
    def test_version_detection(self):
        """Test PostgreSQL version detection"""

        # Helper mocks
        class CursorMock(object):
            "Very simple mock of DB-API cursor"

            def execute(self, arg):
                pass

            def fetchone(self):
                return ["PostgreSQL 9.3"]

            def __enter__(self):
                return self

            def __exit__(self, type, value, traceback):
                pass

        class OlderConnectionMock(object):
            "Mock of psycopg2 (< 2.0.12) connection"

            def cursor(self):
                return CursorMock()

        # psycopg2 < 2.0.12 code path
        conn = OlderConnectionMock()
        self.assertEqual(pg_version.get_version(conn), 90300)
Esempio n. 3
0
    def db_type(self, connection):
        if connection.vendor != 'postgresql':
            raise RuntimeError('JSONBField works only with PostgreSQL')

        if get_version(connection) < 90400:
            raise RuntimeError('JSONBField works only with PostgreSQL >= 9.4')

        return 'jsonb'
Esempio n. 4
0
    def db_type(self, connection):
        if connection.vendor != 'postgresql':
            raise RuntimeError('JSONBField works only with PostgreSQL')

        if get_version(connection) < 90400:
            raise RuntimeError('JSONBField works only with PostgreSQL >= 9.4')

        return 'jsonb'
Esempio n. 5
0
 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']])
         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 CursorWrapper(cursor)
Esempio n. 6
0
    def install_hstore_contrib(self):
        # point to test database
        self.connection.close()
        test_database_name = self._get_test_db_name()
        self.connection.settings_dict["NAME"] = test_database_name
        # Test to see if HSTORE type was already installed
        cursor = self.connection.cursor()
        cursor.execute("SELECT 1 FROM pg_type WHERE typname='hstore';")
        if cursor.fetchone():
            # skip if already exists
            return
        if get_version(self.connection) >= 90100:
            cursor.execute("create extension hstore;")
            self.connection.commit_unless_managed()
            return
        import glob
        import os

        # Quick Hack to run HSTORE sql script for test runs
        sql = getattr(settings, "HSTORE_SQL", None)
        if not sql:
            # Attempt to helpfully locate contrib SQL on typical installs
            for loc in (
                # Ubuntu/Debian Location
                "/usr/share/postgresql/*/contrib/hstore.sql",
                # Redhat/RPM location
                "/usr/share/pgsql/contrib/hstore.sql",
                # MacOSX location
                "/Library/PostgreSQL/*/share/postgresql/contrib/hstore.sql",
                # MacPorts location
                "/opt/local/share/postgresql*/contrib/hstore.sql",
                # Mac HomeBrew location
                "/usr/local/Cellar/postgresql/*/share/contrib/hstore.sql",
                # Windows location
                "C:/Program Files/PostgreSQL/*/share/contrib/hstore.sql",
                # Windows 32-bit location
                "C:/Program Files (x86)/PostgreSQL/*/share/contrib/hstore.sql",
            ):
                files = glob.glob(loc)
                if files and len(files) > 0:
                    sql = sorted(files)[-1]
                    log.info("Found installed HSTORE script: %s" % (sql,))
                    break
        if sql and os.path.isfile(sql):
            self.executescript(sql, "HSTORE")
        else:
            message = (
                "Valid HSTORE sql script not found.  You may need to install the postgres contrib module.\n"
                + "You can explicitly locate it with the HSTORE_SQL property in django settings."
            )
            log.warning(message)
            print >>sys.stderr, message
Esempio n. 7
0
 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']])
         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 CursorWrapper(cursor)
Esempio n. 8
0
 def install_hstore_contrib(self):
     # point to test database
     self.connection.close()
     test_database_name = self._get_test_db_name()
     self.connection.settings_dict["NAME"] = test_database_name
     # Test to see if HSTORE type was already installed
     cursor = self.connection.cursor()
     cursor.execute("SELECT 1 FROM pg_type WHERE typname='hstore';")
     if cursor.fetchone():
         # skip if already exists
         return
     if get_version(self.connection) >= 90100:
         cursor.execute("create extension hstore;")
         self.connection.commit_unless_managed()
         return
     import glob
     import os
     # Quick Hack to run HSTORE sql script for test runs
     sql = getattr(settings, 'HSTORE_SQL', None)
     if not sql:
         # Attempt to helpfully locate contrib SQL on typical installs
         for loc in (
                 # Ubuntu/Debian Location
                 '/usr/share/postgresql/*/contrib/hstore.sql',
                 # Redhat/RPM location
                 '/usr/share/pgsql/contrib/hstore.sql',
                 # MacOSX location
                 '/Library/PostgreSQL/*/share/postgresql/contrib/hstore.sql',
                 # MacPorts location
                 '/opt/local/share/postgresql*/contrib/hstore.sql',
                 # Mac HomeBrew location
                 '/usr/local/Cellar/postgresql/*/share/contrib/hstore.sql',
                 # Windows location
                 'C:/Program Files/PostgreSQL/*/share/contrib/hstore.sql',
                 # Windows 32-bit location
                 'C:/Program Files (x86)/PostgreSQL/*/share/contrib/hstore.sql',
         ):
             files = glob.glob(loc)
             if files and len(files) > 0:
                 sql = sorted(files)[-1]
                 log.info("Found installed HSTORE script: %s" % (sql, ))
                 break
     if sql and os.path.isfile(sql):
         self.executescript(sql, 'HSTORE')
     else:
         message = 'Valid HSTORE sql script not found.  You may need to install the postgres contrib module.\n' + \
             'You can explicitly locate it with the HSTORE_SQL property in django settings.'
         log.warning(message)
         print >> sys.stderr, message
Esempio n. 9
0
 def pg_version(self):
     with self.temporary_connection():
         return get_version(self.connection)
Esempio n. 10
0
 def db_type(self, connection):
     if get_version(connection) < 90200:
         raise RuntimeError("django_pgjson does not supports postgresql version < 9.2")
     return "json"
Esempio n. 11
0
 def db_type(self, connection):
     if get_version(connection) < 90400:
         raise RuntimeError("django_pgjson: PostgreSQL >= 9.4 is required for jsonb support.")
     return "jsonb"
Esempio n. 12
0
 def _get_pg_version(self):
     if self._pg_version is None:
         self._pg_version = get_version(self.connection)
     return self._pg_version
Esempio n. 13
0
 def pg_version(self):
     with self.temporary_connection():
         return get_version(self.connection)
Esempio n. 14
0
 def db_type(self, connection):
     return 'json' if connection.vendor == 'postgresql' and get_version(connection) >= 90200 else 'text'
Esempio n. 15
0
 def db_type(self, connection):
     if get_version(connection) < 90400:
         raise RuntimeError("django_pgjson: PostgreSQL >= 9.4 is required for jsonb support.")
     return "jsonb"
Esempio n. 16
0
File: base.py Progetto: alvz/django
 def pg_version(self):
     return get_version(self.connection)
Esempio n. 17
0
 def _get_postgres_version(self):
     if self._postgres_version is None:
         from django.db.backends.postgresql_psycopg2.version import get_version
         cursor = self.connection.cursor()
         self._postgres_version = get_version(cursor)
     return self._postgres_version
Esempio n. 18
0
 def db_type(self, connection):
     try:
         return 'json' if get_version(connection) >= 90200 else 'text'
     except AttributeError:
         return 'text'
Esempio n. 19
0
 def _get_pg_version(self):
     """Backwards compatibility for django 1.3"""
     if self._pg_version is None:
         self._pg_version = get_version(self.connection)
     return self._pg_version
Esempio n. 20
0
 def db_type(self, connection):
     return 'json' if get_version(connection) >= 90200 else 'text'
Esempio n. 21
0
 def db_type(self, connection):
     return 'json' if get_version(connection) >= 90200 else 'text'
Esempio n. 22
0
 def _get_postgres_version(self):
     if self._postgres_version is None:
         from django.db.backends.postgresql_psycopg2.version import get_version
         cursor = self.connection.cursor()
         self._postgres_version = get_version(cursor)
     return self._postgres_version
Esempio n. 23
0
 def db_type(self, connection):
     return 'json' if connection.vendor == 'postgresql' and get_version(
         connection) >= 90200 else 'text'
Esempio n. 24
0
 def db_type(self, connection):
     if get_version(connection) < 90200:
         raise RuntimeError("django_pgjson does not supports postgresql version < 9.2")
     return "json"
Esempio n. 25
0
 def _get_pg_version(self):
     if self._pg_version is None:
         self._pg_version = get_version(self.connection)
     return self._pg_version
Esempio n. 26
0
def get_postgresql_version(connection):
    """Returns the version number of the PostgreSQL connection."""
    from django.db.backends.postgresql_psycopg2.version import get_version
    return get_version(connection)
Esempio n. 27
0
def get_postgresql_version(connection):
    """Returns the version number of the PostgreSQL connection."""
    from django.db.backends.postgresql_psycopg2.version import get_version
    return get_version(connection)