kexi

utils.cpp

00001 /* This file is part of the KDE project
00002    Copyright (C) 2004-2006 Jaroslaw Staniek <js@iidea.pl>
00003 
00004    This library is free software; you can redistribute it and/or
00005    modify it under the terms of the GNU Library General Public
00006    License as published by the Free Software Foundation; either
00007    version 2 of the License, or (at your option) any later version.
00008 
00009    This library is distributed in the hope that it will be useful,
00010    but WITHOUT ANY WARRANTY; without even the implied warranty of
00011    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00012    Library General Public License for more details.
00013 
00014    You should have received a copy of the GNU Library General Public License
00015    along with this library; see the file COPYING.LIB.  If not, write to
00016    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
00017  * Boston, MA 02110-1301, USA.
00018 */
00019 
00020 #include "utils.h"
00021 #include "cursor.h"
00022 #include "drivermanager.h"
00023 
00024 #include <qmap.h>
00025 #include <qthread.h>
00026 #include <qdom.h>
00027 #include <qintdict.h>
00028 #include <qbuffer.h>
00029 
00030 #include <kdebug.h>
00031 #include <klocale.h>
00032 #include <kstaticdeleter.h>
00033 #include <kmessagebox.h>
00034 #include <klocale.h>
00035 #include <kiconloader.h>
00036 
00037 #include "utils_p.h"
00038 
00039 using namespace KexiDB;
00040 
00042 struct TypeCache
00043 {
00044     QMap< uint, TypeGroupList > tlist;
00045     QMap< uint, QStringList > nlist;
00046     QMap< uint, QStringList > slist;
00047     QMap< uint, Field::Type > def_tlist;
00048 };
00049 
00050 static KStaticDeleter<TypeCache> KexiDB_typeCacheDeleter;
00051 TypeCache *KexiDB_typeCache = 0;
00052 
00053 static void initList()
00054 {
00055     KexiDB_typeCacheDeleter.setObject( KexiDB_typeCache, new TypeCache() );
00056 
00057     for (uint t=0; t<=KexiDB::Field::LastType; t++) {
00058         const uint tg = KexiDB::Field::typeGroup( t );
00059         TypeGroupList list;
00060         QStringList name_list, str_list;
00061         if (KexiDB_typeCache->tlist.find( tg )!=KexiDB_typeCache->tlist.end()) {
00062             list = KexiDB_typeCache->tlist[ tg ];
00063             name_list = KexiDB_typeCache->nlist[ tg ];
00064             str_list = KexiDB_typeCache->slist[ tg ];
00065         }
00066         list+= t;
00067         name_list += KexiDB::Field::typeName( t );
00068         str_list += KexiDB::Field::typeString( t );
00069         KexiDB_typeCache->tlist[ tg ] = list;
00070         KexiDB_typeCache->nlist[ tg ] = name_list;
00071         KexiDB_typeCache->slist[ tg ] = str_list;
00072     }
00073 
00074     KexiDB_typeCache->def_tlist[ Field::InvalidGroup ] = Field::InvalidType;
00075     KexiDB_typeCache->def_tlist[ Field::TextGroup ] = Field::Text;
00076     KexiDB_typeCache->def_tlist[ Field::IntegerGroup ] = Field::Integer;
00077     KexiDB_typeCache->def_tlist[ Field::FloatGroup ] = Field::Double;
00078     KexiDB_typeCache->def_tlist[ Field::BooleanGroup ] = Field::Boolean;
00079     KexiDB_typeCache->def_tlist[ Field::DateTimeGroup ] = Field::Date;
00080     KexiDB_typeCache->def_tlist[ Field::BLOBGroup ] = Field::BLOB;
00081 }
00082 
00083 const TypeGroupList KexiDB::typesForGroup(KexiDB::Field::TypeGroup typeGroup)
00084 {
00085     if (!KexiDB_typeCache)
00086         initList();
00087     return KexiDB_typeCache->tlist[ typeGroup ];
00088 }
00089 
00090 QStringList KexiDB::typeNamesForGroup(KexiDB::Field::TypeGroup typeGroup)
00091 {
00092     if (!KexiDB_typeCache)
00093         initList();
00094     return KexiDB_typeCache->nlist[ typeGroup ];
00095 }
00096 
00097 QStringList KexiDB::typeStringsForGroup(KexiDB::Field::TypeGroup typeGroup)
00098 {
00099     if (!KexiDB_typeCache)
00100         initList();
00101     return KexiDB_typeCache->slist[ typeGroup ];
00102 }
00103 
00104 KexiDB::Field::Type KexiDB::defaultTypeForGroup(KexiDB::Field::TypeGroup typeGroup)
00105 {
00106     if (!KexiDB_typeCache)
00107         initList();
00108     return (typeGroup <= Field::LastTypeGroup) ? KexiDB_typeCache->def_tlist[ typeGroup ] : Field::InvalidType;
00109 }
00110 
00111 void KexiDB::getHTMLErrorMesage(Object* obj, QString& msg, QString &details)
00112 {
00113     Connection *conn = 0;
00114     if (!obj || !obj->error()) {
00115         if (dynamic_cast<Cursor*>(obj)) {
00116             conn = dynamic_cast<Cursor*>(obj)->connection();
00117             obj = conn;
00118         }
00119         else {
00120             return;
00121         }
00122     }
00123 //  if (dynamic_cast<Connection*>(obj)) {
00124     //  conn = dynamic_cast<Connection*>(obj);
00125     //}
00126     if (!obj || !obj->error())
00127         return;
00128     //lower level message is added to the details, if there is alread message specified
00129     if (!obj->msgTitle().isEmpty())
00130         msg += "<p>" + obj->msgTitle();
00131     
00132     if (msg.isEmpty())
00133         msg = "<p>" + obj->errorMsg();
00134     else
00135         details += "<p>" + obj->errorMsg();
00136 
00137     if (!obj->serverErrorMsg().isEmpty())
00138         details += "<p><b><nobr>" +i18n("Message from server:") + "</nobr></b><br>" + obj->serverErrorMsg();
00139     if (!obj->recentSQLString().isEmpty())
00140         details += "<p><b><nobr>" +i18n("SQL statement:") + QString("</nobr></b><br><tt>%1</tt>").arg(obj->recentSQLString());
00141     int serverResult;
00142     QString serverResultName;
00143     if (obj->serverResult()!=0) {
00144         serverResult = obj->serverResult();
00145         serverResultName = obj->serverResultName();
00146     }
00147     else {
00148         serverResult = obj->previousServerResult();
00149         serverResultName = obj->previousServerResultName();
00150     }
00151     if (!serverResultName.isEmpty())
00152         details += (QString("<p><b><nobr>")+i18n("Server result name:")+"</nobr></b><br>"+serverResultName);
00153     if (!details.isEmpty() 
00154         && (!obj->serverErrorMsg().isEmpty() || !obj->recentSQLString().isEmpty() || !serverResultName.isEmpty() || serverResult!=0) )
00155     {
00156         details += (QString("<p><b><nobr>")+i18n("Server result number:")+"</nobr></b><br>"+QString::number(serverResult));
00157     }
00158 
00159     if (!details.isEmpty() && !details.startsWith("<qt>")) {
00160         if (details.startsWith("<p>"))
00161             details = QString::fromLatin1("<qt>")+details;
00162         else
00163             details = QString::fromLatin1("<qt><p>")+details;
00164     }
00165 }
00166 
00167 void KexiDB::getHTMLErrorMesage(Object* obj, QString& msg)
00168 {
00169     getHTMLErrorMesage(obj, msg, msg);
00170 }
00171 
00172 void KexiDB::getHTMLErrorMesage(Object* obj, ResultInfo *result)
00173 {
00174     getHTMLErrorMesage(obj, result->msg, result->desc);
00175 }
00176 
00177 int KexiDB::idForObjectName( Connection &conn, const QString& objName, int objType )
00178 {
00179     RowData data;
00180     if (true!=conn.querySingleRecord(QString("select o_id from kexi__objects where lower(o_name)='%1' and o_type=%2")
00181         .arg(objName.lower()).arg(objType), data))
00182         return 0;
00183     bool ok;
00184     int id = data[0].toInt(&ok);
00185     return ok ? id : 0;
00186 }
00187 
00188 //-----------------------------------------
00189 
00190 TableOrQuerySchema::TableOrQuerySchema(Connection *conn, const QCString& name)
00191  : m_name(name)
00192 {
00193     m_table = conn->tableSchema(QString(name));
00194     m_query = m_table ? 0 : conn->querySchema(QString(name));
00195     if (!m_table && !m_query)
00196         KexiDBWarn << "TableOrQuery(FieldList &tableOrQuery) : "
00197             " tableOrQuery is neither table nor query!" << endl;
00198 }
00199 
00200 TableOrQuerySchema::TableOrQuerySchema(Connection *conn, const QCString& name, bool table)
00201  : m_name(name)
00202  , m_table(table ? conn->tableSchema(QString(name)) : 0)
00203  , m_query(table ? 0 : conn->querySchema(QString(name)))
00204 {
00205     if (table && !m_table)
00206         KexiDBWarn << "TableOrQuery(Connection *conn, const QCString& name, bool table) : "
00207             "no table specified!" << endl;
00208     if (!table && !m_query)
00209         KexiDBWarn << "TableOrQuery(Connection *conn, const QCString& name, bool table) : "
00210             "no query specified!" << endl;
00211 }
00212 
00213 TableOrQuerySchema::TableOrQuerySchema(FieldList &tableOrQuery)
00214  : m_table(dynamic_cast<TableSchema*>(&tableOrQuery))
00215  , m_query(dynamic_cast<QuerySchema*>(&tableOrQuery))
00216 {
00217     if (!m_table && !m_query)
00218         KexiDBWarn << "TableOrQuery(FieldList &tableOrQuery) : "
00219             " tableOrQuery is nether table nor query!" << endl;
00220 }
00221 
00222 TableOrQuerySchema::TableOrQuerySchema(Connection *conn, int id)
00223 {
00224     m_table = conn->tableSchema(id);
00225     m_query = m_table ? 0 : conn->querySchema(id);
00226     if (!m_table && !m_query)
00227         KexiDBWarn << "TableOrQuery(Connection *conn, int id) : no table or query found for id==" 
00228             << id << "!" << endl;
00229 }
00230 
00231 TableOrQuerySchema::TableOrQuerySchema(TableSchema* table)
00232  : m_table(table)
00233  , m_query(0)
00234 {
00235     if (!m_table)
00236         KexiDBWarn << "TableOrQuery(TableSchema* table) : no table specified!" << endl;
00237 }
00238 
00239 TableOrQuerySchema::TableOrQuerySchema(QuerySchema* query)
00240  : m_table(0)
00241  , m_query(query)
00242 {
00243     if (!m_query)
00244         KexiDBWarn << "TableOrQuery(QuerySchema* query) : no query specified!" << endl;
00245 }
00246 
00247 const QueryColumnInfo::Vector TableOrQuerySchema::columns(bool unique)
00248 {
00249     if (m_table)
00250         return m_table->query()->fieldsExpanded(unique ? QuerySchema::Unique : QuerySchema::Default);
00251     
00252     if (m_query)
00253         return m_query->fieldsExpanded(unique ? QuerySchema::Unique : QuerySchema::Default);
00254 
00255     KexiDBWarn << "TableOrQuerySchema::column() : no query or table specified!" << endl;
00256     return QueryColumnInfo::Vector();
00257 }
00258 
00259 QCString TableOrQuerySchema::name() const
00260 {
00261     if (m_table)
00262         return m_table->name().latin1();
00263     if (m_query)
00264         return m_query->name().latin1();
00265     return m_name;
00266 }
00267 
00268 QString TableOrQuerySchema::captionOrName() const
00269 {
00270     SchemaData *sdata = m_table ? static_cast<SchemaData *>(m_table) : static_cast<SchemaData *>(m_query);
00271     if (!sdata)
00272         return m_name;
00273     return sdata->caption().isEmpty() ? sdata->name() : sdata->caption();
00274 }
00275 
00276 Field* TableOrQuerySchema::field(const QString& name)
00277 {
00278     if (m_table)
00279         return m_table->field(name);
00280     if (m_query)
00281         return m_query->field(name);
00282 
00283     return 0;
00284 }
00285 
00286 QueryColumnInfo* TableOrQuerySchema::columnInfo(const QString& name)
00287 {
00288     if (m_table)
00289         return m_table->query()->columnInfo(name);
00290     
00291     if (m_query)
00292         return m_query->columnInfo(name);
00293 
00294     return 0;
00295 }
00296 
00297 QString TableOrQuerySchema::debugString()
00298 {
00299     if (m_table)
00300         return m_table->debugString();
00301     else if (m_query)
00302         return m_query->debugString();
00303     return QString::null;
00304 }
00305 
00306 void TableOrQuerySchema::debug()
00307 {
00308     if (m_table)
00309         return m_table->debug();
00310     else if (m_query)
00311         return m_query->debug();
00312 }
00313 
00314 Connection* TableOrQuerySchema::connection() const
00315 {
00316     if (m_table)
00317         return m_table->connection();
00318     else if (m_query)
00319         return m_query->connection();
00320     return 0;
00321 }
00322 
00323 
00324 //------------------------------------------
00325 
00326 class ConnectionTestThread : public QThread {
00327     public:
00328         ConnectionTestThread(ConnectionTestDialog *dlg, const KexiDB::ConnectionData& connData);
00329         virtual void run();
00330     protected:
00331         ConnectionTestDialog* m_dlg;
00332         KexiDB::ConnectionData m_connData;
00333 };
00334 
00335 ConnectionTestThread::ConnectionTestThread(ConnectionTestDialog* dlg, const KexiDB::ConnectionData& connData)
00336  : m_dlg(dlg), m_connData(connData)
00337 {
00338 }
00339 
00340 void ConnectionTestThread::run()
00341 {
00342     KexiDB::DriverManager manager;
00343     KexiDB::Driver* drv = manager.driver(m_connData.driverName);
00344 //  KexiGUIMessageHandler msghdr;
00345     if (!drv || manager.error()) {
00346 //move      msghdr.showErrorMessage(&Kexi::driverManager());
00347         m_dlg->error(&manager);
00348         return;
00349     }
00350     KexiDB::Connection * conn = drv->createConnection(m_connData);
00351     if (!conn || drv->error()) {
00352 //move      msghdr.showErrorMessage(drv);
00353         delete conn;
00354         m_dlg->error(drv);
00355         return;
00356     }
00357     if (!conn->connect() || conn->error()) {
00358 //move      msghdr.showErrorMessage(conn);
00359         m_dlg->error(conn);
00360         delete conn;
00361         return;
00362     }
00363     // SQL database backends like PostgreSQL require executing "USE database" 
00364     // if we really want to know connection to the server succeeded.
00365     QString tmpDbName;
00366     if (!conn->useTemporaryDatabaseIfNeeded( tmpDbName )) {
00367         m_dlg->error(conn);
00368         delete conn;
00369         return;
00370     }
00371     delete conn;
00372     m_dlg->error(0);
00373 }
00374 
00375 ConnectionTestDialog::ConnectionTestDialog(QWidget* parent, 
00376     const KexiDB::ConnectionData& data,
00377     KexiDB::MessageHandler& msgHandler)
00378  : KProgressDialog(parent, "testconn_dlg",
00379     i18n("Test Connection"), i18n("<qt>Testing connection to <b>%1</b> database server...</qt>")
00380     .arg(data.serverInfoString(true)), true /*modal*/)
00381  , m_thread(new ConnectionTestThread(this, data))
00382  , m_connData(data)
00383  , m_msgHandler(&msgHandler)
00384  , m_elapsedTime(0)
00385  , m_errorObj(0)
00386  , m_stopWaiting(false)
00387 {
00388     showCancelButton(true);
00389     progressBar()->setPercentageVisible(false);
00390     progressBar()->setTotalSteps(0);
00391     connect(&m_timer, SIGNAL(timeout()), this, SLOT(slotTimeout()));
00392     adjustSize();
00393     resize(250, height());
00394 }
00395 
00396 ConnectionTestDialog::~ConnectionTestDialog()
00397 {
00398     m_wait.wakeAll();
00399     m_thread->terminate();
00400     delete m_thread;
00401 }
00402 
00403 int ConnectionTestDialog::exec()
00404 {
00405     m_timer.start(20);
00406     m_thread->start();
00407     const int res = KProgressDialog::exec();
00408     m_thread->wait();
00409     m_timer.stop();
00410     return res;
00411 }
00412 
00413 void ConnectionTestDialog::slotTimeout()
00414 {
00415 //  KexiDBDbg << "ConnectionTestDialog::slotTimeout() " << m_errorObj << endl;
00416     bool notResponding = false;
00417     if (m_elapsedTime >= 1000*5) {//5 seconds
00418         m_stopWaiting = true;
00419         notResponding = true;
00420     }
00421     if (m_stopWaiting) {
00422         m_timer.disconnect(this);
00423         m_timer.stop();
00424         slotCancel();
00425 //      reject();
00426 //      close();
00427         if (m_errorObj) {
00428             m_msgHandler->showErrorMessage(m_errorObj);
00429             m_errorObj = 0;
00430         }
00431         else if (notResponding) {
00432             KMessageBox::sorry(0, 
00433                 i18n("<qt>Test connection to <b>%1</b> database server failed. The server is not responding.</qt>")
00434                     .arg(m_connData.serverInfoString(true)),
00435                 i18n("Test Connection"));
00436         }
00437         else {
00438             KMessageBox::information(0, 
00439                 i18n("<qt>Test connection to <b>%1</b> database server established successfully.</qt>")
00440                     .arg(m_connData.serverInfoString(true)),
00441                 i18n("Test Connection"));
00442         }
00443 //      slotCancel();
00444 //      reject();
00445         m_wait.wakeAll();
00446         return;
00447     }
00448     m_elapsedTime += 20;
00449     progressBar()->setProgress( m_elapsedTime );
00450 }
00451 
00452 void ConnectionTestDialog::error(KexiDB::Object *obj)
00453 {
00454     KexiDBDbg << "ConnectionTestDialog::error()" << endl;
00455     m_stopWaiting = true;
00456     m_errorObj = obj;
00457 /*      reject();
00458         m_msgHandler->showErrorMessage(obj);
00459     if (obj) {
00460     }
00461     else {
00462         accept();
00463     }*/
00464     m_wait.wait();
00465 }
00466 
00467 void ConnectionTestDialog::slotCancel()
00468 {
00469 //  m_wait.wakeAll();
00470     m_thread->terminate();
00471     m_timer.disconnect(this);
00472     m_timer.stop();
00473     KProgressDialog::slotCancel();
00474 }
00475 
00476 void KexiDB::connectionTestDialog(QWidget* parent, const KexiDB::ConnectionData& data, 
00477     KexiDB::MessageHandler& msgHandler)
00478 {
00479     ConnectionTestDialog dlg(parent, data, msgHandler);
00480     dlg.exec();
00481 }
00482 
00483 int KexiDB::rowCount(const KexiDB::TableSchema& tableSchema)
00484 {
00486     if (!tableSchema.connection()) {
00487         KexiDBWarn << "KexiDB::rowsCount(const KexiDB::TableSchema&): no tableSchema.connection() !" << endl;
00488         return -1;
00489     }
00490     int count = -1; //will be changed only on success of querySingleNumber()
00491     tableSchema.connection()->querySingleNumber(
00492         QString::fromLatin1("SELECT COUNT(*) FROM ") 
00493         + tableSchema.connection()->driver()->escapeIdentifier(tableSchema.name()), 
00494         count
00495     );
00496     return count;
00497 }
00498 
00499 int KexiDB::rowCount(KexiDB::QuerySchema& querySchema)
00500 {
00502     if (!querySchema.connection()) {
00503         KexiDBWarn << "KexiDB::rowsCount(const KexiDB::QuerySchema&): no querySchema.connection() !" << endl;
00504         return -1;
00505     }
00506     int count = -1; //will be changed only on success of querySingleNumber()
00507     querySchema.connection()->querySingleNumber(
00508         QString::fromLatin1("SELECT COUNT() FROM (") 
00509         + querySchema.connection()->selectStatement(querySchema) + ")",
00510         count
00511     );
00512     return count;
00513 }
00514 
00515 int KexiDB::rowCount(KexiDB::TableOrQuerySchema& tableOrQuery)
00516 {
00517     if (tableOrQuery.table())
00518         return rowCount( *tableOrQuery.table() );
00519     if (tableOrQuery.query())
00520         return rowCount( *tableOrQuery.query() );
00521     return -1;
00522 }
00523 
00524 int KexiDB::fieldCount(KexiDB::TableOrQuerySchema& tableOrQuery)
00525 {
00526     if (tableOrQuery.table())
00527         return tableOrQuery.table()->fieldCount();
00528     if (tableOrQuery.query())
00529         return tableOrQuery.query()->fieldsExpanded().count();
00530     return -1;
00531 }
00532 
00533 QMap<QString,QString> KexiDB::toMap( const ConnectionData& data )
00534 {
00535     QMap<QString,QString> m;
00536     m["caption"] = data.caption;
00537     m["description"] = data.description;
00538     m["driverName"] = data.driverName;
00539     m["hostName"] = data.hostName;
00540     m["port"] = QString::number(data.port);
00541     m["useLocalSocketFile"] = QString::number((int)data.useLocalSocketFile);
00542     m["localSocketFileName"] = data.localSocketFileName;
00543     m["password"] = data.password;
00544     m["savePassword"] = QString::number((int)data.savePassword);
00545     m["userName"] = data.userName;
00546     m["fileName"] = data.fileName();
00547     return m;
00548 }
00549 
00550 void KexiDB::fromMap( const QMap<QString,QString>& map, ConnectionData& data )
00551 {
00552     data.caption = map["caption"];
00553     data.description = map["description"];
00554     data.driverName = map["driverName"];
00555     data.hostName = map["hostName"];
00556     data.port = map["port"].toInt();
00557     data.useLocalSocketFile = map["useLocalSocketFile"].toInt()==1;
00558     data.localSocketFileName = map["localSocketFileName"];
00559     data.password = map["password"];
00560     data.savePassword = map["savePassword"].toInt()==1;
00561     data.userName = map["userName"];
00562     data.setFileName(map["fileName"]);
00563 }
00564 
00565 bool KexiDB::splitToTableAndFieldParts(const QString& string, 
00566     QString& tableName, QString& fieldName,
00567     SplitToTableAndFieldPartsOptions option)
00568 {
00569     const int id = string.find('.');
00570     if (option & SetFieldNameIfNoTableName && id==-1) {
00571         tableName = QString::null;
00572         fieldName = string;
00573         return !fieldName.isEmpty();
00574     }
00575     if (id<=0 || id==int(string.length()-1))
00576         return false;
00577     tableName = string.left(id);
00578     fieldName = string.mid(id+1);
00579     return !tableName.isEmpty() && !fieldName.isEmpty();
00580 }
00581 
00582 bool KexiDB::supportsVisibleDecimalPlacesProperty(Field::Type type)
00583 {
00585     return Field::isFPNumericType(type);
00586 }
00587 
00588 QString KexiDB::formatNumberForVisibleDecimalPlaces(double value, int decimalPlaces)
00589 {
00591     if (decimalPlaces < 0) {
00592         QString s = QString::number(value, 'f', 10 /*reasonable precision*/);
00593         uint i = s.length()-1;
00594         while (i>0 && s[i]=='0')
00595             i--;
00596         if (s[i]=='.') //remove '.'
00597             i--;
00598         s = s.left(i+1).replace('.', KGlobal::locale()->decimalSymbol());
00599         return s;
00600     }
00601     if (decimalPlaces == 0)
00602         return QString::number((int)value);
00603     return KGlobal::locale()->formatNumber(value, decimalPlaces);
00604 }
00605 
00606 KexiDB::Field::Type KexiDB::intToFieldType( int type )
00607 {
00608     if (type<(int)KexiDB::Field::InvalidType || type>(int)KexiDB::Field::LastType) {
00609         KexiDBWarn << "KexiDB::intToFieldType(): invalid type " << type << endl;
00610         return KexiDB::Field::InvalidType;
00611     }
00612     return (KexiDB::Field::Type)type;
00613 }
00614 
00615 static bool setIntToFieldType( Field& field, const QVariant& value )
00616 {
00617     bool ok;
00618     const int intType = value.toInt(&ok);
00619     if (!ok || KexiDB::Field::InvalidType == intToFieldType(intType)) {//for sanity
00620         KexiDBWarn << "KexiDB::setFieldProperties(): invalid type" << endl;
00621         return false;
00622     }
00623     field.setType((KexiDB::Field::Type)intType);
00624     return true;
00625 }
00626 
00628 static KStaticDeleter< QAsciiDict<char> > KexiDB_builtinFieldPropertiesDeleter;
00630 QAsciiDict<char>* KexiDB_builtinFieldProperties = 0;
00631 
00632 bool KexiDB::isBuiltinTableFieldProperty( const QCString& propertyName )
00633 {
00634     if (!KexiDB_builtinFieldProperties) {
00635         KexiDB_builtinFieldPropertiesDeleter.setObject( KexiDB_builtinFieldProperties, new QAsciiDict<char>(499) );
00636 #define ADD(name) KexiDB_builtinFieldProperties->insert(name, (char*)1)
00637         ADD("type");
00638         ADD("primaryKey");
00639         ADD("indexed");
00640         ADD("autoIncrement");
00641         ADD("unique");
00642         ADD("notNull");
00643         ADD("allowEmpty");
00644         ADD("unsigned");
00645         ADD("name");
00646         ADD("caption");
00647         ADD("description");
00648         ADD("length");
00649         ADD("precision");
00650         ADD("defaultValue");
00651         ADD("width");
00652         ADD("visibleDecimalPlaces");
00654 #undef ADD
00655     }
00656     return KexiDB_builtinFieldProperties->find( propertyName );
00657 }
00658 
00659 bool KexiDB::setFieldProperties( Field& field, const QMap<QCString, QVariant>& values )
00660 {
00661     QMapConstIterator<QCString, QVariant> it;
00662     if ( (it = values.find("type")) != values.constEnd() ) {
00663         if (!setIntToFieldType(field, *it))
00664             return false;
00665     }
00666 
00667 #define SET_BOOLEAN_FLAG(flag, value) { \
00668         constraints |= KexiDB::Field::flag; \
00669         if (!value) \
00670             constraints ^= KexiDB::Field::flag; \
00671     }
00672     
00673     uint constraints = field.constraints();
00674     bool ok = true;
00675     if ( (it = values.find("primaryKey")) != values.constEnd() )
00676         SET_BOOLEAN_FLAG(PrimaryKey, (*it).toBool());
00677     if ( (it = values.find("indexed")) != values.constEnd() )
00678         SET_BOOLEAN_FLAG(Indexed, (*it).toBool());
00679     if ( (it = values.find("autoIncrement")) != values.constEnd() 
00680         && KexiDB::Field::isAutoIncrementAllowed(field.type()) )
00681         SET_BOOLEAN_FLAG(AutoInc, (*it).toBool());
00682     if ( (it = values.find("unique")) != values.constEnd() )
00683         SET_BOOLEAN_FLAG(Unique, (*it).toBool());
00684     if ( (it = values.find("notNull")) != values.constEnd() )
00685         SET_BOOLEAN_FLAG(NotNull, (*it).toBool());
00686     if ( (it = values.find("allowEmpty")) != values.constEnd() )
00687         SET_BOOLEAN_FLAG(NotEmpty, !(*it).toBool());
00688     field.setConstraints( constraints );
00689 
00690     uint options = 0;
00691     if ( (it = values.find("unsigned")) != values.constEnd()) {
00692         options |= KexiDB::Field::Unsigned;
00693         if (!(*it).toBool())
00694             options ^= KexiDB::Field::Unsigned;
00695     }
00696     field.setOptions( options );
00697 
00698     if ( (it = values.find("name")) != values.constEnd())
00699         field.setName( (*it).toString() );
00700     if ( (it = values.find("caption")) != values.constEnd())
00701         field.setCaption( (*it).toString() );
00702     if ( (it = values.find("description")) != values.constEnd())
00703         field.setDescription( (*it).toString() );
00704     if ( (it = values.find("length")) != values.constEnd())
00705         field.setLength( (*it).isNull() ? 0/*default*/ : (*it).toUInt(&ok) );
00706     if (!ok)
00707         return false;
00708     if ( (it = values.find("precision")) != values.constEnd())
00709         field.setPrecision( (*it).isNull() ? 0/*default*/ : (*it).toUInt(&ok) );
00710     if (!ok)
00711         return false;
00712     if ( (it = values.find("defaultValue")) != values.constEnd())
00713         field.setDefaultValue( *it );
00714     if ( (it = values.find("width")) != values.constEnd())
00715         field.setWidth( (*it).isNull() ? 0/*default*/ : (*it).toUInt(&ok) );
00716     if (!ok)
00717         return false;
00718     if ( (it = values.find("visibleDecimalPlaces")) != values.constEnd() 
00719       && KexiDB::supportsVisibleDecimalPlacesProperty(field.type()) )
00720         field.setVisibleDecimalPlaces( (*it).isNull() ? -1/*default*/ : (*it).toInt(&ok) );
00721     if (!ok)
00722         return false;
00723 
00724     // set custom properties
00725     typedef QMap<QCString, QVariant> PropertiesMap;
00726     foreach( PropertiesMap::ConstIterator, it, values ) {
00727         if (!isBuiltinTableFieldProperty( it.key() ) && !isExtendedTableFieldProperty( it.key() )) {
00728             field.setCustomProperty( it.key(), it.data() );
00729         }
00730     }
00731     return true;
00732 #undef SET_BOOLEAN_FLAG
00733 }
00734 
00736 static KStaticDeleter< QAsciiDict<char> > KexiDB_extendedPropertiesDeleter;
00738 QAsciiDict<char>* KexiDB_extendedProperties = 0;
00739 
00740 bool KexiDB::isExtendedTableFieldProperty( const QCString& propertyName )
00741 {
00742     if (!KexiDB_extendedProperties) {
00743         KexiDB_extendedPropertiesDeleter.setObject( KexiDB_extendedProperties, new QAsciiDict<char>(499) );
00744 #define ADD(name) KexiDB_extendedProperties->insert(name, (char*)1)
00745         ADD("visibleDecimalPlaces");
00746 #undef ADD
00747     }
00748     return KexiDB_extendedProperties->find( propertyName );
00749 }
00750 
00751 bool KexiDB::setFieldProperty( Field& field, const QCString& propertyName, const QVariant& value )
00752 {
00753 #define SET_BOOLEAN_FLAG(flag, value) { \
00754             constraints |= KexiDB::Field::flag; \
00755             if (!value) \
00756                 constraints ^= KexiDB::Field::flag; \
00757             field.setConstraints( constraints ); \
00758             return true; \
00759         }
00760 #define GET_INT(method) { \
00761             const uint ival = value.toUInt(&ok); \
00762             if (!ok) \
00763                 return false; \
00764             field.method( ival ); \
00765             return true; \
00766         }
00767     if (propertyName.isEmpty())
00768         return false;
00769 
00770     bool ok;
00771     if (KexiDB::isExtendedTableFieldProperty(propertyName)) {
00772         //a little speedup: identify extended property in O(1)
00773         if ( "visibleDecimalPlaces" == propertyName
00774           && KexiDB::supportsVisibleDecimalPlacesProperty(field.type()) )
00775             GET_INT( setVisibleDecimalPlaces );
00776     }
00777     else {//non-extended
00778         if ( "type" == propertyName )
00779             return setIntToFieldType(field, value);
00780     
00781         uint constraints = field.constraints();
00782         if ( "primaryKey" == propertyName )
00783             SET_BOOLEAN_FLAG(PrimaryKey, value.toBool());
00784         if ( "indexed" == propertyName )
00785             SET_BOOLEAN_FLAG(Indexed, value.toBool());
00786         if ( "autoIncrement" == propertyName
00787             && KexiDB::Field::isAutoIncrementAllowed(field.type()) )
00788             SET_BOOLEAN_FLAG(AutoInc, value.toBool());
00789         if ( "unique" == propertyName )
00790             SET_BOOLEAN_FLAG(Unique, value.toBool());
00791         if ( "notNull" == propertyName )
00792             SET_BOOLEAN_FLAG(NotNull, value.toBool());
00793         if ( "allowEmpty" == propertyName )
00794             SET_BOOLEAN_FLAG(NotEmpty, !value.toBool());
00795 
00796         uint options = 0;
00797         if ( "unsigned" == propertyName ) {
00798             options |= KexiDB::Field::Unsigned;
00799             if (!value.toBool())
00800                 options ^= KexiDB::Field::Unsigned;
00801             field.setOptions( options );
00802             return true;
00803         }
00804 
00805         if ( "name" == propertyName ) {
00806             if (value.toString().isEmpty())
00807                 return false;
00808             field.setName( value.toString() );
00809             return true;
00810         }
00811         if ( "caption" == propertyName ) {
00812             field.setCaption( value.toString() );
00813             return true;
00814         }
00815         if ( "description" == propertyName ) {
00816             field.setDescription( value.toString() );
00817             return true;
00818         }
00819         if ( "length" == propertyName )
00820             GET_INT( setLength );
00821         if ( "precision" == propertyName )
00822             GET_INT( setPrecision );
00823         if ( "defaultValue" == propertyName ) {
00824             field.setDefaultValue( value );
00825             return true;
00826         }
00827         if ( "width" == propertyName )
00828             GET_INT( setWidth );
00829 
00830         // last chance that never fails: custom field property
00831         field.setCustomProperty(propertyName, value);
00832     }
00833 
00834     KexiDBWarn << "KexiDB::setFieldProperty() property \"" << propertyName << "\" not found!" << endl;
00835     return false;
00836 #undef SET_BOOLEAN_FLAG
00837 #undef GET_INT
00838 }
00839 
00840 int KexiDB::loadIntPropertyValueFromDom( const QDomNode& node, bool* ok )
00841 {
00842     QCString valueType = node.nodeName().latin1();
00843     if (valueType.isEmpty() || valueType!="number") {
00844         if (ok)
00845             *ok = false;
00846         return 0;
00847     }
00848     const QString text( QDomNode(node).toElement().text() );
00849     int val = text.toInt(ok);
00850     return val;
00851 }
00852 
00853 QString KexiDB::loadStringPropertyValueFromDom( const QDomNode& node, bool* ok )
00854 {
00855     QCString valueType = node.nodeName().latin1();
00856     if (valueType!="string") {
00857         if (ok)
00858             *ok = false;
00859         return 0;
00860     }
00861     return QDomNode(node).toElement().text();
00862 }
00863 
00864 QVariant KexiDB::loadPropertyValueFromDom( const QDomNode& node )
00865 {
00866     QCString valueType = node.nodeName().latin1();
00867     if (valueType.isEmpty())
00868         return QVariant();
00869     const QString text( QDomNode(node).toElement().text() );
00870     bool ok;
00871     if (valueType == "string") {
00872         return text;
00873     }
00874     else if (valueType == "cstring") {
00875         return QCString(text.latin1());
00876     }
00877     else if (valueType == "number") { // integer or double
00878         if (text.find('.')!=-1) {
00879             double val = text.toDouble(&ok);
00880             if (ok)
00881                 return val;
00882         }
00883         else {
00884             const int val = text.toInt(&ok);
00885             if (ok)
00886                 return val;
00887             const Q_LLONG valLong = text.toLongLong(&ok);
00888             if (ok)
00889                 return valLong;
00890         }
00891     }
00892     else if (valueType == "bool") {
00893         return QVariant(text.lower()=="true" || text=="1", 1);
00894     }
00896     KexiDBWarn << "loadPropertyValueFromDom(): unknown type '" << valueType << "'" << endl;
00897     return QVariant();
00898 }
00899 
00900 QDomElement KexiDB::saveNumberElementToDom(QDomDocument& doc, QDomElement& parentEl, 
00901     const QString& elementName, int value)
00902 {
00903     QDomElement el( doc.createElement(elementName) );
00904     parentEl.appendChild( el );
00905     QDomElement numberEl( doc.createElement("number") );
00906     el.appendChild( numberEl );
00907     numberEl.appendChild( doc.createTextNode( QString::number(value) ) );
00908     return el;
00909 }
00910 
00911 QDomElement KexiDB::saveBooleanElementToDom(QDomDocument& doc, QDomElement& parentEl, 
00912     const QString& elementName, bool value)
00913 {
00914     QDomElement el( doc.createElement(elementName) );
00915     parentEl.appendChild( el );
00916     QDomElement boolEl( doc.createElement("bool") );
00917     el.appendChild( boolEl );
00918     boolEl.appendChild( doc.createTextNode( value ? "true" : "false" ) );
00919     return el;
00920 }
00921 
00923 static KStaticDeleter< QValueVector<QVariant> > KexiDB_emptyValueForTypeCacheDeleter;
00924 QValueVector<QVariant> *KexiDB_emptyValueForTypeCache = 0;
00925 
00926 QVariant KexiDB::emptyValueForType( KexiDB::Field::Type type )
00927 {
00928     if (!KexiDB_emptyValueForTypeCache) {
00929         KexiDB_emptyValueForTypeCacheDeleter.setObject( KexiDB_emptyValueForTypeCache, 
00930             new QValueVector<QVariant>(int(Field::LastType)+1) );
00931 #define ADD(t, value) (*KexiDB_emptyValueForTypeCache)[t]=value;
00932         ADD(Field::Byte, 0);
00933         ADD(Field::ShortInteger, 0);
00934         ADD(Field::Integer, 0);
00935         ADD(Field::BigInteger, 0);
00936         ADD(Field::Boolean, QVariant(false, 0));
00937         ADD(Field::Float, 0.0);
00938         ADD(Field::Double, 0.0);
00940         ADD(Field::Text, QString(" "));
00941         ADD(Field::LongText, QString(" "));
00942         ADD(Field::BLOB, QByteArray());
00943 #undef ADD
00944     }
00945     const QVariant val( KexiDB_emptyValueForTypeCache->at(
00946         (type<=Field::LastType) ? type : Field::InvalidType) );
00947     if (!val.isNull())
00948         return val;
00949     else { //special cases
00950         if (type==Field::Date)
00951             return QDate::currentDate();
00952         if (type==Field::DateTime)
00953             return QDateTime::currentDateTime();
00954         if (type==Field::Time)
00955             return QTime::currentTime();
00956     }
00957     KexiDBWarn << "KexiDB::emptyValueForType() no value for type " 
00958         << Field::typeName(type) << endl;
00959     return QVariant();
00960 }
00961 
00963 static KStaticDeleter< QValueVector<QVariant> > KexiDB_notEmptyValueForTypeCacheDeleter;
00964 QValueVector<QVariant> *KexiDB_notEmptyValueForTypeCache = 0;
00965 
00966 QVariant KexiDB::notEmptyValueForType( KexiDB::Field::Type type )
00967 {
00968     if (!KexiDB_notEmptyValueForTypeCache) {
00969         KexiDB_notEmptyValueForTypeCacheDeleter.setObject( KexiDB_notEmptyValueForTypeCache, 
00970             new QValueVector<QVariant>(int(Field::LastType)+1) );
00971 #define ADD(t, value) (*KexiDB_notEmptyValueForTypeCache)[t]=value;
00972         // copy most of the values
00973         for (int i = int(Field::InvalidType) + 1; i<=Field::LastType; i++) {
00974             if (i==Field::Date || i==Field::DateTime || i==Field::Time)
00975                 continue; //'current' value will be returned
00976             if (i==Field::Text || i==Field::LongText) {
00977                 ADD(i, QVariant(QString("")));
00978                 continue;
00979             }
00980             if (i==Field::BLOB) {
00982                 QByteArray ba;
00983                 QBuffer buffer( ba );
00984                 buffer.open( IO_WriteOnly );
00985                 QPixmap pm(SmallIcon("filenew"));
00986                 pm.save( &buffer, "PNG" );
00987                 ADD(i, ba);
00988                 continue;
00989             }
00990             ADD(i, KexiDB::emptyValueForType((Field::Type)i));
00991         }
00992 #undef ADD
00993     }
00994     const QVariant val( KexiDB_notEmptyValueForTypeCache->at(
00995         (type<=Field::LastType) ? type : Field::InvalidType) );
00996     if (!val.isNull())
00997         return val;
00998     else { //special cases
00999         if (type==Field::Date)
01000             return QDate::currentDate();
01001         if (type==Field::DateTime)
01002             return QDateTime::currentDateTime();
01003         if (type==Field::Time)
01004             return QTime::currentTime();
01005     }
01006     KexiDBWarn << "KexiDB::notEmptyValueForType() no value for type " 
01007         << Field::typeName(type) << endl;
01008     return QVariant();
01009 }
01010 
01011 QString KexiDB::escapeBLOB(const QByteArray& array, BLOBEscapingType type)
01012 {
01013     const int size = array.size();
01014     if (size==0)
01015         return QString::null;
01016     int escaped_length = size*2;
01017     if (type == BLOBEscape0xHex || type == BLOBEscapeOctal)
01018         escaped_length += 2/*0x or X'*/;
01019     else if (type == BLOBEscapeXHex)
01020         escaped_length += 3; //X' + '
01021     QString str;
01022     str.reserve(escaped_length);
01023     if (str.capacity() < (uint)escaped_length) {
01024         KexiDBWarn << "KexiDB::Driver::escapeBLOB(): no enough memory (cannot allocate "<< 
01025             escaped_length<<" chars)" << endl;
01026         return QString::null;
01027     }
01028     if (type == BLOBEscapeXHex)
01029         str = QString::fromLatin1("X'");
01030     else if (type == BLOBEscape0xHex)
01031         str = QString::fromLatin1("0x");
01032     else if (type == BLOBEscapeOctal)
01033         str = QString::fromLatin1("'");
01034     
01035     int new_length = str.length(); //after X' or 0x, etc.
01036     if (type == BLOBEscapeOctal) {
01037         // only escape nonprintable characters as in Table 8-7:
01038         // http://www.postgresql.org/docs/8.1/interactive/datatype-binary.html
01039         // i.e. escape for bytes: < 32, >= 127, 39 ('), 92(\). 
01040         for (int i = 0; i < size; i++) {
01041             const unsigned char val = array[i];
01042             if (val<32 || val>=127 || val==39 || val==92) {
01043                 str[new_length++] = '\\';
01044                 str[new_length++] = '\\';
01045                 str[new_length++] = '0' + val/64;
01046                 str[new_length++] = '0' + (val % 64) / 8;
01047                 str[new_length++] = '0' + val % 8;
01048             }
01049             else {
01050                 str[new_length++] = val;
01051             }
01052         }
01053     }
01054     else {
01055         for (int i = 0; i < size; i++) {
01056             const unsigned char val = array[i];
01057             str[new_length++] = (val/16) < 10 ? ('0'+(val/16)) : ('A'+(val/16)-10);
01058             str[new_length++] = (val%16) < 10 ? ('0'+(val%16)) : ('A'+(val%16)-10);
01059         }
01060     }
01061     if (type == BLOBEscapeXHex || type == BLOBEscapeOctal)
01062         str[new_length++] = '\'';
01063     return str;
01064 }
01065 
01066 QString KexiDB::variantToString( const QVariant& v )
01067 {
01068     if (v.type()==QVariant::ByteArray)
01069         return KexiDB::escapeBLOB(v.toByteArray(), KexiDB::BLOBEscapeHex);
01070     return v.toString();
01071 }
01072 
01073 QVariant KexiDB::stringToVariant( const QString& s, QVariant::Type type, bool &ok )
01074 {
01075     if (s.isNull()) {
01076         ok = true;
01077         return QVariant();
01078     }
01079     if (QVariant::Invalid==type) {
01080         ok = false;
01081         return QVariant();
01082     }
01083     if (type==QVariant::ByteArray) {//special case: hex string
01084         const uint len = s.length();
01085         QByteArray ba(len/2 + len%2);
01086         for (uint i=0; i<(len-1); i+=2) {
01087             int c = s.mid(i,2).toInt(&ok, 16);
01088             if (!ok) {
01089                 KexiDBWarn << "KexiDB::stringToVariant(): Error in digit " << i << endl;
01090                 return QVariant();
01091             }
01092             ba[i/2] = (char)c;
01093         }
01094         ok = true;
01095         return ba;
01096     }
01097     QVariant result(s);
01098     if (!result.cast( type )) {
01099         ok = false;
01100         return QVariant();
01101     }
01102     ok = true;
01103     return result;
01104 }
01105 
01106 bool KexiDB::isDefaultValueAllowed( KexiDB::Field* field )
01107 {
01108     return field && !field->isUniqueKey();
01109 }
01110 
01111 void KexiDB::getLimitsForType(Field::Type type, int &minValue, int &maxValue)
01112 {
01113     switch (type) {
01114     case Field::Byte:
01116         minValue = 0;
01117         maxValue = 255;
01118         break;
01119     case Field::ShortInteger:
01120         minValue = -32768;
01121         maxValue = 32767;
01122         break;
01123     case Field::Integer:
01124     case Field::BigInteger: //cannot return anything larger
01125     default:
01126         minValue = (int)-0x07FFFFFFF;
01127         maxValue = (int)(0x080000000-1);
01128     }
01129 }
01130 
01131 void KexiDB::debugRowData(const RowData& rowData)
01132 {
01133     KexiDBDbg << QString("ROW DATA (%1 columns):").arg(rowData.count()) << endl;
01134     foreach(RowData::ConstIterator, it, rowData)
01135         KexiDBDbg << "- " << (*it) << endl;
01136 }
01137 
01138 Field::Type KexiDB::maximumForIntegerTypes(Field::Type t1, Field::Type t2)
01139 {
01140     if (!Field::isIntegerType(t1) || !Field::isIntegerType(t2))
01141         return Field::InvalidType;
01142     if (t1==t2)
01143         return t2;
01144     if (t1==Field::ShortInteger && t2!=Field::Integer && t2!=Field::BigInteger)
01145         return t1;
01146     if (t1==Field::Integer && t2!=Field::BigInteger)
01147         return t1;
01148     if (t1==Field::BigInteger)
01149         return t1;
01150     return KexiDB::maximumForIntegerTypes(t2, t1); //swap
01151 }
01152 
01153 #include "utils_p.moc"
KDE Home | KDE Accessibility Home | Description of Access Keys