Build a new Backup Engine object.

@param array  $options
@param string $database

@throws BackupException

@return \Cornford\Backup\Contracts\BackupEngineInterface
519426
public function buildBackupEngine(
		array $options = [],
		$database = null
	) {
		$backupProcessInstance = new BackupProcess(new Process(''));

		switch ($database ? $database : $options['default'])
		{
			case 'mysql':
				return new BackupEngineMysql(
					$backupProcessInstance,
					$options['connections'][$options['default']]['database'],
					$options['connections'][$options['default']]['host'],
					isset($options['connections'][$options['default']]['port']) ? $options['connections'][$options['default']]['port'] : 3306,
					$options['connections'][$options['default']]['username'],
					$options['connections'][$options['default']]['password'],
					$options
				);
			case 'pgsql':
				return new BackupEnginePgsql(
					$backupProcessInstance,
					$options['connections'][$options['default']]['database'],
					$options['connections'][$options['default']]['host'],
					null,
					$options['connections'][$options['default']]['username'],
					$options['connections'][$options['default']]['password'],
					$options
				);
			case 'sqlite':
				return new BackupEngineSqlite(
					$backupProcessInstance,
					$options['connections'][$options['default']]['database'],
					null,
					null,
					null,
					null,
					$options
				);
			case 'sqlsrv':
				return new BackupEngineSqlsrv(
					$backupProcessInstance,
					$options['connections'][$options['default']]['database'],
					$options['connections'][$options['default']]['host'],
					null,
					$options['connections'][$options['default']]['username'],
					$options['connections'][$options['default']]['password'],
					$options
				);
			default:
				throw new BackupException('Database driver isn\'t supported.');
		}
	}
27087
public function database(string $database = null): MongoDatabase
    {
        if (empty($database)) {
            $database = $this->config->defaultDatabase();
        }

        //Spiral support ability to link multiple virtual databases together using aliases
        $database = $this->config->resolveAlias($database);

        if (isset($this->databases[$database])) {
            return $this->databases[$database];
        }

        if (!$this->config->hasDatabase($database)) {
            throw new ODMException(
                "Unable to initiate MongoDatabase, no presets for '{$database}' found"
            );
        }

        $options = $this->config->databaseOptions($database);

        //Initiating database instance
        return $this->createDatabase(
            $database,
            $options['server'],
            $options['database'],
            $options['driverOptions'] ?? [],
            $options['options'] ?? []
        );
    }
1107523
private function executeCommand(array $command, array $options)
    {
        return $this
            ->getCommandExecutor()
            ->executeCommand(
                $this->manager,
                $this->databaseName,
                $command,
                $options
            );
    }
353851
protected function prepareConstructOption($options) {
        if ($options instanceof DatabaseConfiguration) {
            $options = $options->toArray();
        }
        $opts          = array_merge([
            'encoding'       => 'UTF8',
            'dbname'         => ':memory:',
            'host'           => 'localhost',
            'port'           => 3306,
            'user'           => 'root',
            'password'       => 'root',
            'driver_options' => []
        ], $options);
        $charset       = isset ($opts ['encoding']) && !empty ($opts ['encoding']) ? $opts ['encoding'] : 'UTF8';
        $dsn           = "sqlite:{$opts['dbname']}";
        $this->charset = $charset;

        return [$dsn, $opts ['user'], $opts ['password'], $opts ['driver_options']];
    }
1190431
public String create(SubscriptionCreationOptions options, String database) {
        if (options == null) {
            throw new IllegalArgumentException("Cannot create a subscription if options is null");
        }

        if (options.getQuery() == null) {
            throw new IllegalArgumentException("Cannot create a subscription if the script is null");
        }

        RequestExecutor requestExecutor = _store.getRequestExecutor(ObjectUtils.firstNonNull(database, _store.getDatabase()));

        CreateSubscriptionCommand command = new CreateSubscriptionCommand(_store.getConventions(), options);
        requestExecutor.execute(command);

        return command.getResult().getName();
    }
