Install/uninstall event.
Executes SQL queries form a file.

@param string $sSqlFile      SQL file located in module docs folder (usually install.sql or uninstall.sql).
@param string $sFailureError An error message to show on failure.
428059
protected static function _dbEvent( $sSqlFile, $sFailureError = "Operation failed: " )
    {
        try {
            $oDb  = oxDb::getDb();
            $sSql = file_get_contents( dirname( __FILE__ ) . '/../docs/' . (string) $sSqlFile );
            $aSql = explode( ';', trim($sSql));

            if ( !empty( $aSql ) ) {
                foreach ( $aSql as $sQuery ) {
                    if ( !empty( $sQuery ) ) {
                        $oDb->execute(trim($sQuery));
                    }
                }

            }
        } catch ( Exception $ex ) {
            error_log( $sFailureError . $ex->getMessage() );
        }

        self::cleanTmp();

        /** @var oxDbMetaDataHandler $oDbHandler */
        $oDbHandler = oxNew( 'oxDbMetaDataHandler' );
        $oDbHandler->updateViews();
    }
820858
public synchronized void open() throws SFException, SnowflakeSQLException
  {
    performSanityCheckOnProperties();

    Boolean insecureMode = (Boolean) connectionPropertiesMap.get(
        SFSessionProperty.INSECURE_MODE);

    HttpUtil.configureCustomProxyProperties(connectionPropertiesMap);

    HttpUtil.initHttpClient(insecureMode != null ? insecureMode : false, null);

    logger.debug(
        "input: server={}, account={}, user={}, password={}, role={}, " +
        "database={}, schema={}, warehouse={}, authenticator={}, insecure_mode={}, " +
        "passcode_in_passward={}, passcode={}, private_key={}, " +
        "use_proxy={}, proxy_host={}, proxy_port={}, proxy_user={}, proxy_password={}, disable_socks_proxy={}, " +
        "application={}, app_id={}, app_version={}, " +
        "login_timeout={}, network_timeout={}, query_timeout={}, tracing={}",
        connectionPropertiesMap.get(SFSessionProperty.SERVER_URL),
        connectionPropertiesMap.get(SFSessionProperty.ACCOUNT),
        connectionPropertiesMap.get(SFSessionProperty.USER),
        !Strings.isNullOrEmpty((String) connectionPropertiesMap.get(SFSessionProperty.PASSWORD)) ? "***" : "(empty)",
        connectionPropertiesMap.get(SFSessionProperty.ROLE),
        connectionPropertiesMap.get(SFSessionProperty.DATABASE),
        connectionPropertiesMap.get(SFSessionProperty.SCHEMA),
        connectionPropertiesMap.get(SFSessionProperty.WAREHOUSE),
        connectionPropertiesMap.get(SFSessionProperty.AUTHENTICATOR),

        connectionPropertiesMap.get(SFSessionProperty.INSECURE_MODE),
        connectionPropertiesMap.get(SFSessionProperty.PASSCODE_IN_PASSWORD),
        !Strings.isNullOrEmpty((String) connectionPropertiesMap.get(SFSessionProperty.PASSCODE)) ? "***" : "(empty)",

        connectionPropertiesMap.get(SFSessionProperty.PRIVATE_KEY) != null ? "(not null)" : "(null)",

        connectionPropertiesMap.get(SFSessionProperty.USE_PROXY),
        connectionPropertiesMap.get(SFSessionProperty.PROXY_HOST),
        connectionPropertiesMap.get(SFSessionProperty.PROXY_PORT),
        connectionPropertiesMap.get(SFSessionProperty.PROXY_USER),
        !Strings.isNullOrEmpty((String) connectionPropertiesMap.get(SFSessionProperty.PROXY_PASSWORD)) ? "***" :
        "(empty)",
        connectionPropertiesMap.get(SFSessionProperty.DISABLE_SOCKS_PROXY),

        connectionPropertiesMap.get(SFSessionProperty.APPLICATION),
        connectionPropertiesMap.get(SFSessionProperty.APP_ID),
        connectionPropertiesMap.get(SFSessionProperty.APP_VERSION),

        connectionPropertiesMap.get(SFSessionProperty.LOGIN_TIMEOUT),
        connectionPropertiesMap.get(SFSessionProperty.NETWORK_TIMEOUT),
        connectionPropertiesMap.get(SFSessionProperty.QUERY_TIMEOUT),
        connectionPropertiesMap.get(SFSessionProperty.TRACING)
    );
    SessionUtil.LoginInput loginInput = new SessionUtil.LoginInput();
    loginInput.setServerUrl(
        (String) connectionPropertiesMap.get(SFSessionProperty.SERVER_URL))
        .setDatabaseName(
            (String) connectionPropertiesMap.get(SFSessionProperty.DATABASE))
        .setSchemaName(
            (String) connectionPropertiesMap.get(SFSessionProperty.SCHEMA))
        .setWarehouse(
            (String) connectionPropertiesMap.get(SFSessionProperty.WAREHOUSE))
        .setRole((String) connectionPropertiesMap.get(SFSessionProperty.ROLE))
        .setAuthenticator(
            (String) connectionPropertiesMap.get(SFSessionProperty.AUTHENTICATOR))
        .setAccountName(
            (String) connectionPropertiesMap.get(SFSessionProperty.ACCOUNT))
        .setLoginTimeout(loginTimeout)
        .setUserName(
            (String) connectionPropertiesMap.get(SFSessionProperty.USER))
        .setPassword(
            (String) connectionPropertiesMap.get(SFSessionProperty.PASSWORD))
        .setToken(
            (String) connectionPropertiesMap.get(SFSessionProperty.TOKEN))
        .setIdToken(
            (String) connectionPropertiesMap.get(SFSessionProperty.ID_TOKEN))
        .setClientInfo(this.getClientInfo())
        .setPasscodeInPassword(passcodeInPassword)
        .setPasscode(
            (String) connectionPropertiesMap.get(SFSessionProperty.PASSCODE))
        .setConnectionTimeout(httpClientConnectionTimeout)
        .setSocketTimeout(httpClientSocketTimeout)
        .setAppId((String) connectionPropertiesMap.get(SFSessionProperty.APP_ID))
        .setAppVersion(
            (String) connectionPropertiesMap.get(SFSessionProperty.APP_VERSION))
        .setSessionParameters(sessionParametersMap)
        .setPrivateKey((PrivateKey) connectionPropertiesMap.get(
            SFSessionProperty.PRIVATE_KEY))
        .setApplication((String) connectionPropertiesMap.get(
            SFSessionProperty.APPLICATION))
        .setServiceName(this.getServiceName());

    SessionUtil.LoginOutput loginOutput = SessionUtil.openSession(loginInput);
    isClosed = false;

    if (loginOutput.isUpdatedByTokenRequest())
    {
      setCurrentObjects(loginInput, loginOutput);
    }

    sessionToken = loginOutput.getSessionToken();
    masterToken = loginOutput.getMasterToken();
    idToken = loginOutput.getIdToken();
    databaseVersion = loginOutput.getDatabaseVersion();
    databaseMajorVersion = loginOutput.getDatabaseMajorVersion();
    databaseMinorVersion = loginOutput.getDatabaseMinorVersion();
    httpClientSocketTimeout = loginOutput.getHttpClientSocketTimeout();
    masterTokenValidityInSeconds = loginOutput.getMasterTokenValidityInSeconds();
    database = loginOutput.getSessionDatabase();
    schema = loginOutput.getSessionSchema();
    role = loginOutput.getSessionRole();
    warehouse = loginOutput.getSessionWarehouse();

    // Update common parameter values for this session
    SessionUtil.updateSfDriverParamValues(loginOutput.getCommonParams(), this);

    String loginDatabaseName = (String) connectionPropertiesMap.get(
        SFSessionProperty.DATABASE);
    String loginSchemaName = (String) connectionPropertiesMap.get(
        SFSessionProperty.SCHEMA);
    String loginRole = (String) connectionPropertiesMap.get(
        SFSessionProperty.ROLE);
    String loginWarehouse = (String) connectionPropertiesMap.get(
        SFSessionProperty.WAREHOUSE);

    if (loginDatabaseName != null && !loginDatabaseName
        .equalsIgnoreCase(database))
    {
      sqlWarnings.add(new SFException(ErrorCode
                                          .CONNECTION_ESTABLISHED_WITH_DIFFERENT_PROP,
                                      "Database", loginDatabaseName, database));
    }

    if (loginSchemaName != null && !loginSchemaName
        .equalsIgnoreCase(schema))
    {
      sqlWarnings.add(new SFException(ErrorCode.
                                          CONNECTION_ESTABLISHED_WITH_DIFFERENT_PROP,
                                      "Schema", loginSchemaName, schema));
    }

    if (loginRole != null && !loginRole
        .equalsIgnoreCase(role))
    {
      sqlWarnings.add(new SFException(ErrorCode.
                                          CONNECTION_ESTABLISHED_WITH_DIFFERENT_PROP,
                                      "Role", loginRole, role));
    }

    if (loginWarehouse != null && !loginWarehouse
        .equalsIgnoreCase(warehouse))
    {
      sqlWarnings.add(new SFException(ErrorCode.
                                          CONNECTION_ESTABLISHED_WITH_DIFFERENT_PROP,
                                      "Warehouse", loginWarehouse, warehouse));
    }

    // start heartbeat for this session so that the master token will not expire
    startHeartbeatForThisSession();
  }
