Ejemplo n.º 1
0
void testCreateTable(void) {

  struct Command* createDBCommand = createCreateDatabaseCommand("foo");
  createDatabase(createDBCommand);
  assert(strcmp(currentDatabase, "foo") == 0, "currentDatabase should be set!");
  char tableFolderPath[PATH_SIZE];

  char names[FIELD_SIZE][NAME_LIMIT] = { "name1", "name2", "name3", "name4", };

  char values[FIELD_SIZE][VALUE_LIMIT] = { "1", "value2", "1/1/2015", "3", };

  FieldType types[FIELD_SIZE][1] = { INTEGER, TEXT, DATE, INTEGER, };
  struct Field* fields = createFieldList(names, values, types, 4);

  struct Command* createTableCmd = createCreateTableCommand("bar", fields);
  createTable(createTableCmd);
  sprintf(tableFolderPath, "%s/foo/bar", DATABASE_DIR);
  assert(access(tableFolderPath, F_OK) != -1, "Table file was not constructed!");

  char fileContents[RECORD_SIZE];
  FILE* file = fopen(tableFolderPath, "r");
  fgets(fileContents, RECORD_SIZE, file);

  char* header = "name1[I]|name2[T]|name3[D]|name4[I]\n";
  assert(strcmp(fileContents, header) == 0, "Table was not written correctly!");

  // cleanup garbage
  fclose(file);
  destroyCommand(createDBCommand);
  destroyCommand(createTableCmd);
}
Ejemplo n.º 2
0
void testStore(void) {

  // setup
  struct Command* createDatabaseCommand = createCreateDatabaseCommand("test_store");
  createDatabase(createDatabaseCommand);

  char names[FIELD_SIZE][NAME_LIMIT] = { "name1", "name2", "name3", "name4", };

  char values[FIELD_SIZE][VALUE_LIMIT] = { "1", "value2", "1/1/2015", "3", };

  FieldType types[FIELD_SIZE][1] = { INTEGER, TEXT, DATE, INTEGER, };

  struct Field* fields = createFieldList(names, values, types, 4);
  struct Command* createTableCmd = createCreateTableCommand("table",
      fields);
  createTable(createTableCmd);


  // test
  struct Command* insertCmd = createInsertCommand("table", fields);
  insertTuple(insertCmd);
  values[0][0] = '2';
  insertTuple(insertCmd);

  // teardown
  destroyCommand(createDatabaseCommand);
  destroyCommand(createTableCmd);
}
Ejemplo n.º 3
0
/*
 * Given a time, returns an iterator to the appropriate database, creating it if
 * it doesn't exist.
 */