263483
public function databaseBackup($environmentUuid, $dbName, $backupId)
    {
        return new BackupResponse(
            $this->connector->request(
                'get',
                "/environments/${environmentUuid}/databases/${dbName}/backups/${backupId}",
                $this->query
            )
        );
    }
989033
private function create($options = [])
	{
		$this->before_create();

		$statement = 'INSERT INTO ' . static::$table_name . ' (';

		if (isset($options['include_primary_key'])) {
			$statement .= implode(', ', $this->_keys(false, true)) . ') VALUES (';
			$values = $this->_values(false);
		} else {
			$statement .= implode(', ', $this->_keys(true, true)) . ') VALUES (';
			$values = $this->_values();
		}

		$value_set = [];

		foreach ($values as $value) {
			$value_set[] = '?';
		}

		$statement .= implode(', ', $value_set) . ')';

		$result = $this->db->query($statement, $values, 'last_id');

		/* NOTE: PDO's lastInsertId does not work with PostgreSQL unless we supply
		 *       the sequence name. This is a hack to circumvent this.
		 *
		 *       Also: it would be nice to handle this in the DB wrapper, but
		 *       unfortunately we don't have any information about the query or table
		 *       there, so the hack has to stay here for now.
		 */
		if ('pgsql' === $this->db->type()) {
			$result = $this->db->lastInsertId(static::$table_name . '_id_seq');
		}

		$this->stored = true;
		$this->updated = false;
		$this->id = $result;

		$this->after_create();

		return true;
	}
601660
public function getBackupInstance($database = null)
	{
		$configuration = array_merge($this->getConfig('database'), $this->getConfig('backup::config'));
		$this->backupInstance = $this->backupFactory->build($configuration, $database);

		return $this->backupInstance;
	}
196584
public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addModelTransformer(new CallbackTransformer(
            function ($original) {
                $tree = $this->blockService->getTree($original);

                return json_encode($tree);
            },
            function ($submitted) {
                $array = json_decode($submitted, true);

                $stripped = $this->stripMetadata($array);

                return trim(json_encode($stripped));
            }
        ));
    }
171671
public function prepare($statement, $options = null)
    {
        $options = is_null($options) ? [] : $options;
        if (strpos($statement, ':') !== false) {
            $i = 0;
            $bindKeyMap = [];
            $statement = preg_replace_callback('/:([a-zA-Z_]\w*?)\b/', function ($matches) use (&$i, &$bindKeyMap) {
                $bindKeyMap[$matches[1]] = $i++;

                return '?';
            }, $statement);
        }

        $stmtObj = $this->client->prepare($statement);

        if ($stmtObj) {
            $stmtObj->bindKeyMap = $bindKeyMap ?? [];

            return new PDOStatement($this, $stmtObj, $options);
        } else {
            $statementException = new StatementException($this->client->error, $this->client->errno);
            throw new QueryException($statement, [], $statementException);
        }
    }
337152
public function prepare($sql, $options = null)
    {

        $md5 = md5($sql);

        if (isset($this->prepared_sql[$md5])) {
            return $this->prepared_sql[$md5];
        }

        //$this->writeToLog("Preparing: ".$sql);
        $stmt = parent::prepare($sql);
        $this->prepared_sql[$md5] = $stmt;
        return $stmt;
    }
