コード例 #1
0
ファイル: wb_dbms.cpp プロジェクト: jordibrus/proview
MYSQL *wb_dbms_env::createDb(void)
{
    m_con = mysql_init(NULL);

    MYSQL *con = mysql_real_connect(m_con, host(), user(), passwd(), 0, port(), socket(), 0);
    // printf("Tried to connect to database, con %x: Status: %s\n", (int)con, mysql_error(m_con));
    if (con == 0) {
        printf("Failed to connect to database: Error: %s\n", mysql_error(m_con));
        return 0;
    }

    char sql[255];

    sprintf(sql, "create database %s", dbName());
    int rc = mysql_query(m_con, sql);
    if (rc) {
        printf("%s\n", mysql_error(m_con));
        printf("%s\n", sql);
        return 0;
    }

    sprintf(sql, "use %s", dbName());
    rc = mysql_query(m_con, sql);
    if (rc) {
        printf("%s\n", mysql_error(m_con));
        printf("%s\n", sql);
        return 0;
    }

    return con;
}
コード例 #2
0
ファイル: wb_dbms.cpp プロジェクト: jordibrus/proview
int wb_dbms_env::open(const char *v_host, const char *v_user, const char *v_passwd,
                      const char *v_dbName, unsigned int v_port, const char *v_socket)
{

    host(v_host);
    user(v_user);
    passwd(v_passwd);
    dbName(v_dbName);
    port(v_port);
    socket(v_socket);

    m_con = mysql_init(NULL);

    MYSQL *con = mysql_real_connect(m_con, host(), user(), passwd(), dbName(), port(), socket(), 0);
    if (con == 0) {
        printf("Failed to connect to database: Error: %s\n", mysql_error(m_con));
        return 1;
    }

    char sql[255];

    sprintf(sql, "use %s", dbName());
    int rc = mysql_query(m_con, sql);
    if (rc) {
        printf("%s\n", mysql_error(m_con));
        printf("%s\n", sql);
        return rc;
    } else {
        printf("database open %s\n", sql);
    }

    return 0;
}
コード例 #3
0
ファイル: repo.cpp プロジェクト: CSRedRat/hiphop-php
void Repo::attachLocal(const char* path, bool isWritable) {
  std::string repoPath = insertSchema(path);
  if (!isWritable) {
    // Make sure the repo exists before attaching it, in order to avoid
    // creating a read-only repo.
    struct stat buf;
    if (!strchr(repoPath.c_str(), ':') &&
        stat(repoPath.c_str(), &buf) != 0) {
      return;
    }
  }
  try {
    std::stringstream ssAttach;
    ssAttach << "ATTACH DATABASE '" << repoPath << "' as "
             << dbName(RepoIdLocal) << ";";
    exec(ssAttach.str());
    pragmas(RepoIdLocal);
  } catch (RepoExc& re) {
    return;
  }
  if (initSchema(RepoIdLocal, isWritable)) {
    return;
  }
  m_localRepo = repoPath;
  m_localReadable = true;
  m_localWritable = isWritable;
  TRACE(1, "Local repo: '%s' (read%s)\n",
           m_localRepo.c_str(), m_localWritable ? "-write" : "-only");
}
コード例 #4
0
ファイル: repo.cpp プロジェクト: CSRedRat/hiphop-php
void Repo::setTextPragma(int repoId, const char* name, const char* val) {
  // Pragma writes must be executed outside transactions, since they may change
  // transaction behavior.
  std::stringstream ssPragma;
  ssPragma << "PRAGMA " << dbName(repoId) << "." << name << " = " << val << ";";
  exec(ssPragma.str());
  if (debug) {
    // Verify that the pragma had the desired effect.
    std::string newval = "?";
    getTextPragma(repoId, name, newval);
    if (strcmp(newval.c_str(), val)) {
      throw RepoExc("Unexpected PRAGMA %s.%s value: %s\n",
                    dbName(repoId), name, newval.c_str());
    }
  }
}
コード例 #5
0
void KeychainDbCommon::sleepProcessing()
{
	secdebug("KCdb", "common %s(%p) sleep-lock processing", dbName(), this);
	StLock<Mutex> _(*this);
	if (mParams.lockOnSleep)
		lockDb();
}
コード例 #6
0
ファイル: mainwindow.cpp プロジェクト: Sun-rt/GitRepository
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    BasicInfoDialog *infoDialog = new BasicInfoDialog(this);
    infoDialog->exec();
    QString localhost = infoDialog->getLocalHost();
    QString username = infoDialog->getUserName();
    QString password = infoDialog->getPassWord();
    
    
    DBOperationSingleton *operSingle = DBOperationSingleton::getInstance();

    QStringList *dbNameList = operSingle->getDBName(localhost, username, password);
    
    if(dbNameList->size() == 0)
    {
        return;
    }
    DataBaseInfoDialog *baseInfoDia = new DataBaseInfoDialog(localhost, username, password, this);
    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addWidget(baseInfoDia);
    this->centralWidget()->setLayout(mainLayout);

    QString dbName("new_schema");
    bool bVar = operSingle->openDB(dbName);
    qDebug()<<bVar;
}
コード例 #7
0
ファイル: bfcompany.cpp プロジェクト: i02sopop/Bulmages
/**
\param splash
\return
**/
void BfCompany::createMainWindows ( BlSplashScreen *splash )
{
    BL_FUNC_DEBUG

    /// Comprobamos que tengamos permisos para trabajar con 'Paises'.
    m_bulmafact->actionPaises->setEnabled ( false );
    if ( hasTablePrivilege ( "pais", "SELECT" ) ) {
        m_bulmafact->actionPaises->setEnabled ( true );
    } // end if


    /// Disparamos los plugins.
    int res = g_plugins->run ( "BfCompany_createMainWindows_Post", this );
    if ( res != 0 ) {
        return;
    } // end if

    cargaConf();

    /// pb = 100%
    m_progressbar->setValue ( 100 );

    /// Ponemos el titulo de la ventana
    m_bulmafact->statusBar() ->showMessage ( dbName(), 2000 );
    m_bulmafact->setWindowTitle ( g_confpr->value( CONF_MAIN_WINDOW_TITLE ).isEmpty() ? _( "Facturacion GPL" ) : g_confpr->value( CONF_MAIN_WINDOW_TITLE ) + " :: " + currentUser() + "@" + dbName() );

    
}
コード例 #8
0
/**
Second phase constructor.

@param aServerType 	ETransientServer if the Server is transient,
ENonTransientServer if the Server is not transient.
*/
void CCntDbManagerController::ConstructL(TCntServerType aServerType)
	{
	User::LeaveIfError(iFs.Connect());
	iBackupRestoreAgent = CCntBackupRestoreAgent::NewL(iFs, *this);
	iIniFileManager = CIniFileManager::NewL(iFs, *this);
	
	// Controller requires one Persistence Layer instance.
	iPersistenceLayer = CPersistenceLayer::NewLC(iFs);
	CleanupStack::Pop(iPersistenceLayer);

	// Create a backup registration file for the Contacts Model initialisation
	// file.
	TFileName iniFile;
	iIniFileManager->GetIniFileNameL(iniFile, EFalse);
	iBackupRestoreAgent->CreateBackupRegistrationFileL(iniFile);
	
	// Only now safe to start the Backup/Restore Agent since it relies on the
	// iIniFileManager object being fully constructed in the case where, within
	// the StartL() method, the value of the Backup/Restore property indicates
	// either a Backup or Restore is in progress.
	iBackupRestoreAgent->StartL();
	
	// Start the pre-creation of the default application data:
	// Open the default file and create the default remote
	// view(s) so they are ready for use by client applications.
	if (aServerType == ENonTransientServer)
		{
		iPermanentData = CCntPermanentData::NewL(*this);
		// If the permanent data creation step leaves, it should not
		// cause the server to panic. Instead, TRAP it and ignore
		// it - it is not fatal to normal server operation anyway.
		TRAP_IGNORE(iPermanentData->StartDataCreationL());
		}

	// Retrieve the list of contact databases on the C: drive.
	MLplContactsFile& contactsFile = iPersistenceLayer->ContactsFileL();
	TDriveUnit cDrive(EDriveC);
	CDesCArray* list(contactsFile.ListL(&cDrive)); 
	CleanupStack::PushL(list);
	
	// Check that each database has a back up registration XML file.
	// If not, create one.  
	const TInt KListLen(list->Count());
	for (TInt i = 0; i < KListLen; ++i)
		{
		TFileName dbName((*list)[i]);
		HBufC* backupFileNameBuf = iBackupRestoreAgent->
			CreateBackupRegistrationFileNameLC(dbName.Mid(cDrive.Name().Length()));
		TFileName backupFileName;
		backupFileName.Append(cDrive.Name());
		backupFileName.Append(*backupFileNameBuf);
		CleanupStack::PopAndDestroy(backupFileNameBuf);
		if (!BaflUtils::FileExists(iFs, backupFileName))
			{
			TRAP_IGNORE(iBackupRestoreAgent->CreateBackupRegistrationFileL(dbName));
			}
		}
	CleanupStack::PopAndDestroy(list);		
	}
