Exemplo n.º 1
0
    def __call__(self, *args, **kwargs):
        nameWithArgs = u'{0}({1})'.format(self._name, u', '.join(self._db.formatArg(it) for it in args))

        if self._type == CDatabaseRoutine.PROCEDURE:
            return self._db.query(u'CALL {0};'.format(nameWithArgs))
        else:
            return CSqlExpression(self._db, nameWithArgs)
Exemplo n.º 2
0
 def __getitem__(self, key):
     key = str(key)
     result = self.fieldsDict.get(key, None)
     if result:
         return result if not self.aliasName else result.toTable(self.aliasName)
     elif key == '*':
         return CSqlExpression(self.database, '{0}.*'.format(self.tableName))
     else:
         raise CDatabaseException(u'В таблице %s не найдено поле "%s"' % (self.tableName, key))
Exemplo n.º 3
0
 def __lt__(self, val):
     return CSqlExpression(self.database,
                           self.lt(self.database.forceField(val)))
Exemplo n.º 4
0
 def __div__(self, other):
     return CSqlExpression(self.database, u'{0} / {1}'.format(self, other))
Exemplo n.º 5
0
 def __and__(self, other):
     return CSqlExpression(self.database,
                           u'{0} AND {1}'.format(self, other))
Exemplo n.º 6
0
 def __not__(self):
     return CSqlExpression(self.database, u'NOT {0}'.format(self))
Exemplo n.º 7
0
class CMySqlDatabase(CDatabase):
    limit1 = 'LIMIT 0, %d'
    limit2 = 'LIMIT %d, %d'
    CR_SERVER_GONE_ERROR = 2006
    CR_SERVER_LOST = 2013

    returnedDeadlockErrorText = u'Deadlock found when trying to get lock;'

    def __init__(self,
                 serverName,
                 serverPort,
                 databaseName,
                 userName,
                 password,
                 connectionName=None,
                 compressData=False,
                 **kwargs):
        CDatabase.__init__(self)
        self.createConnection('QMYSQL', connectionName, serverName, serverPort,
                              databaseName, userName, password)
        options = []
        if compressData:
            options.append('CLIENT_COMPRESS=1')
        if options:
            self.db.setConnectOptions(';'.join(options))
        self.connectUp()
        self.query('SET NAMES \'utf8\' COLLATE \'utf8_general_ci\';')
        self.query('SET SQL_AUTO_IS_NULL=0;')
        self.query('SET SQL_MODE=\'\';')

        self._func = None
        self._proc = None

    def escapeFieldName(self, name):
        u = unicode(name)
        if u.startswith('`') and u.endswith('`'):
            return u
        else:
            return '`' + u + '`'

    escapeTableName = escapeFieldName
    escapeSchemaName = escapeFieldName

    NULL = property(lambda self: CSqlExpression(self, 'NULL'))
    func = property(lambda self: self.loadFunctions()._func)
    proc = property(lambda self: self.loadFunctions()._proc)

    def loadFunctions(self):
        if self._func is None:
            self._func = CMySqlRoutineMap(self, CDatabaseRoutine.FUNCTION)
        if self._proc is None:
            self._proc = CMySqlRoutineMap(self, CDatabaseRoutine.PROCEDURE)
        return self

    def getConnectionId(self):
        query = self.query('SELECT CONNECTION_ID();')
        return forceRef(query.record().value(0)) if query.first() else None

    def prepareLimit(self, limit):
        if isinstance(limit, (list, tuple)):
            assert len(limit) == 2
            return self.limit2 % limit
        elif isinstance(limit, int):
            return self.limit1 % limit
        else:
            return ''

    def nestedTransaction(self):
        QtSql.QSqlQuery(self.db).exec_('SAVEPOINT LEVEL_%d' %
                                       (self._openTransactionsCount + 1))
        if self.db.lastError().isValid():
            raise CDatabaseException(CDatabase.errTransactionError,
                                     self.db.lastError())

    def nestedCommit(self):
        QtSql.QSqlQuery(self.db).exec_('RELEASE SAVEPOINT LEVEL_%d' %
                                       self._openTransactionsCount)
        if self.db.lastError().isValid():
            raise CDatabaseException(CDatabase.errNestedCommitTransactionError,
                                     self.db.lastError())

    def nestedRollback(self):
        QtSql.QSqlQuery(self.db).exec_('ROLLBACK TO SAVEPOINT LEVEL_%d' %
                                       self._openTransactionsCount)
        if self.db.lastError().isValid():
            raise CDatabaseException(
                CDatabase.errNestedRollbackTransactionError,
                self.db.lastError())

    def isConnectionLostError(self, sqlError):
        if sqlError and sqlError.number() in [
                CMySqlDatabase.CR_SERVER_GONE_ERROR,
                CMySqlDatabase.CR_SERVER_LOST
        ]:
            return True
        return CDatabase.isConnectionLostError(self, sqlError)