Backup current DB to file local/backup/update.sql
@return bool if it succeeds, false otherwise
@throws \Exception
325763
public function backupDb()
    {
        $database = new Database($this->connection);

        if (! $this->checkBackupIsPossible()) {
            $message = 'Your database is too big for an automatic backup';

            $this->log('error', $message);

            throw new UpdateException($message);
        }

        $this->backupFile = THELIA_ROOT . $this->backupDir . 'update.sql';
        $backupDir = THELIA_ROOT . $this->backupDir;

        $fs = new Filesystem();

        try {
            $this->log('debug', sprintf('Backup database to file : %s', $this->backupFile));

            // test if backup dir exists
            if (!$fs->exists($backupDir)) {
                $fs->mkdir($backupDir);
            }

            if (!is_writable($backupDir)) {
                throw new \RuntimeException(sprintf('impossible to write in directory : %s', $backupDir));
            }

            // test if backup file already exists
            if ($fs->exists($this->backupFile)) {
                // remove file
                $fs->remove($this->backupFile);
            }

            $database->backupDb($this->backupFile);
        } catch (\Exception $ex) {
            $this->log('error', sprintf('error during backup process with message : %s', $ex->getMessage()));
            throw $ex;
        }
    }
397300
protected function createSnapshot() {
		// Mark self as creating a snapshot
		$this->Status = 'Started';
		$this->Doing = 'Snapshot';
		$this->log("{$this->Title} creating snapshot of database");
		$this->write();

		// Skip deployment for dry run
		if($this->Pipeline()->DryRun) {
			$this->log("[Skipped] Create DNDataTransfer backup");
			return true;
		}

		// Skip snapshot for environments with no build
		if(!$this->Pipeline()->Environment()->CurrentBuild()) {
			$this->log('[Skipped] No current build, skipping snapshot');
			return true;
		}

		// create a snapshot
		$pipeline = $this->Pipeline();
		$job = DNDataTransfer::create();
		$job->EnvironmentID = $pipeline->EnvironmentID;
		$job->Direction = 'get';
		$job->Mode = 'db';
		$job->DataArchiveID = null;
		$job->AuthorID = $pipeline->AuthorID;
		$job->write();
		$job->start();

		$pipeline->PreviousSnapshotID = $job->ID;
		$pipeline->write();

		return true;
	}
1324346
public function exec() {
        try {
            $query = $this->db->prepare($this->q->get());
            $this->bindValues($query);
            $query->execute();

            // Set the last inserted id but only
            // of $this->db->lastInsertId() is not empty
            if (!empty($this->db->lastInsertId())) {
                $this->lastInsertId = $this->db->lastInsertId();
            }

            $this->clear();

            return true;
        } catch (\PDOException $e) {
            $this->setError('d', $e->getMessage());
            return false;
        }
    }
89526
public function update()
    {
        // convert to condition.
        $args = func_get_args();
        $attributes = array_shift($args);
        $cond = call_user_func_array(array($this, 'toCondition'), $args);

        // to SQL.
        $sql = $cond->toUpdateSQL($attributes);
        var_dump($sql, $cond->getParams());

        // query.
        $sth = $this->query($sql, $cond->getParams());
        return $sth->isSuccess();
    }
357824
public function commit()
    {
        try {
            $toUpdate = array_merge($this->getFieldsToUpdate(), $this->getFieldsToDelete());

            if (! empty($toUpdate)) {
                $idField  = $this->_item->getIdField();

                $query = "
                    UPDATE
                        `" . $this->getDbPrefix() . $this->_item->getDbContainer() . "`
                    SET
                        " . $this->_getPreparedFields($toUpdate) . "
                    WHERE
                        `$idField` = ?";

                if (! array_key_exists($idField, $toUpdate)) {
                    $toUpdate[$idField] = $this->_item->getId()->getOrig();
                }

                $prepared = Agl::app()->getDb()->getConnection()->prepare($query);

                if (! $prepared->execute(array_values($toUpdate))) {
                    $error = $prepared->errorInfo();
                    throw new Exception("The update query failed (table '" . $this->getDbPrefix() . $this->_item->getDbContainer() . "') with message '" . $error[2] . "'");
                }

                if (Agl::app()->isDebugMode()) {
                    Agl::app()->getDb()->incrementCounter();
                }

                return $prepared->rowCount();
            }
        } catch (Exception $e) {
            throw new Exception($e);
        }

        return true;
    }
127863
public function commit()
    {
        switch ($this->mode) {

            case "mysql":
                $result = $this->server->commit();
                break;

            case "postgres":
            case "redshift":
                $result = $this->query("COMMIT");
                break;

            case "odbc":
                $result = odbc_commit($this->server);
                break;

            default:
                throw new \Exception("commit() not supported in this mode (" . $this->mode . ")");
        }

        if (!$result) {
            $this->error();
        }

        return true;
    }