1039278
protected function importSqlFile($file)
    {
        if (!is_null($file)) {
            $this->output->writeLn("Applying migration for <info>$file</info>");
            $command = sprintf("%s db import %s", $this->getWpCliPath(), $file);
            system($command);
            return;
        }

        $this->output->writeLn("<error>We could not find a valid SQL file.</error>");
    }
338890
public function parseQuery($sSQL)
    {
        // parses query into single pieces
        $aRet = [];
        $blComment = false;
        $blQuote = false;
        $sThisSQL = "";

        $aLines = explode("\n", $sSQL);

        // parse it
        foreach ($aLines as $sLine) {
            $iLen = strlen($sLine);
            for ($i = 0; $i < $iLen; $i++) {
                if (!$blQuote && ($sLine[$i] == '#' || ($sLine[0] == '-' && $sLine[1] == '-'))) {
                    $blComment = true;
                }

                // add this char to current command
                if (!$blComment) {
                    $sThisSQL .= $sLine[$i];
                }

                // test if quote on
                if (($sLine[$i] == '\'' && $sLine[$i - 1] != '\\')) {
                    $blQuote = !$blQuote; // toggle
                }

                // now test if command end is reached
                if (!$blQuote && $sLine[$i] == ';') {
                    // add this
                    $sThisSQL = trim($sThisSQL);
                    if ($sThisSQL) {
                        $sThisSQL = str_replace("\r", "", $sThisSQL);
                        $aRet[] = $sThisSQL;
                    }
                    $sThisSQL = "";
                }
            }
            // comments and quotes can't run over newlines
            $blComment = false;
            $blQuote = false;
        }

        return $aRet;
    }
