Example #1
0
    def __init__(self, host, db, port='3050', user='******',
                 password='******', autoCommit=1,
                 dialect=None, role=None, charset=None, **kw):
        global kinterbasdb
        if kinterbasdb is None:
            import kinterbasdb
            # See http://kinterbasdb.sourceforge.net/dist_docs/usage.html
            # for an explanation; in short: use datetime, decimal and unicode.
            kinterbasdb.init(type_conv=200)
        self.module = kinterbasdb

        self.host = host
        self.port = port
        self.db = db
        self.user = user
        self.password = password
        if dialect:
            self.dialect = int(dialect)
        else:
            self.dialect = None
        self.role = role
        if charset:
            self.dbEncoding = charset.replace('-', '') # encoding defined by user in the connection string
        else:
            self.dbEncoding = charset
        self.defaultDbEncoding = '' # encoding defined during database creation and stored in the database
        DBAPI.__init__(self, **kw)
Example #2
0
    def __init__(self, host, db, user='******',
                 passwd='masterkey', autoCommit=1,
                 dialect=None, role=None, charset=None, **kw):
        global kinterbasdb
        if kinterbasdb is None:
            import kinterbasdb
        self.module = kinterbasdb
        
        self.limit_re = re.compile('^\s*(select )(.*)', re.IGNORECASE)

        if not autoCommit and not kw.has_key('pool'):
            # Pooling doesn't work with transactions...
            kw['pool'] = 0

        self.host = host
        self.db = db
        self.user = user
        self.passwd = passwd
        if dialect:
            self.dialect = int(dialect)
        else:
            self.dialect = None
        self.role = role
        self.charset = charset

        DBAPI.__init__(self, **kw)
Example #3
0
 def __init__(self, db, user, password='', host='localhost', port=0, **kw):
     global MySQLdb
     if MySQLdb is None:
         import MySQLdb, MySQLdb.constants.CR, MySQLdb.constants.ER
     self.module = MySQLdb
     self.host = host
     self.port = port
     self.db = db
     self.user = user
     self.password = password
     self.kw = {}
     if MySQLdb.version_info[:3] >= (1, 2, 1):
         self.need_unicode = True
     else:
         self.need_unicode = False
     for key in ("unix_socket", "init_command",
             "read_default_file", "read_default_group", "conv"):
         if key in kw:
             self.kw[key] = col.popKey(kw, key)
     for key in ("connect_timeout", "compress", "named_pipe", "use_unicode",
             "client_flag", "local_infile"):
         if key in kw:
             self.kw[key] = int(col.popKey(kw, key))
     if "charset" in kw:
         self.dbEncoding = self.kw["charset"] = col.popKey(kw, "charset")
     else:
         self.dbEncoding = None
     if "sqlobject_encoding" in kw:
         self.encoding = col.popKey(kw, "sqlobject_encoding")
     else:
         self.encoding = 'ascii'
     DBAPI.__init__(self, **kw)
Example #4
0
    def __init__(self, dsn=None, host=None, db=None,
                 user=None, passwd=None, usePygresql=False,
                 **kw):
        global psycopg, pgdb
        if usePygresql:
            if pgdb is None:
                import pgdb
            self.module = pgdb
        else:
            if psycopg is None:
                import psycopg
            self.module = psycopg

            # Register a converter for psycopg Binary type.
            registerConverter(type(psycopg.Binary('')),
                              PsycoBinaryConverter)

        if dsn is None:
            dsn = []
            if db:
                dsn.append('dbname=%s' % db)
            if user:
                dsn.append('user=%s' % user)
            if passwd:
                dsn.append('password=%s' % passwd)
            if host:
                # @@: right format?
                dsn.append('host=%s' % host)
            dsn = ' '.join(dsn)
        self.dsn = dsn
        DBAPI.__init__(self, **kw)

        # Server version cache
        self._server_version = None # Not yet initialized
Example #5
0
 def __init__(self, db, user, password='', host='localhost', port=0, **kw):
     global MySQLdb
     if MySQLdb is None:
         import MySQLdb, MySQLdb.constants.CR, MySQLdb.constants.ER
     self.module = MySQLdb
     self.host = host
     self.port = port
     self.db = db
     self.user = user
     self.password = password
     self.kw = {}
     for key in ("unix_socket", "init_command",
             "read_default_file", "read_default_group", "conv"):
         if key in kw:
             self.kw[key] = kw.pop(key)
     for key in ("connect_timeout", "compress", "named_pipe", "use_unicode",
             "client_flag", "local_infile"):
         if key in kw:
             self.kw[key] = int(kw.pop(key))
     for key in ("ssl_key", "ssl_cert", "ssl_ca", "ssl_capath"):
         if key in kw:
             if "ssl" not in self.kw:
                 self.kw["ssl"] = {}
             self.kw["ssl"][key[4:]] = kw.pop(key)
     if "charset" in kw:
         self.dbEncoding = self.kw["charset"] = kw.pop("charset")
     else:
         self.dbEncoding = None
     if "sqlobject_encoding" in kw:
         del kw["sqlobject_encoding"]
         deprecated("sqlobject_encoding is deprecated and no longer used.")
     DBAPI.__init__(self, **kw)
Example #6
0
    def __init__(self, db, user, password="", host="localhost", port=0, **kw):
        import MySQLdb, MySQLdb.constants.CR, MySQLdb.constants.ER

        self.module = MySQLdb
        self.host = host
        self.port = port
        self.db = db
        self.user = user
        self.password = password
        self.kw = {}
        for key in ("unix_socket", "init_command", "read_default_file", "read_default_group", "conv"):
            if key in kw:
                self.kw[key] = kw.pop(key)
        for key in ("connect_timeout", "compress", "named_pipe", "use_unicode", "client_flag", "local_infile"):
            if key in kw:
                self.kw[key] = int(kw.pop(key))
        for key in ("ssl_key", "ssl_cert", "ssl_ca", "ssl_capath"):
            if key in kw:
                if "ssl" not in self.kw:
                    self.kw["ssl"] = {}
                self.kw["ssl"][key[4:]] = kw.pop(key)
        if "charset" in kw:
            self.dbEncoding = self.kw["charset"] = kw.pop("charset")
        else:
            self.dbEncoding = None

        # MySQLdb < 1.2.1: only ascii
        # MySQLdb = 1.2.1: only unicode
        # MySQLdb > 1.2.1: both ascii and unicode
        self.need_unicode = (self.module.version_info[:3] >= (1, 2, 1)) and (self.module.version_info[:3] < (1, 2, 2))

        DBAPI.__init__(self, **kw)