654443
public function save(): bool
	{
		$success = true;

		if(!$this->isPersisted)
		{
			// This is a new record so we need to insert it into the database.

			$this->insertRecord($this->builder());

			$this->isPersisted = true;
		}
		elseif($this->isModified())
		{
			// This record exists and is modified so all we have to do is update it.

			$success = $this->updateRecord($this->builder());
		}

		if($success)
		{
			// Sync up if save was successful

			$this->synchronize();
		}

		return $success;
	}
920947
public function rollback(): bool {
        if ($this->transactionExists) {
            $rolledBack = $this->pdo->rollBack();
            $this->transactionExists = !$rolledBack;
            return $rolledBack;
        }
        return false;
    }
89203
protected function backupComposer()
    {
        $composerDir = $this->composer->getVendorDirectory() . '/composer';
        $composerBak = $composerDir . '.bak';

        // Remove old backup folder.
        if (is_dir($composerBak)) {
            $process = new Process('rm -rf "' . $composerBak . '"');
            $process->run();
            $isSuccessful = $process->isSuccessful();

            unset($process);

            if (!$isSuccessful) {
                return false;
            }
        }

        // Backup
        $process = new Process('cp -R "' . $composerDir . '" "' . $composerBak . '"');
        $process->run();
        $isSuccessful = $process->isSuccessful();

        unset($process);

        return $isSuccessful;
    }
244469
public function Backup_Init()
    {
        $sql = "-- -----------------------------\n";
        $sql .= "-- Think MySQL Data Transfer \n";
        $sql .= "-- \n";
        $sql .= "-- Host     : " . $this->dbconfig['hostname'] . "\n";
        $sql .= "-- Port     : " . $this->dbconfig['hostport'] . "\n";
        $sql .= "-- Database : " . $this->dbconfig['database'] . "\n";
        $sql .= "-- \n";
        $sql .= "-- Part : #{$this->file['part']}\n";
        $sql .= "-- Date : " . date("Y-m-d H:i:s") . "\n";
        $sql .= "-- -----------------------------\n\n";
        $sql .= "SET FOREIGN_KEY_CHECKS = 0;\n\n";
        return $this->write($sql);
    }
129503
private function makeBackup()
    {
        if ((null === $this->backupFile) || !file_exists($this->filename)) {
            return;
        }

        if (!is_dir(dirname($this->backupFile))) {
            mkdir(dirname($this->backupFile), 0700, true);
        }

        copy($this->filename, $this->backupFile);
    }
51383
private function backup()
    {
        if (! $this->disk->exists(storage_path('langmanGUI'))) {
            $this->disk->makeDirectory(storage_path('langmanGUI'));

            $this->disk->put(storage_path('langmanGUI'.'/.gitignore'), "*\n!.gitignore");
        }

        $this->disk->copyDirectory(resource_path('lang'), storage_path('langmanGUI/'.time()));
    }
1287259
def backup_db():
    
    if not os.path.exists('backups'):
        os.makedirs('backups')
    local('python manage.py dump_database | gzip > backups/' + _sql_paths('local', datetime.now()))
884402
protected function doExecute()
    {
        if ($this->console->getMode() !== 'dev') {
            throw new \RuntimeException(
                '<error>STOP!</error> please run <info>' . $this->getEnvCmd() . '</info>.'
            );
        }

        if (!(new BooleanPrompter())
            ->ask('This action will drop all tables, do you really want to do this? [N/y]', false)) {
            $this->out('  Canceled.');

            return false;
        }

        if (!$this->io->getOption('no-backup')) {
            // backup
            $this->backup();
        }

        $db = $this->console->database;

        $tables = $db->getDatabase()->getTables(true);

        foreach ($tables as $table) {
            $db->getTable($table, true)->drop(true);

            $this->out('  Drop table: <comment>' . $table . '</comment>');
        }

        return true;
    }