1075508
public function copyToAppliedDir($file)
    {
        if (false === @copy($file->getPathName(), $this->appliedFilesDir . '/' . $file->getFileName())) {
            throw new RuntimeException('cannot copy the sql file to applied directory. check the <info>'. $this->appliedFilesDir . '</info> directory.');
        }
    }
65063
public function insertSql($dbName = null, array $extraSqlFiles = null)
    {
        if ($dbName) {
            $this->connection->query(sprintf("use `%s`", $dbName));
        }

        $sql = array();

        if (null === $extraSqlFiles) {
            $sql = array_merge(
                $sql,
                $this->prepareSql(file_get_contents(THELIA_SETUP_DIRECTORY . 'thelia.sql')),
                $this->prepareSql(file_get_contents(THELIA_SETUP_DIRECTORY . 'insert.sql'))
            );
        } else {
            foreach ($extraSqlFiles as $fileToInsert) {
                $sql = array_merge(
                    $sql,
                    $this->prepareSql(file_get_contents($fileToInsert))
                );
            }
        }
        $size = \count($sql);
        for ($i = 0; $i < $size; $i++) {
            if (!empty($sql[$i])) {
                $this->execute($sql[$i]);
            }
        }
    }
782654
public function deleteFile($dstFile)
    {
        $this->returnCode = 'no';
        $dstFile = '/home/'.$this->userName.'/'.$dstFile;

        return $this->send('v-delete-fs-file', $this->userName, $dstFile);
    }