Example #7
0
 def __init__(self, db, user, passwd='', host='localhost', **kw):
     global MySQLdb
     if MySQLdb is None:
         import MySQLdb
     self.module = MySQLdb
     self.host = host
     self.db = db
     self.user = user
     self.password = passwd
     DBAPI.__init__(self, **kw)
 def releaseConnection(self, conn, explicit=False):
     if self._memory:
         return
     threadid = self._threadOrigination.get(id(conn))
     DBAPI.releaseConnection(self, conn, explicit=explicit)
     if (self._pool is not None and threadid
         and threadid not in self._threadPool):
         self._threadPool[threadid] = conn
     else:
         if self._pool and conn in self._pool:
             self._pool.remove(conn)
         conn.close()
 def __init__(self, host, db, port='3050', user='******',
              password='******', autoCommit=1,
              dialect=None, role=None, charset=None, **kw):
     drivers = kw.pop('driver', None) or 'fdb,kinterbasdb'
     for driver in drivers.split(','):
         driver = driver.strip()
         if not driver:
             continue
         try:
             if driver == 'fdb':
                 import fdb
                 self.module = fdb
             elif driver == 'kinterbasdb':
                 import kinterbasdb
                 # See
                 # http://kinterbasdb.sourceforge.net/dist_docs/usage.html
                 # for an explanation; in short: use datetime, decimal and
                 # unicode.
                 kinterbasdb.init(type_conv=200)
                 self.module = kinterbasdb
             elif driver in ('firebirdsql', 'pyfirebirdsql'):
                 import firebirdsql
                 self.module = firebirdsql
             else:
                 raise ValueError(
                     'Unknown FireBird driver "%s", '
                     'expected fdb, kinterbasdb or firebirdsql' % driver)
         except ImportError:
             pass
         else:
             break
     else:
         raise ImportError(
             'Cannot find an FireBird driver, tried %s' % drivers)
     self.host = host
     self.port = port
     self.db = db
     self.user = user
     self.password = password
     if dialect:
         self.dialect = int(dialect)
     else:
         self.dialect = None
     self.role = role
     if charset:
         # Encoding defined by user in the connection string.
         self.dbEncoding = charset.replace('-', '')
     else:
         self.dbEncoding = charset
     # Encoding defined during database creation and stored in the database.
     self.defaultDbEncoding = ''
     DBAPI.__init__(self, **kw)
Example #10
0
    def __init__(self, db, user, password='', host='localhost',
                 autoCommit=0, **kw):
        global sqlmodule
        if not sqlmodule:
            try:
                import adodbapi as sqlmodule
            except ImportError:
                import pymssql as sqlmodule

        if sqlmodule.__name__ == 'adodbapi':
            import adodbapi as sqlmodule
            self.dbconnection = sqlmodule.connect
            # ADO uses unicode only (AFAIK)
            self.usingUnicodeStrings = True

            # Need to use SQLNCLI provider for SQL Server Express Edition
            if kw.get("ncli"):
                conn_str = "Provider=SQLNCLI;"
            else:
                conn_str = "Provider=SQLOLEDB;"

            conn_str += "Data Source=%s;Initial Catalog=%s;"

            # MSDE does not allow SQL server login 
            if kw.get("sspi"):
                conn_str += "Integrated Security=SSPI;Persist Security Info=False"
                self.make_conn_str = lambda keys: [conn_str % (keys.host, keys.db)]
            else:
                conn_str += "User Id=%s;Password=%s"
                self.make_conn_str = lambda keys: [conn_str % (keys.host, keys.db, keys.user, keys.password)]

            kw.pop("sspi", None)
            kw.pop("ncli", None)

        else: # pymssql
            self.dbconnection = sqlmodule.connect
            sqlmodule.Binary = lambda st: str(st)
            # don't know whether pymssql uses unicode
            self.usingUnicodeStrings = False
            self.make_conn_str = lambda keys:  \
                   ["", keys.user, keys.password, keys.host, keys.db]

        self.autoCommit=int(autoCommit)
        self.host = host
        self.db = db
        self.user = user
        self.password = password
        self.limit_re = re.compile('^\s*(select )(.*)', re.IGNORECASE)
        self.password = password
        self.module = sqlmodule
        self._can_use_max_types = None
        DBAPI.__init__(self, **kw)
    def __init__(self, host='', port=None, user=None, password=None,
                 database=None, autoCommit=1, sqlmode='internal',
                 isolation=None, timeout=None, **kw):
        from sapdb import dbapi
        self.module = dbapi
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.db = database
        self.autoCommit = autoCommit
        self.sqlmode = sqlmode
        self.isolation = isolation
        self.timeout = timeout

        DBAPI.__init__(self, **kw)
Example #12
0
    def __init__ (self, host='', port=None, user=None, password=None,
                  database=None, autoCommit=1, sqlmode='internal',
                  isolation=None, timeout=None, **kw):
        from sapdb import dbapi
        self.module = dbapi
        self.host      = host
        self.port      = port
        self.user      = user
        self.password  = password
        self.db        = database
        self.autoCommit = autoCommit
        self.sqlmode   = sqlmode
        self.isolation = isolation
        self.timeout   = timeout

        DBAPI.__init__(self, **kw)
 def _insertSQL(self, table, names, values):
     if not names:
         assert not values
         # INSERT INTO table () VALUES () isn't allowed in
         # SQLite (though it is in other databases)
         return ("INSERT INTO %s VALUES (NULL)" % table)
     else:
         return DBAPI._insertSQL(self, table, names, values)
 def _insertSQL(self, table, names, values):
     if not names:
         assert not values
         # INSERT INTO table () VALUES () isn't allowed in
         # SQLite (though it is in other databases)
         return ("INSERT INTO %s VALUES (NULL)" % table)
     else:
         return DBAPI._insertSQL(self, table, names, values)
Example #15
0
    def __init__(self, dsn=None, host=None, port=None, db=None,
                 user=None, password=None, unicodeCols=False, **kw):
        from rdbhdb import rdbhdb as rdb
        # monkey patch % escaping into Cursor._execute
        old_execute = getattr(rdb.Cursor, '_execute')
        setattr(rdb.Cursor, '_old_execute', old_execute)

        def _execute(self, query, *args):
            assert not any([a for a in args])
            query = query.replace('%', '%%')
            self._old_execute(query, (), (), ())
        setattr(rdb.Cursor, '_execute', _execute)

        self.module = rdb
        self.user = user
        self.host = host
        self.port = port
        self.db = db
        self.password = password
        self.dsn_dict = dsn_dict = {}
        self.use_dsn = dsn is not None
        if host:
            dsn_dict["host"] = host
        if user:
            dsn_dict["role"] = user
        if password:
            dsn_dict["authcode"] = password
        if dsn is None:
            dsn = []
            if db:
                dsn.append('dbname=%s' % db)
            if user:
                dsn.append('user=%s' % user)
            if password:
                dsn.append('password=%s' % password)
            if host:
                dsn.append('host=%s' % host)
            if port:
                dsn.append('port=%d' % port)
            dsn = ' '.join(dsn)
        self.dsn = dsn
        self.unicodeCols = unicodeCols
        self.schema = kw.pop('schema', None)
        self.dbEncoding = 'utf-8'
        DBAPI.__init__(self, **kw)
    def __init__(
        self,
        host,
        db,
        port="3050",
        user="******",
        password="******",
        autoCommit=1,
        dialect=None,
        role=None,
        charset=None,
        **kw
    ):
        try:
            import fdb

            self.module = fdb
        except ImportError:
            import kinterbasdb

            # See http://kinterbasdb.sourceforge.net/dist_docs/usage.html
            # for an explanation; in short: use datetime, decimal and
            # unicode.
            kinterbasdb.init(type_conv=200)
            self.module = kinterbasdb

        self.host = host
        self.port = port
        self.db = db
        self.user = user
        self.password = password
        if dialect:
            self.dialect = int(dialect)
        else:
            self.dialect = None
        self.role = role
        if charset:
            # Encoding defined by user in the connection string.
            self.dbEncoding = charset.replace("-", "")
        else:
            self.dbEncoding = charset
        # Encoding defined during database creation and stored in the database.
        self.defaultDbEncoding = ""
        DBAPI.__init__(self, **kw)
    def __init__(self, host, port, db, user='******',
                 password='******', autoCommit=1,
                 dialect=None, role=None, charset=None, **kw):
        import kinterbasdb
        self.module = kinterbasdb

        self.host = host
        self.port = port
        self.db = db
        self.user = user
        self.password = password
        if dialect:
            self.dialect = int(dialect)
        else:
            self.dialect = None
        self.role = role
        self.charset = charset

        DBAPI.__init__(self, **kw)
