Пример #1
0
bool pqxxSqlConnection::drv_getTablesList( QStringList &list )
{
	KexiDB::Cursor *cursor;
	m_sql = "select lower(relname) from pg_class where relkind='r'";
	if (!(cursor = executeQuery( m_sql ))) {
		KexiDBDrvWarn << "pqxxSqlConnection::drv_getTablesList(): !executeQuery()" << endl;
		return false;
	}
	list.clear();
	cursor->moveFirst();
	while (!cursor->eof() && !cursor->error()) {
		list += cursor->value(0).toString();
		cursor->moveNext();
	}
	if (cursor->error()) {
		deleteCursor(cursor);
		return false;
	}
	return deleteCursor(cursor);
}
Пример #2
0
bool SQLiteConnection::drv_getTablesList(QStringList &list)
{
    KexiDB::Cursor *cursor;
    m_sql = "select name from sqlite_master where type='table'";
    if (!(cursor = executeQuery(m_sql))) {
        KexiDBWarn << "Connection::drv_getTablesList(): !executeQuery()";
        return false;
    }
    list.clear();
    cursor->moveFirst();
    while (!cursor->eof() && !cursor->error()) {
        list += cursor->value(0).toString();
        cursor->moveNext();
    }
    if (cursor->error()) {
        deleteCursor(cursor);
        return false;
    }
    return deleteCursor(cursor);
}
Пример #3
0
int main(int argc, char * argv[])
{
    KComponentData componentData("newapi");
    KexiDB::DriverManager manager;
    QStringList names = manager.driverNames();
    kDebug() << "DRIVERS: ";
    for (QStringList::ConstIterator it = names.constBegin(); it != names.constEnd() ; ++it)
        kDebug() << *it;
    if (manager.error()) {
        kDebug() << manager.errorMsg();
        return 1;
    }

    //get driver
    KexiDB::Driver *driver = manager.driver("mySQL");
    if (manager.error()) {
        kDebug() << manager.errorMsg();
        return 1;
    }

    //connection data that can be later reused
    KexiDB::ConnectionData conn_data;

    conn_data.userName = "******";
    if (argc > 1)
        conn_data.password = argv[1];
    else
        conn_data.password = "******";
    conn_data.hostName = "localhost";

    KexiDB::Connection *conn = driver->createConnection(conn_data);
    if (driver->error()) {
        kDebug() << driver->errorMsg();
        return 1;
    }
    if (!conn->connect()) {
        kDebug() << conn->errorMsg();
        return 1;
    }
    if (!conn->useDatabase("test")) {
        kDebug() << "use db:" << conn->errorMsg();
        return 1;
    }

    kDebug() << "Creating first cursor";
    KexiDB::Cursor *c = conn->executeQuery("select * from Applications");
    if (!c) kDebug() << conn->errorMsg();
    kDebug() << "Creating second cursor";
    KexiDB::Cursor *c2 = conn->executeQuery("select * from Applications");
    if (!c2) kDebug() << conn->errorMsg();

    QStringList l = conn->databaseNames();
    if (l.isEmpty()) kDebug() << conn->errorMsg();
    kDebug() << "Databases:";
    for (QStringList::ConstIterator it = l.constBegin(); it != l.constEnd() ; ++it)
        kDebug() << *it;

    if (c) {
        while (c->moveNext()) {
            kDebug() << "Cursor: Value(0)" << c->value(0).toString();
            kDebug() << "Cursor: Value(1)" << c->value(1).toString();
        }
        kDebug() << "Cursor error:" << c->errorMsg();
    }
    if (c2) {
        while (c2->moveNext()) {
            kDebug() << "Cursor2: Value(0)" << c2->value(0).toString();
            kDebug() << "Cursor2: Value(1)" << c2->value(1).toString();
        }
    }
    if (c) {
        kDebug() << "Cursor::prev";
        while (c->movePrev()) {
            kDebug() << "Cursor: Value(0)" << c->value(0).toString();
            kDebug() << "Cursor: Value(1)" << c->value(1).toString();

        }
        kDebug() << "up/down";
        c->moveNext();
        kDebug() << "Cursor: Value(0)" << c->value(0).toString();
        kDebug() << "Cursor: Value(1)" << c->value(1).toString();
        c->moveNext();
        kDebug() << "Cursor: Value(0)" << c->value(0).toString();
        kDebug() << "Cursor: Value(1)" << c->value(1).toString();
        c->movePrev();
        kDebug() << "Cursor: Value(0)" << c->value(0).toString();
        kDebug() << "Cursor: Value(1)" << c->value(1).toString();
        c->movePrev();
        kDebug() << "Cursor: Value(0)" << c->value(0).toString();
        kDebug() << "Cursor: Value(1)" << c->value(1).toString();

    }
#if 0
    KexiDB::Table *t = conn->tableSchema("persons");
    if (t)
        t->debug();
    t = conn->tableSchema("cars");
    if (t)
        t->debug();

// conn->tableNames();

    if (!conn->disconnect()) {
        kDebug() << conn->errorMsg();
        return 1;
    }
    debug("before del");
    delete conn;
    debug("after del");
#endif
    return 0;
}
Пример #4
0
bool Authenticator::loadStore() {
    KexiDB::TableSchema* table = KexiWebForms::Model::gConnection->tableSchema("kexi__users");

    if (!table) {
        // the table doesn't exist, create it (programmatically)
        kDebug() << "kexi__users table does not exist, creating it";
        KexiDB::TableSchema* kexi__users = new KexiDB::TableSchema("kexi__users");
        kexi__users->setNative(true);
        KexiDB::Field* id = new KexiDB::Field("u_id", KexiDB::Field::Integer);
        id->setAutoIncrement(true);
        id->setPrimaryKey(true);
        kexi__users->insertField(0, id);
        KexiDB::Field* name = new KexiDB::Field("u_name", KexiDB::Field::Text);
        kexi__users->insertField(1, name);
        KexiDB::Field* password = new KexiDB::Field("u_password", KexiDB::Field::Text);
        kexi__users->insertField(2, password);
        KexiDB::Field* create = new KexiDB::Field("u_create", KexiDB::Field::Boolean);
        kexi__users->insertField(3, create);
        KexiDB::Field* read = new KexiDB::Field("u_read", KexiDB::Field::Boolean);
        kexi__users->insertField(4, read);
        KexiDB::Field* update = new KexiDB::Field("u_update", KexiDB::Field::Boolean);
        kexi__users->insertField(5, update);
        KexiDB::Field* fdelete = new KexiDB::Field("u_delete", KexiDB::Field::Boolean);
        kexi__users->insertField(6, fdelete);
        KexiDB::Field* fquery = new KexiDB::Field("u_query", KexiDB::Field::Boolean);
        kexi__users->insertField(7, fquery);

        if (!KexiWebForms::Model::gConnection->createTable(kexi__users)) {
            // Table was not created, fatal error
            kError() << "Failed to create system table kexi__users";
            kError() << "Error string: " << KexiWebForms::Model::gConnection->errorMsg();
            delete kexi__users;
            return false;
        } else {
            // Table was created, create two standard accounts
            KexiDB::QuerySchema query(*kexi__users);
            KexiDB::Cursor* cursor = KexiWebForms::Model::gConnection->prepareQuery(query);
            KexiDB::RecordData recordData(kexi__users->fieldCount());
            KexiDB::RowEditBuffer editBuffer(true);
            // root
            QVariant vtrue(true);
            QVariant vfalse(false);
            kDebug() << "Creating user root with password root";
            QVariant user_root("root");
            QVariant password_root("root");
            editBuffer.insert(*query.columnInfo(name->name()), user_root);
            editBuffer.insert(*query.columnInfo(password->name()), password_root);
            editBuffer.insert(*query.columnInfo(create->name()), vtrue);
            editBuffer.insert(*query.columnInfo(read->name()), vtrue);
            editBuffer.insert(*query.columnInfo(update->name()), vtrue);
            editBuffer.insert(*query.columnInfo(fdelete->name()), vtrue);
            editBuffer.insert(*query.columnInfo(fquery->name()), vtrue);
            kDebug() << "Registering user within database";
            if (cursor->insertRow(recordData, editBuffer)) {
                kDebug() << "Succeeded";
                User* u = new User("root", "root");
                m_users.append(*u);
                m_auth->addUser(u->name().toUtf8().constData(), u->password().toUtf8().constData());
            } else {
                kError() << "An error occurred";
                return false;
            }

            // anonymous
            kDebug() << "Creating user anonymous with password guest";
            QVariant user_anonymous("anonymous");
            QVariant password_anonymous("guest");
            editBuffer.insert(*query.columnInfo(name->name()), user_anonymous);
            editBuffer.insert(*query.columnInfo(password->name()), password_anonymous);
            editBuffer.insert(*query.columnInfo(create->name()), vfalse);
            editBuffer.insert(*query.columnInfo(read->name()), vfalse);
            editBuffer.insert(*query.columnInfo(update->name()), vfalse);
            editBuffer.insert(*query.columnInfo(fdelete->name()), vfalse);
            editBuffer.insert(*query.columnInfo(fquery->name()), vfalse);
            if (cursor->insertRow(recordData, editBuffer)) {
                kDebug() << "Succeeded";
                User* u = new User("anonymous", "guest");
                m_users.append(*u);
                m_auth->addUser(u->name().toUtf8().constData(), u->password().toUtf8().constData());
            } else {
                kError() << "An error occurred";
                return false;
            }
            KexiWebForms::Model::gConnection->deleteCursor(cursor);
        }
    } else {
        // load stuff from the store, create appropriated User objects, store them within
        // Authenticator
        KexiDB::QuerySchema query(*table);
        KexiDB::Cursor* cursor = KexiWebForms::Model::gConnection->executeQuery(query);
        while (cursor->moveNext()) {
            // Skip id
            QString* username = new QString(cursor->value(1).toString());
            QString* password = new QString(cursor->value(2).toString());
            QList<Permission>* perms = new QList<Permission>;

            if (cursor->value(3).toBool()) perms->append(CREATE);
            if (cursor->value(4).toBool()) perms->append(READ);
            if (cursor->value(5).toBool()) perms->append(UPDATE);
            if (cursor->value(6).toBool()) perms->append(DELETE);
            if (cursor->value(7).toBool()) perms->append(QUERY);

            User* u = new User(*username, *password, *perms);
            m_users.append(*u);
            m_auth->addUser(u->name().toUtf8().constData(), u->password().toUtf8().constData());
            kDebug() << "Loaded user " << *username << " from store";
        }
    }

    return true;
}
Пример #5
0
bool KexiCSVExport::exportData(KexiDB::TableOrQuerySchema& tableOrQuery, 
	const Options& options, int rowCount, QTextStream *predefinedTextStream)
{
	KexiDB::Connection* conn = tableOrQuery.connection();
	if (!conn)
		return false;

	if (rowCount == -1)
		rowCount = KexiDB::rowCount(tableOrQuery);
	if (rowCount == -1)
		return false;

//! @todo move this to non-GUI location so it can be also used via command line
//! @todo add a "finish" page with a progressbar.
//! @todo look at rowCount whether the data is really large; 
//!       if so: avoid copying to clipboard (or ask user) because of system memory

//! @todo OPTIMIZATION: use fieldsExpanded(true /*UNIQUE*/)
//! @todo OPTIMIZATION? (avoid multiple data retrieving) look for already fetched data within KexiProject..

	KexiDB::QuerySchema* query = tableOrQuery.query();
	if (!query)
		query = tableOrQuery.table()->query();

	KexiDB::QueryColumnInfo::Vector fields( query->fieldsExpanded( KexiDB::QuerySchema::WithInternalFields ) );
	QString buffer;

	KSaveFile *kSaveFile = 0;
	QTextStream *stream = 0;

	const bool copyToClipboard = options.mode==Clipboard;
	if (copyToClipboard) {
//! @todo (during exporting): enlarge bufSize by factor of 2 when it became too small
		uint bufSize = QMIN((rowCount<0 ? 10 : rowCount) * fields.count() * 20, 128000);
		buffer.reserve( bufSize );
		if (buffer.capacity() < bufSize) {
			kdWarning() << "KexiCSVExportWizard::exportData() cannot allocate memory for " << bufSize 
				<< " characters" << endl;
			return false;
		}
	}
	else {
		if (predefinedTextStream) {
			stream = predefinedTextStream;
		}
		else {
			if (options.fileName.isEmpty()) {//sanity
				kdWarning() << "KexiCSVExportWizard::exportData(): fname is empty" << endl;
				return false;
			}
			kSaveFile = new KSaveFile(options.fileName);
			if (0 == kSaveFile->status())
				stream = kSaveFile->textStream();
			if (0 != kSaveFile->status() || !stream) {//sanity
				kdWarning() << "KexiCSVExportWizard::exportData(): status != 0 or stream == 0" << endl;
				delete kSaveFile;
				return false;
			}
		}
	}

//! @todo escape strings

#define _ERR \
	delete [] isText; \
	if (kSaveFile) { kSaveFile->abort(); delete kSaveFile; } \
	return false

#define APPEND(what) \
		if (copyToClipboard) buffer.append(what); else (*stream) << (what)

// line endings should be as in RFC 4180
#define CSV_EOLN "\r\n"

	// 0. Cache information
	const uint fieldsCount = query->fieldsExpanded().count(); //real fields count without internals
	const QCString delimiter( options.delimiter.left(1).latin1() );
	const bool hasTextQuote = !options.textQuote.isEmpty();
	const QString textQuote( options.textQuote.left(1) );
	const QCString escapedTextQuote( (textQuote + textQuote).latin1() ); //ok?
	//cache for faster checks
	bool *isText = new bool[fieldsCount]; 
	bool *isDateTime = new bool[fieldsCount]; 
	bool *isTime = new bool[fieldsCount]; 
	bool *isBLOB = new bool[fieldsCount]; 
	uint *visibleFieldIndex = new uint[fieldsCount];
//	bool isInteger[fieldsCount]; //cache for faster checks
//	bool isFloatingPoint[fieldsCount]; //cache for faster checks
	for (uint i=0; i<fieldsCount; i++) {
		KexiDB::QueryColumnInfo* ci;
		const int indexForVisibleLookupValue = fields[i]->indexForVisibleLookupValue();
		if (-1 != indexForVisibleLookupValue) {
			ci = query->expandedOrInternalField( indexForVisibleLookupValue );
			visibleFieldIndex[i] = indexForVisibleLookupValue;
		}
		else {
			ci = fields[i];
			visibleFieldIndex[i] = i;
		}

		isText[i] = ci->field->isTextType();
		isDateTime[i] = ci->field->type()==KexiDB::Field::DateTime;
		isTime[i] = ci->field->type()==KexiDB::Field::Time;
		isBLOB[i] = ci->field->type()==KexiDB::Field::BLOB;
//		isInteger[i] = fields[i]->field->isIntegerType() 
//			|| fields[i]->field->type()==KexiDB::Field::Boolean;
//		isFloatingPoint[i] = fields[i]->field->isFPNumericType();
	}

	// 1. Output column names
	if (options.addColumnNames) {
		for (uint i=0; i<fieldsCount; i++) {
			if (i>0)
				APPEND( delimiter );
			if (hasTextQuote){
				APPEND( textQuote + fields[i]->captionOrAliasOrName().replace(textQuote, escapedTextQuote) + textQuote );
			}
			else {
				APPEND( fields[i]->captionOrAliasOrName() );
			}
		}
		APPEND(CSV_EOLN);
	}
	
	KexiGUIMessageHandler handler;
	KexiDB::Cursor *cursor = conn->executeQuery(*query);
	if (!cursor) {
		handler.showErrorMessage(conn);
		_ERR;
	}
	for (cursor->moveFirst(); !cursor->eof() && !cursor->error(); cursor->moveNext()) {
		const uint realFieldCount = QMIN(cursor->fieldCount(), fieldsCount);
		for (uint i=0; i<realFieldCount; i++) {
			const uint real_i = visibleFieldIndex[i];
			if (i>0)
				APPEND( delimiter );
			if (cursor->value(real_i).isNull())
				continue;
			if (isText[real_i]) {
				if (hasTextQuote)
					APPEND( textQuote + QString(cursor->value(real_i).toString()).replace(textQuote, escapedTextQuote) + textQuote );
				else
					APPEND( cursor->value(real_i).toString() );
			}
			else if (isDateTime[real_i]) { //avoid "T" in ISO DateTime
				APPEND( cursor->value(real_i).toDateTime().date().toString(Qt::ISODate)+" "
					+ cursor->value(real_i).toDateTime().time().toString(Qt::ISODate) );
			}
			else if (isTime[real_i]) { //time is temporarily stored as null date + time...
				APPEND( cursor->value(real_i).toTime().toString(Qt::ISODate) );
			}
			else if (isBLOB[real_i]) { //BLOB is escaped in a special way
				if (hasTextQuote)
//! @todo add options to suppport other types from KexiDB::BLOBEscapingType enum...
					APPEND( textQuote + KexiDB::escapeBLOB(cursor->value(real_i).toByteArray(), KexiDB::BLOBEscapeHex) + textQuote );
				else
					APPEND( KexiDB::escapeBLOB(cursor->value(real_i).toByteArray(), KexiDB::BLOBEscapeHex) );
			}
			else {//other types
				APPEND( cursor->value(real_i).toString() );
			}
		}
		APPEND(CSV_EOLN);
	}

	if (copyToClipboard)
		buffer.squeeze();

	if (!conn->deleteCursor(cursor)) {
		handler.showErrorMessage(conn);
		_ERR;
	}

	if (copyToClipboard)
		kapp->clipboard()->setText(buffer, QClipboard::Clipboard);

	delete [] isText;
	delete [] isDateTime;
	delete [] isTime;
	delete [] isBLOB;
	delete [] visibleFieldIndex;

	if (kSaveFile) {
		if (!kSaveFile->close()) {
			kdWarning() << "KexiCSVExportWizard::exportData(): error close(); status == " 
				<< kSaveFile->status() << endl;
		}
		delete kSaveFile;
	}
	return true;
}