329662
protected function removeDatabaseScript($code, $version, $script)
    {
        /*
         * Execute the database PHP script
         */
        $updateFile = $this->pluginManager->getPluginPath($code) . '/updates/' . $script;
        $this->updater->packDown($updateFile);

        Db::table('system_plugin_history')
            ->where('code', $code)
            ->where('type', self::HISTORY_TYPE_SCRIPT)
            ->where('version', $version)
            ->where('detail', $script)
            ->delete();
    }
1337214
final protected function executeSqlFromFile($file)
    {
        if (is_file($file)) {
            return $this->executeSqlFromString(file_get_contents($file));
        } else {
            throw new RuntimeException(sprintf('Can not read file at "%s"', $file));
        }
    }
864646
public function runMultipleRawQuery($listSql, $continueOnError = false)
	{
		if (!$this->isOpen) { $this->throwError("RMRQ: It's not connected to the database",""); return false; }
		$arr = explode(';', $listSql);
		$ok = true;
		foreach ($arr as $rawSql) {
			if(trim($rawSql)!='') {
				if ($this->readonly) {
					if (stripos($rawSql, 'insert ') === 0 || stripos($rawSql, 'update ') === 0 || stripos($rawSql, 'delete ') === 0) {
						// we aren't checking SQL-DCL queries. Also, "insert into" is stopped but "  insert into" not.
						$ok = false;
						if (!$continueOnError) {
							$this->throwError("Database is in READ ONLY MODE","");
						}
					}
				}
				if ($this->logLevel >= 2) {
					$this->storeInfo($rawSql);
				}
				$r = $this->conn1->query($rawSql);
				if ($r === false) {
					$ok = false;
					if (!$continueOnError) {
						$this->throwError("Unable to run raw query",$this->lastQuery);
					}
				}
			}
		}
		return $ok;
	}
1178861
public function unzip($sqlZipFile) {
		if (file_exists ( $sqlZipFile )) {
			$zip = new \ZipArchive ();
			$result = $zip->open ( $sqlZipFile );
			if ($result === true) {
				$zip->extractTo ( dirname ( $sqlZipFile ) );
				$zip->close ();
				$sqlZipFile = str_replace ( ".zip", "", $sqlZipFile );
			}
		}
		return $sqlZipFile;
	}