Example #18
0
    def __init__(
        self, host, db, user="******", password="******", autoCommit=1, dialect=None, role=None, charset=None, **kw
    ):
        global kinterbasdb
        if kinterbasdb is None:
            import kinterbasdb
        self.module = kinterbasdb

        self.host = host
        self.db = db
        self.user = user
        self.password = password
        if dialect:
            self.dialect = int(dialect)
        else:
            self.dialect = None
        self.role = role
        self.charset = charset

        DBAPI.__init__(self, **kw)
Example #19
0
 def __init__(self, db, user, passwd='', host='localhost', port=None, **kw):
     global MySQLdb
     if MySQLdb is None:
         import MySQLdb
     self.module = MySQLdb
     self.host = host
     self.port = port
     self.db = db
     self.user = user
     self.password = passwd
     self.kw = {}
     for key in ("unix_socket", "named_pipe", "init_command",
             "read_default_file", "read_default_group"):
         if key in kw:
             self.kw[key] = col.popKey(kw, key)
     for key in ("connect_time", "compress", "named_pipe", "use_unicode",
             "client_flag", "local_infile"):
         if key in kw:
             self.kw[key] = int(col.popKey(kw, key))
     DBAPI.__init__(self, **kw)
    def __init__(self,
                 host,
                 db,
                 port='3050',
                 user='******',
                 password='******',
                 autoCommit=1,
                 dialect=None,
                 role=None,
                 charset=None,
                 **kw):
        try:
            import fdb
            self.module = fdb
        except ImportError:
            import kinterbasdb
            # See http://kinterbasdb.sourceforge.net/dist_docs/usage.html
            # for an explanation; in short: use datetime, decimal and
            # unicode.
            kinterbasdb.init(type_conv=200)
            self.module = kinterbasdb

        self.host = host
        self.port = port
        self.db = db
        self.user = user
        self.password = password
        if dialect:
            self.dialect = int(dialect)
        else:
            self.dialect = None
        self.role = role
        if charset:
            # Encoding defined by user in the connection string.
            self.dbEncoding = charset.replace('-', '')
        else:
            self.dbEncoding = charset
        # Encoding defined during database creation and stored in the database.
        self.defaultDbEncoding = ''
        DBAPI.__init__(self, **kw)
    def __init__(self, db, user, password='', host='localhost', port=0, **kw):
        import MySQLdb, MySQLdb.constants.CR, MySQLdb.constants.ER  # noqa
        self.module = MySQLdb
        self.host = host
        self.port = port
        self.db = db
        self.user = user
        self.password = password
        self.kw = {}
        for key in ("unix_socket", "init_command", "read_default_file",
                    "read_default_group", "conv"):
            if key in kw:
                self.kw[key] = kw.pop(key)
        for key in ("connect_timeout", "compress", "named_pipe", "use_unicode",
                    "client_flag", "local_infile"):
            if key in kw:
                self.kw[key] = int(kw.pop(key))
        for key in ("ssl_key", "ssl_cert", "ssl_ca", "ssl_capath"):
            if key in kw:
                if "ssl" not in self.kw:
                    self.kw["ssl"] = {}
                self.kw["ssl"][key[4:]] = kw.pop(key)
        if "charset" in kw:
            self.dbEncoding = self.kw["charset"] = kw.pop("charset")
        else:
            self.dbEncoding = None

        global mysql_Bin
        if not PY2 and mysql_Bin is None:
            mysql_Bin = MySQLdb.Binary
            MySQLdb.Binary = lambda x: mysql_Bin(x).decode(
                'ascii', errors='surrogateescape')

        if self.module.version_info[:3] < (1, 2, 2):
            raise ValueError('SQLObject requires MySQLdb 1.2.2 or later')

        self._server_version = None
        self._can_use_microseconds = None
        DBAPI.__init__(self, **kw)
Example #22
0
    def __init__(self, db, user, password='', host='localhost', port=0, **kw):
        import MySQLdb, MySQLdb.constants.CR, MySQLdb.constants.ER  # noqa
        self.module = MySQLdb
        self.host = host
        self.port = port
        self.db = db
        self.user = user
        self.password = password
        self.kw = {}
        for key in ("unix_socket", "init_command",
                    "read_default_file", "read_default_group", "conv"):
            if key in kw:
                self.kw[key] = kw.pop(key)
        for key in ("connect_timeout", "compress", "named_pipe", "use_unicode",
                    "client_flag", "local_infile"):
            if key in kw:
                self.kw[key] = int(kw.pop(key))
        for key in ("ssl_key", "ssl_cert", "ssl_ca", "ssl_capath"):
            if key in kw:
                if "ssl" not in self.kw:
                    self.kw["ssl"] = {}
                self.kw["ssl"][key[4:]] = kw.pop(key)
        if "charset" in kw:
            self.dbEncoding = self.kw["charset"] = kw.pop("charset")
        else:
            self.dbEncoding = None

        global mysql_Bin
        if not PY2 and mysql_Bin is None:
            mysql_Bin = MySQLdb.Binary
            MySQLdb.Binary = lambda x: mysql_Bin(x).decode(
                'ascii', errors='surrogateescape')

        if self.module.version_info[:3] < (1, 2, 2):
            raise ValueError('SQLObject requires MySQLdb 1.2.2 or later')

        self._server_version = None
        self._can_use_microseconds = None
        DBAPI.__init__(self, **kw)
Example #23
0
    def __init__(self, host, db, user='******',
                 passwd='masterkey', autoCommit=1,
                 dialect=None, role=None, charset=None, **kw):
        global kinterbasdb
        if kinterbasdb is None:
            import kinterbasdb
        self.module = kinterbasdb

        self.limit_re = re.compile('^\s*(select )(.*)', re.IGNORECASE)

        self.host = host
        self.db = db
        self.user = user
        self.passwd = passwd
        if dialect:
            self.dialect = int(dialect)
        else:
            self.dialect = None
        self.role = role
        self.charset = charset

        DBAPI.__init__(self, **kw)
Example #24
0
    def __init__(self, filename, autoCommit=1, **kw):
        global sqlite
        global using_sqlite2
        if sqlite is None:
            try:
                from pysqlite2 import dbapi2 as sqlite

                using_sqlite2 = True
            except ImportError:
                import sqlite

                using_sqlite2 = False
        self.module = sqlite
        self.filename = filename  # full path to sqlite-db-file
        # connection options
        opts = {}
        if using_sqlite2:
            if autoCommit:
                opts["isolation_level"] = None
            if "encoding" in kw:
                import warnings

                warnings.warn(DeprecationWarning("pysqlite2 does not support the encoding option"))
            opts["detect_types"] = sqlite.PARSE_DECLTYPES
            for col_type in "text", "char", "varchar":
                sqlite.register_converter(col_type, stop_pysqlite2_converting_strings_to_unicode)
                sqlite.register_converter(col_type.upper(), stop_pysqlite2_converting_strings_to_unicode)
        else:
            opts["autocommit"] = autoCommit
            if "encoding" in kw:
                opts["encoding"] = popKey(kw, "encoding")
            if "mode" in kw:
                opts["mode"] = int(popKey(kw, "mode"), 0)
        if "timeout" in kw:
            opts["timeout"] = float(popKey(kw, "timeout"))
        # use only one connection for sqlite - supports multiple)
        # cursors per connection
        self._conn = sqlite.connect(self.filename, **opts)
        DBAPI.__init__(self, **kw)