コード例 #9
0
ファイル: Database.cpp プロジェクト: adam-zhang/tiger
void Database::initialize()
{
	QString dbName("mails.sqlite");
	QFile file(dbName);
	if (file.exists())
		return;
	else
		createDBFile(dbName);
}
コード例 #10
0
//
// Encode the current database as a blob.
// Note that this returns memory we own and keep.
// Caller must hold common lock.
//
void KeychainDatabase::encode()
{
	DbBlob *blob = common().encode(*this);
	Allocator::standard().free(mBlob);
	mBlob = blob;
	version = common().version;
	secdebug("KCdb", "encoded database %p common %p(%s) version %u params=(%u,%u)",
		this, &common(), dbName(), version,
		common().mParams.idleTimeout, common().mParams.lockOnSleep);
}
コード例 #11
0
//
// Modify database parameters
//
void KeychainDatabase::setParameters(const DBParameters &params)
{
	StLock<Mutex> _(common());
    makeUnlocked();
	common().mParams = params;
    common().invalidateBlob();		// invalidate old blobs
    activity();				// (also resets the timeout timer)
	secdebug("KCdb", "%p common %p(%s) set params=(%u,%u)",
		this, &common(), dbName(), params.idleTimeout, params.lockOnSleep);
}
コード例 #12
0
ファイル: repo.cpp プロジェクト: CSRedRat/hiphop-php
void Repo::getIntPragma(int repoId, const char* name, int& val) {
  RepoTxn txn(*this);
  std::stringstream ssPragma;
  ssPragma << "PRAGMA " << dbName(repoId) << "." << name << ";";
  RepoStmt stmt(*this);
  stmt.prepare(ssPragma.str());
  RepoTxnQuery query(txn, stmt);
  query.step();
  query.getInt(0, val);
  txn.commit();
}
コード例 #13
0
ファイル: wb_dbms.cpp プロジェクト: jordibrus/proview
wb_dbms_env::wb_dbms_env(const char *v_host, const char *v_user, const char *v_passwd,
                         const char *v_dbName, unsigned int v_port, const char *v_socket) :
    m_con(0), m_fileName(0), m_host(0), m_user(0), m_passwd(0), m_dbName(0), m_port(0), m_socket(0), m_exists(false)
{
    host(v_host);
    user(v_user);
    passwd(v_passwd);
    dbName(v_dbName);
    port(v_port);
    socket(v_socket);
}
コード例 #14
0
ファイル: wb_dbms.cpp プロジェクト: jordibrus/proview
MYSQL *wb_dbms_env::openDb()
{
    m_con = mysql_init(NULL);

    MYSQL *con = mysql_real_connect(m_con, host(), user(), passwd(), dbName(), port(), socket(), 0);
    // printf("Tried to connect to database, con %x: Status: %s\n", (int)con, mysql_error(m_con));
    if (con == 0) {
        printf("Failed to connect to database: Error: %s\n", mysql_error(m_con));
        return 0;
    }

    return con;
}
コード例 #15
0
ファイル: wb_dbms.cpp プロジェクト: jordibrus/proview
int wb_dbms_env::create(const char *v_fileName, const char *v_host, const char *v_user,
                        const char *v_passwd, const char *v_dbName, unsigned int v_port,
                        const char *v_socket)
{
    fileName(v_fileName);
    host(v_host);
    user(v_user);
    passwd(v_passwd);
    dbName(v_dbName);
    port(v_port);
    socket(v_socket);

    create();

    return 0;
}
コード例 #16
0
ファイル: bfcompany.cpp プロジェクト: i02sopop/Bulmages
void BfCompany::guardaConf()
{
    BL_FUNC_DEBUG
    QFile file ( g_confpr->value( CONF_DIR_USER ) + "bulmafact_" + dbName() + ".cfn" );
    /// Guardado del orden y de configuraciones varias.
    if ( file.open ( QIODevice::WriteOnly ) ) {

	 /// Saber si una ventana est&aacuta; maximizada
	 bool isMaximized = false;
	 if ( m_bulmafact->windowState() == Qt::WindowMaximized
	   || m_bulmafact->windowState() == Qt::WindowFullScreen )
	     isMaximized = true;

        QTextStream stream ( &file );
        stream << "<CONFIG>\n";
        stream << "\t<PRINCIPAL>\n";
        stream << "\t\t\t<X>" + QString::number ( m_bulmafact->geometry().x() ) + "</X>\n";
	  stream << "\t\t\t<Y>" + QString::number ( m_bulmafact->geometry().y() ) + "</Y>\n";
        stream << "\t\t\t<WIDTH>" + QString::number ( m_bulmafact->width() ) + "</WIDTH>\n";
        stream << "\t\t\t<HEIGHT>" + QString::number ( m_bulmafact->height() ) + "</HEIGHT>\n";
	  stream << "\t\t\t<INDEXADOR>" + ( QString ( m_bulmafact->actionIndexador->isChecked() ? "true" : "false" ) ) + "</INDEXADOR>\n";
        stream << "\t\t\t<TOOLBARSDOCKWIDGETS>" + QString ( m_bulmafact->saveState().toBase64() ) + "</TOOLBARSDOCKWIDGETS>\n";
	  stream << "\t\t\t<MAXIMIZED>" + QString ( isMaximized ? "true" : "false" ) + "</MAXIMIZED>\n";
        stream << "\t</PRINCIPAL>\n";

        for ( int i = 0; i < m_windowListDock->numVentanas(); i++ ) {
            QObject *obj = m_windowListDock->ventana ( i );
            QWidget *wid = ( QWidget * ) obj;
            stream << "\t<VENTANA>\n";
            stream << "\t\t<VNAME>" + obj->objectName() + "</VNAME>\n";
            stream << "\t\t<VX>" + QString::number ( wid->parentWidget() ->x() ) + "</VX>\n";
            stream << "\t\t<VY>" + QString::number ( wid->parentWidget() ->y() ) + "</VY>\n";
            stream << "\t\t<VWIDTH>" + QString::number ( wid->width() ) + "</VWIDTH>\n";
            stream << "\t\t<VHEIGHT>" + QString::number ( wid->height() ) + "</VHEIGHT>\n";
            stream << "\t\t<VVISIBLE>" + ( wid->isVisible() ? QString ( "true" ) : QString ( "false" ) ) + "</VVISIBLE>\n";
            stream << "\t\t<VMAXIMIZED>" + ( wid->isMaximized() ? QString ( "true" ) : QString ( "false" ) ) + "</VMAXIMIZED>\n";
            stream << "\t\t<VACTIVEWINDOW>" + ( m_bulmafact->workspace() ->activeWindow() == wid ? QString ( "true" ) : QString ( "false" ) ) + "</VACTIVEWINDOW>\n";
            stream << "\t</VENTANA>\n";
        } // end for

        stream << "</CONFIG>\n";
        file.close();
    } // end if
    
}
コード例 #17
0
ファイル: repo.cpp プロジェクト: SecureCloud-biz/hhvm
std::string Repo::table(int repoId, const char* tablePrefix) {
  std::stringstream ss;
  ss << dbName(repoId) << "." << tablePrefix << "_" << repoSchemaId();
  return ss.str();
}
コード例 #18
0
NS_IMETHODIMP nsMsgBrkMBoxStore::CopyFolder(nsIMsgFolder *aSrcFolder,
                                            nsIMsgFolder *aDstFolder,
                                            bool aIsMoveFolder,
                                            nsIMsgWindow *aMsgWindow,
                                            nsIMsgCopyServiceListener *aListener,
                                            const nsAString &aNewName)
{
  NS_ENSURE_ARG_POINTER(aSrcFolder);
  NS_ENSURE_ARG_POINTER(aDstFolder);

  nsAutoString folderName;
  if (aNewName.IsEmpty())
    aSrcFolder->GetName(folderName);
  else
    folderName.Assign(aNewName);

  nsAutoString safeFolderName(folderName);
  NS_MsgHashIfNecessary(safeFolderName);
  nsCOMPtr<nsIMsgLocalMailFolder> localSrcFolder(do_QueryInterface(aSrcFolder));
  nsCOMPtr<nsIMsgDatabase> srcDB;
  if (localSrcFolder)
    localSrcFolder->GetDatabaseWOReparse(getter_AddRefs(srcDB));
  bool summaryValid = !!srcDB;
  srcDB = nullptr;
  aSrcFolder->ForceDBClosed();

  nsCOMPtr<nsIFile> oldPath;
  nsresult rv = aSrcFolder->GetFilePath(getter_AddRefs(oldPath));
  NS_ENSURE_SUCCESS(rv,rv);

  nsCOMPtr<nsIFile> summaryFile;
  GetSummaryFileLocation(oldPath, getter_AddRefs(summaryFile));

  nsCOMPtr<nsIFile> newPath;
  rv = aDstFolder->GetFilePath(getter_AddRefs(newPath));
  NS_ENSURE_SUCCESS(rv,rv);

  bool newPathIsDirectory = false;
  newPath->IsDirectory(&newPathIsDirectory);
  if (!newPathIsDirectory)
  {
    AddDirectorySeparator(newPath);
    newPath->Create(nsIFile::DIRECTORY_TYPE, 0700);
  }

  nsCOMPtr<nsIFile> origPath;
  oldPath->Clone(getter_AddRefs(origPath));

   //copying necessary for aborting.... if failure return
  rv = oldPath->CopyTo(newPath, safeFolderName);
  NS_ENSURE_SUCCESS(rv, rv); // Will fail if a file by that name exists

  // Copy to dir can fail if filespec does not exist. If copy fails, we test
  // if the filespec exist or not, if it does not that's ok, we continue
  // without copying it. If it fails and filespec exist and is not zero sized
  // there is real problem
  // Copy the file to the new dir
  nsAutoString dbName(safeFolderName);
  dbName += NS_LITERAL_STRING(SUMMARY_SUFFIX);
  rv = summaryFile->CopyTo(newPath, dbName);
  if (NS_FAILED(rv)) // Test if the copy is successful
  {
    // Test if the filespec has data
    bool exists;
    int64_t fileSize;
    summaryFile->Exists(&exists);
    summaryFile->GetFileSize(&fileSize);
    if (exists && fileSize > 0)
      NS_ENSURE_SUCCESS(rv, rv); // Yes, it should have worked !
    // else case is filespec is zero sized, no need to copy it,
    // not an error
  }

  nsCOMPtr<nsIMsgFolder> newMsgFolder;
  rv = aDstFolder->AddSubfolder(safeFolderName, getter_AddRefs(newMsgFolder));
  NS_ENSURE_SUCCESS(rv, rv);

  // linux and mac are not good about maintaining the file stamp when copying
  // folders around. So if the source folder db is good, set the dest db as
  // good too.
  nsCOMPtr<nsIMsgDatabase> destDB;
  if (summaryValid)
  {
    nsAutoString folderLeafName;
    origPath->GetLeafName(folderLeafName);
    newPath->Append(folderLeafName);
    nsCOMPtr<nsIMsgDBService> msgDBService =
      do_GetService(NS_MSGDB_SERVICE_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    rv = msgDBService->OpenMailDBFromFile(newPath, newMsgFolder, false,
                                          true, getter_AddRefs(destDB));
    if (rv == NS_MSG_ERROR_FOLDER_SUMMARY_OUT_OF_DATE && destDB)
      destDB->SetSummaryValid(true);
  }
  newMsgFolder->SetPrettyName(folderName);
  uint32_t flags;
  aSrcFolder->GetFlags(&flags);
  newMsgFolder->SetFlags(flags);
  bool changed = false;
  rv = aSrcFolder->MatchOrChangeFilterDestination(newMsgFolder, true, &changed);
  if (changed)
    aSrcFolder->AlertFilterChanged(aMsgWindow);

  nsCOMPtr<nsISimpleEnumerator> enumerator;
  rv = aSrcFolder->GetSubFolders(getter_AddRefs(enumerator));
  NS_ENSURE_SUCCESS(rv, rv);

  // Copy subfolders to the new location
  nsresult copyStatus = NS_OK;
  nsCOMPtr<nsIMsgLocalMailFolder> localNewFolder(do_QueryInterface(newMsgFolder, &rv));
  if (NS_SUCCEEDED(rv))
  {
    bool hasMore;
    while (NS_SUCCEEDED(enumerator->HasMoreElements(&hasMore)) && hasMore &&
           NS_SUCCEEDED(copyStatus))
    {
      nsCOMPtr<nsISupports> item;
      enumerator->GetNext(getter_AddRefs(item));

      nsCOMPtr<nsIMsgFolder> folder(do_QueryInterface(item));
      if (!folder)
        continue;

      copyStatus = localNewFolder->CopyFolderLocal(folder, false,
                                                   aMsgWindow, aListener);
      // Test if the call succeeded, if not we have to stop recursive call
      if (NS_FAILED(copyStatus))
      {
        // Copy failed we have to notify caller to handle the error and stop
        // moving the folders. In case this happens to the topmost level of
        // recursive call, then we just need to break from the while loop and
        // go to error handling code.
        if (!aIsMoveFolder)
          return copyStatus;
        break;
      }
    }
  }

  if (aIsMoveFolder && NS_SUCCEEDED(copyStatus))
  {
    if (localNewFolder)
    {
      nsCOMPtr<nsISupports> srcSupport(do_QueryInterface(aSrcFolder));
      localNewFolder->OnCopyCompleted(srcSupport, true);
    }

    // Notify the "folder" that was dragged and dropped has been created. No
    // need to do this for its subfolders. isMoveFolder will be true for folder.
    aDstFolder->NotifyItemAdded(newMsgFolder);

    nsCOMPtr<nsIMsgFolder> msgParent;
    aSrcFolder->GetParent(getter_AddRefs(msgParent));
    aSrcFolder->SetParent(nullptr);
    if (msgParent)
    {
      // The files have already been moved, so delete storage false
      msgParent->PropagateDelete(aSrcFolder, false, aMsgWindow);
      oldPath->Remove(false);  //berkeley mailbox
     // We need to force closed the source db
      nsCOMPtr<nsIMsgDatabase> srcDB;
      aSrcFolder->Delete();

      nsCOMPtr<nsIFile> parentPath;
      rv = msgParent->GetFilePath(getter_AddRefs(parentPath));
      NS_ENSURE_SUCCESS(rv,rv);

      AddDirectorySeparator(parentPath);
      nsCOMPtr<nsISimpleEnumerator> children;
      parentPath->GetDirectoryEntries(getter_AddRefs(children));
      bool more;
      // checks if the directory is empty or not
      if (children && NS_SUCCEEDED(children->HasMoreElements(&more)) && !more)
        parentPath->Remove(true);
    }
  }
  else
  {
    // This is the case where the copy of a subfolder failed.
    // We have to delete the newDirectory tree to make a "rollback".
    // Someone should add a popup to warn the user that the move was not
    // possible.
    if (aIsMoveFolder && NS_FAILED(copyStatus))
    {
      nsCOMPtr<nsIMsgFolder> msgParent;
      newMsgFolder->ForceDBClosed();
      newMsgFolder->GetParent(getter_AddRefs(msgParent));
      newMsgFolder->SetParent(nullptr);
      if (msgParent)
      {
        msgParent->PropagateDelete(newMsgFolder, false, aMsgWindow);
        newMsgFolder->Delete();
        newMsgFolder->ForceDBClosed();
        AddDirectorySeparator(newPath);
        newPath->Remove(true);  //berkeley mailbox
      }
      return NS_ERROR_FAILURE;
    }
  }
  return NS_OK;
}
コード例 #19
0
NS_IMETHODIMP nsMsgBrkMBoxStore::RenameFolder(nsIMsgFolder *aFolder,
                                              const nsAString & aNewName,
                                              nsIMsgFolder **aNewFolder)
{
  NS_ENSURE_ARG_POINTER(aFolder);
  NS_ENSURE_ARG_POINTER(aNewFolder);

  uint32_t numChildren;
  aFolder->GetNumSubFolders(&numChildren);
  nsString existingName;
  aFolder->GetName(existingName);

  nsCOMPtr<nsIFile> oldPathFile;
  nsresult rv = aFolder->GetFilePath(getter_AddRefs(oldPathFile));
  if (NS_FAILED(rv))
    return rv;

  nsCOMPtr<nsIMsgFolder> parentFolder;
  rv = aFolder->GetParent(getter_AddRefs(parentFolder));
  if (!parentFolder)
    return NS_ERROR_NULL_POINTER;

  nsCOMPtr<nsISupports> parentSupport = do_QueryInterface(parentFolder);

  nsCOMPtr<nsIFile> oldSummaryFile;
  rv = aFolder->GetSummaryFile(getter_AddRefs(oldSummaryFile));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIFile> dirFile;
  oldPathFile->Clone(getter_AddRefs(dirFile));

  if (numChildren > 0)
  {
    rv = CreateDirectoryForFolder(dirFile);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  nsAutoString safeName(aNewName);
  NS_MsgHashIfNecessary(safeName);

  nsAutoCString oldLeafName;
  oldPathFile->GetNativeLeafName(oldLeafName);

  nsCOMPtr<nsIFile> parentPathFile;
  parentFolder->GetFilePath(getter_AddRefs(parentPathFile));
  NS_ENSURE_SUCCESS(rv,rv);

  bool isDirectory = false;
  parentPathFile->IsDirectory(&isDirectory);
  if (!isDirectory)
  {
    nsAutoString leafName;
    parentPathFile->GetLeafName(leafName);
    leafName.AppendLiteral(FOLDER_SUFFIX);
    rv = parentPathFile->SetLeafName(leafName);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  aFolder->ForceDBClosed();
  //save off dir name before appending .msf
  rv = oldPathFile->MoveTo(nullptr, safeName);
  if (NS_FAILED(rv))
    return rv;

  nsString dbName(safeName);
  dbName += NS_LITERAL_STRING(SUMMARY_SUFFIX);
  oldSummaryFile->MoveTo(nullptr, dbName);

  if (numChildren > 0)
  {
    // rename "*.sbd" directory
    nsAutoString newNameDirStr(safeName);
    newNameDirStr += NS_LITERAL_STRING(".sbd");
    dirFile->MoveTo(nullptr, newNameDirStr);
  }

  return parentFolder->AddSubfolder(safeName, aNewFolder);
}
コード例 #20
0
ファイル: TcDatabase.cpp プロジェクト: jonixfu/tianchi
void TcDatabase::loadEngine(const QString& filename)
{
    m_sqls.clear();
    if ( m_handle.isOpen() )
    {
        if ( dbType() == SQLSERVER )
        {
            // 取出存储过程名
            QSqlQuery procedures_query = QSqlQuery(m_handle);
            QSqlQuery query = QSqlQuery(m_handle);
            if ( procedures_query.exec("exec sp_procedures_rowset2") )
            {
                while(procedures_query.next())
                {
                    QSqlRecord procedures = procedures_query.record();
                    QSqlField  fieldSchema = procedures.field("PROCEDURE_SCHEMA");
                    if ( fieldSchema.isValid() && fieldSchema.value() != "sys" )
                    {
                        QSqlField  field = procedures.field("PROCEDURE_NAME");
                        if ( field.isValid() )
                        {
                            SQLContext cnt;
                            QString procedureID = field.value().toString().toLower();
                            int index = procedureID.indexOf(";");
                            if ( index >= 0 )
                            {
                                procedureID = procedureID.left(index);
                            }
                            cnt.id = procedureID;
                            QString paramsLine;
                            if ( query.exec("exec sp_procedure_params_rowset '"+procedureID+"'") )
                            {
                                while(query.next())
                                {
                                    QSqlRecord paramField = query.record();
                                    QSqlField  paramName = paramField.field("PARAMETER_NAME");
                                    QString pname = paramName.value().toString();

                                    if ( pname.compare("@RETURN_VALUE", Qt::CaseInsensitive) != 0 )
                                    {
                                        QSqlField  paramType = paramField.field("TYPE_NAME");
                                        pname.remove(0, 1);

                                        QString ptype = paramType.value().toString().toLower();
                                        if ( ptype == "nvarchar" )
                                        {
                                            ptype = "string";
                                        }

                                        cnt.params.insert(pname, ptype);
                                        paramsLine += ", :" + pname;
                                    }
                                }
                                query.finish();

                                if ( ! paramsLine.isEmpty() )
                                {
                                    paramsLine.remove(0, 2);
                                }
                            }
                            cnt.text = "exec " + procedureID + " " + paramsLine;
                            m_sqls[procedureID] = cnt;
                            Q_EMIT dbiLoading(m_sqls.count(), procedureID);
                        }
                    }
                }
                procedures_query.finish();
            }
        }else
        if ( dbType() == MYSQL )
        {
            // 取出存储过程名
            QString sql = "SELECT `name`, `param_list`, `body`, `returns` FROM `mysql`.`proc` WHERE `language` = 'SQL' AND `db` = '"+dbName()+"';";
            QSqlQuery query = QSqlQuery(m_handle);
            if ( query.exec(sql) )
            {
                QSqlField  field;
                while(query.next())
                {
                    QSqlRecord procedures = query.record();

                    QString param_line;

                    SQLContext cnt;
                    cnt.id     = procedures.field("name").value().toString();
                    cnt.params =  getParamList(param_line, procedures.field("param_list").value().toString());
                    cnt.text   = "call " + cnt.id + "(" + param_line + ");";
                    //cnt.text   = procedures.field("body").value().toString();
                    m_sqls[cnt.id] = cnt;
                    Q_EMIT dbiLoading(m_sqls.count(), cnt.id);
                    Q_EMIT dbiLoading(m_sqls.count(), cnt.text);
                }
                query.finish();
            }
        }else
        if ( dbType() == POSTGRESQL )
        {
            // 取出存储过程名
            QSqlQuery storedproc_query = QSqlQuery(m_handle);
            QSqlQuery query = QSqlQuery(m_handle);
            if ( storedproc_query.exec("SELECT specific_name"
                                           " , routine_name"
                                        " FROM information_schema.routines"
                                       " WHERE specific_schema = 'public'"
                                         " AND routine_schema  = 'public'"
                                         " AND routine_type    = 'FUNCTION';") )
            {
                while(storedproc_query.next())
                {
                    QSqlRecord storedprocs = storedproc_query.record();
                    QSqlField  fieldspecific = storedprocs.field("specific_name");
                    QSqlField  fieldsqlid    = storedprocs.field("routine_name" );
                    if ( fieldspecific.isValid() && fieldsqlid.isValid() )
                    {
                        SQLContext cnt;
                        cnt.id = fieldsqlid.value().toString().toLower();
                        QString paramsLine;
                        if ( query.exec("SELECT parameter_name"
                                            " , udt_name"
                                         " FROM information_schema.parameters"
                                        " WHERE specific_schema = 'public'"
                                          " AND specific_name   = '"+fieldspecific.value().toString()+"'"
                                          " AND parameter_mode   = 'IN'"
                                        " ORDER BY ordinal_position;") )
                        {
                            while(query.next())
                            {
                                QSqlRecord fields = query.record();
                                QSqlField  paramName = fields.field("parameter_name");
                                QSqlField  paramType = fields.field("udt_name"      );
                                if ( paramName.isValid() && paramType.isValid() )
                                {
                                    cnt.params.insert(paramName.value().toString(),
                                                      paramType.value().toString());
                                    paramsLine += ", :" + paramName.value().toString();
                                }
                            }
                            query.finish();

                            if ( ! paramsLine.isEmpty() )
                            {
                                paramsLine.remove(0, 2);
                            }
                        }
                        cnt.text = "SELECT * FROM " + cnt.id + "(" + paramsLine + ");";
                        m_sqls[cnt.id] = cnt;
                        Q_EMIT dbiLoading(m_sqls.count(), cnt.id);
                    }
                }
                storedproc_query.finish();
            }
        }
    }
    QStringList filenames;
    QDir dir(filename);
    if ( dir.exists() )
    {
        filenames = dir.entryList(QStringList(), QDir::Files, QDir::Name);
        for( int i=0; i<filenames.count(); i++ )
        {
            QString ddlfile = filenames.at(i);
            filenames[i] = dir.absolutePath() + QDir::separator() + ddlfile;
        }
    }else
    {
        QFileInfo sqlsInfo(filename);
        if ( sqlsInfo.exists() )
        {
            filenames.append(filename);
        }
    }
    foreach(QString ddlfile, filenames)
    {
        QFile f(ddlfile);
        if ( f.open(QFile::Text | QFile::ReadOnly) )
        {
            m_engineFile = ddlfile;

            QTextStream in(&f);

            int                     rdType = 0;
            QString                 sqlId;
            QString                 sqlText;
            QMultiHash<QString, QString> sqlParams;
            while(!in.atEnd())
            {
                QString line = in.readLine().trimmed();
                clearComment(line);
                if ( line.isEmpty() )
                {

                }else
                if ( line.startsWith("SQL:", Qt::CaseInsensitive) )
                {
                    if ( ! sqlId.isEmpty() && ! sqlText.isEmpty() )
                    {
                        sqlText.replace("@", ":");

                        SQLContext cnt;
                        cnt.id     = sqlId;
                        cnt.text   = sqlText;
                        cnt.params = sqlParams;
                        m_sqls[sqlId] = cnt;
                        Q_EMIT dbiLoading(m_sqls.count(), sqlId);
                    }
                    sqlId = line.mid(4).trimmed().toLower();
                    sqlText.clear();
                    sqlParams.clear();
                    rdType = 1;
                }else
                if ( line.startsWith("Params:", Qt::CaseInsensitive) )
                {
                    rdType = 2;
                }else
                if ( ! sqlId.isEmpty() )
                {
                    switch(rdType)
                    {
                    case 1:
                        sqlText += line + "\n";
                        break;
                    case 2:
                    {
                        QString paramName;
                        QString paramType = "string";
                        int pos;
                        if ( (pos=line.indexOf(" ")) >0 )
                        {
                            paramName = line.left(pos);
                            line = line.remove(0, pos).trimmed();
                            if ( (pos=line.indexOf(" ")) >0 )
                            {
                                paramType = line.left(pos);
                            }else
                            {
                                paramType = line;
                            }
                        }else
                        {
                            paramName = line;
                        }
                        QChar c = paramName.at(0);
                        if ( c == ':' || c == '@' )
                        {
                            paramName.remove(0, 1);
                        }
                        sqlParams.insert(paramName, paramType.toLower());
                        break;
                    }
                    }
                }
            }
            f.close();

            if ( ! sqlId.isEmpty() && ! sqlText.isEmpty() )
            {
                SQLContext cnt;
                cnt.id     = sqlId;
                cnt.text   = sqlText;
                cnt.params = sqlParams;
                m_sqls[sqlId] = cnt;
                Q_EMIT dbiLoading(m_sqls.count(), sqlId);
            }
        }
    }
コード例 #21
0
//
// Send out a "keychain" notification for this database
//
void TokenDbCommon::notify(NotificationEvent event)
{
	DbCommon::notify(event, DLDbIdentifier(dbName().c_str(), gGuidAppleSdCSPDL,
		subservice(), CSSM_SERVICE_DL | CSSM_SERVICE_CSP));
}
コード例 #22
0
ファイル: TcDatabase.cpp プロジェクト: jonixfu/tianchi
int TcDatabase::open()
{
    int ret = 0;
    close();
    switch(dbType())
    {
    case SQLSERVER:
        //QSqlDatabase::removeDatabase("FriendSafe");
        m_handle = QSqlDatabase::addDatabase("QODBC");
        {
            QString dsn = QString("DRIVER={SQL SERVER};SERVER=%1;DATABASE=%2;").arg(hostName()).arg(dbName());
            m_handle.setDatabaseName(dsn);
            m_handle.setUserName(m_username);
            m_handle.setPassword(m_password);
        }
        ret = m_handle.open() ? 1 : 0;
        break;

    case MYSQL:
        //QSqlDatabase::removeDatabase("qt_sql_default_connection");
        m_handle = QSqlDatabase::addDatabase("QMYSQL");//, "qt_sql_default_connection");//, "allowMultiQueries=true");
        m_handle.setHostName(hostName());
        m_handle.setDatabaseName(dbName());
        m_handle.setUserName(m_username);
        m_handle.setPassword(m_password);
        //m_handle.setConnectOptions("allowMultiQueries=true");
        //m_handle.cloneDatabase()
        ret = m_handle.open() ? 1 : 0;
//DEBUG_OUT(m_handle.connectionName())
//DEBUG_OUT(m_handle.connectionNames().join("\n"))
        break;

    case POSTGRESQL:
        //QSqlDatabase::removeDatabase("");
        m_handle = QSqlDatabase::addDatabase("QPSQL");
        m_handle.setHostName(hostName());
        m_handle.setDatabaseName(dbName());
        m_handle.setUserName(m_username);
        m_handle.setPassword(m_password);
        //m_handle.setConnectOptions("allowMultiQueries=true");
        //m_handle.cloneDatabase()
        ret = m_handle.open() ? 1 : 0;
//DEBUG_OUT(m_handle.connectionName())
//DEBUG_OUT(m_handle.connectionNames().join("\n"))
        break;

    case SQLTIE:
        //QSqlDatabase::removeDatabase("FriendSafe");
        m_handle = QSqlDatabase::addDatabase("QSQLITE");

        QFileInfo dbFile(m_dbName);
        QDir dir(dbFile.absoluteDir());
        dir.mkpath(dbFile.absolutePath());
        m_handle.setDatabaseName(m_dbName);
        m_handle.setUserName(m_username);
        m_handle.setPassword(m_password);

        if ( m_handle.open() )
        {
            m_hostName = "localhost";
            m_hostPort = 0;
            QStringList tables = m_handle.tables();
            if ( tables.count() <= 0 )
            {
                // 没有任何表,这个库是新建的。
                QFile f(CreateDDL);
                if ( f.open(QFile::Text | QFile::ReadOnly) )
                {
                    QTextStream in(&f);
                    QString fileText = in.readAll();
                    f.close();

                    ret = 1;
                    QSqlQuery query = QSqlQuery(m_handle);
                    int pos;
                    while((pos=fileText.indexOf(";")) >-1)
                    {
                        QString sqlText = fileText.mid(0, pos).trimmed();
                        fileText.remove(0, pos+1);
                        fileText = fileText.trimmed();

                        QStringList sqlLines = sqlText.split("\n", QString::SkipEmptyParts);
                        QString sql;
                        for( int i=0;i<sqlLines.count();i++ )
                        {
                            QString s = sqlLines.at(i);
                            if ( ! s.startsWith("--") )
                            {
                                sql += s + "\n";
                            }
                        }
                        if ( ! sql.isEmpty() && ! query.exec(sql) )
                        {
                            ret = -1;
                        }
                    }
                    query.finish();
                }
            }else
            {
                ret = 1;
            }
        }
        break;
    }
    m_accepted = ret >0;
    return ret;
}
コード例 #23
0
ファイル: qsql_symsql.cpp プロジェクト: maxxant/qt
/*!   
    Opens the database connection using the given connection options. Returns true on success; otherwise returns false.
    Error information can be retrieved using the lastError() function. Symbian SQL dbs have no \a user, \a password, \a host
    or \a port just file names.
    
    \a connOpts Connection options hold definition for security policies and all parameters that does not contain "POLICY_" will be
    passed to RSqlDatabase. Policy will be filled according to parsed values.

    Value in database wide parameters starts by definition which can be vendorId or secureId. These come directly from TSecurityPolicy class in Symbian. 
    
    POLICY_DB_DEFAULT
    Default security policy which will be used for the database and all database objects. POLICY_DB_DEFAULT must be 
    defined before any other policy definitions can be used.    
    POLICY_DB_READ
    Read database security policy. An application with read database security policy can read from database.    
    POLICY_DB_WRITE:
    Write database security policy. An application with write database security policy can write to database. 
    POLICY_DB_SCHEMA:
    Schema database security policy. An application with schema database security policy can modify
    the database schema, write to database, read from database.   
    
    Format:
    POLICY_DB_DEFAULT=cap1,cap2,cap3,cap4,cap5,cap6,cap7    (Up to 7 capabilities) 
    POLICY_DB_READ=cap1,cap2,cap3,cap4,cap5,cap6,cap7       (Up to 7 capabilities)
    POLICY_DB_WRITE=vendorid,cap1,cap2,cap3                 (Vendor ID and up to 3 capabilities)
    POLICY_DB_SCHEMA=secureid,cap1,cap2,cap3                (Secure ID and up to 3 capabilities)  
    
    Table policies does not support schema policy as database level does.
    
    Table specific parameters would be as:    
    POLICY_TABLE_WRITE=tablename,cap1,cap2,cap3,cap4,cap5,cap6,cap7
    POLICY_TABLE_READ=tablename,cap1,cap2,cap3,cap4,cap5,cap6,cap7    
    
    Vendor Id and Secure id format:    
    vid[0x12345678]                              (Hex)    
    sid[0x12345678]                              (Hex)                        
    
    Example:   
    \code   
    QSqlDatabase database = QSqlDatabase::addDatabase("QSYMSQL", "MyConnection");
    database.setConnectOptions("POLICY_DB_DEFAULT=ReadDeviceData");
    database.setDatabaseName("[12345678]myDatabase");
    bool ok = database.open();   
    \encode    
    
    \code   
    QSqlDatabase database = QSqlDatabase::addDatabase("QSYMSQL", "MyConnection");
    database.setConnectOptions("POLICY_DB_DEFAULT=None; POLICY_DB_WRITE=sid[0x12345678], WriteDeviceData");
    database.setDatabaseName("[12345678]myDatabase");
    bool ok = database.open();   
    \encode    
    
    FOREIGN KEY:  
    Enabling foreign key support from underlying SQLite
    add: "foreign_keys = ON" to your connection options string. This will be passes to SQLite.
   
    Foreign key Example:   
    \code
    QSqlDatabase database = QSqlDatabase::addDatabase("QSYMSQL", "MyConnection");
    database.setDatabaseName("[12345678]myDatabase");
    database.setConnectOptions("foreign_keys = ON");
    bool ok = database.open();
    \encode
    
   More information about Symbian Security Policy can be found from Symbian documentation.
    
*/
bool QSymSQLDriver::open(const QString & db, const QString &, const QString &, const QString &, int, const QString &conOpts)
{                                
    if (isOpen())
        close();
    if (db.isEmpty())
        return false;
    
    //Separating our parameters from Symbian ones and construct new connection options
    const QString itemSeparator(QLatin1String(";"));
    QRegExp isOurOption(QLatin1String("POLICY_*"), Qt::CaseInsensitive, QRegExp::Wildcard); 
    
    QStringList optionList = conOpts.split(itemSeparator, QString::SkipEmptyParts);
    QStringList symbianList;
    
    for (int i = optionList.count() - 1; i >= 0; i--) {
        if (!optionList[i].contains(isOurOption)) {
            symbianList.append(optionList[i]);
            optionList.removeAt(i);
        } else {
            //Removing whitespace
            QString formatted = optionList[i];
            formatted = formatted.remove(QLatin1Char(' '));
            formatted = formatted.remove(QLatin1Char('\t'));
            formatted = formatted.remove(QLatin1Char('\n'));
            formatted = formatted.remove(QLatin1Char('\r'));
            optionList[i] = formatted;
        }
    }
    
    QString symbianOpt;
    
    for (int i = 0; i < symbianList.count(); i++) {
        symbianOpt += symbianList[i];
        symbianOpt += itemSeparator;
    }

    TPtrC dbName(qt_QString2TPtrC(db));
    QByteArray conOpts8 = symbianOpt.toUtf8();    
    const TPtrC8 config(reinterpret_cast<const TUint8*>(conOpts8.constData()), (conOpts8.length()));
    
    TInt res = d->access.Open(dbName, &config);
    
    if (res == KErrNotFound) {

        QRegExp findDefault(QLatin1String("POLICY_DB_DEFAULT=*"), Qt::CaseInsensitive, QRegExp::Wildcard);
        QRegExp findRead(QLatin1String("POLICY_DB_READ=*"), Qt::CaseInsensitive, QRegExp::Wildcard);
        QRegExp findWrite(QLatin1String("POLICY_DB_WRITE=*"), Qt::CaseInsensitive, QRegExp::Wildcard);
        QRegExp findSchema(QLatin1String("POLICY_DB_SCHEMA=*"), Qt::CaseInsensitive, QRegExp::Wildcard);
        QRegExp findTableRead(QLatin1String("POLICY_TABLE_READ=*"), Qt::CaseInsensitive, QRegExp::Wildcard);
        QRegExp findTableWrite(QLatin1String("POLICY_TABLE_WRITE=*"), Qt::CaseInsensitive, QRegExp::Wildcard);
               
        int policyIndex = optionList.indexOf(findDefault);
        
        if (policyIndex != -1) {
            QString defaultPolicyString = optionList[policyIndex];
            optionList.removeAt(policyIndex);
            
            TSecurityPolicy policyItem;
            
            if (qExtractSecurityPolicyFromString(defaultPolicyString, policyItem)) {
                RSqlSecurityPolicy policy;
                res = policy.Create(policyItem);
                
                if (res == KErrNone) {
                    for (int i = 0; i < optionList.count(); i++) {
                        QString option = optionList[i];
                        
                        if (option.contains(findRead)) {
                            if (qExtractSecurityPolicyFromString(option, policyItem)) {
                                res = policy.SetDbPolicy(RSqlSecurityPolicy::EReadPolicy, policyItem);
                            } else {
                                res = KErrArgument;
                            }
                        } else if (option.contains(findWrite)) {
                            if (qExtractSecurityPolicyFromString(option, policyItem)) {
                                res = policy.SetDbPolicy(RSqlSecurityPolicy::EWritePolicy, policyItem);
                            } else {
                                res = KErrArgument;
                            }
                        } else if (option.contains(findSchema)) {
                            if (qExtractSecurityPolicyFromString(option, policyItem)) {
                                res = policy.SetDbPolicy(RSqlSecurityPolicy::ESchemaPolicy, policyItem);
                            } else {
                                res = KErrArgument;
                            }
                        } else if (option.contains(findTableWrite)) {
                            QString tableOption = option.mid(option.indexOf(QLatin1Char('=')) + 1);
                            int firstComma = tableOption.indexOf(QLatin1Char(','));
                            
                            if (firstComma != -1) {
                                QString tableName = tableOption.left(firstComma);
                                tableOption = tableOption.mid(firstComma + 1);
                                
                                if (qExtractSecurityPolicyFromString(tableOption, policyItem)) {
                                    TPtrC symTableName(qt_QString2TPtrC(tableName));
                                                                
                                    res = policy.SetPolicy(RSqlSecurityPolicy::ETable, symTableName,
                                                        RSqlSecurityPolicy::EWritePolicy, policyItem);
                                } else {
                                    res = KErrArgument;
                                }
                            } else {
                                res = KErrArgument;
                            }
                        } else if (option.contains(findTableRead)) {
                            QString tableOption = option.mid(option.indexOf(QLatin1Char('=')) + 1);
                            int firstComma = tableOption.indexOf(QLatin1Char(','));
                            
                            if (firstComma != -1) {
                                QString tableName = tableOption.left(firstComma);
                                tableOption = tableOption.mid(firstComma + 1);
                                
                                if (qExtractSecurityPolicyFromString(tableOption, policyItem)) {
                                    TPtrC symTableName(qt_QString2TPtrC(tableName));
                                                                
                                    res = policy.SetPolicy(RSqlSecurityPolicy::ETable, symTableName,
                                                        RSqlSecurityPolicy::EReadPolicy, policyItem);
                                } else {
                                    res = KErrArgument;
                                }
                            } else {
                                res = KErrArgument;
                            }
                        } else {
                            res = KErrArgument;
                        }
                        
                        if (res != KErrNone) {
                            setLastError(gMakeErrorOpen(tr("Invalid option: ") + option, QSqlError::ConnectionError, res));
                            break;
                        }
                    }
                    
                    if (res == KErrNone) {
                        res = d->access.Create(dbName, policy, &config);
                        policy.Close();
                        
                        if (res != KErrNone) 
                            setLastError(gMakeErrorOpen(tr("Error opening database"), QSqlError::ConnectionError, res));
                    }
                }
                
            } else {
                res = KErrArgument;
                setLastError(gMakeErrorOpen(tr("Invalid option: ") + defaultPolicyString, QSqlError::ConnectionError, res));
            }
            
        } else {
            //Check whether there is some of our options, fail if so.
            policyIndex = optionList.indexOf(isOurOption);
            
            if (policyIndex == -1) {
                res = d->access.Create(dbName, &config);
            
                if (res != KErrNone) 
                    setLastError(gMakeErrorOpen(tr("Error opening database"), QSqlError::ConnectionError, res));
            } else {
                res = KErrArgument;
                setLastError(gMakeErrorOpen(tr("POLICY_DB_DEFAULT must be defined before any other POLICY definitions can be used"), QSqlError::ConnectionError, res));
            }
        }
    }
    
    if (res == KErrNone) {
        setOpen(true);
        setOpenError(false);
        return true;
    } else {
        setOpenError(true);
        return false;
    }
}
コード例 #24
0
nsresult
nsFolderCompactState::FinishCompact()
{
  if (!m_folder)
    return NS_ERROR_NOT_INITIALIZED;

  // All okay time to finish up the compact process
  nsCOMPtr<nsILocalFile> path;
  nsCOMPtr<nsIDBFolderInfo> folderInfo;

  // get leaf name and database name of the folder
  nsresult rv = m_folder->GetFilePath(getter_AddRefs(path));
  nsCOMPtr <nsILocalFile> folderPath = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);
  nsCOMPtr <nsILocalFile> summaryFile;
  folderPath->InitWithFile(path);
  // need to make sure we put the .msf file in the same directory
  // as the original mailbox, so resolve symlinks.
  folderPath->SetFollowLinks(true);
  GetSummaryFileLocation(folderPath, getter_AddRefs(summaryFile));

  nsCString leafName;
  summaryFile->GetNativeLeafName(leafName);
  nsCAutoString dbName(leafName);

  path->GetNativeLeafName(leafName);

    // close down the temp file stream; preparing for deleting the old folder
    // and its database; then rename the temp folder and database
  m_fileStream->Flush();
  m_fileStream->Close();
  m_fileStream = nsnull;

  // make sure the new database is valid.
  // Close it so we can rename the .msf file.
  if (m_db)
  {
    m_db->ForceClosed();
    m_db = nsnull;
  }

  nsCOMPtr <nsILocalFile> newSummaryFile;
  GetSummaryFileLocation(m_file, getter_AddRefs(newSummaryFile));

  nsCOMPtr <nsIDBFolderInfo> transferInfo;
  m_folder->GetDBTransferInfo(getter_AddRefs(transferInfo));

  // close down database of the original folder
  m_folder->ForceDBClosed();

  nsCOMPtr<nsIFile> cloneFile;
  PRInt64 fileSize;
  m_file->Clone(getter_AddRefs(cloneFile));
  cloneFile->GetFileSize(&fileSize);
  bool tempFileRightSize = (fileSize == m_totalMsgSize);
  NS_ASSERTION(tempFileRightSize, "temp file not of expected size in compact");
  
  bool folderRenameSucceeded = false;
  bool msfRenameSucceeded = false;
  if (tempFileRightSize)
  {
    bool summaryFileExists;
    // remove the old folder and database
    rv = summaryFile->Remove(false);
    summaryFile->Exists(&summaryFileExists);
    if (NS_SUCCEEDED(rv) && !summaryFileExists)
    {
      bool folderPathExists;
      rv = folderPath->Remove(false);
      folderPath->Exists(&folderPathExists);
      if (NS_SUCCEEDED(rv) && !folderPathExists)
      {
        // rename the copied folder and database to be the original folder and
        // database 
        rv = m_file->MoveToNative((nsIFile *) nsnull, leafName);
        NS_ASSERTION(NS_SUCCEEDED(rv), "error renaming compacted folder");
        if (NS_SUCCEEDED(rv))
        {
          folderRenameSucceeded = true;
          rv = newSummaryFile->MoveToNative((nsIFile *) nsnull, dbName);
          NS_ASSERTION(NS_SUCCEEDED(rv), "error renaming compacted folder's db");
          msfRenameSucceeded = NS_SUCCEEDED(rv);
        }
      }
    }
    NS_ASSERTION(msfRenameSucceeded && folderRenameSucceeded, "rename failed in compact");
  }
  if (!folderRenameSucceeded)
    m_file->Remove(false);
  if (!msfRenameSucceeded)
    newSummaryFile->Remove(false);
  rv = ReleaseFolderLock();
  NS_ASSERTION(NS_SUCCEEDED(rv),"folder lock not released successfully");
  if (msfRenameSucceeded && folderRenameSucceeded)
  {
    nsCOMPtr<nsIMsgDBService> msgDBService =
      do_GetService(NS_MSGDB_SERVICE_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    rv = msgDBService->OpenFolderDB(m_folder, true, getter_AddRefs(m_db));
    m_db->SetSummaryValid(true);
    m_folder->SetDBTransferInfo(transferInfo);

    nsCOMPtr<nsIDBFolderInfo> dbFolderInfo;

    m_db->GetDBFolderInfo(getter_AddRefs(dbFolderInfo));

    // since we're transferring info from the old db, we need to reset the expunged bytes,
    // and set the summary valid again.
    if(dbFolderInfo)
      dbFolderInfo->SetExpungedBytes(0);
  }
  if (m_db)
    m_db->Close(true);
  m_db = nsnull;

  // Notify that compaction of the folder is completed.
  nsCOMPtr<nsIMsgFolderNotificationService>
    notifier(do_GetService(NS_MSGNOTIFICATIONSERVICE_CONTRACTID));
  if (notifier)
    notifier->NotifyItemEvent(m_folder,
                              NS_LITERAL_CSTRING("FolderCompactFinish"),
                              nsnull);
  m_folder->NotifyCompactCompleted();

  if (m_compactAll)
    rv = CompactNextFolder();
  else
    CompactCompleted(NS_OK);
      
  return rv;
}
コード例 #25
0
ファイル: wb_dbms.cpp プロジェクト: jordibrus/proview
int wb_dbms_env::open(void)
{
    char var[32];
    char value[32];
    char buf[512];
    char *s;
    char *valp;
    int rc;

    cdh_ToLower(m_fileName, m_fileName);

    sprintf(buf, "%s/%s", m_fileName, "connection.dmsql");

    FILE *fp = fopen(buf, "r");
    if (fp == NULL) {
        printf("** Cannot open file: %s, %s\n", buf, strerror(errno));
        return errno;
    }

    while ((s = fgets(buf, sizeof(buf) - 1, fp))) {
        if (*s == '#')
            continue;

        rc = sscanf(s, " %[A-Z_] %*[^ ] %s", var, value);
        if (rc < 1)
            continue;
        if (rc == 1)
            valp = 0;
        else
            valp = value;

        if (strcmp(valp, "(null)") == 0)
            valp = 0;

        if (strcmp(var, "HOST") == 0) {
            host(valp);
        }
        else if (strcmp(var, "USER") == 0) {
            user(valp);
        }
        else if (strcmp(var, "PASSWD") == 0) {
            passwd(valp);
        }
        else if (strcmp(var, "DB_NAME") == 0) {
            dbName(valp);
        }
        else if (strcmp(var, "PORT") == 0) {
            if (valp == 0)
                port(0);
            else
                port(atoi(valp));
        }
        else if (strcmp(var, "SOCKET") == 0) {
            socket(valp);
        }
        else {
            printf("Unknown connection parameter! : %s\n", var);
        }
    }

    fclose(fp);

    m_exists = true;

    return 0;
}
コード例 #26
0
//
// Perform deferred lock processing for a database.
//
void KeychainDbCommon::action()
{
	secdebug("KCdb", "common %s(%p) locked by timer", dbName(), this);
	lockDb();
}
コード例 #27
0
// select exact
bool CmpSeabaseDDLauth::selectExactRow(const NAString & cmd)
{
  ExeCliInterface cliInterface(STMTHEAP);

  Int32 cliRC = cliInterface.fetchRowsPrologue(cmd.data(), true/*no exec*/);
  if (cliRC < 0)
    {
      cliInterface.retrieveSQLDiagnostics(CmpCommon::diags());
      DDLException excp (cliRC, NULL, 0);
      excp.throwException();
    }

  cliRC = cliInterface.clearExecFetchClose(NULL, 0);
  if (cliRC < 0)
    {
      cliInterface.retrieveSQLDiagnostics(CmpCommon::diags());
      DDLException excp (cliRC, NULL, 0);
      excp.throwException();
    }

  // if diags not cleared, then no error is returned -- ??
  if (cliRC == 100) // did not find the row
  {
    cliInterface.clearGlobalDiags();
    return false;
  }

  char * ptr = NULL;
  Lng32 len = 0;
  char type [6];

  // value 1:  auth_id (int32)
  cliInterface.getPtrAndLen(1, ptr, len);
  setAuthID(*(Int32*)ptr);

  // value 2: auth_db_name (NAString)
  cliInterface.getPtrAndLen(2,ptr,len);
  NAString dbName(ptr,len);
  setAuthDbName(dbName);

  // value 3: auth_ext_name (NAString)
  cliInterface.getPtrAndLen(3,ptr,len);
  NAString extName(ptr,len);
  setAuthExtName(extName);

  // value 4: auth_type (char)
  // str_cpy_and_null params: *tgt, *src, len, endchar, blank, null term
  cliInterface.getPtrAndLen(4,ptr,len);
  str_cpy_and_null(type, ptr, len, '\0', ' ', true);
  if ( type[0] == 'U')
    setAuthType(COM_USER_CLASS);
  else if (type[0] == 'R')
    setAuthType(COM_USER_CLASS);
  else
    setAuthType(COM_UNKNOWN_ID_CLASS);

  // value 5: auth_creator (int32)
  cliInterface.getPtrAndLen(5,ptr,len);
  setAuthCreator(*(Int32*)ptr);

  // value 6: auth_is_valid (char)
  cliInterface.getPtrAndLen(6,ptr,len);
  str_cpy_and_null(type, ptr, len, '\0', ' ', true);
  if (type[0] == 'Y')
    setAuthValid(true);
  else
    setAuthValid(false);

  // value 7: auth_create_time (int64)
  cliInterface.getPtrAndLen(7,ptr,len);
  Int64 intValue = *(Int64*)ptr;
  setAuthCreateTime((ComTimestamp) intValue);

  // value 8: auth_redef_time (int64)
  cliInterface.getPtrAndLen(8,ptr,len);
  intValue = *(Int64*)ptr;
  setAuthRedefTime((ComTimestamp) intValue);

  cliInterface.fetchRowsEpilogue(NULL, true);
  return true;
}
コード例 #28
0
NS_IMETHODIMP nsMsgMaildirStore::CopyFolder(nsIMsgFolder *aSrcFolder,
                                            nsIMsgFolder *aDstFolder,
                                            bool aIsMoveFolder,
                                            nsIMsgWindow *aMsgWindow,
                                            nsIMsgCopyServiceListener *aListener,
                                            const nsAString &aNewName)
{
  NS_ENSURE_ARG_POINTER(aSrcFolder);
  NS_ENSURE_ARG_POINTER(aDstFolder);

  nsAutoString folderName;
  if (aNewName.IsEmpty())
    aSrcFolder->GetName(folderName);
  else
    folderName.Assign(aNewName);

  nsAutoString safeFolderName(folderName);
  NS_MsgHashIfNecessary(safeFolderName);
  nsCOMPtr<nsIMsgLocalMailFolder> localSrcFolder(do_QueryInterface(aSrcFolder));
  aSrcFolder->ForceDBClosed();

  nsCOMPtr<nsIFile> oldPath;
  nsresult rv = aSrcFolder->GetFilePath(getter_AddRefs(oldPath));
  NS_ENSURE_SUCCESS(rv,rv);

  nsCOMPtr<nsIFile> summaryFile;
  GetSummaryFileLocation(oldPath, getter_AddRefs(summaryFile));

  nsCOMPtr<nsIFile> newPath;
  rv = aDstFolder->GetFilePath(getter_AddRefs(newPath));
  NS_ENSURE_SUCCESS(rv, rv);

  // create target directory based on our current path
  bool isServer;
  aDstFolder->GetIsServer(&isServer);
  rv = CreateDirectoryForFolder(newPath, isServer);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIFile> origPath;
  oldPath->Clone(getter_AddRefs(origPath));

  rv = oldPath->CopyTo(newPath, safeFolderName);
  NS_ENSURE_SUCCESS(rv, rv); //will fail if a file by that name exists

  // Copy to dir can fail if file does not exist. If copy fails, we test
  // if the file exists or not, if it does not that's ok, we continue
  // without copying it. If it fails and file exist and is not zero sized
  // there is real problem.
  nsAutoString dbName(safeFolderName);
  dbName += NS_LITERAL_STRING(SUMMARY_SUFFIX);
  rv = summaryFile->CopyTo(newPath, dbName);
  if (!NS_SUCCEEDED(rv))
  {
    // Test if the file is not empty
    bool exists;
    int64_t fileSize;
    summaryFile->Exists(&exists);
    summaryFile->GetFileSize(&fileSize);
    if (exists && fileSize > 0)
      NS_ENSURE_SUCCESS(rv, rv); // Yes, it should have worked!
    // else case is file is zero sized, no need to copy it,
    // not an error
    // else case is file does not exist - not an error
  }

  nsCOMPtr<nsIMsgFolder> newMsgFolder;
  rv = aDstFolder->AddSubfolder(safeFolderName, getter_AddRefs(newMsgFolder));
  NS_ENSURE_SUCCESS(rv, rv);

  newMsgFolder->SetPrettyName(folderName);
  uint32_t flags;
  aSrcFolder->GetFlags(&flags);
  newMsgFolder->SetFlags(flags);
  bool changed = false;
  rv = aSrcFolder->MatchOrChangeFilterDestination(newMsgFolder, true, &changed);
  if (changed)
    aSrcFolder->AlertFilterChanged(aMsgWindow);

  nsCOMPtr<nsISimpleEnumerator> enumerator;
  rv = aSrcFolder->GetSubFolders(getter_AddRefs(enumerator));
  NS_ENSURE_SUCCESS(rv, rv);

  // Copy subfolders to the new location
  nsresult copyStatus = NS_OK;
  nsCOMPtr<nsIMsgLocalMailFolder> localNewFolder(do_QueryInterface(newMsgFolder, &rv));
  if (NS_SUCCEEDED(rv))
  {
    bool hasMore;
    while (NS_SUCCEEDED(enumerator->HasMoreElements(&hasMore)) && hasMore &&
           NS_SUCCEEDED(copyStatus))
    {
      nsCOMPtr<nsISupports> item;
      enumerator->GetNext(getter_AddRefs(item));

      nsCOMPtr<nsIMsgFolder> folder(do_QueryInterface(item));
      if (!folder)
        continue;

      copyStatus = localNewFolder->CopyFolderLocal(folder, false, aMsgWindow,
                                                   aListener);
      // Test if the call succeeded, if not we have to stop recursive call
      if (NS_FAILED(copyStatus))
      {
        // Copy failed we have to notify caller to handle the error and stop
        // moving the folders. In case this happens to the topmost level of
        // recursive call, then we just need to break from the while loop and
        // go to error handling code.
        if (!aIsMoveFolder)
          return copyStatus;
        break;
      }
    }
  }

  if (aIsMoveFolder && NS_SUCCEEDED(copyStatus))
  {
    if (localNewFolder)
    {
      nsCOMPtr<nsISupports> srcSupport(do_QueryInterface(aSrcFolder));
      localNewFolder->OnCopyCompleted(srcSupport, true);
    }

    // Notify that the folder that was dragged and dropped has been created.
    // No need to do this for its subfolders - isMoveFolder will be true for folder.
    aDstFolder->NotifyItemAdded(newMsgFolder);

    nsCOMPtr<nsIMsgFolder> msgParent;
    aSrcFolder->GetParent(getter_AddRefs(msgParent));
    aSrcFolder->SetParent(nullptr);
    if (msgParent)
    {
      // The files have already been moved, so delete storage false
      msgParent->PropagateDelete(aSrcFolder, false, aMsgWindow);
      oldPath->Remove(true);
      nsCOMPtr<nsIMsgDatabase> srcDB; // we need to force closed the source db
      aSrcFolder->Delete();

      nsCOMPtr<nsIFile> parentPath;
      rv = msgParent->GetFilePath(getter_AddRefs(parentPath));
      NS_ENSURE_SUCCESS(rv,rv);

      AddDirectorySeparator(parentPath);
      nsCOMPtr<nsISimpleEnumerator> children;
      parentPath->GetDirectoryEntries(getter_AddRefs(children));
      bool more;
      // checks if the directory is empty or not
      if (children && NS_SUCCEEDED(children->HasMoreElements(&more)) && !more)
        parentPath->Remove(true);
    }
  }
  else
  {
    // This is the case where the copy of a subfolder failed.
    // We have to delete the newDirectory tree to make a "rollback".
    // Someone should add a popup to warn the user that the move was not
    // possible.
    if (aIsMoveFolder && NS_FAILED(copyStatus))
    {
      nsCOMPtr<nsIMsgFolder> msgParent;
      newMsgFolder->ForceDBClosed();
      newMsgFolder->GetParent(getter_AddRefs(msgParent));
      newMsgFolder->SetParent(nullptr);
      if (msgParent)
      {
        msgParent->PropagateDelete(newMsgFolder, false, aMsgWindow);
        newMsgFolder->Delete();
        newMsgFolder->ForceDBClosed();
        AddDirectorySeparator(newPath);
        newPath->Remove(true); //berkeley mailbox
      }
      return NS_ERROR_FAILURE;
    }
  }
  return NS_OK;
}
コード例 #29
0
ファイル: bfcompany.cpp プロジェクト: i02sopop/Bulmages
/**
\return
**/
void BfCompany::cargaConf()
{
    BL_FUNC_DEBUG
    QFile file ( g_confpr->value( CONF_DIR_USER ) + "bulmafact_" + dbName() + ".cfn" );
    QDomDocument doc ( "mydocument" );
    if ( !file.open ( QIODevice::ReadOnly ) )
        return;
    if ( !doc.setContent ( &file ) ) {
        file.close();
        return;
    }
    file.close();

    // print out the element names of all elements that are direct children
    // of the outermost element.
    QDomElement docElem = doc.documentElement();
    QDomElement principal = docElem.firstChildElement ( "PRINCIPAL" );
    /// Cogemos la coordenada X
    QString nx = principal.firstChildElement ( "X" ).toElement().text();

    /// Cogemos la coordenada Y
    QString ny = principal.firstChildElement ( "Y" ).toElement().text();

    /// Cogemos el ancho
    QString nwidth = principal.firstChildElement ( "WIDTH" ).toElement().text();

    /// Cogemos el alto
    QString nheight = principal.firstChildElement ( "HEIGHT" ).toElement().text();

    /// Si est&aacute; maximizada, ignoramos las otras dimensiones
    if (principal.firstChildElement ( "MAXIMIZED" ).toElement().text() == "true")
	 m_bulmafact->setWindowState(Qt::WindowMaximized);
    else /// Establecemos la geometria de la ventana principal.
	 m_bulmafact->setGeometry ( nx.toInt(), ny.toInt(), nwidth.toInt(), nheight.toInt() );

    /// Cogemos el indexador
    QString indexador = principal.firstChildElement ( "INDEXADOR" ).toElement().text();
    if ( indexador == "true" ) {
        s_indexadorCambiaEstado ( true );
        m_bulmafact->actionIndexador->setChecked ( true );
    } else {
        s_indexadorCambiaEstado ( false );
        m_bulmafact->actionIndexador->setChecked ( false );
    } // end if

    /// Cogemos el ancho del indexador
    m_bulmafact->restoreState ( QByteArray::fromBase64 ( QByteArray ( principal.firstChildElement ( "TOOLBARSDOCKWIDGETS" ).toElement().text().toLatin1() ) ) );

    /// Tratamos cada ventana
    QWidget *activewindow = NULL;
    QDomNodeList nodos = docElem.elementsByTagName ( "VENTANA" );
    for ( int i = 0; i < nodos.count(); i++ ) {
        QDomNode ventana = nodos.item ( i );
        QDomElement e1 = ventana.toElement(); /// try to convert the node to an element.
        if ( !e1.isNull() ) { /// the node was really an element.
            QString vname = e1.firstChildElement ( "VNAME" ).toElement().text();
            for ( int j = 0; j < m_windowListDock->numVentanas(); j++ ) {
                QObject *obj = m_windowListDock->ventana ( j );
                QWidget *wid = ( QWidget * ) obj;
                if ( obj->objectName() == vname ) {
                    QString vx = e1.firstChildElement ( "VX" ).toElement().text();
                    QString vy = e1.firstChildElement ( "VY" ).toElement().text();
                    QString vwidth = e1.firstChildElement ( "VWIDTH" ).toElement().text();
                    QString vheight = e1.firstChildElement ( "VHEIGHT" ).toElement().text();
                    QString vvisible = e1.firstChildElement ( "VVISIBLE" ).toElement().text();
                    QString vmaximized = e1.firstChildElement ( "VMAXIMIZED" ).toElement().text();
                    QString vactivewindow = e1.firstChildElement ( "VACTIVEWINDOW" ).toElement().text();
                    /// Establecemos la geometria de la ventana principal.
                    wid->resize ( vwidth.toInt(), vheight.toInt() );
                    wid->parentWidget() ->move ( vx.toInt(), vy.toInt() );
                    if ( vvisible == "true" ) {
                        wid->showNormal();
                    } // end if
                    if ( vmaximized == "true" ) {
                        wid->showMaximized();
                    }
                    if ( vactivewindow == "true" ) {
                        activewindow = wid;
                    }
                } // end if
            } // end for
        } // end if
    } // end for
    /// Si hay una ventana activa se pone como activa.
    if ( activewindow )
	activewindow->activateWindow();
    
}