std::tr1::unordered_map <uint32_t, _BerkeleyDB*>::iterator BerkeleyDB::findDatabase(const uint32_t hourStartTime) {
  std::tr1::unordered_map <uint32_t, _BerkeleyDB*>::iterator databaseItr = databases.find(hourStartTime);
  if (databaseItr != databases.end()) {
    return databaseItr;
  }
  return createDatabase(hourStartTime);
}
Ejemplo n.º 4
0
void Database_SQLite3::openDatabase()
{
	if (m_database) return;

	std::string dbp = m_savedir + DIR_DELIM + "map.sqlite";

	// Open the database connection

	if (!fs::CreateAllDirs(m_savedir)) {
		infostream << "Database_SQLite3: Failed to create directory \""
			<< m_savedir << "\"" << std::endl;
		throw FileNotGoodException("Failed to create database "
				"save directory");
	}

	bool needs_create = !fs::PathExists(dbp);

	SQLOK(sqlite3_open_v2(dbp.c_str(), &m_database,
			SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL),
		std::string("Failed to open SQLite3 database file ") + dbp);

	SQLOK(sqlite3_busy_handler(m_database, Database_SQLite3::busyHandler,
		m_busy_handler_data), "Failed to set SQLite3 busy handler");

	if (needs_create) {
		createDatabase();
	}

	std::string query_str = std::string("PRAGMA synchronous = ")
			 + itos(g_settings->getU16("sqlite_synchronous"));
	SQLOK(sqlite3_exec(m_database, query_str.c_str(), NULL, NULL, NULL),
		"Failed to modify sqlite3 synchronous mode");
}
Ejemplo n.º 5
0
void
TrainDB::initDatabase(QDir home)
{


    if(db->database(sessionid).isOpen()) return;

    // get a connection
    sessionid = "train";
    db = new QSqlDatabase(QSqlDatabase::addDatabase("QSQLITE", sessionid));
    db->setDatabaseName(home.canonicalPath() + "/trainDB");

    if (!db->database(sessionid).isOpen()) {
        QMessageBox::critical(0, qApp->translate("TrainDB","Cannot open database"),
                       qApp->translate("TrainDB","Unable to establish a database connection.\n"
                                       "This feature requires SQLite support. Please read "
                                       "the Qt SQL driver documentation for information how "
                                       "to build it.\n\n"
                                       "Click Cancel to exit."), QMessageBox::Cancel);
    } else {

        // create database - does nothing if its already there
        createDatabase();
    }
}
void Database_SQLite3::openDatabase()
{
	if (m_database) return;

	std::string dbp = m_savedir + DIR_DELIM + "map.sqlite";

	// Open the database connection

	if (!fs::CreateAllDirs(m_savedir)) {
		infostream << "Database_SQLite3: Failed to create directory \""
			<< m_savedir << "\"" << std::endl;
		throw FileNotGoodException("Failed to create database "
				"save directory");
	}

	bool needs_create = !fs::PathExists(dbp);

	if (sqlite3_open_v2(dbp.c_str(), &m_database,
			SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
			NULL) != SQLITE_OK) {
		errorstream << "SQLite3 database failed to open: "
			<< sqlite3_errmsg(m_database) << std::endl;
		throw FileNotGoodException("Cannot open database file");
	}

	if (needs_create) {
		createDatabase();
	}

	std::string query_str = std::string("PRAGMA synchronous = ")
			 + itos(g_settings->getU16("sqlite_synchronous"));
	SQLOK(sqlite3_exec(m_database, query_str.c_str(), NULL, NULL, NULL));
}
void Database_PostgreSQL::connectToDatabase()
{
	m_conn = PQconnectdb(m_connect_string.c_str());

	if (PQstatus(m_conn) != CONNECTION_OK) {
		throw DatabaseException(std::string(
			"PostgreSQL database error: ") +
			PQerrorMessage(m_conn));
	}

	m_pgversion = PQserverVersion(m_conn);

	/*
	* We are using UPSERT feature from PostgreSQL 9.5
	* to have the better performance where possible.
	*/
	if (m_pgversion < 90500) {
		warningstream << "Your PostgreSQL server lacks UPSERT "
			<< "support. Use version 9.5 or better if possible."
			<< std::endl;
	}

	infostream << "PostgreSQL Database: Version " << m_pgversion
			<< " Connection made." << std::endl;

	createDatabase();
	initStatements();
}
Ejemplo n.º 8
0
Controller::Controller(QObject *parent) : QObject(parent)
{


    connect(&main_window, SIGNAL(InserisciClicked_SIGNAL()), this, SLOT(createPersonfromInputForm()));
    connect(this, SIGNAL(inputNotValid()), &main_window, SLOT(reInsertInput()));

    connect(this, SIGNAL(newPersonRegistered()), &main_window, SLOT(on_RegistrationComplete()));
    connect(this, SIGNAL(registrationFailed()), &main_window, SLOT(on_RegistrationFailed()));
    connect(&main_window, SIGNAL(CancellaClicked_SIGNAL()), &main_window, SLOT(on_Cancella()));

    connect(&main_window, SIGNAL(VisualizzaClicked_SIGNAL(bool)), this, SLOT(fillSearchResultsTable(bool)));

    connect(&main_window, SIGNAL(ImportDatabaseDoubleClicked_SIGNAL(QString)), this, SLOT(ImportDatabase(QString)));

    connect(&main_window, SIGNAL(Visualizza_in_scadenza_button_clicked_SIGNAL(bool)), this, SLOT(fillSearchResultsTable(bool)));

    connect(&main_window, SIGNAL(setDbPath()), this, SLOT(createDbPathDialog()));
    connect(&main_window, SIGNAL(setExcelPath()), this, SLOT(createExcelPathDialog()));



    connect(&db_path_dialog, SIGNAL(showNameDialog_SIGNAL()), this, SLOT(showNameDialog()));
    connect(&db_name_dialog, SIGNAL(createDatabase_SIGNAL()), this, SLOT(createDatabase()));


}
Ejemplo n.º 9
0
SyncDatabase::SyncDatabase(int page_id, QString * temp_path)
{
    this->page_id = page_id;
    this->temp_path = new QString(*temp_path);
    this->db = NULL;

    createDatabase();
}
Ejemplo n.º 10
0
void MainWindow::setupConnections()
{
  /*
   * Actions
   */
  connect(actionAbout,        SIGNAL(triggered()),  aboutDial,     SLOT(exec()));
  connect(actionAddDb,        SIGNAL(triggered()),  this,          SLOT(createDatabase()));
  connect(actionClearRecent,  SIGNAL(triggered()),  this,          SLOT(clearRecent()));
  connect(actionCloseTab,     SIGNAL(triggered()),  this,          SLOT(closeCurrentTab()));
  connect(actionCopy,         SIGNAL(triggered()),  this,          SLOT(copy()));
  connect(actionCut,          SIGNAL(triggered()),  this,          SLOT(cut()));
  connect(actionDbManager,    SIGNAL(triggered()),  dbDialog,      SLOT(exec()));
  connect(actionLogs,         SIGNAL(triggered()),  logDial,       SLOT(exec()));
  connect(actionNewQuery,     SIGNAL(triggered()),  this,          SLOT(newQuery()));
  connect(actionNextTab,      SIGNAL(triggered()),  this,          SLOT(nextTab()));
  connect(actionOpenQuery,    SIGNAL(triggered()),  this,          SLOT(openQuery()));
  connect(actionPaste,        SIGNAL(triggered()),  this,          SLOT(paste()));
  connect(actionPlugins,      SIGNAL(triggered()),  pluginDialog,  SLOT(exec()));
  connect(actionPreferences,  SIGNAL(triggered()),  confDial,      SLOT(exec()));
  connect(actionPreviousTab,  SIGNAL(triggered()),  this,          SLOT(previousTab()));
  connect(actionPrint,        SIGNAL(triggered()),  this,          SLOT(print()));
  connect(actionRedo,         SIGNAL(triggered()),  this,          SLOT(redo()));
  connect(actionSaveQuery,    SIGNAL(triggered()),  this,          SLOT(saveQuery()));
  connect(actionSaveQueryAs,  SIGNAL(triggered()),  this,          SLOT(saveQueryAs()));
  connect(actionSearch,       SIGNAL(triggered()),  this,          SLOT(search()));
  connect(actionSelect_all,   SIGNAL(triggered()),  this,          SLOT(selectAll()));
  connect(actionUndo,         SIGNAL(triggered()),  this,          SLOT(undo()));

  /*
   * DbTreeView
   */
  connect(dbTreeView, SIGNAL(tableSelected(QSqlDatabase*,QString)),
          this, SLOT(openTable(QSqlDatabase*,QString)));

  /*
   * DbManager
   */
  connect(DbManager::instance(), SIGNAL(statusChanged(QSqlDatabase*)),
          this, SLOT(checkDb(QSqlDatabase*)));
  connect(DbManager::model(), SIGNAL(dataChanged(QModelIndex,QModelIndex)),
          this, SLOT(reloadDbList()));

  /*
   * Dialogs
   */
  connect(dbWizard, SIGNAL(accepted()), this, SLOT(reloadDbList()));
  connect(logDial,  SIGNAL(event(QString)),
          QMainWindow::statusBar(), SLOT(showMessage(QString)));

  connect(QueryScheduler::instance(), SIGNAL(countChanged(int)),
          this, SLOT(setQueryCount(int)));

  /*
   * Tab widget
   */
  connect(tabWidget, SIGNAL(currentChanged(int)), this, SLOT(refreshTab()));
  connect(tabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(closeTab(int)));
}
Ejemplo n.º 11
0
void Database_SQLite3::verifyDatabase() {
	if(m_database)
		return;
	
	{
		std::string dbp = m_savedir + DIR_DELIM + "map.sqlite";
		bool needs_create = false;
		int d;
		
		/*
			Open the database connection
		*/
	
		createDirs(m_savedir); // ?
	
		if(!fs::PathExists(dbp))
			needs_create = true;
	
		d = sqlite3_open_v2(dbp.c_str(), &m_database, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
		if(d != SQLITE_OK) {
			infostream<<"WARNING: SQLite3 database failed to open: "<<sqlite3_errmsg(m_database)<<std::endl;
			throw FileNotGoodException("Cannot open database file");
		}
		
		if(needs_create)
			createDatabase();

		std::string querystr = std::string("PRAGMA synchronous = ")
				 + itos(g_settings->getU16("sqlite_synchronous"));
		d = sqlite3_exec(m_database, querystr.c_str(), NULL, NULL, NULL);
		if(d != SQLITE_OK) {
			infostream<<"WARNING: Database pragma set failed: "
					<<sqlite3_errmsg(m_database)<<std::endl;
			throw FileNotGoodException("Cannot set pragma");
		}

		d = sqlite3_prepare(m_database, "SELECT `data` FROM `blocks` WHERE `pos`=? LIMIT 1", -1, &m_database_read, NULL);
		if(d != SQLITE_OK) {
			infostream<<"WARNING: SQLite3 database read statment failed to prepare: "<<sqlite3_errmsg(m_database)<<std::endl;
			throw FileNotGoodException("Cannot prepare read statement");
		}
		
		d = sqlite3_prepare(m_database, "REPLACE INTO `blocks` VALUES(?, ?)", -1, &m_database_write, NULL);
		if(d != SQLITE_OK) {
			infostream<<"WARNING: SQLite3 database write statment failed to prepare: "<<sqlite3_errmsg(m_database)<<std::endl;
			throw FileNotGoodException("Cannot prepare write statement");
		}
		
		d = sqlite3_prepare(m_database, "SELECT `pos` FROM `blocks`", -1, &m_database_list, NULL);
		if(d != SQLITE_OK) {
			infostream<<"WARNING: SQLite3 database list statment failed to prepare: "<<sqlite3_errmsg(m_database)<<std::endl;
			throw FileNotGoodException("Cannot prepare read statement");
		}
		
		infostream<<"ServerMap: SQLite3 database opened"<<std::endl;
	}
}
////////////////////////////////////////////////////////////////
///Adds new files to the database
void FileSniffer::addToDatabase()
{
	try{
	for (std::set<std::string>::iterator itfiles=newfilesList.begin(); itfiles != newfilesList.end(); itfiles++)	//insert new files in the fileset
			fileset.insert(*itfiles);
	createDatabase(fileset);	//create new database from fileset
	}catch(std::exception& ex){
      std::cout << "\n\n    " << ex.what() << "\n\n"; }	
}
Ejemplo n.º 13
0
PassRefPtr<DatabaseBackendBase> DatabaseServer::openDatabase(RefPtr<DatabaseContext>& backendContext,
        DatabaseType type, const String& name, const String& expectedVersion, const String& displayName,
        unsigned long estimatedSize, bool setVersionInNewDatabase, DatabaseError &error, String& errorMessage)
{
    RefPtr<DatabaseBackendBase> database;
    if (DatabaseTracker::tracker().canEstablishDatabase(backendContext.get(), name, displayName, estimatedSize, error))
        database = createDatabase(backendContext, type, name, expectedVersion, displayName, estimatedSize, setVersionInNewDatabase, error, errorMessage);
    return database.release();
}
Ejemplo n.º 14
0
DataBase::DataBase()
{
   twitter = Twitter::getcls();
   twitterDB = twitter->getDatabase();
   if (!twitter->getDatabaseStatus())
   {
       createDatabase();
   }
}
Ejemplo n.º 15
0
//Checks if the database exists. If not, the function creates the database.
void doesDatabaseExist(char *databaseName) {
    if(access(databaseName, F_OK) != -1 ) {
        //puts("Database.db exists.");
    }
    else {
        //puts("Database.db does not exist. Creating it.");
        createDatabase(databaseName);
        puts("Database created. Default login: admin, 123456");
    }
}
Ejemplo n.º 16
0
void KueueApp::createApp()
{
    bool update = false;
    
    if ( Settings::appVersion() != QApplication::applicationVersion() )
    {
        update = true;
        QDir dir = QDir( QDesktopServices::storageLocation( QDesktopServices::DataLocation ) );
        qDebug() << "Removing" << dir.path() + "/database.sqlite";
        QFile::remove( dir.path() + "/database.sqlite" );
    }
       
    createSystray();
    createDatabase();
    createMainWindow();
        
    mDataThread = &mDataThread->thread();
    connectDataThread();

    if ( update )
    {
        /*UpdateDialog* ud = new UpdateDialog( this );
        
        qDebug() << "[KUEUE] Update detected: " << Settings::appVersion() << "vs." << QApplication::applicationVersion();
        qDebug() << "[KUEUE] Updatedialog? Anything you'd like to share?";
        
        if ( ud->smthToSay() )
        {
            ud->exec();
        }
        
        qDebug() << "[KUEUE] OK, thanks. I'll delete you and rebuild the DB.";
        
        delete ud;*/
        
        Settings::setAppVersion( QApplication::applicationVersion() );
    }
    
    QShortcut* testNotification = new QShortcut( QKeySequence( Qt::CTRL + Qt::Key_N ), mWindow );
    QShortcut* newUnityTab = new QShortcut( QKeySequence( Qt::CTRL + Qt::Key_U ), mWindow );
    QShortcut* dbrebuild = new QShortcut( QKeySequence( Qt::CTRL + Qt::Key_R ), mWindow );
   
    QNetworkReply* r = Network::get( "latestkueue" );
        
    connect( r, SIGNAL( finished() ),
             this, SLOT( updateJobDone() ) );    
    connect( testNotification, SIGNAL( activated() ),
             this, SLOT( sendTestNotification() ) );
    connect( newUnityTab, SIGNAL( activated() ),
             mTabWidget, SLOT( addUnityBrowser() ) );
    connect( dbrebuild, SIGNAL( activated() ),
             this, SLOT( newDB() ) );
}
BlockIO InterpreterCreateQuery::execute()
{
    ASTCreateQuery & create = typeid_cast<ASTCreateQuery &>(*query_ptr);

    /// CREATE|ATTACH DATABASE
    if (!create.database.empty() && create.table.empty())
    {
        createDatabase(create);
        return {};
    }
    else
        return createTable(create);
}
Ejemplo n.º 18
0
	void Database::init(QString p_path, QString p_script, QString database_name) {
		setScriptPath(p_script);

		QSqlDatabase db = add(p_path, database_name);

		if (not QFileInfo(path()).exists())
			createDatabase();

		if (not db.open())
			throw new ErrorOpeningDatabase(path());

		//db.close();
	}
Ejemplo n.º 19
0
Database::Database() :QObject(0), subset(false), ssAlbum(0), fillingProgress(0), filling(false)
{
    QMutexLocker locker(&lock);
    db = QSqlDatabase::addDatabase("QSQLITE", "CollectionDB");
    db.setDatabaseName(QDir::homePath()+"/.cuberok/collection.db");
	// db.setConnectOptions("QSQLITE_ENABLE_SHARED_CACHE=1");
    if(QFile::exists(db.databaseName())) {
        if(!db.open()) {
            qDebug("Can not open database");
            proxy->error("Can not open database");
            open = false;
        } else {
            open = true;
            QSqlQuery q1("select value from Version", db);
            int ver = -1;
            if(q1.next()) ver = q1.value(0).toString().toInt();
			if(ver == -1) {
				open = createDatabase();
			} else if(ver < DB_VERSION) {
                open = updateDatabase(ver);
                if(!open) db.close();
            } else if(ver > DB_VERSION) {
                open = false;
                db.close();
                qDebug("Wrong database version (%d)", ver);
                proxy->error("Wrong database version -" + QString::number(ver));
            }
        }
    } else {
        if(!QDir().mkpath(QDir::homePath()+"/.cuberok") || !db.open()) {
            qDebug("Can not create database");
            proxy->error("Can not create database");
            open = false;
        } else {
			open = createDatabase();
        }
    }
    if(open) proxy->message("Database ready");
}
Ejemplo n.º 20
0
QSqlDatabase QrSqlDatabase::getDatabaseByCurThreadId(QSqlError &dbError)
{
//    QMutexLocker locker(&mutexDb);
    mutexDb.lock();
    dbError = QSqlError();

    Qt::HANDLE curThreadIdHandle = QThread::currentThreadId ();
    if (! curThreadIdHandle) {
        qDebug() << "unable to find current thread id";
        dbError = QSqlError("'unable to find current thread id'", "", QSqlError::UnknownError);
        Q_ASSERT(false);
        mutexDb.unlock();
        return QrSqlDatabase::null;
    }

    if (! listDbByThread.contains (curThreadIdHandle)) {
        auto db = createDatabase (dbError);
        mutexDb.unlock();
        if(dbFileIsCreated) {
            callAfterSuccessCreateDatabase();
        }
        return db;
    }

    QString connectionName = listDbByThread.value (curThreadIdHandle);
    if (! QSqlDatabase::contains (connectionName)) {
        auto db = createDatabase (dbError);
        mutexDb.unlock();
        if(dbFileIsCreated) {
            callAfterSuccessCreateDatabase();
        }
        return db;
    }

    auto db = QSqlDatabase::database (connectionName);
    mutexDb.unlock();
    return db;
}
Ejemplo n.º 21
0
databasePTR init_database(char *file_path) 
{
    size_t len;
    ssize_t chars;
    FILE *customerFile;
    char *token;
    char *linebuffer;
    char* name;
    float credit;
    int c_id;
    
    databasePTR db = createDatabase();

    //make sure filepath is referencing a valid file
    if (!checkFile(file_path)) 
    {
        printf("Error with filepath \n", file_path);
        exit(EXIT_FAILURE);
    }

    customerFile = fopen(file_path, "r");

    len = 0;
    linebuffer = NULL;

    while ( (chars = getline(&linebuffer, &len, customerFile) != -1) )  // tokenize for each line in input file
    {

        token = strtok(linebuffer, "|");                                           // name is first
        if (!token) {printf("Invalid customer file format \n"); exit(1);}
        name = strdup(token);
        printf("name: %s \n", name);

        token = strtok(NULL, "|");                                                         // then ID
        if (!token) {printf("Invalid customer file format \n"); exit(1);}
        c_id = atoi(token);
        printf("cid: %d \n", c_id);

        token = strtok(NULL, "|");                                                     // then credit limit
        if (!token) {printf("Invalid customer file format \n"); exit(1);}
        credit = atof(token);

        customerPTR newCustomer = createCustomer(name, c_id, credit);
        addCustomer(db, newCustomer);

    }
    free(linebuffer);
    fclose(customerFile);
    return db;
}
Ejemplo n.º 22
0
/*Creates database.db if doesn't exist.
 This is the database where remendo stores which events
 have been fixed, or not fixed*/
int checkDatabase(){
	// Create database.db if doesn't exists
	if(access(db_uri, F_OK) == -1) {
		printf("File database.db not found. Creating it now...\n");
		if(createDatabase() == 0){
			printf("Database created.\n");
		}
		else{
			printf("Something went wrong while creating database.db\n");
			return 1;
		}
	}
	return 0;
}
Ejemplo n.º 23
0
void MainWindow::onNewDatabase()
{
	QString databaseName = getNewDatabaseName();
	if(databaseName.length() == 0)
	{
		QMessageBox::critical(this,
				tr("Sqlite"),
				tr("Invalid file name!"));
		return;
	}
	qDebug() << databaseName;
	createDatabase(databaseName);
	addDatabase(databaseName);
}
BlockIO InterpreterCreateQuery::execute()
{
    ASTCreateQuery & create = typeid_cast<ASTCreateQuery &>(*query_ptr);
    checkAccess(create);
    ASTQueryWithOutput::resetOutputASTIfExist(create);

    /// CREATE|ATTACH DATABASE
    if (!create.database.empty() && create.table.empty())
    {
        return createDatabase(create);
    }
    else
        return createTable(create);
}
Ejemplo n.º 25
0
void Startup::createConfig( void )
{
    QMessageBox msgBox;
    msgBox.setText("No config found !");
    msgBox.setInformativeText("Do you want to create a new database \n or would you register your existing databases?");
    msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
    msgBox.setDefaultButton(QMessageBox::Ok);
    int ret = msgBox.exec();
    if( ret == QMessageBox::Ok )
    {
        cdlg = new ConfigDialog();
        connect( cdlg, SIGNAL(changedDialog()), this, SLOT(createDatabase()));
        cdlg->show();
    }
}
RecipeDB* RecipeDB::createDatabase( const QString &dbType, const QString &file )
{
	kDebug()<<" type :"<<dbType<<" file :"<<file;
	KConfigGroup config = KGlobal::config()->group( "Server" );
	QString host = config.readEntry( "Host", "localhost" );
	QString user = config.readEntry( "Username", QString() );
	QString pass = config.readEntry( "Password", QString() );
	QString dbname = config.readEntry( "DBName", DEFAULT_DB_NAME );
	int port = config.readEntry( "Port", 0 );

	QString f = file;
	if ( f.isEmpty() )
		f = config.readEntry( "DBFile", KStandardDirs::locateLocal ( "appdata", DB_FILENAME ) );
	kDebug()<<" f :"<<f;
	return createDatabase( dbType, host, user, pass, dbname, port, f );
}
Ejemplo n.º 27
0
dataFetch::dataFetch()
{
    //Setting the databease type (SQLite).
    db = QSqlDatabase::addDatabase("QSQLITE");
    QFile dbfile;
    //If the database file does not exist it is created.
    if(!dbfile.exists(constants::NAME_OF_DATABASE))
    {
        createDatabase();
        return;
    }
    //The database filename.
    QString dbName = constants::NAME_OF_DATABASE;
    //Connecting the Qt database object to the actual database file.
    db.setDatabaseName(dbName);
    db.open();
}
Ejemplo n.º 28
0
/**==============================================================
 * Description: Constructor of BookMarkServer
 * Author: Chandrashekar.V
 * EmpId:  10289207
 ================================================================*/
BookMarkServer::BookMarkServer() :
    m_sessionCount(0)
    {

    m_server = new WRT::ServiceFwIPCServer(this, this);
    createDatabase();
    bool ret = m_server->listen(BOOKMARKSENGINESERVER);
    if (!ret)
        {
        qDebug() << " Failed to LISTEN" << '\n';
        QTimer::singleShot(1, this, SLOT(closeServer()));
        return;
        }

    m_server->configIpcServerLifetime(true);

    }
Ejemplo n.º 29
0
void MainWindow::startUp()
{
    //read settings
    QSettings settings(QSettings::IniFormat, QSettings::UserScope, "QTwitdget", "QTwitdget");
    m_userId = settings.value("user_id", 0).toInt();
    m_userScreenName = settings.value("user_screenname").toString();
    QString oauthToken = settings.value("oauth_token").toString();
    QString oauthTokenSecret = settings.value("oauth_token_secret").toString();

    if (!m_userScreenName.isEmpty())
        emit userScreenNameChanged();

    if(m_userId != 0 && !oauthToken.isEmpty() && !oauthTokenSecret.isEmpty()){
        m_oauthTwitter->setOAuthToken(oauthToken.toUtf8());
        m_oauthTwitter->setOAuthTokenSecret(oauthTokenSecret.toUtf8());

        //create or change database according to user id
        createDatabase(QString::number(m_userId));

        //show/animate tweets list page
        QGraphicsObject *obj = rootObject();
        obj->setProperty("authed", true);

        //set user id in the models
        m_tweetListModel->setUserID(m_userId);
        m_mentionsListModel->setUserID(m_userId);
        m_directMessagesListModel->setUserID(m_userId);
        m_conversationListModel->setUserID(m_userId);

        //show last tweets from database
        m_tweetListModel->loadTweetsFromDatabase();
        m_mentionsListModel->loadTweetsFromDatabase();
        m_directMessagesListModel->loadTweetsFromDatabase();

        //then fetch last 200 tweets
        m_tweetListModel->fetchLastTweets();
        m_mentionsListModel->fetchLastTweets();
        m_directMessagesListModel->fetchLastTweets();

        m_userStream->startFetching();

    } else {
        changeUserPass();
    }
}
Ejemplo n.º 30
0
ComicEntryListModel::ComicEntryListModel(QObject *parent) :
    QAbstractListModel(parent),
    m_comicEntries(),
    m_dbFullPath(QDesktopServices::storageLocation(QDesktopServices::DataLocation))
{
    QHash<int, QByteArray> roles;
    roles[ComicEntryNameRole] = "title";
    roles[ComicEntryFormattedDateRole] = "formattedDate";
    roles[ComicEntryAltTextRole] = "altText";
    roles[ComicEntryFavoriteRole] = "isFavorite";
    roles[ComicEntryIdRole] = "entryId";
    roles[ComicEntryMonthRole] = "month";
    roles[ComicEntryImageSourceRole] = "imageSource";
    setRoleNames(roles);

    createDatabase();
    loadComicEntries();
}