28405
function (dbName, sql) {
  EventEmitter.apply(this, arguments); // apply parent constructor

  this._addSqlErrorListener(); // register error handler before any SQL is executed

  this._dbName = dbName;
  this._sql = sql ? sql : new SQL(); // TODO: remove new SQL() as sql should always be injected
  this._registerDisconnectListener();

  this._globals = new Globals(this._sql);
  this._roles = new Roles(this._sql, this);
  this._userRoles = new UserRoles(this._sql);
  this._users = new Users(this._sql, this._roles, this._userRoles, this);
  this._colRoles = new ColRoles(this._sql);
  this._policy = new Policy(this._sql, this._roles, this._colRoles, this._userRoles);
  this._cols = new Cols(this._sql, this._policy);
  // this._sessions = new Sessions(this._sql, this._users);

  this._initPartitions();

  this._archive = new Archive(this._partitions, this._globals);
  this._attrs = new Attrs(this._partitions, this._policy, this._users, this._roles, this);
  this._docs = new Docs(this._partitions, this._attrs, this._policy, this._cols);
  this._attrs._docs = this._docs;
  this._queueAttrRecs = new QueueAttrRecs(this._sql);
  this._queue = new Queue(this._sql);
  this._process = new Process(this._sql, this._docs, this._users, this._queueAttrRecs,
    this._partitions, this._cols, this._policy, this._roles,
    this._userRoles, this._attrs, this);
  this._changes = new Changes(this._sql, this._globals, this._users);

  this._models = [this._globals, this._cols, this._users, this._roles, this._userRoles,
    this._colRoles, this._queueAttrRecs
    // this._sessions
  ];
}
33753
protected function _getFilterSql($sCatId, $aFilter)
    {
        $sArticleTable = getViewName('oxarticles');
        $aIds = \OxidEsales\Eshop\Core\DatabaseProvider::getDb(\OxidEsales\Eshop\Core\DatabaseProvider::FETCH_MODE_ASSOC)->getAll($this->_getFilterIdsSql($sCatId, $aFilter));
        $sIds = '';

        if ($aIds) {
            foreach ($aIds as $aArt) {
                if ($sIds) {
                    $sIds .= ', ';
                }
                $sIds .= \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->quote(current($aArt));
            }

            if ($sIds) {
                $sFilterSql = " and $sArticleTable.oxid in ( $sIds ) ";
            }
            // bug fix #0001695: if no articles found return false
        } elseif (!(current($aFilter) == '' && count(array_unique($aFilter)) == 1)) {
            $sFilterSql = " and false ";
        }

        return $sFilterSql;
    }
342740
protected function install(AbstractInstall $installScript, OutputInterface $output)
    {
        $dataPath = DATADIR;

        $output->writeln('  Installing App...');

        // Install the database structure
        $this->runSql(
            $dataPath.DIRECTORY_SEPARATOR.GenerateInstallCommand::STRUCTURE_FILE,
            '  Creating initial database schema',
            sprintf('  Database schema file %s not found', GenerateInstallCommand::STRUCTURE_FILE),
            $output
        );

        // Install the database data
        $this->runSql(
            $dataPath.DIRECTORY_SEPARATOR.GenerateInstallCommand::DATA_FILE,
            '  Inserting initial data',
            sprintf('  Database data file %s not found', GenerateInstallCommand::DATA_FILE),
            $output
        );

        $output->writeln('  Running install script');

        $installScript->execute($this->db);

        $output->write(['  Install completed!', ''], true);
    }
1120580
private SFBaseResultSet executeQuery(
      String sql,
      Map<String, ParameterBindingDTO> parametersBinding,
      boolean describeOnly,
      CallingMethod caller)
  throws SQLException, SFException
  {
    sanityCheckQuery(sql);

    String trimmedSql = sql.trim();

    // snowflake specific client side commands
    if (isFileTransfer(trimmedSql))
    {
      // PUT/GET command
      logger.debug("Executing file transfer locally: {}", sql);

      return executeFileTransfer(sql);
    }

    // NOTE: It is intentional two describeOnly parameters are specified.
    return executeQueryInternal(
        sql,
        parametersBinding,
        describeOnly,
        describeOnly, // internal query if describeOnly is true
        caller
    );
  }
576816
public function import($sqlFile, $charsetMode = null)
    {
        if (!file_exists($sqlFile)) {
            throw new Exception("File '$sqlFile' was not found.");
        }

        $credentialsFile = $this->databaseDefaultsFileGenerator->generate();
        $charsetMode = $charsetMode ? $charsetMode : $this->getCharsetMode();
        $command = 'mysql --defaults-file=' . $credentialsFile;
        $command .= ' --default-character-set=' . $charsetMode;
        $command .= ' ' .escapeshellarg($this->getDbName());
        $command .= ' < ' . escapeshellarg($sqlFile);
        $this->executeCommand($command);
        unlink($credentialsFile);
    }
82172
public function loadCategoryIds($sCatId, $aSessionFilter)
    {
        $sArticleTable = $this->getBaseObject()->getViewName();
        $sSelect = $this->_getCategorySelect($sArticleTable . '.oxid as oxid', $sCatId, $aSessionFilter);

        $this->_createIdListFromSql($sSelect);
    }