Beispiel #1
0
bool
FirebirdDriver::initialize()
{
    if (_library != NULL)
	return true;

    FirebirdConfig config;
    if (!config.load())
	return error("Can't read firebird.cfg file");

    // Set firebird install directory
#ifdef WIN32
    SetEnvironmentVariable("INTERBASE", parseDir(config.installDir));
    SetEnvironmentVariable("FIREBIRD", parseDir(config.installDir));
#else
    setenv("INTERBASE", parseDir(config.installDir), true);
    setenv("FIREBIRD", parseDir(config.installDir), true);
#endif

    // Try to load the library
    QLibrary* library = new QLibrary(config.library);
    if (!library->load()) {
	libraryError();
	delete library;
	return error("Can't load firebird library: " + config.library);
    }

    _library = library;
    _procs = new FirebirdProcs(_library);

    return true;
}
void FileManagerAddDlg::setupUi(void)
{
	resize(792, 420);

	buttonLayout.addWidget(&abortBtn);
	buttonLayout.addWidget(&okBtn);
	dlgLayout.addWidget(&dlgLabel);
	dlgLayout.addWidget(&listWidget);
	dlgLayout.addLayout(&buttonLayout);

	listWidget.setSelectionMode(QAbstractItemView::MultiSelection);

	QObject::connect(&okBtn, SIGNAL(clicked()), this, SLOT(slotBtnOk()));
	QObject::connect(&abortBtn, SIGNAL(clicked()), this, SLOT(reject()));

	const QList<QTreeWidgetItem*> items = fileViewRef->selectedItems();

	QDir parseDir(globals::MUSIC_ROOT);

	/*QListIterator<QTreeWidgetItem*> i(items);
	while (i.hasNext()) {
		QTreeWidgetItem* QString& curItem =
		grepNewFiles(i.next(), &parseDir);
	}*/

	QSqlQuery query = sqlhelper.exec("SELECT * FROM main;");
	QList<QString> dbNameList;
	while (query.next()) {
		dbNameList.push_back( query.value(13).toString() );
	}
	qSort( dbNameList );
	
	grepNewFiles(fileViewRef->topLevelItem(0)->child(0), &parseDir, &listWidget, &dbNameList);
	listWidget.selectAll();
}
Beispiel #3
0
void NDirWatcherThread::parseDir(const QString & path, bool recursive, const QString & rootPath)
{
    QDir d(path);
    if (!d.exists() || d.dirName() == "." || d.dirName() == "..")
        return;

    QString absolutePath = d.absolutePath();
    if (m_notSharedDirs.contains(absolutePath))
    {	// Excluded dir, we don't add it in database
        NDir dir = m_notSharedDirs[absolutePath];
        if (dir.recursive()) // Recursive exclusion
            return;
        // but we can add children in database
    } else {
        // Include dir
        QDir dir(rootPath);
        dir.cdUp();
        m_dirs.addDir(absolutePath, dir.absolutePath());
    }

    if (!recursive)
        return;

    d.setFilter(QDir::Dirs | QDir::Readable | QDir::NoDotAndDotDot | QDir::NoSymLinks);
    QFileInfoList list = d.entryInfoList();
    for(int i = 0; i < list.count(); i++)
    {
        const QFileInfo & fi = list[i];
        if (isStopping())
            break;
        //qDebug(qPrintable(fi.absoluteFilePath()));
        parseDir(fi.absoluteFilePath(), recursive, rootPath); // absoluteFilePath because dir is considered has a file
    }
}
Beispiel #4
0
UpdateScreen::UpdateScreen(const CompanyDefn& company)
    : QMainWindow(0, "UpdateScreen", WType_TopLevel | WDestructiveClose),
      _connection(NULL)
{
    QFrame* frame = new QFrame(this);

    QLabel* fromLabel = new QLabel(tr("From Version:"), frame);
    _fromVersion = new LineEdit(14, frame);
    _fromVersion->setFocusPolicy(NoFocus);

    QLabel* toLabel = new QLabel(tr("To Version:"), frame);
    _toVersion = new ComboBox(frame);
    toLabel->setBuddy(_toVersion);

    QFrame* buttons = new QFrame(frame);
    _update = new QPushButton(tr("&Update"), buttons);
    _close = new QPushButton(tr("&Close"), buttons);

    connect(_update, SIGNAL(clicked()), SLOT(slotUpdate()));
    connect(_close, SIGNAL(clicked()), SLOT(slotClose()));

    QGridLayout* buttonGrid = new QGridLayout(buttons);
    buttonGrid->setSpacing(6);
    buttonGrid->setMargin(6);
    buttonGrid->setColStretch(0, 1);
    buttonGrid->addWidget(_update, 0, 1);
    buttonGrid->addWidget(_close, 0, 2);

    QGridLayout* grid = new QGridLayout(frame);
    grid->setSpacing(3);
    grid->setMargin(3);
    grid->setColStretch(2, 1);
    grid->addColSpacing(2, 20);
    grid->addWidget(fromLabel, 0, 0);
    grid->addWidget(_fromVersion, 0, 1, AlignLeft | AlignVCenter);
    grid->addWidget(toLabel, 0, 3);
    grid->addWidget(_toVersion, 0, 4, AlignLeft | AlignVCenter);
    grid->addMultiCellWidget(buttons, 1, 1, 0, 4);

    ServerConfig config;
    config.load();

    _fromVersion->setText(company.version());

    QDir dir(parseDir(config.dataDir), "*.xml");
    dir.cd("models");
    QStringList entries = dir.entryList();
    for (unsigned int i = 0; i < entries.size(); ++i) {
	QString version = QFileInfo(entries[i]).baseName();
	if (version < company.version()) continue;
	_toVersion->insertItem(version);
    }
    _toVersion->setCurrentItem(company.version());

    _company = company;

    setCentralWidget(frame);
    setCaption(tr("Version Update: %1").arg(company.name()));
}
Beispiel #5
0
bool
FirebirdDriver::create(CompanyDefn& company)
{
    if (!initialize())
	return error("Driver failed to initialize");

    FirebirdConfig config;
    if (!config.load())
	return error("Can't read firebird.cfg file");

    // Decide on database filepath
    QString name = company.name();
    name.replace(QRegExp(" "), "_");
    QString database = parseDir(config.databaseDir) + "/" + name +
	".fdb";

    // Determine existence of db to be created
    if (QFileInfo(database).exists())
        return error("A database of the same name already exists");

    // Database connection string
    QString dbName = config.hostname;
    if (config.port != 3050)
	dbName += "/" + QString::number(config.port);
    if (!dbName.isEmpty())
	dbName += ":";
    dbName += database;

    // Create database command
    QString cmd = "create database '" + dbName + "' user 'sysdba' password '" +
	config.dbaPassword + "' page_size " + QString::number(config.blockSize)
	+ " default character set " + config.charSet;

    ISC_STATUS status[20];
    isc_db_handle db = 0L;
    isc_tr_handle trans = 0L;
    char* command = strdup(cmd.latin1());
    _procs->isc_dsql_execute_immediate(status, &db, &trans, 0, command,
				       SQL_DIALECT_V6, NULL);
    free(command);
    if (status[0] == 1 && status[1]) {
	qWarning("Error in: %s", command);
	_procs->isc_print_status(status);
	return error("Failed creating database");
    }

    _procs->isc_detach_database(status, &db);

    company.setDatabase(database);
    company.setDBType("Firebird");
    return true;
}
Beispiel #6
0
ModelEdit::ModelEdit(ModelMainWindow* main, const QString& version)
    : QMainWindow(NULL, "ModelEdit", WDestructiveClose), _main(main)
{
    createWidgets();

    ServerConfig config;
    config.load();
    QString dataDir = parseDir(config.dataDir);
    _orig.load(dataDir + "/models/" + version + ".xml");

    _curr = _orig;
    setWidgets();
}
Beispiel #7
0
int runChangeDir(char *consoleinput)
{
	int result =0;
	if(strlen(consoleinput)<=3)
	{
		printf("cd error: no path specified.");
	}
	else
	{
		char *pathname = parseDir(consoleinput);
		result = chdir(pathname);
	}
	return (result==0)?0:errno;
}
Beispiel #8
0
void
ImportScreen::slotOpenFile()
{
    QString start = _filePath->text();
    QString filter = "Import Files (*.xml)";

    if (start.isEmpty()) {
	ServerConfig config;
	config.load();
	start = parseDir(config.importDir);
    }

    QString file = QFileDialog::getOpenFileName(start, filter, this);
    if (file.isEmpty()) return;

    _filePath->setText(file);
}
Beispiel #9
0
/* Get a transliterator */
ERL_NIF_TERM get_transliterator(ErlNifEnv* env, int argc, 
    const ERL_NIF_TERM argv[])
{
    ERL_NIF_TERM out;
    char id[LOCALE_LEN], dir[ATOM_LEN];
    UErrorCode status = U_ZERO_ERROR;
    UTransliterator* obj;
    cloner* res;
    int parsed_dir;


    if (argc != 2)
        return enif_make_badarg(env);

    if (!(enif_get_atom(env, argv[0], (char*) id, LOCALE_LEN, ERL_NIF_LATIN1)
       && enif_get_atom(env, argv[1], (char*) dir, ATOM_LEN, ERL_NIF_LATIN1)
        )) {
        return enif_make_badarg(env);
    }

    parsed_dir = parseDir(dir);
    if ((parsed_dir == -1)) 
        return enif_make_badarg(env);

    obj = utrans_open((char *) id, (UTransDirection) parsed_dir, 
            NULL, 0, NULL, &status);
    CHECK(env, status);



    res = (cloner*) enif_alloc_resource(trans_type, sizeof(cloner));

    if (trans_open(obj, res)) {
        enif_release_resource(res);
        return enif_make_badarg(env);
    }

    out = enif_make_resource(env, res);
    enif_release_resource(res);
    /* resource now only owned by "Erlang" */
    return out;
}
Beispiel #10
0
void NDirWatcherThread::parseSharedDirs()
{
    //logDebug("NDirWatcherThread", "parseSharedDirs start");

    for(int i = 0; i < m_sharedDirectories.count(); i++)
    {
        const NDir & dir = m_sharedDirectories[i];
        if (isStopping())
            break;

        if (!dir.shared())
            continue;

        if (!dir.dir().exists())
            continue;

        parseDir(dir.dir().absolutePath(), dir.recursive(), dir.dir().absolutePath());
    }
    //logDebug("NDirWatcherThread", "parseSharedDirs stop");
}
Beispiel #11
0
bool
ModelEdit::slotOk()
{
    getWidgets();

    if (_curr != _orig) {
	ServerConfig config;
	config.load();
	QString dataDir = parseDir(config.dataDir);
	_curr.save(dataDir + "/models/" + _curr.version + ".xml");

	if (_curr.version != _orig.version)
	    QFile::remove(dataDir + "/models/" + _orig.version + ".xml");

	// TODO: inform model_main_window of changes
    }

    _orig = _curr;
    close();
    return true;
}
Beispiel #12
0
  int