Example #25
0
 def __init__(self, db, user, password='', host='localhost',
              locking=1, **kw):
     db = db.strip('/')
     global Sybase
     if Sybase is None:
         import Sybase
         Sybase._ctx.debug = 0
         from Sybase import NumericType
         from sqlobject.converters import registerConverter, IntConverter
         registerConverter(NumericType, IntConverter)
     self.module = Sybase
     self.locking = int(locking)
     self.host = host
     self.db = db
     self.user = user
     self.password = password
     autoCommit = kw.get('autoCommit')
     if autoCommit:
        autoCommmit = int(autoCommit)
     else:
         autoCommit = None
     kw['autoCommit'] = autoCommit
     DBAPI.__init__(self, **kw)
Example #26
0
    def __init__(self, db, user, password='', host='localhost', port=0, **kw):
        import MySQLdb, MySQLdb.constants.CR, MySQLdb.constants.ER
        self.module = MySQLdb
        self.host = host
        self.port = port
        self.db = db
        self.user = user
        self.password = password
        self.kw = {}
        for key in ("unix_socket", "init_command", "read_default_file",
                    "read_default_group", "conv"):
            if key in kw:
                self.kw[key] = kw.pop(key)
        for key in ("connect_timeout", "compress", "named_pipe", "use_unicode",
                    "client_flag", "local_infile"):
            if key in kw:
                self.kw[key] = int(kw.pop(key))
        for key in ("ssl_key", "ssl_cert", "ssl_ca", "ssl_capath"):
            if key in kw:
                if "ssl" not in self.kw:
                    self.kw["ssl"] = {}
                self.kw["ssl"][key[4:]] = kw.pop(key)
        if "charset" in kw:
            self.dbEncoding = self.kw["charset"] = kw.pop("charset")
        else:
            self.dbEncoding = None

        # MySQLdb < 1.2.1: only ascii
        # MySQLdb = 1.2.1: only unicode
        # MySQLdb > 1.2.1: both ascii and unicode
        self.need_unicode = (self.module.version_info[:3] >=
                             (1, 2, 1)) and (self.module.version_info[:3] <
                                             (1, 2, 2))

        self._server_version = None
        self._can_use_microseconds = None
        DBAPI.__init__(self, **kw)
 def _runWithConnection(self, meth, *args):
     if not self.autoCommit:
         return DBAPI._runWithConnection(self, meth, args)
     conn = self.getConnection()
     # @@: Horrible auto-commit implementation.  Just horrible!
     try:
         conn.begin()
     except self.module.ProgrammingError:
         pass
     try:
         val = meth(conn, *args)
         try:
             conn.commit()
         except self.module.ProgrammingError:
             pass
     finally:
         self.releaseConnection(conn)
     return val
 def _runWithConnection(self, meth, *args):
     if not self.autoCommit:
         return DBAPI._runWithConnection(self, meth, args)
     conn = self.getConnection()
     # @@: Horrible auto-commit implementation.  Just horrible!
     try:
         conn.begin()
     except self.module.ProgrammingError:
         pass
     try:
         val = meth(conn, *args)
         try:
             conn.commit()
         except self.module.ProgrammingError:
             pass
     finally:
         self.releaseConnection(conn)
     return val
 def __init__(self, filename, autoCommit=1, **kw):
     drivers = kw.pop('driver', None) or 'pysqlite2,sqlite3,sqlite'
     for driver in drivers.split(','):
         driver = driver.strip()
         if not driver:
             continue
         try:
             if driver in ('sqlite2', 'pysqlite2'):
                 from pysqlite2 import dbapi2 as sqlite
                 self.using_sqlite2 = True
             elif driver == 'sqlite3':
                 import sqlite3 as sqlite
                 self.using_sqlite2 = True
             elif driver in ('sqlite', 'sqlite1'):
                 import sqlite
                 self.using_sqlite2 = False
             else:
                 raise ValueError(
                     'Unknown SQLite driver "%s", expected pysqlite2, sqlite3 or sqlite'
                     % driver)
         except ImportError:
             pass
         else:
             break
     else:
         raise ImportError('Cannot find an SQLite driver, tried %s' %
                           drivers)
     if self.using_sqlite2:
         sqlite.encode = base64.encodestring
         sqlite.decode = base64.decodestring
     self.module = sqlite
     self.filename = filename  # full path to sqlite-db-file
     self._memory = filename == ':memory:'
     if self._memory and not self.using_sqlite2:
         raise ValueError("You must use sqlite2 to use in-memory databases")
     # connection options
     opts = {}
     if self.using_sqlite2:
         if autoCommit:
             opts["isolation_level"] = None
         global sqlite2_Binary
         if sqlite2_Binary is None:
             sqlite2_Binary = sqlite.Binary
             sqlite.Binary = lambda s: sqlite2_Binary(sqlite.encode(s))
         if 'factory' in kw:
             factory = kw.pop('factory')
             if isinstance(factory, str):
                 factory = globals()[factory]
             opts['factory'] = factory(sqlite)
     else:
         opts['autocommit'] = Boolean(autoCommit)
         if 'encoding' in kw:
             opts['encoding'] = kw.pop('encoding')
         if 'mode' in kw:
             opts['mode'] = int(kw.pop('mode'), 0)
     if 'timeout' in kw:
         if self.using_sqlite2:
             opts['timeout'] = float(kw.pop('timeout'))
         else:
             opts['timeout'] = int(float(kw.pop('timeout')) * 1000)
     if 'check_same_thread' in kw:
         opts["check_same_thread"] = Boolean(kw.pop('check_same_thread'))
     # use only one connection for sqlite - supports multiple)
     # cursors per connection
     self._connOptions = opts
     self.use_table_info = Boolean(kw.pop("use_table_info", True))
     DBAPI.__init__(self, **kw)
     self._threadPool = {}
     self._threadOrigination = {}
     if self._memory:
         self._memoryConn = sqlite.connect(self.filename,
                                           **self._connOptions)
         # Convert text data from SQLite to str, not unicode -
         # SQLObject converts it to unicode itself.
         self._memoryConn.text_factory = str
Example #30
0
    def __init__(self,
                 dsn=None,
                 host=None,
                 port=None,
                 db=None,
                 user=None,
                 password=None,
                 unicodeCols=False,
                 driver='rdbhost',
                 **kw):
        drivers = driver
        for driver in drivers.split(','):
            driver = driver.strip()
            if not driver:
                continue
            try:
                if driver == 'rdbhost':
                    from rdbhdb import rdbhdb as rdb
                    # monkey patch % escaping into Cursor._execute
                    old_execute = getattr(rdb.Cursor, '_execute')
                    setattr(rdb.Cursor, '_old_execute', old_execute)

                    def _execute(self, query, *args):
                        assert not any([a for a in args])
                        query = query.replace('%', '%%')
                        self._old_execute(query, (), (), ())

                    setattr(rdb.Cursor, '_execute', _execute)
                    self.module = rdb
                else:
                    raise ValueError('Unknown Rdbhost driver %s' % driver)
            except ImportError:
                pass
            else:
                break
        else:
            raise ImportError('Cannot find the Rdbhost driver')
        self.user = user
        self.host = host
        self.port = port
        self.db = db
        self.password = password
        self.dsn_dict = dsn_dict = {}
        self.use_dsn = dsn is not None
        if host:
            dsn_dict["host"] = host
        if user:
            dsn_dict["role"] = user
        if password:
            dsn_dict["authcode"] = password
        if dsn is None:
            dsn = []
            if db:
                dsn.append('dbname=%s' % db)
            if user:
                dsn.append('user=%s' % user)
            if password:
                dsn.append('password=%s' % password)
            if host:
                dsn.append('host=%s' % host)
            if port:
                dsn.append('port=%d' % port)
            dsn = ' '.join(dsn)
        self.dsn = dsn
        self.unicodeCols = unicodeCols
        self.schema = kw.pop('schema', None)
        self.dbEncoding = 'utf-8'
        DBAPI.__init__(self, **kw)
