bool QSpatiaLiteResult::prepare(const QString &query) { if (!driver() || !driver()->isOpen() || driver()->isOpenError()) return false; d->cleanup(); setSelect(false); const void *pzTail = NULL; #if (SQLITE_VERSION_NUMBER >= 3003011) int res = sqlite3_prepare16_v2(d->access, query.constData(), (query.size() + 1) * sizeof(QChar), &d->stmt, &pzTail); #else int res = sqlite3_prepare16(d->access, query.constData(), (query.size() + 1) * sizeof(QChar), &d->stmt, &pzTail); #endif if (res != SQLITE_OK) { setLastError(qMakeError(d->access, QCoreApplication::translate("QSpatiaLiteResult", "Unable to execute statement"), QSqlError::StatementError, res)); d->finalize(); return false; } else if (pzTail && !QString::fromUtf16( (const ushort *) pzTail ).trimmed().isEmpty()) { setLastError(qMakeError(d->access, QCoreApplication::translate("QSpatiaLiteResult", "Unable to execute multiple statements at a time"), QSqlError::StatementError, SQLITE_MISUSE)); d->finalize(); return false; } return true; }
bool SQLiteResult::prepare(const QString &query) { if (!driver() || !driver()->isOpen() || driver()->isOpenError()) return false; d->cleanup(); setSelect(false); const void *pzTail = NULL; #if (SQLITE_VERSION_NUMBER >= 3003011) int res = sqlite3_prepare16_v2(d->access, query.constData(), (query.size() + 1) * sizeof(QChar), &d->stmt, &pzTail); #else int res = sqlite3_prepare16(d->access, query.constData(), (query.size() + 1) * sizeof(QChar), &d->stmt, &pzTail); #endif if (res != SQLITE_OK) { #if defined(SQLITEDRIVER_DEBUG) trace(NULL, query.toUtf8().constData()); #endif setLastError(qMakeError(d->access, QCoreApplication::translate("SQLiteResult", "Unable to execute statement"), QSqlError::StatementError, res)); d->finalize(); return false; } else if (pzTail && !stringFromUnicode(reinterpret_cast<const QChar *>(pzTail)).trimmed().isEmpty()) { setLastError(qMakeError(d->access, QCoreApplication::translate("SQLiteResult", "Unable to execute multiple statements at a time"), QSqlError::StatementError, SQLITE_MISUSE)); d->finalize(); return false; } return true; }
bool QPSQLResult::prepare(const QString &query) { if (!d->preparedQueriesEnabled) return QSqlResult::prepare(query); cleanup(); if (!d->preparedStmtId.isEmpty()) qDeallocatePreparedStmt(d); const QString stmtId = qMakePreparedStmtId(); const QString stmt = QString(QLatin1String("PREPARE %1 AS ")).arg(stmtId).append(qReplacePlaceholderMarkers(query)); PGresult *result = PQexec(d->driver->connection, d->driver->isUtf8 ? stmt.toUtf8().constData() : stmt.toLocal8Bit().constData()); if (PQresultStatus(result) != PGRES_COMMAND_OK) { setLastError(qMakeError(QCoreApplication::translate("QPSQLResult", "Unable to prepare statement"), QSqlError::StatementError, d->driver)); PQclear(result); d->preparedStmtId = QString(); return false; } PQclear(result); d->preparedStmtId = stmtId; return true; }
static int CS_PUBLIC qTdsErrHandler(DBPROCESS* dbproc, int /*severity*/, int dberr, int /*oserr*/, char* dberrstr, char* oserrstr) { QTDSResultPrivate* p = errs()->value(dbproc); if (!p) { qWarning("QTDSDriver error (%d): [%s] [%s]", dberr, dberrstr, oserrstr); return INT_CANCEL; } /* * If the process is dead or NULL and * we are not in the middle of logging in... */ if((dbproc == NULL || DBDEAD(dbproc))) { qWarning("QTDSDriver error (%d): [%s] [%s]", dberr, dberrstr, oserrstr); return INT_CANCEL; } QString errMsg = QString::fromLatin1("%1 %2\n").arg(QLatin1String(dberrstr)).arg( QLatin1String(oserrstr)); errMsg += p->getErrorMsgs(); p->lastError = qMakeError(errMsg, QSqlError::UnknownError, dberr); p->clearErrorMsgs(); return INT_CANCEL ; }
bool QTDSDriver::open(const QString & db, const QString & user, const QString & password, const QString & host, int /*port*/, const QString& /*connOpts*/) { if (isOpen()) close(); if (!dbinit()) { setOpenError(true); return false; } d->login = dblogin(); if (!d->login) { setOpenError(true); return false; } DBSETLPWD(d->login, const_cast<char*>(password.toLocal8Bit().constData())); DBSETLUSER(d->login, const_cast<char*>(user.toLocal8Bit().constData())); // Now, try to open and use the database. If this fails, return false. DBPROCESS* dbproc; dbproc = dbopen(d->login, const_cast<char*>(host.toLatin1().constData())); if (!dbproc) { setLastError(qMakeError(tr("Unable to open connection"), QSqlError::ConnectionError, -1)); setOpenError(true); return false; } if (dbuse(dbproc, const_cast<char*>(db.toLatin1().constData())) == FAIL) { setLastError(qMakeError(tr("Unable to use database"), QSqlError::ConnectionError, -1)); setOpenError(true); return false; } dbclose( dbproc ); setOpen(true); setOpenError(false); d->hostName = host; d->db = db; return true; }
void SQLiteDriver::close() { if (isOpen()) { if (sqlite3_close(d->access) != SQLITE_OK) setLastError(qMakeError(d->access, tr("Error closing database"), QSqlError::ConnectionError)); d->access = 0; setOpen(false); setOpenError(false); } }
bool embeddedResult::reset (const QString& query) { if (!driver() || !driver()->isOpen() || driver()->isOpenError() || !d->driver) return false; d->preparedQuery = false; cleanup(); //qDebug() << "In reset: " + query; const QByteArray encQuery(fromUnicode(d->driver->d->tc, query)); //const QByteArray encQuery = query.toLocal8Bit(); if (mysql_real_query(d->driver->d->mysql, encQuery.data(), encQuery.length())) { setLastError(qMakeError(QCoreApplication::translate("embeddedResult", "Unable to execute query"), QSqlError::StatementError, d->driver->d)); return false; } d->result = mysql_store_result(d->driver->d->mysql); if (!d->result && mysql_field_count(d->driver->d->mysql) > 0) { setLastError(qMakeError(QCoreApplication::translate("embeddedResult", "Unable to store result"), QSqlError::StatementError, d->driver->d)); return false; } int numFields = mysql_field_count(d->driver->d->mysql); setSelect(numFields != 0); d->fields.resize(numFields); d->rowsAffected = mysql_affected_rows(d->driver->d->mysql); if (isSelect()) { for(int i = 0; i < numFields; i++) { MYSQL_FIELD* field = mysql_fetch_field_direct(d->result, i); d->fields[i].type = qDecodeMYSQLType(field->type, field->flags); } setAt(QSql::BeforeFirstRow); } setActive(true); return isActive(); }
bool QSymSQLResultPrivate::fetchNext(bool initialFetch) { int res; if (skipRow) { // already fetched Q_ASSERT(!initialFetch); skipRow = false; return skippedStatus; } skipRow = initialFetch; res = stmt.Next(); switch(res) { case KSqlAtRow: return true; case KSqlAtEnd: stmt.Reset(); return false; case KSqlErrGeneral: // KSqlErrGeneral is a generic error code and we must call stmt.Reset() // to get the specific error message. stmt.Reset(); q->setLastError(qMakeError(access, QCoreApplication::translate("QSymSQLResult", "Unable to fetch row"), QSqlError::ConnectionError, res)); q->setAt(QSql::AfterLastRow); return false; case KSqlErrMisuse: case KSqlErrBusy: default: // something wrong, don't get col info, but still return false q->setLastError(qMakeError(access, QCoreApplication::translate("QSymSQLResult", "Unable to fetch row"), QSqlError::ConnectionError, res)); stmt.Reset(); q->setAt(QSql::AfterLastRow); return false; } return false; }
bool QMYSQLResult::reset ( const QString& query ) { if ( !driver() ) return FALSE; if ( !driver()-> isOpen() || driver()->isOpenError() ) return FALSE; cleanup(); const char *encQuery = query.ascii(); if ( mysql_real_query( d->mysql, encQuery, qstrlen(encQuery) ) ) { setLastError( qMakeError("Unable to execute query", QSqlError::Statement, d ) ); return FALSE; } if ( isForwardOnly() ) { if ( isActive() || isValid() ) // have to empty the results from previous query fetchLast(); d->result = mysql_use_result( d->mysql ); } else { d->result = mysql_store_result( d->mysql ); } if ( !d->result && mysql_field_count( d->mysql ) > 0 ) { setLastError( qMakeError( "Unable to store result", QSqlError::Statement, d ) ); return FALSE; } int numFields = mysql_field_count( d->mysql ); setSelect( !( numFields == 0) ); d->fieldTypes.resize( numFields ); if ( isSelect() ) { for( int i = 0; i < numFields; i++) { MYSQL_FIELD* field = mysql_fetch_field_direct( d->result, i ); if ( field->type == FIELD_TYPE_DECIMAL ) d->fieldTypes[i] = QVariant::String; else d->fieldTypes[i] = qDecodeMYSQLType( field->type, field->flags ); } } setActive( TRUE ); return TRUE; }
void QSymSQLResultPrivate::initColumns(QSqlRecord& rec) { int nCols = stmt.ColumnCount(); if (nCols <= 0) { q->setLastError(qMakeError(access, QCoreApplication::translate("QSymSQLResult", "Error retrieving column count"), QSqlError::UnknownError, nCols)); return; } for (int i = 0; i < nCols; ++i) { TPtrC cName; TInt err = stmt.ColumnName(i, cName); if (err != KErrNone) { q->setLastError(qMakeError(access, QCoreApplication::translate("QSymSQLResult", "Error retrieving column name"), QSqlError::UnknownError, err)); return; } QString colName = qt_TDesC2QString(cName); // must use typeName for resolving the type to match QSymSQLDriver::record TPtrC tName; TSqlColumnType decColType; err = stmt.DeclaredColumnType(i, decColType); if (err != KErrNone) { q->setLastError(qMakeError(access, QCoreApplication::translate("QSymSQLResult", "Error retrieving column type"), QSqlError::UnknownError, err)); return; } int dotIdx = colName.lastIndexOf(QLatin1Char('.')); QSqlField fld(colName.mid(dotIdx == -1 ? 0 : dotIdx + 1), qGetColumnType(decColType)); rec.append(fld); } }
void QSpatiaLiteDriver::close() { if (isOpen()) { foreach (QSpatiaLiteResult *result, d->results) result->d->finalize(); if (QgsSLConnect::sqlite3_close(d->access) != SQLITE_OK) setLastError(qMakeError(d->access, tr("Error closing database"), QSqlError::ConnectionError)); d->access = 0; setOpen(false); setOpenError(false); } }
bool QMYSQLDriver::rollbackTransaction() { #ifndef CLIENT_TRANSACTIONS return FALSE; #endif if ( !isOpen() ) { #ifdef QT_CHECK_RANGE qWarning( "QMYSQLDriver::rollbackTransaction: Database not open" ); #endif return FALSE; } if ( mysql_query( d->mysql, "ROLLBACK" ) ) { setLastError( qMakeError("Unable to rollback transaction", QSqlError::Statement, d ) ); return FALSE; } return TRUE; }
bool QPSQLDriver::open(const QString & db, const QString & user, const QString & password, const QString & host, int port, const QString& connOpts) { if (isOpen()) close(); QString connectString; if (!host.isEmpty()) connectString.append(QLatin1String("host=")).append(qQuote(host)); if (!db.isEmpty()) connectString.append(QLatin1String(" dbname=")).append(qQuote(db)); if (!user.isEmpty()) connectString.append(QLatin1String(" user="******" password="******" port=")).append(qQuote(QString::number(port))); // add any connect options - the server will handle error detection if (!connOpts.isEmpty()) { QString opt = connOpts; opt.replace(QLatin1Char(';'), QLatin1Char(' '), Qt::CaseInsensitive); connectString.append(QLatin1Char(' ')).append(opt); } d->connection = PQconnectdb(connectString.toLocal8Bit().constData()); if (PQstatus(d->connection) == CONNECTION_BAD) { setLastError(qMakeError(tr("Unable to connect"), QSqlError::ConnectionError, d)); setOpenError(true); PQfinish(d->connection); d->connection = 0; return false; } d->pro = getPSQLVersion(d->connection); d->isUtf8 = setEncodingUtf8(d->connection); setDatestyle(d->connection); setOpen(true); setOpenError(false); return true; }
bool QPSQLResultPrivate::processResults() { if (!result) return false; int status = PQresultStatus(result); if (status == PGRES_TUPLES_OK) { q->setSelect(true); q->setActive(true); currentSize = PQntuples(result); return true; } else if (status == PGRES_COMMAND_OK) { q->setSelect(false); q->setActive(true); currentSize = -1; return true; } q->setLastError(qMakeError(QCoreApplication::translate("QPSQLResult", "Unable to create query"), QSqlError::StatementError, driver)); return false; }
bool QSymSQLResult::prepare(const QString &query) { if (!driver() || !driver()->isOpen() || driver()->isOpenError()) return false; d->cleanup(); setSelect(false); TInt res = d->stmt.Prepare(d->access, qt_QString2TPtrC(query)); if (res != KErrNone) { setLastError(qMakeError(d->access, QCoreApplication::translate("QSymSQLResult", "Unable to execute statement"), QSqlError::StatementError, res)); d->finalize(); return false; } d->prepareCalled = true; return true; }
/* SQLite dbs have no user name, passwords, hosts or ports. just file names. */ bool QSpatiaLiteDriver::open(const QString & db, const QString &, const QString &, const QString &, int, const QString &conOpts) { if (isOpen()) close(); if (db.isEmpty()) return false; bool sharedCache = false; int openMode = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, timeOut=5000; QStringList opts=QString(conOpts).remove(QLatin1Char(' ')).split(QLatin1Char(';')); foreach(const QString &option, opts) { if (option.startsWith(QLatin1String("QSQLITE_BUSY_TIMEOUT="))) { bool ok; int nt = option.mid(21).toInt(&ok); if (ok) timeOut = nt; } if (option == QLatin1String("QSQLITE_OPEN_READONLY")) openMode = SQLITE_OPEN_READONLY; if (option == QLatin1String("QSQLITE_ENABLE_SHARED_CACHE")) sharedCache = true; } sqlite3_enable_shared_cache(sharedCache); if (QgsSLConnect::sqlite3_open_v2(db.toUtf8().constData(), &d->access, openMode, NULL) == SQLITE_OK) { sqlite3_busy_timeout(d->access, timeOut); setOpen(true); setOpenError(false); return true; } else { setLastError(qMakeError(d->access, tr("Error opening database"), QSqlError::ConnectionError)); setOpenError(true); return false; } }
static int CS_PUBLIC qTdsMsgHandler (DBPROCESS* dbproc, DBINT msgno, int msgstate, int severity, char* msgtext, char* srvname, char* /*procname*/, int line) { QTDSResultPrivate* p = errs()->value(dbproc); if (!p) { // ### umm... temporary disabled since this throws a lot of warnings... // qWarning("QTDSDriver warning (%d): [%s] from server [%s]", msgstate, msgtext, srvname); return INT_CANCEL; } if (severity > 0) { QString errMsg = QString::fromLatin1("%1 (Msg %2, Level %3, State %4, Server %5, Line %6)") .arg(QString::fromAscii(msgtext)) .arg(msgno) .arg(severity) .arg(msgstate) .arg(QString::fromAscii(srvname)) .arg(line); p->addErrorMsg(errMsg); if (severity > 10) { // Severe messages are really errors in the sense of lastError errMsg = p->getErrorMsgs(); p->lastError = qMakeError(errMsg, QSqlError::UnknownError, msgno); p->clearErrorMsgs(); } } return INT_CANCEL; }
/* SQLite dbs have no user name, passwords, hosts or ports. just file names. */ bool SQLiteDriver::open(const QString & db, const QString &, const QString &, const QString &, int, const QString &) { if (isOpen()) close(); if (db.isEmpty()) return false; if (sqlite3_open16(db.utf16(), &d->access) == SQLITE_OK) { sqlite3_busy_timeout(d->access, 500); #if defined(SQLITEDRIVER_DEBUG) sqlite3_trace(d->access, trace, NULL); #endif setOpen(true); setOpenError(false); installSQLiteExtension(d->access); return true; } else { setLastError(qMakeError(d->access, tr("Error opening database"), QSqlError::ConnectionError)); setOpenError(true); return false; } }
bool QSpatiaLiteResultPrivate::fetchNext(QSqlCachedResult::ValueCache &values, int idx, bool initialFetch) { int res; int i; if (skipRow) { // already fetched Q_ASSERT(!initialFetch); skipRow = false; for(int i=0;i<firstRow.count();i++) values[i]=firstRow[i]; return skippedStatus; } skipRow = initialFetch; if(initialFetch) { firstRow.clear(); firstRow.resize(sqlite3_column_count(stmt)); } if (!stmt) { q->setLastError(QSqlError(QCoreApplication::translate("QSpatiaLiteResult", "Unable to fetch row"), QCoreApplication::translate("QSpatiaLiteResult", "No query"), QSqlError::ConnectionError)); q->setAt(QSql::AfterLastRow); return false; } res = sqlite3_step(stmt); switch(res) { case SQLITE_ROW: // check to see if should fill out columns if (rInf.isEmpty()) // must be first call. initColumns(false); if (idx < 0 && !initialFetch) return true; for (i = 0; i < rInf.count(); ++i) { switch (sqlite3_column_type(stmt, i)) { case SQLITE_BLOB: values[i + idx] = QByteArray(static_cast<const char *>( sqlite3_column_blob(stmt, i)), sqlite3_column_bytes(stmt, i)); break; case SQLITE_INTEGER: values[i + idx] = sqlite3_column_int64(stmt, i); break; case SQLITE_FLOAT: switch(q->numericalPrecisionPolicy()) { case QSql::LowPrecisionInt32: values[i + idx] = sqlite3_column_int(stmt, i); break; case QSql::LowPrecisionInt64: values[i + idx] = sqlite3_column_int64(stmt, i); break; case QSql::LowPrecisionDouble: case QSql::HighPrecision: default: values[i + idx] = sqlite3_column_double(stmt, i); break; }; break; case SQLITE_NULL: values[i + idx] = QVariant(QVariant::String); break; default: values[i + idx] = QString(reinterpret_cast<const QChar *>( sqlite3_column_text16(stmt, i)), sqlite3_column_bytes16(stmt, i) / sizeof(QChar)); break; } } return true; case SQLITE_DONE: if (rInf.isEmpty()) // must be first call. initColumns(true); q->setAt(QSql::AfterLastRow); sqlite3_reset(stmt); return false; case SQLITE_CONSTRAINT: case SQLITE_ERROR: // SQLITE_ERROR is a generic error code and we must call sqlite3_reset() // to get the specific error message. res = sqlite3_reset(stmt); q->setLastError(qMakeError(access, QCoreApplication::translate("QSpatiaLiteResult", "Unable to fetch row"), QSqlError::ConnectionError, res)); q->setAt(QSql::AfterLastRow); return false; case SQLITE_MISUSE: case SQLITE_BUSY: default: // something wrong, don't get col info, but still return false q->setLastError(qMakeError(access, QCoreApplication::translate("QSpatiaLiteResult", "Unable to fetch row"), QSqlError::ConnectionError, res)); sqlite3_reset(stmt); q->setAt(QSql::AfterLastRow); return false; } }
bool QSymSQLResult::exec() { if (d->prepareCalled == false) { setLastError(qMakeError(d->access, QCoreApplication::translate("QSymSQLResult", "Statement is not prepared"), QSqlError::StatementError, KErrGeneral)); return false; } const QVector<QVariant> values = boundValues(); d->skippedStatus = false; d->skipRow = false; setAt(QSql::BeforeFirstRow); setLastError(QSqlError()); int res = d->stmt.Reset(); if (res != KErrNone) { setLastError(qMakeError(d->access, QCoreApplication::translate("QSymSQLResult", "Unable to reset statement"), QSqlError::StatementError, res)); d->finalize(); return false; } TPtrC tmp; TInt paramCount = 0; while (d->stmt.ParamName(paramCount, tmp) == KErrNone) paramCount++; if (paramCount == values.count()) { for (int i = 0; i < paramCount; ++i) { res = KErrNone; const QVariant value = values.at(i); if (value.isNull()) { res = d->stmt.BindNull(i); //replaced i + 1 with i } else { switch (value.type()) { case QVariant::ByteArray: { const QByteArray *ba = static_cast<const QByteArray*>(value.constData()); TPtrC8 data(reinterpret_cast<const TUint8 *>(ba->constData()), ba->length()); res = d->stmt.BindBinary(i, data); //replaced i + 1 with i break; } case QVariant::Int: res = d->stmt.BindInt(i, value.toInt()); //replaced i + 1 with i break; case QVariant::Double: res = d->stmt.BindReal(i, value.toDouble()); //replaced i + 1 with i break; case QVariant::UInt: case QVariant::LongLong: res = d->stmt.BindReal(i, value.toLongLong()); //replaced i + 1 with i break; case QVariant::String: { // lifetime of string == lifetime of its qvariant const QString *str = static_cast<const QString*>(value.constData()); res = d->stmt.BindText(i, qt_QString2TPtrC(*str)); // replaced i + 1 with i break; } default: { QString str = value.toString(); res = d->stmt.BindText(i, qt_QString2TPtrC(str)); //replaced i + 1 with i break; } } } if (res != KErrNone) { setLastError(qMakeError(d->access, QCoreApplication::translate("QSymSQLResult", "Unable to bind parameters"), QSqlError::StatementError, res)); d->finalize(); return false; } } } else { setLastError(QSqlError(QCoreApplication::translate("QSymSQLResult", "Parameter count mismatch"), QString(), QSqlError::StatementError)); return false; } d->skippedStatus = d->fetchNext(true); if (lastError().isValid()) { setSelect(false); setActive(false); return false; } if (d->stmt.ColumnCount() > 0) { //If there is something, it has to be select setSelect(true); } else { //If there isn't it might be just bad query, let's check manually whether we can find SELECT QString query = this->lastQuery(); query = query.trimmed(); query = query.toLower(); //Just check whether there is one in the beginning, don't know if this is enough //Comments should be at the end of line if those are passed //For some reason, case insensitive indexOf didn't work for me if (query.indexOf(QLatin1String("select")) == 0) { setSelect(true); } else { setSelect(false); } } setActive(true); return true; }
bool QMYSQLDriver::open( const QString& db, const QString& user, const QString& password, const QString& host, int port, const QString& connOpts ) { if ( isOpen() ) close(); unsigned int optionFlags = 0; QStringList raw = QStringList::split( ';', connOpts ); QStringList opts; QStringList::ConstIterator it; // extract the real options from the string for ( it = raw.begin(); it != raw.end(); ++it ) { QString tmp( *it ); int idx; if ( (idx = tmp.find( '=' )) != -1 ) { QString val( tmp.mid( idx + 1 ) ); val.simplifyWhiteSpace(); if ( val == "TRUE" || val == "1" ) opts << tmp.left( idx ); else qWarning( "QMYSQLDriver::open: Illegal connect option value '%s'", tmp.latin1() ); } else { opts << tmp; } } for ( it = opts.begin(); it != opts.end(); ++it ) { QString opt( (*it).upper() ); if ( opt == "CLIENT_COMPRESS" ) optionFlags |= CLIENT_COMPRESS; else if ( opt == "CLIENT_FOUND_ROWS" ) optionFlags |= CLIENT_FOUND_ROWS; else if ( opt == "CLIENT_IGNORE_SPACE" ) optionFlags |= CLIENT_IGNORE_SPACE; else if ( opt == "CLIENT_INTERACTIVE" ) optionFlags |= CLIENT_INTERACTIVE; else if ( opt == "CLIENT_NO_SCHEMA" ) optionFlags |= CLIENT_NO_SCHEMA; else if ( opt == "CLIENT_ODBC" ) optionFlags |= CLIENT_ODBC; else if ( opt == "CLIENT_SSL" ) optionFlags |= CLIENT_SSL; else qWarning( "QMYSQLDriver::open: Unknown connect option '%s'", (*it).latin1() ); } if ( (d->mysql = mysql_init((MYSQL*) 0)) && mysql_real_connect( d->mysql, host, user, password, db.isNull() ? QString("") : db, (port > -1) ? port : 0, NULL, optionFlags ) ) { if ( !db.isEmpty() && mysql_select_db( d->mysql, db )) { setLastError( qMakeError("Unable open database '" + db + "'", QSqlError::Connection, d ) ); mysql_close( d->mysql ); setOpenError( TRUE ); return FALSE; } } else { setLastError( qMakeError( "Unable to connect", QSqlError::Connection, d ) ); mysql_close( d->mysql ); setOpenError( TRUE ); return FALSE; } setOpen( TRUE ); setOpenError( FALSE ); return TRUE; }
bool QSpatiaLiteResult::exec() { const QVector<QVariant> values = boundValues(); d->skippedStatus = false; d->skipRow = false; d->rInf.clear(); clearValues(); setLastError(QSqlError()); int res = sqlite3_reset(d->stmt); if (res != SQLITE_OK) { setLastError(qMakeError(d->access, QCoreApplication::translate("QSpatiaLiteResult", "Unable to reset statement"), QSqlError::StatementError, res)); d->finalize(); return false; } int paramCount = sqlite3_bind_parameter_count(d->stmt); if (paramCount == values.count()) { for (int i = 0; i < paramCount; ++i) { res = SQLITE_OK; const QVariant value = values.at(i); if (value.isNull()) { res = sqlite3_bind_null(d->stmt, i + 1); } else { switch (value.type()) { case QVariant::ByteArray: { const QByteArray *ba = static_cast<const QByteArray*>(value.constData()); res = sqlite3_bind_blob(d->stmt, i + 1, ba->constData(), ba->size(), SQLITE_STATIC); break; } case QVariant::Int: res = sqlite3_bind_int(d->stmt, i + 1, value.toInt()); break; case QVariant::Double: res = sqlite3_bind_double(d->stmt, i + 1, value.toDouble()); break; case QVariant::UInt: case QVariant::LongLong: res = sqlite3_bind_int64(d->stmt, i + 1, value.toLongLong()); break; case QVariant::String: { // lifetime of string == lifetime of its qvariant const QString *str = static_cast<const QString*>(value.constData()); res = sqlite3_bind_text16(d->stmt, i + 1, str->utf16(), (str->size()) * sizeof(QChar), SQLITE_STATIC); break; } default: { QString str = value.toString(); // SQLITE_TRANSIENT makes sure that sqlite buffers the data res = sqlite3_bind_text16(d->stmt, i + 1, str.utf16(), (str.size()) * sizeof(QChar), SQLITE_TRANSIENT); break; } } } if (res != SQLITE_OK) { setLastError(qMakeError(d->access, QCoreApplication::translate("QSpatiaLiteResult", "Unable to bind parameters"), QSqlError::StatementError, res)); d->finalize(); return false; } } } else { setLastError(QSqlError(QCoreApplication::translate("QSpatiaLiteResult", "Parameter count mismatch"), QString(), QSqlError::StatementError)); return false; } d->skippedStatus = d->fetchNext(d->firstRow, 0, true); if (lastError().isValid()) { setSelect(false); setActive(false); return false; } setSelect(!d->rInf.isEmpty()); setActive(true); return true; }
/* SQLite dbs have no user name, passwords, hosts or ports. just file names. */ bool QSQLiteDriver::open(const QString & db, const QString &, const QString &, const QString &, int, const QString &conOpts) { if (isOpen()) close(); if (db.isEmpty()) return false; bool sharedCache = false; int openMode = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, timeOut=5000; QStringList opts=QString(conOpts).remove(QLatin1Char(' ')).split(QLatin1Char(';')); foreach(const QString &option, opts) { if (option.startsWith(QLatin1String("QSQLITE_BUSY_TIMEOUT="))) { bool ok; int nt = option.mid(21).toInt(&ok); if (ok) timeOut = nt; } if (option == QLatin1String("QSQLITE_OPEN_READONLY")) openMode = SQLITE_OPEN_READONLY; if (option == QLatin1String("QSQLITE_ENABLE_SHARED_CACHE")) sharedCache = true; } sqlite3_enable_shared_cache(sharedCache); #ifndef QT_WEBOS if (sqlite3_open_v2(db.toUtf8().constData(), &d->access, openMode, NULL) == SQLITE_OK) { #else // QT_WEBOS #if SQLITE_VERSION_NUMBER >= 3005000 if (sqlite3_open_v2(db.toUtf8().constData(), &d->access, openMode, NULL) == SQLITE_OK) { #else if (sqlite3_open(db.toUtf8().constData(), &d->access) == SQLITE_OK) { #endif #endif // QT_WEBOS sqlite3_busy_timeout(d->access, timeOut); setOpen(true); setOpenError(false); return true; } else { setLastError(qMakeError(d->access, tr("Error opening database"), QSqlError::ConnectionError)); setOpenError(true); return false; } } void QSQLiteDriver::close() { if (isOpen()) { foreach (QSQLiteResult *result, d->results) result->d->finalize(); if (sqlite3_close(d->access) != SQLITE_OK) setLastError(qMakeError(d->access, tr("Error closing database"), QSqlError::ConnectionError)); d->access = 0; setOpen(false); setOpenError(false); } } QSqlResult *QSQLiteDriver::createResult() const { return new QSQLiteResult(this); } bool QSQLiteDriver::beginTransaction() { if (!isOpen() || isOpenError()) return false; QSqlQuery q(createResult()); if (!q.exec(QLatin1String("BEGIN"))) { setLastError(QSqlError(tr("Unable to begin transaction"), q.lastError().databaseText(), QSqlError::TransactionError)); return false; } return true; } bool QSQLiteDriver::commitTransaction() { if (!isOpen() || isOpenError()) return false; QSqlQuery q(createResult()); if (!q.exec(QLatin1String("COMMIT"))) { setLastError(QSqlError(tr("Unable to commit transaction"), q.lastError().databaseText(), QSqlError::TransactionError)); return false; } return true; } bool QSQLiteDriver::rollbackTransaction() { if (!isOpen() || isOpenError()) return false; QSqlQuery q(createResult()); if (!q.exec(QLatin1String("ROLLBACK"))) { setLastError(QSqlError(tr("Unable to rollback transaction"), q.lastError().databaseText(), QSqlError::TransactionError)); return false; } return true; } QStringList QSQLiteDriver::tables(QSql::TableType type) const { QStringList res; if (!isOpen()) return res; QSqlQuery q(createResult()); q.setForwardOnly(true); QString sql = QLatin1String("SELECT name FROM sqlite_master WHERE %1 " "UNION ALL SELECT name FROM sqlite_temp_master WHERE %1"); if ((type & QSql::Tables) && (type & QSql::Views)) sql = sql.arg(QLatin1String("type='table' OR type='view'")); else if (type & QSql::Tables) sql = sql.arg(QLatin1String("type='table'")); else if (type & QSql::Views) sql = sql.arg(QLatin1String("type='view'")); else sql.clear(); if (!sql.isEmpty() && q.exec(sql)) { while(q.next()) res.append(q.value(0).toString()); } if (type & QSql::SystemTables) { // there are no internal tables beside this one: res.append(QLatin1String("sqlite_master")); } return res; } static QSqlIndex qGetTableInfo(QSqlQuery &q, const QString &tableName, bool onlyPIndex = false) { QString schema; QString table(tableName); int indexOfSeparator = tableName.indexOf(QLatin1Char('.')); if (indexOfSeparator > -1) { schema = tableName.left(indexOfSeparator).append(QLatin1Char('.')); table = tableName.mid(indexOfSeparator + 1); } q.exec(QLatin1String("PRAGMA ") + schema + QLatin1String("table_info (") + _q_escapeIdentifier(table) + QLatin1String(")")); QSqlIndex ind; while (q.next()) { bool isPk = q.value(5).toInt(); if (onlyPIndex && !isPk) continue; QString typeName = q.value(2).toString().toLower(); QSqlField fld(q.value(1).toString(), qGetColumnType(typeName)); if (isPk && (typeName == QLatin1String("integer"))) // INTEGER PRIMARY KEY fields are auto-generated in sqlite // INT PRIMARY KEY is not the same as INTEGER PRIMARY KEY! fld.setAutoValue(true); fld.setRequired(q.value(3).toInt() != 0); fld.setDefaultValue(q.value(4)); ind.append(fld); } return ind; }