main(int argc, char **argv) {
    
    if (argc < 1) {
        printf("usage: %s <item> [<item> ...]\n", argv[0]);
        printf("An <item> can be a file path, a directory path, or a pid.\n");
        return 1;
    }
    
    int itemCount = argc - 1;
    
    struct kevent events[itemCount];
    t_watchInfo watchInfos[itemCount];
    int timeoutTime = -1;
    itemCount = 0;
    for (int i = 1; i < argc; i++) {
        char *item = argv[i];

        if (strcmp(item, "-t") == 0) {
            timeoutTime = atoi(argv[++i]);
        } else if (isdigit(item[0])) {
            int pid = atoi(item);
            EV_SET(&events[itemCount], pid, EVFILT_PROC,
                   EV_ADD | EV_ENABLE | EV_CLEAR, NOTE_EXIT, 0, NULL);
            ++itemCount;
            
        } else {
            struct stat sb;
            if (stat(item, &sb) == -1) {
                die("stat");
            }
            if (S_ISDIR(sb.st_mode)) {
                watchInfos[itemCount].dir = parseDir(item);
            } else {
                watchInfos[itemCount].dir = NULL;
            }
            watchInfos[itemCount].path = item;
            
            int fd = open(item, O_RDONLY);
            if (fd == -1) {
                die("open");
                exit(-1);
            }
            EV_SET(&events[itemCount], fd, EVFILT_VNODE,
                   EV_ADD | EV_ENABLE | EV_CLEAR, NOTE_RENAME | NOTE_WRITE, 0,
                   &watchInfos[itemCount]);
            ++itemCount;
        }
    }
    
    struct timespec timeout;
    memset(&timeout, 0, sizeof(struct timespec));
    timeout.tv_sec = timeoutTime;
    int result = kevent(kqueue(), events, itemCount, events, itemCount,
                        timeoutTime >= 0 ? &timeout : NULL);
    if (result > 0) {
        for (int i = 0; i < result; ++i) {
            t_watchInfo *hit = events[i].udata;
            if (hit == NULL) {
                fprintf(stdout, "proc %d\n", (int) events[i].ident);
            } else if (hit->dir != NULL) {
                t_dirContents *dirNow = parseDir(hit->path);
                t_dirContents *dirDiffs = diffs(hit->dir, dirNow);
                if (dirDiffs->count > 0) {
                    fprintf(stdout, "%s %s%s%s\n",
                            ((hit->dir != NULL && dirNow != NULL &&
                                 hit->dir->count > dirNow->count) ||
                             (hit->dir != NULL && dirNow == NULL)) ? "-" : "+",
                            hit->path,
                            (hit->path[strlen(hit->path)-1] == '/') ? "" : "/",
                            dirDiffs->entries[0]);
                }
            } else {
                fprintf(stdout, "%s\n", hit->path);
            }
        }
        return 0;
    } else if (result == 0) {
        fprintf(stdout, "timeout\n");
    } else {
        fprintf(stderr, "result: %d\n", result);
        die("kevent");
    }
    return 1;
}
Beispiel #13
0
int main(int argc, char** argv){

  if(2 > argc){
    printf("usage: %s <file> [ <file>]+\n", argv[0]);
    return 1;
  }

  int filesCount = argc - 1;

  struct kevent ev[filesCount];

  struct stat sb;

  namedDirInfo ndi[filesCount];

  dirInfo *diBefore, *diAfter, *diDifference;

  for(int i = 0; i < filesCount; i++){
    char *filePath = argv[i+1];
    void *data;

    int fd = -1;

    if( stat( filePath, &sb) == -1 ){
      perror("stat");
      exit(EXIT_FAILURE);
    }
    if( S_ISDIR( sb.st_mode) ){
      diBefore = parseDir( filePath );
      ndi[i].path = filePath;
      ndi[i].di = diBefore;
      data = &ndi[i];
    }
    else
      data = filePath;

    if( -1 == fd ){
      fd = open(filePath, O_RDONLY);
      if( -1 == fd) {
        perror("open");
        return -1;
      }
    }

    EV_SET(&ev[i], fd, EVFILT_VNODE,
        EV_ADD | EV_ENABLE | EV_CLEAR,
        TARGET_EVTS, 0, data);
  }

  int kq = kqueue();

  int result =
    kevent(kq, ev, filesCount, ev, 1, NULL);

  if( result > 0 ){
    debug(result, ev);
    if( S_ISDIR( sb.st_mode ) ){
      namedDirInfo *ndip;
      ndip = ev[0].udata;
      if( ev[0].fflags & NOTE_DELETE )
        fprintf(stdout, "- %s\n", ndip->path);
      else {
        diAfter = parseDir( (char*) ndip->path);
        diDifference = symmetricDifference(ndip->di, diAfter);
        if( DEBUG ) {
          printDirInfo( ndip->di );
          printDirInfo( diAfter );
          printDirInfo( diDifference );
        }
        else if( NULL != diDifference && diDifference->count > 0 )
          fprintf(stdout, "%s %s%s%s\n",
              (
               // dir was non empty before and is non empty after
               (NULL != ndip->di && NULL != diAfter &&
                  // some thing has gone, iff #entries decreased
                  (ndip->di->count > diAfter->count))
               ||
               // dir was non empty before and is empty after
               // -> something is gone
               (NULL != ndip->di && NULL == diAfter)
              ) ? "-" : "+",
              ndip->path,
              // if path does not end with '/' insert one
              ('/' == ndip->path[strlen(ndip->path)-1]) ? "" : "/",
              diDifference->entries[0]);
        else
          fprintf(stdout, "%s\n", ndip->path);
      }
    }
    else
      fprintf(stdout, "%s\n", (char*) ev[0].udata);
    return 0;
  }
  else{
    fprintf(stderr, "result: %d\n", result);
    perror("kevent");
  }
  return 1;
}
Beispiel #14
0
/**
 * @brief Arguments handling : All the parameters of the program are handled here (expect from the special arguments which are handled before)
 *
 * @param desc the Description we are about to change to handle the special args
 * @param argc the number of arguments passed to the program
 * @param argv the strings table of arguments passed to the program
 */