Example #31
0
    def __init__(self, dsn=None, host=None, port=None, db=None,
                 user=None, passwd=None, usePygresql=False, unicodeCols=False,
                 **kw):
        global psycopg, pgdb
        self.usePygresql = usePygresql
        if usePygresql:
            if pgdb is None:
                import pgdb
            self.module = pgdb
        else:
            if psycopg is None:
                import psycopg
            self.module = psycopg

            # Register a converter for psycopg Binary type.
            registerConverter(type(psycopg.Binary('')),
                              PsycoBinaryConverter)

        self.user = user
        self.host = host
        self.port = port
        self.db = db
        self.password = passwd
        self.dsn_dict = dsn_dict = {}
        if host:
            dsn_dict["host"] = host
        if port:
            if usePygresql:
                dsn_dict["host"] = "%s:%d" % (host, port)
            else:
                dsn_dict["port"] = str(port)
        if db:
            dsn_dict["database"] = db
        if user:
            dsn_dict["user"] = user
        if passwd:
            dsn_dict["password"] = passwd
        self.use_dsn = dsn is not None
        if dsn is None:
            if usePygresql:
                dsn = ''
                if host:
                    dsn += host
                dsn += ':'
                if db:
                    dsn += db
                dsn += ':'
                if user:
                    dsn += user
                dsn += ':'
                if passwd:
                    dsn += passwd
            else:
                dsn = []
                if db:
                    dsn.append('dbname=%s' % db)
                if user:
                    dsn.append('user=%s' % user)
                if passwd:
                    dsn.append('password=%s' % passwd)
                if host:
                    dsn.append('host=%s' % host)
                if port:
                    dsn.append('port=%d' % port)
                dsn = ' '.join(dsn)
        self.dsn = dsn
        self.unicodeCols = unicodeCols
        DBAPI.__init__(self, **kw)

        # Server version cache
        self._server_version = None # Not yet initialized
Example #32
0
    def __init__(self,
                 db,
                 user,
                 password='',
                 host='localhost',
                 port=None,
                 autoCommit=0,
                 **kw):
        drivers = kw.pop('driver', None) or 'adodb,pymssql'
        for driver in drivers.split(','):
            driver = driver.strip()
            if not driver:
                continue
            try:
                if driver in ('adodb', 'adodbapi'):
                    import adodbapi as sqlmodule
                elif driver == 'pymssql':
                    import pymssql as sqlmodule
                else:
                    raise ValueError(
                        'Unknown MSSQL driver "%s", expected adodb or pymssql'
                        % driver)
            except ImportError:
                pass
            else:
                break
        else:
            raise ImportError('Cannot find an MSSQL driver, tried %s' %
                              drivers)
        self.module = sqlmodule

        if sqlmodule.__name__ == 'adodbapi':
            self.dbconnection = sqlmodule.connect
            # ADO uses unicode only (AFAIK)
            self.usingUnicodeStrings = True

            # Need to use SQLNCLI provider for SQL Server Express Edition
            if kw.get("ncli"):
                conn_str = "Provider=SQLNCLI;"
            else:
                conn_str = "Provider=SQLOLEDB;"

            conn_str += "Data Source=%s;Initial Catalog=%s;"

            # MSDE does not allow SQL server login
            if kw.get("sspi"):
                conn_str += "Integrated Security=SSPI;Persist Security Info=False"
                self.make_conn_str = lambda keys: conn_str % (keys.host, keys.
                                                              db)
            else:
                conn_str += "User Id=%s;Password=%s"
                self.make_conn_str = lambda keys: conn_str % (
                    keys.host, keys.db, keys.user, keys.password)

            kw.pop("sspi", None)
            kw.pop("ncli", None)

        else:  # pymssql
            self.dbconnection = sqlmodule.connect
            sqlmodule.Binary = lambda st: str(st)
            # don't know whether pymssql uses unicode
            self.usingUnicodeStrings = False

            def _make_conn_str(keys):
                keys_dict = {}
                for attr, value in (
                    ('user', keys.user),
                    ('password', keys.password),
                    ('host', keys.host),
                    ('port', keys.port),
                    ('database', keys.db),
                ):
                    if value: keys_dict[attr] = value
                return keys_dict

            self.make_conn_str = _make_conn_str

        self.autoCommit = int(autoCommit)
        self.user = user
        self.password = password
        self.host = host
        self.port = port
        self.db = db
        self._server_version = None
        self._can_use_max_types = None
        DBAPI.__init__(self, **kw)
Example #33
0
    def __init__(self,
                 dsn=None,
                 host=None,
                 port=None,
                 db=None,
                 user=None,
                 password=None,
                 **kw):
        drivers = kw.pop('driver', None) or 'psycopg'
        for driver in drivers.split(','):
            driver = driver.strip()
            if not driver:
                continue
            try:
                if driver == 'psycopg2':
                    import psycopg2 as psycopg
                elif driver == 'psycopg1':
                    import psycopg
                elif driver == 'psycopg':
                    try:
                        import psycopg2 as psycopg
                    except ImportError:
                        import psycopg
                elif driver == 'pygresql':
                    import pgdb
                    self.module = pgdb
                else:
                    raise ValueError(
                        'Unknown PostgreSQL driver "%s", '
                        'expected psycopg2, psycopg1 or pygresql' % driver)
            except ImportError:
                pass
            else:
                break
        else:
            raise ImportError('Cannot find a PostgreSQL driver, tried %s' %
                              drivers)
        if driver.startswith('psycopg'):
            self.module = psycopg
            # Register a converter for psycopg Binary type.
            registerConverter(type(psycopg.Binary('')), PsycoBinaryConverter)

        self.user = user
        self.host = host
        self.port = port
        self.db = db
        self.password = password
        self.dsn_dict = dsn_dict = {}
        if host:
            dsn_dict["host"] = host
        if port:
            if driver == 'pygresql':
                dsn_dict["host"] = "%s:%d" % (host, port)
            else:
                if psycopg.__version__.split('.')[0] == '1':
                    dsn_dict["port"] = str(port)
                else:
                    dsn_dict["port"] = port
        if db:
            dsn_dict["database"] = db
        if user:
            dsn_dict["user"] = user
        if password:
            dsn_dict["password"] = password
        sslmode = kw.pop("sslmode", None)
        if sslmode:
            dsn_dict["sslmode"] = sslmode
        self.use_dsn = dsn is not None
        if dsn is None:
            if driver == 'pygresql':
                dsn = ''
                if host:
                    dsn += host
                dsn += ':'
                if db:
                    dsn += db
                dsn += ':'
                if user:
                    dsn += user
                dsn += ':'
                if password:
                    dsn += password
            else:
                dsn = []
                if db:
                    dsn.append('dbname=%s' % db)
                if user:
                    dsn.append('user=%s' % user)
                if password:
                    dsn.append('password=%s' % password)
                if host:
                    dsn.append('host=%s' % host)
                if port:
                    dsn.append('port=%d' % port)
                if sslmode:
                    dsn.append('sslmode=%s' % sslmode)
                dsn = ' '.join(dsn)
        self.driver = driver
        self.dsn = dsn
        self.unicodeCols = kw.pop('unicodeCols', False)
        self.schema = kw.pop('schema', None)
        self.dbEncoding = kw.pop("charset", None)
        DBAPI.__init__(self, **kw)