335910
public static function createDbo($driver, array $options)
    {
        // Sanitize the database connector options.
        $options['driver'] = preg_replace('/[^A-Z0-9_\.-]/i', '', $driver);
        $options['database'] = $options['database'] ?? null;
        $options['select'] = $options['select'] ?? true;

        // Use custom Resource
        $resource = $options['resource'] ?? null;

        // Derive the class name from the driver.
        $class = '\\Windwalker\\Database\\Driver\\' . ucfirst(strtolower($options['driver'])) . '\\'
            . ucfirst(strtolower($options['driver'])) . 'Driver';

        // If the class still doesn't exist we have nothing left to do but throw an exception.  We did our best.
        if (!class_exists($class)) {
            throw new \RuntimeException(sprintf('Unable to load Database Driver: %s', $options['driver']));
        }

        /** @var DatabaseDriverInterface $class */
        if (!$class::isSupported()) {
            throw new \RangeException('Database driver ' . $driver . ' not supported.');
        }

        // Create our new Driver connector based on the options given.
        try {
            $instance = new $class($resource, $options);
        } catch (\RuntimeException $e) {
            throw new \RuntimeException(sprintf('Unable to connect to the Database: %s', $e->getMessage()));
        }

        return $instance;
    }
1227100
protected function buildDatabase(array $options)
    {
        return (new Database())
            ->setPort($options['db-port'])
            ->setUser($options['db-user'])
            ->setPassword($options['db-pass'])
            ->setDatabase($options['db-name'])
            ->setHostname($options['db-host'])
            ->setProtocol($options['db-protocol']);
    }
1280126
static public function connect(Application $app,
                                   $dsn,
                                  $username,
                                  $password,
                                  $options = [])
    {
        $options += [
            \PDO::ATTR_ERRMODE =>\PDO::ERRMODE_EXCEPTION,
            \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES'utf8';",
            \PDO::MYSQL_ATTR_FOUND_ROWS => true
        ];

        $connection = new \PDO($dsn, $username, $password, $options);
        return new DB($app, $connection);
    }
1248489
public function getConnection(?string $connection = 'local', array $options = []): AbstractDatabaseDriver
    {
        $key = 'connection.' . $connection;

        if (!$this->container->has($key)) {
            $this->container->share($key, $this->createConnection($connection, $options));
        }

        return $this->container->get($key);
    }
145771
public function createBackuper(array $metaEnities = null): Backuper {
		return new PgsqlBackuper($this->dbh, $this->createDatabase(), $metaEnities);
	}
1264605
static public function install($options, $sql, $adapterNamespace)
    {
        $adapterNamespace = !empty($adapterNamespace) ? $adapterNamespace : self::$adapterNamespace;
        $options['adapter']   = preg_replace('/[^A-Z0-9_\.-]/i', '', $options['adapter']);
        $class = self::$adapterNamespace . ucfirst(strtolower($options['adapter'])) . 'Adapter';
        
        if (!class_exists($class)) {
            throw new DbException('The database adapter ' . $class . ' is not valid.');
        }
        // If Sqlite
        if ( strtolower($options['adapter']) == 'sqlite' || strtolower($options['adapter']) == 'pdo') {
            if (!file_exists($options['database'])) {
                touch($options['database']);
                chmod($options['database'], 0777);
            }
            if (!file_exists($options['database'])) {
                throw new DbException('Could not create the database file.');
            }
        }
        
        $conn  = new $class($options);
        $lines = file($sql);
        
        // Remove comments, execute queries
        if (count($lines) > 0) {
            $insideComment = false;
            foreach ($lines as $i => $line) {
                if ($insideComment) {
                    if (substr($line, 0, 2) == '*/') {
                        $insideComment = false;
                    }
                    unset($lines[$i]);
                } else {
                    if ((substr($line, 0, 1) == '-') || (substr($line, 0, 1) == '#')) {
                        unset($lines[$i]);
                    } else if (substr($line, 0, 2) == '/*') {
                        $insideComment = true;
                        unset($lines[$i]);
                    }
                }
            }
            
            $sqlString  = trim(implode('', $lines));
            $newLine    = (strpos($sqlString, ";\r\n") !== false) ? ";\r\n" : ";\n";
            $statements = explode($newLine, $sqlString);
            
            foreach ($statements as $statement) {
                if (!empty($statement)) {
                    if (isset($options['table_prefix'])) {
                        $statement = str_replace('[{table_prefix}]', $options['table_prefix'], trim($statement));
                    }
                    $conn->query($statement);
                }
            }
        }
    }