static inline void Option_handleArguments (SDescription *desc, int argc, char *argv[])
{
	char *configFileName = Description_getConfigFile (desc);
	long val;
	int opt;
	FILE *f;
	unsigned m_nb_args;
	char **m_argv;
	
	// First, we have to parse the XML config file
	if (configFileName != NULL)
	{
		if (Config_parseXML (desc, configFileName) == -1)
		{
			Log_output (-1, "Error: An error occured while parsing the XML config file.\n");
			exit (EXIT_FAILURE);
		}
	}
	
	// Then, we can now handle other arguments in the command line
	optind = 1;

	/* Then, the final values have to be those of the command line */
	while ((opt = getopt_long (argc, argv, "", option_list, NULL)) != -1) {
		switch (opt) {
		case 'a': // --summary
			Description_enableSummary(desc);
			break;
		case 'A': // --alloclib
			Description_setDynAllocLib(desc, optarg);
			break;
		 case 'b': // --basename
			Description_setBaseName (desc, optarg);
			break;
		 case 'B': // --verifylib
			Description_setVerificationLibraryName (desc, optarg);
			break;
		case 'c': // --cpupin
            parseCPUPinning (desc, optarg);
			break;
		case 'd': // --sizedummy
			val = Option_transformArgument (optarg);
			Description_setDummySize (desc, val);
			break;
		case 'D': // --output-dir
			Description_setOutputPath (desc, optarg);
			break;
		case 'e': // --endvector
			val = Option_transformArgument (optarg);
			Description_setEndVectorSize (desc, val); 
			break;
		case 'f': // --kernelfunction
			Description_setDynamicFunctionName (desc, optarg);
			break;
		case 'F': // --no-eval-stack
			Description_disableEvalStack (desc);
			break;
		case 'g': // --output-same-dir
			Description_setOutputPath (desc, ".");
			break;
        case 'G':
            Description_setExecPath (desc, optarg);
            break;
		case 'i': // --stepvector
			val = Option_transformArgument (optarg);
			Description_setVectorSizeStep (desc, val);
			break;
		case 'I': // --info
			Description_parseInfoDisplayedInput (desc, optarg);
			break;
		case 'k': // --kernelname
			if (isFile (optarg))
			{
				Description_setKernelFileNamesTabSize (desc, 1);
				Description_setKernelFileNameAt (desc, optarg, 0);
			}
			else if (isDirectory (optarg))
			{
				parseDir (optarg, desc);
			}
			else
			{
				Log_output (-1, "Error: Cannot resolve kernel name filetype.\n");
				exit (EXIT_FAILURE);
			}
			Description_setKernelFileName (desc, optarg);
			break;
		case 'l': // --logverbosity
			val = Option_transformArgument (optarg);
			Log_setVerbosity (val);
			break;
		case 'm': // --metarepetition
			val = Option_transformArgument (optarg);
			Description_setMetaRepetition (desc, val);
			break;
		case 'M': // --vectorspacing
			val = Option_transformArgument (optarg);
			Description_setVectorSpacing (desc, val);
			break;
		case 'N': // --no-output
			Description_setPromptOutputCsv (desc, 0);
			break;
		case 'o': // --log-output
			f = fopen (optarg, "w");
			Log_setOutput (f);
			break;
		case 'O': // --nbprocess
			val = Option_transformArgument (optarg);

            if (Description_getNbProcess (desc) > 0 && Description_getNbProcess (desc) != val)
            {
                Log_output (-1, "Error: Number of processes already defined and not the same value\n");
                exit (EXIT_FAILURE);
            }
            else
            {
                if (Description_getNbProcess (desc) < 0)
                {
        			Description_setNbProcess (desc, val);
                }
            }
			break;
		case 'p': // --pagecollide
			val = Option_transformArgument (optarg);
				Description_setNbPagesForCollision (desc, val);
			break;
		case 'P': // --pagesize
			val = Option_transformArgument (optarg);
			Description_setPageSize (desc, val);
			break;
		case 'q': // --vectsurveyor
			parse_vect_surveyor (desc,optarg);
			break;	
		case 'Q': // --executerepetition
			val = Option_transformArgument (optarg);
			Description_setExecuteRepets (desc, val);
			break;
		case 'r': // --repetition
			val = Option_transformArgument (optarg);
			Description_setRepetition (desc, val);
			break;
		case 's': // --startvector
			val = Option_transformArgument (optarg);
			Description_setStartVectorSize (desc, val);
			break;
		case 'S': // --maxstride
			val = Option_transformArgument (optarg);
			Description_setMaxStride (desc, val);
			break;
		case 't': // --omppath
			Description_setOmpPath (desc, optarg);
			break;
		case 'T': // --execname
			Description_setExecFileName (desc, optarg);
			break;
		case 'u': // --execargs
			m_argv = getArgs (desc, optarg, &m_nb_args);
			Description_setExecArgc (desc, m_nb_args);
			Description_setExecArgv (desc, m_argv);
			break;
		case 'U': // --suppress-output
			Description_setSuppressOutput (desc, 1);
			break;
		case 'v': // --iteration-count
			val = Option_transformArgument (optarg);
			Description_setIterationCount (desc, val);
			Description_iterationCountEnable (desc);
			break;
		case 'V': // --execoutput
			Description_setOutputFileStream (desc, optarg);
			break;
		case 'w': // --initfunction
			Description_setKernelInitFunctionName (desc, optarg);
			break;
		case 'W': // --data-size
			/* If user specifies "float", let's allocate sizeof(float) */
			if (strncmp ("float", optarg, STRBUF_MAXLEN) == 0)
			{
				Description_setVectorElementSize (desc, sizeof (float));
			}
			/* If he specifies "double", let's allocate sizeof(double) */
			else if (strncmp ("double", optarg, STRBUF_MAXLEN) == 0)
			{
				Description_setVectorElementSize (desc, sizeof (double));
			}
			/* Else, he must have specified a numeric constant */
			else
			{
				val = Option_transformArgument (optarg);
				Description_setVectorElementSize (desc, val);
			}
			break;
		case 'x': // --nbsizes
			Description_nbSizesEnable (desc);
			parseVectorSizes (desc, optarg);
			break;
		case 'X': // --no-thread-pin
			Description_pinThreadDisable (desc);
			break;
		case 'y': // --all-print-out
			Description_setAllPrintOut (desc, 1);
			break;
		case 'Y': // --all-metric-output
			Description_allProcessOutputEnable (desc);
			break;
		case 'z': // --resumeid
			val = Option_transformArgument (optarg);
			Description_setResumeId (desc, val);
			break;
		default:
			assert (argv != NULL && argv[0] != 0);
			break;
		}
	}
}
Beispiel #15
0
void
UpdateScreen::slotUpdate()
{
    QString from = _fromVersion->text();
    QString to = _toVersion->currentText();

    if (from == to) {
	qApp->beep();
	QString message = tr("Versions must be different");
	QMessageBox::critical(this, tr("Error"), message);
	return;
    }

    // Connect to company database
    Driver* driver = Driver::getDriver(_company.dbType());
    if (driver == NULL) {
	qApp->beep();
	QString message = tr("Get driver failed: %1").arg(driver->lastError());
	QMessageBox::critical(this, tr("Error"), message);
	return;
    }

    _connection = driver->allocConnection();
    if (!_connection->dbaConnect(_company.database())) {
	qApp->beep();
	QString message = tr("Open company failed: %1")
	    .arg(_connection->lastError());
	QMessageBox::critical(this, tr("Error"), message);
	return;
    }

    ServerConfig config;
    config.load();

    QString dataDir = parseDir(config.dataDir);
    QString version = to;

    QValueVector<DataModel> models;
    while (true) {
	QString filePath = dataDir + "/models/" + version + ".xml";
	DataModel model;
	if (!model.load(filePath)) {
	    qApp->beep();
	    QString message = tr("Failed loading model: %1").arg(filePath);
	    QMessageBox::critical(this, tr("Error"), message);
	    return;
	}

	if (model.fromVersion.isEmpty()) {
	    qApp->beep();
	    QString message = tr("Didn't find version: " + from);
	    QMessageBox::critical(this, tr("Error"), message);
	    return;
	}

	models.push_back(model);
	version = model.fromVersion;
	if (version == from) break;
    }

    if (models.size() == 0) {
	qApp->beep();
	QString message = tr("No models found for update use");
	QMessageBox::critical(this, tr("Error"), message);
	return;
    }

    QString dbType = _company.dbType();
    for (int i = models.size() - 1; i >= 0; --i) {
	DataModel& model = models[i];
	bool good = true;

	QValueVector<UpdateDefn> completed;
	for (unsigned int j = 0; j < model.updates.size(); ++j) {
	    UpdateDefn& update = model.updates[j];

	    // Only run update if its for All or the right type
	    if (!update.databases.contains("All"))
		if (!update.databases.contains(dbType))
		    continue;

	    // Run update commands catching errors
	    for (unsigned int k = 0; k < update.updateCmds.size(); ++k) {
		QString cmd = update.updateCmds[k];
		Stmt stmt(_connection, cmd);
		if (!stmt.execute()) {
		    qWarning(stmt.lastError());
		    good = false;
		    break;
		}
	    }

	    completed.push_back(update);
	}

	// If good then try to run cleanup commands
	if (good) {
	    for (unsigned int j = 0; j < completed.size(); ++j) {
		UpdateDefn& update = completed[j];

		for (unsigned int k = 0; k < update.cleanupCmds.size(); ++k) {
		    QString cmd = update.cleanupCmds[k];
		    Stmt stmt(_connection, cmd);
		    if (!stmt.execute()) {
			qWarning(stmt.lastError());
			good = false;
			break;
		    }
		}
	    }
	}

	// If still good then update version in database
	if (good) {
	    QString cmd = "update db_config set config_value='" +
		model.version + "' where config_key='version'";
	    Stmt stmt(_connection, cmd);
	    if (!stmt.execute()) {
		qWarning(stmt.lastError());
		good = false;
	    }
	    _connection->commit();
	}

	// If failed then run restore commands and inform user
	if (!good) {
	    for (unsigned int j = 0; j < completed.size(); ++j) {
		UpdateDefn& update = completed[j];

		for (unsigned int k = 0; k < update.restoreCmds.size(); ++k) {
		    QString cmd = update.restoreCmds[k];
		    Stmt stmt(_connection, cmd);
		    if (!stmt.execute()) {
			qWarning(stmt.lastError());
		    }
		}
	    }

	    qApp->beep();
	    QString message = tr("Update failed on version: " + model.version);
	    QMessageBox::critical(this, tr("Error"), message);
	    close();
	    return;
	}

	// Set new version in CompanyDefn
	CompanyDefn company = _company;
	company.setVersion(model.version);
	company.save(company.filePath(), true);
	_company = company;
    }

    QMessageBox::information(this, tr("Finished"), tr("Update successful"));
    close();
}