Example #34
0
    def __init__(self, db, user, password="", host="localhost", port=None, autoCommit=0, **kw):
        drivers = kw.pop("driver", None) or "adodb,pymssql"
        for driver in drivers.split(","):
            driver = driver.strip()
            if not driver:
                continue
            try:
                if driver in ("adodb", "adodbapi"):
                    import adodbapi as sqlmodule
                elif driver == "pymssql":
                    import pymssql as sqlmodule
                else:
                    raise ValueError('Unknown MSSQL driver "%s", expected adodb or pymssql' % driver)
            except ImportError:
                pass
            else:
                break
        else:
            raise ImportError("Cannot find an MSSQL driver, tried %s" % drivers)
        self.module = sqlmodule

        if sqlmodule.__name__ == "adodbapi":
            self.dbconnection = sqlmodule.connect
            # ADO uses unicode only (AFAIK)
            self.usingUnicodeStrings = True

            # Need to use SQLNCLI provider for SQL Server Express Edition
            if kw.get("ncli"):
                conn_str = "Provider=SQLNCLI;"
            else:
                conn_str = "Provider=SQLOLEDB;"

            conn_str += "Data Source=%s;Initial Catalog=%s;"

            # MSDE does not allow SQL server login
            if kw.get("sspi"):
                conn_str += "Integrated Security=SSPI;Persist Security Info=False"
                self.make_conn_str = lambda keys: [conn_str % (keys.host, keys.db)]
            else:
                conn_str += "User Id=%s;Password=%s"
                self.make_conn_str = lambda keys: [conn_str % (keys.host, keys.db, keys.user, keys.password)]

            kw.pop("sspi", None)
            kw.pop("ncli", None)

        else:  # pymssql
            self.dbconnection = sqlmodule.connect
            sqlmodule.Binary = lambda st: str(st)
            # don't know whether pymssql uses unicode
            self.usingUnicodeStrings = False
            self.make_conn_str = lambda keys: ["", keys.user, keys.password, keys.host, keys.db]

        self.autoCommit = int(autoCommit)
        self.host = host
        self.port = port
        self.db = db
        self.user = user
        self.password = password
        self.password = password
        self._can_use_max_types = None
        DBAPI.__init__(self, **kw)
Example #35
0
 def __init__(self, filename, autoCommit=1, **kw):
     global sqlite
     global using_sqlite2
     if sqlite is None:
         try:
             from pysqlite2 import dbapi2 as sqlite
             using_sqlite2 = True
         except ImportError:
             import sqlite
             using_sqlite2 = False
     self.module = sqlite
     self.filename = filename  # full path to sqlite-db-file
     self._memory = filename == ':memory:'
     if self._memory:
         if not using_sqlite2:
             raise ValueError(
                 "You must use sqlite2 to use in-memory databases")
     # connection options
     opts = {}
     if using_sqlite2:
         if autoCommit:
             opts["isolation_level"] = None
         if 'encoding' in kw:
             import warnings
             warnings.warn(DeprecationWarning("pysqlite2 does not support the encoding option"))
         opts["detect_types"] = sqlite.PARSE_DECLTYPES
         for col_type in "text", "char", "varchar":
             sqlite.register_converter(col_type, stop_pysqlite2_converting_strings_to_unicode)
             sqlite.register_converter(col_type.upper(), stop_pysqlite2_converting_strings_to_unicode)
         try:
             from sqlite import encode, decode
         except ImportError:
             import base64
             sqlite.encode = base64.encodestring
             sqlite.decode = base64.decodestring
         else:
             sqlite.encode = encode
             sqlite.decode = decode
         global sqlite2_Binary
         if sqlite2_Binary is None:
             sqlite2_Binary = sqlite.Binary
             sqlite.Binary = lambda s: sqlite2_Binary(sqlite.encode(s))
     else:
         opts['autocommit'] = bool(autoCommit)
         if 'encoding' in kw:
             opts['encoding'] = popKey(kw, 'encoding')
         if 'mode' in kw:
             opts['mode'] = int(popKey(kw, 'mode'), 0)
     if 'timeout' in kw:
         opts['timeout'] = float(popKey(kw, 'timeout'))
     if 'check_same_thread' in kw:
         opts["check_same_thread"] = bool(popKey(kw, 'check_same_thread'))
     # use only one connection for sqlite - supports multiple)
     # cursors per connection
     self._connOptions = opts
     DBAPI.__init__(self, **kw)
     self._threadPool = {}
     self._threadOrigination = {}
     if self._memory:
         self._memoryConn = sqlite.connect(
             self.filename, **self._connOptions)
Example #36
0
    def __init__(self, dsn=None, host=None, port=None, db=None,
                 user=None, password=None, **kw):
        drivers = kw.pop('driver', None) or 'psycopg'
        for driver in drivers.split(','):
            driver = driver.strip()
            if not driver:
                continue
            try:
                if driver == 'psycopg2':
                    import psycopg2 as psycopg
                elif driver == 'psycopg1':
                    import psycopg
                elif driver == 'psycopg':
                    try:
                        import psycopg2 as psycopg
                    except ImportError:
                        import psycopg
                elif driver == 'pygresql':
                    import pgdb
                    self.module = pgdb
                else:
                    raise ValueError('Unknown PostgreSQL driver "%s", expected psycopg2, psycopg1 or pygresql' % driver)
            except ImportError:
                pass
            else:
                break
        else:
            raise ImportError('Cannot find a PostgreSQL driver, tried %s' % drivers)
        if driver.startswith('psycopg'):
            self.module = psycopg
            # Register a converter for psycopg Binary type.
            registerConverter(type(psycopg.Binary('')),
                              PsycoBinaryConverter)

        self.user = user
        self.host = host
        self.port = port
        self.db = db
        self.password = password
        self.dsn_dict = dsn_dict = {}
        if host:
            dsn_dict["host"] = host
        if port:
            if driver == 'pygresql':
                dsn_dict["host"] = "%s:%d" % (host, port)
            else:
                if psycopg.__version__.split('.')[0] == '1':
                    dsn_dict["port"] = str(port)
                else:
                    dsn_dict["port"] = port
        if db:
            dsn_dict["database"] = db
        if user:
            dsn_dict["user"] = user
        if password:
            dsn_dict["password"] = password
        sslmode = kw.pop("sslmode", None)
        if sslmode:
            dsn_dict["sslmode"] = sslmode
        self.use_dsn = dsn is not None
        if dsn is None:
            if driver == 'pygresql':
                dsn = ''
                if host:
                    dsn += host
                dsn += ':'
                if db:
                    dsn += db
                dsn += ':'
                if user:
                    dsn += user
                dsn += ':'
                if password:
                    dsn += password
            else:
                dsn = []
                if db:
                    dsn.append('dbname=%s' % db)
                if user:
                    dsn.append('user=%s' % user)
                if password:
                    dsn.append('password=%s' % password)
                if host:
                    dsn.append('host=%s' % host)
                if port:
                    dsn.append('port=%d' % port)
                if sslmode:
                    dsn.append('sslmode=%s' % sslmode)
                dsn = ' '.join(dsn)
        self.driver = driver
        self.dsn = dsn
        self.unicodeCols = kw.pop('unicodeCols', False)
        self.schema = kw.pop('schema', None)
        self.dbEncoding = kw.pop("charset", None)
        DBAPI.__init__(self, **kw)
