Esempio n. 1
0
void ConnectionTestThread::run()
{
    KexiDB::DriverManager manager;
    KexiDB::Driver* drv = manager.driver(m_connData.driverName);
// KexiGUIMessageHandler msghdr;
    if (!drv || manager.error()) {
//move  msghdr.showErrorMessage(&Kexi::driverManager());
        m_dlg->error(&manager);
        return;
    }
    KexiDB::Connection * conn = drv->createConnection(m_connData);
    if (!conn || drv->error()) {
//move  msghdr.showErrorMessage(drv);
        delete conn;
        m_dlg->error(drv);
        return;
    }
    if (!conn->connect() || conn->error()) {
//move  msghdr.showErrorMessage(conn);
        m_dlg->error(conn);
        delete conn;
        return;
    }
    // SQL database backends like PostgreSQL require executing "USE database"
    // if we really want to know connection to the server succeeded.
    QString tmpDbName;
    if (!conn->useTemporaryDatabaseIfNeeded(tmpDbName)) {
        m_dlg->error(conn);
        delete conn;
        return;
    }
    delete conn;
    m_dlg->error(0);
}
Esempio n. 2
0
bool Part::remove(KexiPart::Item &item)
{
    KexiDB::Connection *conn = KexiMainWindowIface::global()->project()->dbConnection();
    if (!conn)
        return false;
    return conn->removeObject(item.identifier());
}
Esempio n. 3
0
bool KexiMigrate::checkIfDestinationDatabaseOverwritingNeedsAccepting(Kexi::ObjectStatus* result,
        bool& acceptingNeeded)
{
    acceptingNeeded = false;
    if (result)
        result->clearStatus();

    KexiDB::DriverManager drvManager;
    KexiDB::Driver *destDriver = drvManager.driver(
                                     m_migrateData->destination->connectionData()->driverName);
    if (!destDriver) {
        result->setStatus(&drvManager,
                          i18n("Could not create database \"%1\".",
                               m_migrateData->destination->databaseName()));
        return false;
    }

    // For file-based dest. projects, we've already asked about overwriting
    // existing project but for server-based projects we need to ask now.
    if (destDriver->isFileDriver())
        return true; //nothing to check
    KexiDB::Connection *tmpConn
    = destDriver->createConnection(*m_migrateData->destination->connectionData());
    if (!tmpConn || destDriver->error() || !tmpConn->connect()) {
        delete tmpConn;
        return true;
    }
    if (tmpConn->databaseExists(m_migrateData->destination->databaseName())) {
        acceptingNeeded = true;
    }
    tmpConn->disconnect();
    delete tmpConn;
    return true;
}
tristate KexiAutoFormView::afterSwitchFrom(Kexi::ViewMode mode)
{
    kDebug();
    kDebug() << tempData()->name;
    
    QDomElement e = tempData()->autoformDefinition;
    
    //if (tempData()->schemaChangedInPreviousView) {
        if (m_autoForm) {
            m_scrollArea->takeWidget();
            delete m_autoForm;
        }
        m_autoForm = new AutoForm(this, m_pageSelector);
        
        KexiDB::Connection *conn = KexiMainWindowIface::global()->project()->dbConnection();
        KexiDB::Cursor *cursor = conn->executeQuery(*(conn->tableSchema("actor")));
        
        if (cursor) {
            kDebug() << "Opened Cursor";
            KexiTableViewData *data = new KexiTableViewData(cursor);
            data->preloadAllRows();
            m_autoForm->setData(data);
            
        }
        m_scrollArea->setWidget(m_autoForm);
    //}
    return true;
}
KexiDB::SchemaData* KexiReportDesignView::storeNewData(const KexiDB::SchemaData& sdata, bool &cancel)
{
    KexiDB::SchemaData *s = KexiView::storeNewData(sdata, cancel);
    kexipluginsdbg << "new id:" << s->id();

    if (!s || cancel) {
        delete s;
        return 0;
    }
    if (!storeData()) {
        //failure: remove object's schema data to avoid garbage
        KexiDB::Connection *conn = KexiMainWindowIface::global()->project()->dbConnection();
        conn->removeObject(s->id());
        delete s;
        return 0;
    }
    return s;
    
    
    
    
    #if 0
    
    
    KexiDB::SchemaData *rpt = new KexiDB::SchemaData();
    *rpt = sdata;
    //sdata.setName ( name );
    //sdata.setDescription ( _rd->reportTitle() );
    KexiDB::Connection *conn = KexiMainWindowIface::global()->project()->dbConnection();

    if (conn->storeObjectSchemaData(*rpt, true /*newObject*/)) {
        window()->setId(rpt->id());

        if (rpt->id() > 0 && storeDataBlock(_rd->document().toString(), "pgzreport_layout")) {
            kDebug() << "Saved OK " << rpt->id();
        } else {
            kDebug() << "NOT Saved OK";
            return 0;
        }
    } else {
        kDebug() << "Unable to store schema data";
        return 0;
    }
    return rpt;
    #endif
}
Esempio n. 6
0
QString Field::debugString() const
{
    KexiDB::Connection *conn = table() ? table()->connection() : 0;
    QString dbg = (m_name.isEmpty() ? QString::fromLatin1("<NONAME> ") : m_name + ' ');
    if (m_options & Field::Unsigned)
        dbg += " UNSIGNED ";
    dbg += (conn && conn->driver()) ? conn->driver()->sqlTypeName(type()) : Driver::defaultSQLTypeName(type());
    if (isFPNumericType() && m_precision > 0) {
        if (scale() > 0)
            dbg += QString::fromLatin1("(%1,%2)").arg(m_precision).arg(scale());
        else
            dbg += QString::fromLatin1("(%1)").arg(m_precision);
    } else if (m_type == Field::Text && m_maxLength > 0)
        dbg += QString::fromLatin1("(%1)").arg(m_maxLength);
    if (m_constraints & Field::AutoInc)
        dbg += " AUTOINC";
    if (m_constraints & Field::Unique)
        dbg += " UNIQUE";
    if (m_constraints & Field::PrimaryKey)
        dbg += " PKEY";
    if (m_constraints & Field::ForeignKey)
        dbg += " FKEY";
    if (m_constraints & Field::NotNull)
        dbg += " NOTNULL";
    if (m_constraints & Field::NotEmpty)
        dbg += " NOTEMPTY";
    if (!m_defaultValue.isNull())
        dbg += QString(" DEFAULT=[%1]").arg(m_defaultValue.typeName()) + KexiDB::variantToString(m_defaultValue);
    if (m_expr)
        dbg += " EXPRESSION=" + m_expr->debugString();
    if (m_customProperties && !m_customProperties->isEmpty()) {
        dbg += QString(" CUSTOM PROPERTIES (%1): ").arg(m_customProperties->count());
        bool first = true;
        for (CustomPropertiesMap::ConstIterator it(m_customProperties->constBegin());
                it != m_customProperties->constEnd(); ++it) {
            if (first)
                first = false;
            else
                dbg += ", ";
            dbg += QString("%1 = %2 (%3)").arg(QString(it.key())).arg(it.value().toString())
                   .arg(it.value().typeName());
        }
    }
    return dbg;
}
Esempio n. 7
0
KexiDB::SchemaData* KexiView::copyData(const KexiDB::SchemaData& sdata,
                                        KexiView::StoreNewDataOptions options,
                                        bool &cancel)
{
    Q_UNUSED(options)
    Q_UNUSED(cancel)
    QScopedPointer<KexiDB::SchemaData> new_schema(new KexiDB::SchemaData);
    *new_schema = sdata;

    KexiDB::Connection *conn = KexiMainWindowIface::global()->project()->dbConnection();
    if (!conn->storeObjectSchemaData(*new_schema.data(), true)
        || !conn->copyDataBlock(d->window->id(), new_schema->id())
        || !KexiMainWindowIface::global()->project()->copyUserDataBlock(d->window->id(), new_schema->id())
       )
    {
        return 0;
    }
    d->newlyAssignedID = new_schema->id();
    return new_schema.take();
}
KexiDB::SchemaData* KexiReportDesignView::storeNewData(const KexiDB::SchemaData& sdata,
                                                       KexiView::StoreNewDataOptions options,
                                                       bool &cancel)
{
    KexiDB::SchemaData *s = KexiView::storeNewData(sdata, options, cancel);
    kDebug() << "new id:" << s->id();

    if (!s || cancel) {
        delete s;
        return 0;
    }
    if (!storeData()) {
        //failure: remove object's schema data to avoid garbage
        KexiDB::Connection *conn = KexiMainWindowIface::global()->project()->dbConnection();
        conn->removeObject(s->id());
        delete s;
        return 0;
    }
    return s;

}
KexiRelationMainDlg::KexiRelationMainDlg(QWidget *parent)
        : KexiView(parent)
{
    kDebug() << "KexiRelationMainDlg()";
// setIcon(SmallIcon("relation"));
    m_defaultIconName = "relation";
    setWindowTitle(i18n("Relationships"));
// setDocID( win->generatePrivateDocID() );

    m_rel = new KexiRelationsView(this);
    //the view can receive some our actions
    addActionProxyChild(m_rel);
// addActionProxyChild( m_view->relationsView() );

    QVBoxLayout *g = new QVBoxLayout(this);
    g->addWidget(m_rel);

    //show all tables
    KexiDB::Connection *conn = KexiMainWindowIface::global()->project()->dbConnection();
    QStringList tables = conn->tableNames();
    for (QStringList::ConstIterator it = tables.constBegin(); it != tables.constEnd(); ++it) {
        m_rel->addTable(*it);
    }
}
Esempio n. 10
0
void
KexiDBSubForm::setFormName(const QString &name)
{
    if (m_formName == name)
        return;

    m_formName = name; //assign, even if the name points to nowhere

    if (name.isEmpty()) {
        delete m_widget;
        m_widget = 0;
        updateScrollBars();
        return;
    }

    QWidget *pw = parentWidget();
    KexiFormView *view = 0;
    QSet<QString> names;
    while (pw) {
        if (KexiUtils::objectIsA(pw, "KexiDBSubForm")) {
            if (names.contains(pw->objectName())) {
//! @todo error message
                return; // Be sure to don't run into a endless-loop cause of recursive subforms.
            }
            names.insert(pw->objectName());
        } else if (! view && KexiUtils::objectIsA(pw, "KexiFormView")) {
            view = static_cast<KexiFormView*>(pw); // we need a KexiFormView*
        }
        pw = pw->parentWidget();
    }

    if (!view || !view->window() || !KexiMainWindowIface::global()->project()->dbConnection())
        return;

    KexiDB::Connection *conn = KexiMainWindowIface::global()->project()->dbConnection();

    // we check if there is a form with this name
    int id = KexiDB::idForObjectName(*conn, name, KexiPart::FormObjectType);
    if ((id == 0) || (id == view->window()->id())) // == our form
        return; // because of recursion when loading

    // we create the container widget
    delete m_widget;
    m_widget = new QWidget(viewport());
    m_widget->setObjectName("KexiDBSubForm_widget");
    m_widget->show();
    addChild(m_widget);
    m_form = new KFormDesigner::Form(m_parentForm);
    m_form->setObjectName(QString("KFormDesigner::Form_") + objectName());
    m_form->createToplevel(m_widget);

    // and load the sub form
    QString data;
    tristate res = conn->loadDataBlock(id, data, QString());
    if (res == true)
        res = KFormDesigner::FormIO::loadFormFromString(m_form, m_widget, data);
    if (res != true) {
        delete m_widget;
        m_widget = 0;
        updateScrollBars();
        m_formName.clear();
        return;
    }
    m_form->setMode(KFormDesigner::Form::DataMode);

    // Install event filters on the whole newly created form
    KFormDesigner::ObjectTreeItem *tree = m_parentForm->objectTree()->lookup(QObject::objectName());
    KFormDesigner::installRecursiveEventFilter(this, tree->eventEater());
}
Esempio n. 11
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;
}
Esempio n. 12
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;
}