246877
public function createBackup()
    {
        $this->output->outputLine();

        if ( !file_exists($this->createFilePath([$this->localBackupTarget, 'key'])) ) {
            $this->output->outputLine('<b>You don\'t have a keyfile!</b>');
            $this->output->outputLine();
            $this->output->outputLine('Call \'./flow backup:key\' to to generate it.');
            $this->output->outputLine();
            return;
        }

        $this->output->outputLine('<b>Prepare Backup</b>');
        $this->output->outputLine();

        $this->emitBackupStarted();
        $newVersion = time();

        $stats = array(
            'checked' => 0,
            'added' => 0,
            'updated' => 0,
            'removed' => 0,
        );

        $this->collectSystemSettings();

        $this->dumpDatabase();

        foreach ($this->backupFolders as $folderIndex => $folder) {
            $relativeFolder = $this->getPathByFlowRoot($folder);

            $this->output->outputLine('<b>'.($folderIndex+1).'/'.count($this->backupFolders).' Backup '.$relativeFolder.'</b>');
            $this->output->outputLine();
            $this->output->outputLine('Load Backup Versions..');

            $latestFlatBackup = $this->getFlatBackup($folder);
            $newBackupClean = $this->getBackupActions($folder, $newVersion, $latestFlatBackup);
            $stats['checked'] = $stats['checked'] + count($latestFlatBackup);

            if ( count($newBackupClean)>0 ) {
                // encrypt and create backup..
                $this->files->createDirectoryRecursively($this->createDirectoryPath([$this->localBackupTarget, $newVersion, $relativeFolder]));
                $this->output->outputLine('Backup Files..');
                $this->output->progressStart(count($newBackupClean));
                $i = 0;
                foreach ($newBackupClean as $sha1 => $fileItem) {
                    if ($fileItem['action'] == 'add' || $fileItem['action'] == 'update') {
                        if ($fileItem['action'] == 'add') {
                            $stats['added']++;
                        } else {
                            $stats['updated']++;
                        }

                        $this->cryptService->encryptFileToFile(
                            $this->createFilePath([FLOW_PATH_ROOT, $fileItem['file']]),
                            $this->createFilePath([$this->localBackupTarget, $newVersion, $relativeFolder, $sha1 . '.file']));
                        file_put_contents(
                            $this->createFilePath([$this->localBackupTarget, $newVersion, $relativeFolder, $sha1 . '.meta']),
                            json_encode($fileItem));

                    } else {
                        if ($fileItem['action'] == 'remove') {
                            $stats['removed']++;

                            file_put_contents(
                                $this->createFilePath([$this->localBackupTarget, $newVersion, $relativeFolder, $sha1 . '.meta']),
                                json_encode($fileItem));
                        }
                    }
                    $i++;
                    $this->output->progressSet($i);
                }
                $this->output->progressFinish();
                $this->output->outputLine();
            }
        }

        if ( file_exists($this->createDirectoryPath([$this->localBackupTarget, $newVersion])) ) {
            $this->meta['version'] = $newVersion;
            $now = new \DateTime();
            $this->meta['timestamp'] = $now->getTimestamp();
            $this->meta['stats'] = $stats;
            file_put_contents($this->createFilePath([$this->localBackupTarget, $newVersion, 'info.meta']),
                json_encode($this->meta, JSON_PRETTY_PRINT));
        }

        $this->deleteTempFolders();

        $this->removeOldBackups();

        $this->output->outputLine('<b>Backup Finished</b>');
        $this->output->outputLine(' - Checked: '.$stats['checked']);
        $this->output->outputLine(' - Added:   '.$stats['added']);
        $this->output->outputLine(' - Updated: '.$stats['updated']);
        $this->output->outputLine(' - Removed: '.$stats['removed']);
        $this->output->outputLine();
        $this->emitBackupFinished($this->output, $stats);
        return;
    }
89261
protected function continueRevertDatabase() {
		$this->log("Checking status of {$this->Title}...");

		// Skip snapshot for dry run
		if($this->Pipeline()->DryRun) {
			$this->log("[Skipped] Checking progress of snapshot restore");
			return $this->finish();
		}

		// Get related snapshot
		$transfer = $this->RollbackDatabase();
		if(empty($transfer) || !$transfer->exists()) {
			$this->log("Missing database transfer for in-progress {$this->Title}");
			$this->markFailed();
			return false;
		}

		// Check finished state
		$status = $transfer->ResqueStatus();
		if($this->checkResqueStatus($status)) {
			// Re-enable the site by disabling the maintenance, since the DB restored successfully
			$this->Pipeline()->Environment()->disableMaintenance($this->Pipeline()->getLogger());

			// After revert is complete we are done
			return $this->finish();
		}
	}
427770
public function execute()
    {
        try {
            $opts = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
            $pdo  = new PDO('mysql:host=' . $this->host, $this->user, $this->pass, $opts);

            foreach ($this->queries as $query) {
                if (!is_array($query)) {
                    // Simple query
                    $pdo->query($this->phpci->interpolate($query));
                } elseif (isset($query['import'])) {
                    // SQL file execution
                    $this->executeFile($query['import']);
                } else {
                    throw new \Exception(Lang::get('invalid_command'));
                }
            }
        } catch (\Exception $ex) {
            $this->phpci->logFailure($ex->getMessage());
            return false;
        }
        return true;
    }