Example #37
0
    def __init__(self, db, user, password='', host='localhost', port=0, **kw):
        drivers = kw.pop('driver', None) or 'mysqldb'
        for driver in drivers.split(','):
            driver = driver.strip()
            if not driver:
                continue
            try:
                if driver.lower() in ('mysqldb', 'pymysql'):
                    if driver.lower() == 'pymysql':
                        import pymysql
                        pymysql.install_as_MySQLdb()
                    import MySQLdb
                    if driver.lower() == 'mysqldb':
                        if MySQLdb.version_info[:3] < (1, 2, 2):
                            raise ValueError(
                                'SQLObject requires MySQLdb 1.2.2 or later')
                    import MySQLdb.constants.CR
                    import MySQLdb.constants.ER
                    self.module = MySQLdb
                    if driver.lower() == 'mysqldb':
                        self.CR_SERVER_GONE_ERROR = \
                            MySQLdb.constants.CR.SERVER_GONE_ERROR
                        self.CR_SERVER_LOST = \
                            MySQLdb.constants.CR.SERVER_LOST
                    else:
                        self.CR_SERVER_GONE_ERROR = \
                            MySQLdb.constants.CR.CR_SERVER_GONE_ERROR
                        self.CR_SERVER_LOST = \
                            MySQLdb.constants.CR.CR_SERVER_LOST
                    self.ER_DUP_ENTRY = MySQLdb.constants.ER.DUP_ENTRY
                elif driver == 'connector':
                    import mysql.connector
                    self.module = mysql.connector
                    self.CR_SERVER_GONE_ERROR = \
                        mysql.connector.errorcode.CR_SERVER_GONE_ERROR
                    self.CR_SERVER_LOST = \
                        mysql.connector.errorcode.CR_SERVER_LOST
                    self.ER_DUP_ENTRY = mysql.connector.errorcode.ER_DUP_ENTRY
                elif driver == 'oursql':
                    import oursql
                    self.module = oursql
                    self.CR_SERVER_GONE_ERROR = \
                        oursql.errnos['CR_SERVER_GONE_ERROR']
                    self.CR_SERVER_LOST = oursql.errnos['CR_SERVER_LOST']
                    self.ER_DUP_ENTRY = oursql.errnos['ER_DUP_ENTRY']
                elif driver == 'pyodbc':
                    import pyodbc
                    self.module = pyodbc
                elif driver == 'pypyodbc':
                    import pypyodbc
                    self.module = pypyodbc
                elif driver == 'odbc':
                    try:
                        import pyodbc
                    except ImportError:
                        import pypyodbc as pyodbc
                    self.module = pyodbc
                else:
                    raise ValueError('Unknown MySQL driver "%s", '
                                     'expected mysqldb, connector, '
                                     'oursql, pymysql, '
                                     'odbc, pyodbc or pypyodbc' % driver)
            except ImportError:
                pass
            else:
                break
        else:
            raise ImportError('Cannot find a MySQL driver, tried %s' % drivers)
        self.host = host
        self.port = port or 3306
        self.db = db
        self.user = user
        self.password = password
        self.kw = {}
        for key in ("unix_socket", "init_command", "read_default_file",
                    "read_default_group", "conv"):
            if key in kw:
                self.kw[key] = kw.pop(key)
        for key in ("connect_timeout", "compress", "named_pipe", "use_unicode",
                    "client_flag", "local_infile"):
            if key in kw:
                self.kw[key] = int(kw.pop(key))
        for key in ("ssl_key", "ssl_cert", "ssl_ca", "ssl_capath"):
            if key in kw:
                if "ssl" not in self.kw:
                    self.kw["ssl"] = {}
                self.kw["ssl"][key[4:]] = kw.pop(key)
        if "charset" in kw:
            self.dbEncoding = self.kw["charset"] = kw.pop("charset")
        else:
            self.dbEncoding = None
        self.driver = driver

        if driver in ('odbc', 'pyodbc', 'pypyodbc'):
            self.make_odbc_conn_str(
                kw.pop('odbcdrv', 'MySQL ODBC 5.3 ANSI Driver'), db, host,
                port, user, password)
            self.CR_SERVER_GONE_ERROR = 2006
            self.CR_SERVER_LOST = 2013
            self.ER_DUP_ENTRY = '23000'

        global mysql_Bin
        if not PY2 and mysql_Bin is None:
            mysql_Bin = self.module.Binary
            self.module.Binary = lambda x: mysql_Bin(x).decode(
                'ascii', errors='surrogateescape')

        self._server_version = None
        self._can_use_microseconds = None
        DBAPI.__init__(self, **kw)
    def __init__(
        self,
        dsn=None,
        host=None,
        port=None,
        db=None,
        user=None,
        password=None,
        unicodeCols=False,
        driver="rdbhost",
        **kw
    ):
        drivers = driver
        for driver in drivers.split(","):
            driver = driver.strip()
            if not driver:
                continue
            try:
                if driver == "rdbhost":
                    from rdbhdb import rdbhdb as rdb

                    # monkey patch % escaping into Cursor._execute
                    old_execute = getattr(rdb.Cursor, "_execute")
                    setattr(rdb.Cursor, "_old_execute", old_execute)

                    def _execute(self, query, *args):
                        assert not any([a for a in args])
                        query = query.replace("%", "%%")
                        self._old_execute(query, (), (), ())

                    setattr(rdb.Cursor, "_execute", _execute)
                    self.module = rdb
                else:
                    raise ValueError("Unknown Rdbhost driver %s" % driver)
            except ImportError:
                pass
            else:
                break
        else:
            raise ImportError("Cannot find the Rdbhost driver")
        self.user = user
        self.host = host
        self.port = port
        self.db = db
        self.password = password
        self.dsn_dict = dsn_dict = {}
        self.use_dsn = dsn is not None
        if host:
            dsn_dict["host"] = host
        if user:
            dsn_dict["role"] = user
        if password:
            dsn_dict["authcode"] = password
        if dsn is None:
            dsn = []
            if db:
                dsn.append("dbname=%s" % db)
            if user:
                dsn.append("user=%s" % user)
            if password:
                dsn.append("password=%s" % password)
            if host:
                dsn.append("host=%s" % host)
            if port:
                dsn.append("port=%d" % port)
            dsn = " ".join(dsn)
        self.dsn = dsn
        self.unicodeCols = unicodeCols
        self.schema = kw.pop("schema", None)
        self.dbEncoding = "utf-8"
        DBAPI.__init__(self, **kw)
 def close(self):
     DBAPI.close(self)
     self._threadPool = {}
Example #40
0
 def close(self):
     DBAPI.close(self)
     self._threadPool = {}
     if self._memory:
         self._memoryConn.close()
         self.makeMemoryConnection()
Example #41
0
    def __init__(self, dsn=None, host=None, port=None, db=None,
                 user=None, password=None, usePygresql=False, **kw):
        global psycopg, pgdb
        self.usePygresql = usePygresql
        if usePygresql:
            if pgdb is None:
                import pgdb
            self.module = pgdb
        else:
            if psycopg is None:
                try:
                    import psycopg2 as psycopg
                except ImportError:
                    import psycopg
            self.module = psycopg

            # Register a converter for psycopg Binary type.
            registerConverter(type(psycopg.Binary('')),
                              PsycoBinaryConverter)

        self.user = user
        self.host = host
        self.port = port
        self.db = db
        self.password = password
        self.dsn_dict = dsn_dict = {}
        if host:
            dsn_dict["host"] = host
        if port:
            if usePygresql:
                dsn_dict["host"] = "%s:%d" % (host, port)
            else:
                if psycopg.__version__.split('.')[0] == '1':
                    dsn_dict["port"] = str(port)
                else:
                    dsn_dict["port"] = port
        if db:
            dsn_dict["database"] = db
        if user:
            dsn_dict["user"] = user
        if password:
            dsn_dict["password"] = password
        self.use_dsn = dsn is not None
        if dsn is None:
            if usePygresql:
                dsn = ''
                if host:
                    dsn += host
                dsn += ':'
                if db:
                    dsn += db
                dsn += ':'
                if user:
                    dsn += user
                dsn += ':'
                if password:
                    dsn += password
            else:
                dsn = []
                if db:
                    dsn.append('dbname=%s' % db)
                if user:
                    dsn.append('user=%s' % user)
                if password:
                    dsn.append('password=%s' % password)
                if host:
                    dsn.append('host=%s' % host)
                if port:
                    dsn.append('port=%d' % port)
                dsn = ' '.join(dsn)
        self.dsn = dsn
        self.unicodeCols = kw.pop('unicodeCols', False)
        self.schema = kw.pop('schema', None)
        DBAPI.__init__(self, **kw)
 def close(self):
     DBAPI.close(self)
     self._threadPool = {}
     if self._memory:
         self._memoryConn.close()
         self.makeMemoryConnection()
Example #43
0
    def __init__(self, dsn=None, host=None, port=None, db=None,
                 user=None, password=None, **kw):
        drivers = kw.pop('driver', None) or 'psycopg'
        for driver in drivers.split(','):
            driver = driver.strip()
            if not driver:
                continue
            try:
                if driver == 'psycopg2':
                    import psycopg2 as psycopg
                    self.module = psycopg
                elif driver == 'psycopg1':
                    import psycopg
                    self.module = psycopg
                elif driver == 'psycopg':
                    try:
                        import psycopg2 as psycopg
                    except ImportError:
                        import psycopg
                    self.module = psycopg
                elif driver == 'pygresql':
                    import pgdb
                    self.module = pgdb
                elif driver in ('py-postgresql', 'pypostgresql'):
                    from postgresql.driver import dbapi20
                    self.module = dbapi20
                elif driver == 'pyodbc':
                    import pyodbc
                    self.module = pyodbc
                elif driver == 'pypyodbc':
                    import pypyodbc
                    self.module = pypyodbc
                elif driver == 'odbc':
                    try:
                        import pyodbc
                    except ImportError:
                        import pypyodbc as pyodbc
                    self.module = pyodbc
                else:
                    raise ValueError(
                        'Unknown PostgreSQL driver "%s", '
                        'expected psycopg, psycopg2, psycopg1, '
                        'pygresql, pypostgresql, '
                        'odbc, pyodbc or pypyodbc' % driver)
            except ImportError:
                pass
            else:
                break
        else:
            raise ImportError(
                'Cannot find a PostgreSQL driver, tried %s' % drivers)

        if driver.startswith('psycopg'):
            # Register a converter for psycopg Binary type.
            registerConverter(type(self.module.Binary('')),
                              PsycoBinaryConverter)
        elif type(self.module.Binary) in (type, type(PostgresBinaryConverter)):
            # Register a converter for Binary type.
            registerConverter(type(self.module.Binary(b'')),
                              PostgresBinaryConverter)

        self.db = db
        self.user = user
        self.password = password
        self.host = host
        self.port = port
        if driver in ('odbc', 'pyodbc', 'pypyodbc'):
            self.make_odbc_conn_str(kw.pop('odbcdrv', 'PostgreSQL ANSI'),
                                    db, host, port, user, password
                                    )
            sslmode = kw.pop("sslmode", None)
            if sslmode:
                self.odbc_conn_str += ';sslmode=require'
        else:
            self.dsn_dict = dsn_dict = {}
            if host:
                dsn_dict["host"] = host
            if port:
                if driver == 'pygresql':
                    dsn_dict["host"] = "%s:%d" % (host, port)
                elif driver.startswith('psycopg') and \
                        psycopg.__version__.split('.')[0] == '1':
                    dsn_dict["port"] = str(port)
                else:
                    dsn_dict["port"] = port
            if db:
                dsn_dict["database"] = db
            if user:
                dsn_dict["user"] = user
            if password:
                dsn_dict["password"] = password
            sslmode = kw.pop("sslmode", None)
            if sslmode:
                dsn_dict["sslmode"] = sslmode
            self.use_dsn = dsn is not None
            if dsn is None:
                if driver == 'pygresql':
                    dsn = ''
                    if host:
                        dsn += host
                    dsn += ':'
                    if db:
                        dsn += db
                    dsn += ':'
                    if user:
                        dsn += user
                    dsn += ':'
                    if password:
                        dsn += password
                else:
                    dsn = []
                    if db:
                        dsn.append('dbname=%s' % db)
                    if user:
                        dsn.append('user=%s' % user)
                    if password:
                        dsn.append('password=%s' % password)
                    if host:
                        dsn.append('host=%s' % host)
                    if port:
                        dsn.append('port=%d' % port)
                    if sslmode:
                        dsn.append('sslmode=%s' % sslmode)
                    dsn = ' '.join(dsn)
            if driver in ('py-postgresql', 'pypostgresql'):
                if host and host.startswith('/'):
                    dsn_dict["host"] = dsn_dict["port"] = None
                    dsn_dict["unix"] = host
                else:
                    if "unix" in dsn_dict:
                        del dsn_dict["unix"]
            self.dsn = dsn
        self.driver = driver
        self.unicodeCols = kw.pop('unicodeCols', False)
        self.schema = kw.pop('schema', None)
        self.dbEncoding = kw.pop("charset", None)
        DBAPI.__init__(self, **kw)
 def __init__(self, filename, autoCommit=1, **kw):
     drivers = kw.pop('driver', None) or 'pysqlite2,sqlite3,sqlite'
     for driver in drivers.split(','):
         driver = driver.strip()
         if not driver:
             continue
         try:
             if driver in ('sqlite2', 'pysqlite2'):
                     from pysqlite2 import dbapi2 as sqlite
                     self.using_sqlite2 = True
             elif driver == 'sqlite3':
                     import sqlite3 as sqlite
                     self.using_sqlite2 = True
             elif driver in ('sqlite', 'sqlite1'):
                     import sqlite
                     self.using_sqlite2 = False
             else:
                 raise ValueError('Unknown SQLite driver "%s", expected pysqlite2, sqlite3 or sqlite' % driver)
         except ImportError:
             pass
         else:
             break
     else:
         raise ImportError('Cannot find an SQLite driver, tried %s' % drivers)
     if self.using_sqlite2:
         sqlite.encode = base64.encodestring
         sqlite.decode = base64.decodestring
     self.module = sqlite
     self.filename = filename  # full path to sqlite-db-file
     self._memory = filename == ':memory:'
     if self._memory and not self.using_sqlite2:
         raise ValueError("You must use sqlite2 to use in-memory databases")
     # connection options
     opts = {}
     if self.using_sqlite2:
         if autoCommit:
             opts["isolation_level"] = None
         global sqlite2_Binary
         if sqlite2_Binary is None:
             sqlite2_Binary = sqlite.Binary
             sqlite.Binary = lambda s: sqlite2_Binary(sqlite.encode(s))
         if 'factory' in kw:
             factory = kw.pop('factory')
             if isinstance(factory, str):
                 factory = globals()[factory]
             opts['factory'] = factory(sqlite)
     else:
         opts['autocommit'] = Boolean(autoCommit)
         if 'encoding' in kw:
             opts['encoding'] = kw.pop('encoding')
         if 'mode' in kw:
             opts['mode'] = int(kw.pop('mode'), 0)
     if 'timeout' in kw:
         if self.using_sqlite2:
             opts['timeout'] = float(kw.pop('timeout'))
         else:
             opts['timeout'] = int(float(kw.pop('timeout')) * 1000)
     if 'check_same_thread' in kw:
         opts["check_same_thread"] = Boolean(kw.pop('check_same_thread'))
     # use only one connection for sqlite - supports multiple)
     # cursors per connection
     self._connOptions = opts
     self.use_table_info = Boolean(kw.pop("use_table_info", True))
     DBAPI.__init__(self, **kw)
     self._threadPool = {}
     self._threadOrigination = {}
     if self._memory:
         self.makeMemoryConnection()