Find migrations and execute them in order.

.. warning:: Use ";" semicolon between full statements. If you leave empty statement
between two semilocons MySQL ->exec() seems to fail.
963148
public function migrate()
    {
        // find migrations
        $folders = $this->app->pathfinder->search('dbupdates', '', 'path');
        // todo - sort files in folders
        foreach ($folders as $dir) {
            $files = scandir($dir);
            sort($files);
            foreach ($files as $name) {
                if (strtolower(substr($name, -4)) != '.sql') {
                    continue;
                }
                $q = $this->db->dsql()
                    ->table('_db_update')
                    ->where('name', strtolower($name))
                    ->field('status');
                if ($q->getOne() === 'ok') {
                    continue;
                }
                $migration = file_get_contents($dir.'/'.$name);
                $q->set('name', strtolower($name));
                try {
                    $this->db->dbh->exec($migration);
                    $q->set('status', 'ok')->replace();
                } catch (Exception $e) {
                    $q->set('status', 'fail')->replace();
                    if (!$e instanceof BaseException) {
                        $e = $this->exception()
                            ->addMoreInfo('Original error', $e->getMessage());
                    }
                    throw $e->addMoreInfo('file', $name);
                }
            }
        }

        return $this;
    }
239300
public function execute() {
        global $DB;

        $userid = $this->get_custom_data()->userid;

        // Get the user's preference.
        $hasbeenmigrated = get_user_preferences('core_message_migrate_data', false, $userid);

        if (!$hasbeenmigrated) {
            // To determine if we should update the preference.
            $updatepreference = true;

            // Get all the users the current user has received a message from.
            $sql = "SELECT DISTINCT(useridfrom)
                      FROM {message} m
                     WHERE useridto = ?
                     UNION
                    SELECT DISTINCT(useridfrom)
                      FROM {message_read} m
                     WHERE useridto = ?";
            $users = $DB->get_records_sql($sql, [$userid, $userid]);

            // Get all the users the current user has messaged.
            $sql = "SELECT DISTINCT(useridto)
                      FROM {message} m
                     WHERE useridfrom = ?
                     UNION
                    SELECT DISTINCT(useridto)
                      FROM {message_read} m
                     WHERE useridfrom = ?";
            $users = $users + $DB->get_records_sql($sql, [$userid, $userid]);
            if (!empty($users)) {
                // Loop through each user and migrate the data.
                foreach ($users as $otheruserid => $user) {
                    $ids = [$userid, $otheruserid];
                    sort($ids);
                    $key = implode('_', $ids);

                    // Set the lock data.
                    $timeout = 5; // In seconds.
                    $locktype = 'core_message_migrate_data';

                    // Get an instance of the currently configured lock factory.
                    $lockfactory = \core\lock\lock_config::get_lock_factory($locktype);

                    // See if we can grab this lock.
                    if ($lock = $lockfactory->get_lock($key, $timeout)) {
                        try {
                            $transaction = $DB->start_delegated_transaction();
                            $this->migrate_data($userid, $otheruserid);
                            $transaction->allow_commit();
                        } catch (\Throwable $e) {
                            throw $e;
                        } finally {
                            $lock->release();
                        }
                    } else {
                        // Couldn't get a lock, move on to next user but make sure we don't update user preference so
                        // we still try again.
                        $updatepreference = false;
                        continue;
                    }
                }
            }

            if ($updatepreference) {
                set_user_preference('core_message_migrate_data', true, $userid);
            } else {
                // Throwing an exception in the task will mean that it isn't removed from the queue and is tried again.
                throw new \moodle_exception('Task failed.');
            }
        }
    }
689555
function exec($sql)
    {
        if ($this->trace_count){
            Trace::groups('DB')->group('count')->set(Trace::groups('DB')->group('count')->get()+1);
        }
        if ($this->trace_sql){
            Benchmark::start('sql');
            $sql = $this->addPrefixes($sql);
            $result = parent::exec($sql);
            $bm = Benchmark::stop('sql', true);
            if ($bm['time'] >= $this->slow_query){
                Trace::groups('DB')->group('query')->group()->set(array(
                    'sql' => $sql,
                    'benchmark' => $bm
                    )
                );
                Trace::groups('DB')->group('sql_time')->set(Trace::groups('DB')->group('sql_time')->get()+$bm['time']);
                Trace::groups('DB')->group('slow_count')->set(Trace::groups('DB')->group('slow_count')->get()+1);
            }
            return $result;
        }
        return parent::exec($this->addPrefixes($sql));
    }
1259189
def execute(self, i, o):
        
        super(ResetCommand, self).execute(i, o)

        dialog = self.get_helper('dialog')
        confirm = dialog.ask_confirmation(
            o,
            '<question>Are you sure you want to reset all of the migrations?</question> ',
            False
        )
        if not confirm:
            return

        database = i.get_option('database')
        repository = DatabaseMigrationRepository(self._resolver, 'migrations')

        migrator = Migrator(repository, self._resolver)

        self._prepare_database(migrator, database, i, o)

        pretend = bool(i.get_option('pretend'))

        path = i.get_option('path')

        if path is None:
            path = self._get_migration_path()

        while True:
            count = migrator.rollback(path, pretend)

            for note in migrator.get_notes():
                o.writeln(note)

            if count == 0:
                break
1142936
protected function execPre()
    {
        foreach ($this->preQueries as $pq) {
            if (is_array($pq)) {
                $pattern = $pq[0];
                $data = isset($pq[1]) ? $pq[1] : null;
            } else {
                $pattern = $pq;
                $data = null;
            }
            $this->query($pattern, $data);
        }
        $this->preQueries = array();
    }
580344
function execute(sql, params) {

	if (0 === sql.trim().length) {
		console.error("\nNo SQL to process\n");
		yargs.showHelp();
		process.exit(1);
	}

	for (var i = 1; i < params.length; i++) {
		var a = params[i];
		if (a[0] !== '"' && a[0] !== "'") {
			if (+a == a) { // jshint ignore:line
				params[i] = +a;
			}
		}
	}

	alasql.promise(sql, params)
		.then(function (res) {
			if (!alasql.options.stdout) {
				console.log(formatOutput(res));
			}
			process.exit(0);
		}).catch(function (err) {
			let errorJsonObj = JSON.parse(JSON.stringify(err, Object.getOwnPropertyNames(err)));
			console.error(formatOutput({
				error: errorJsonObj
			}));
			process.exit(1);
		});
}
667650
function execute() {
		try {

			// we need to bind in order
			if (empty($this->refactored_stmt)) {
				$index = [];

				$this->refactored_stmt = $this->query;

				# 
				# We need to sort by length to avoid replacing keys that are
				# prefixes of other keys, thereby invaliding the bigger keys
				#

				$keylengths = [];
				foreach (\array_keys($this->params) as $key) {
					$keylengths[$key] = strlen($key);
				}

				\asort($keylengths, SORT_NUMERIC);

				$keys = \array_keys(\array_reverse($keylengths, true));

				foreach ($keys as $key) {
					$position = \strpos($this->query, $key);
					if ($position == false) {
						throw new Panic("Tried to bind parameter $key but it's not present in statement.");
					}

					$this->refactored_stmt = \str_replace($key, '?', $this->refactored_stmt);

					$index[$key] = $position;
				}

				\asort($index, SORT_NUMERIC);

				$this->stmt = \mysqli_prepare($this->dbh, $this->refactored_stmt);

				if ( ! $this->stmt) {
					throw new Panic('Failed to prepare statement');
				}

				$bindings = '';
				$args = [ $this->stmt, null ];
				foreach (array_keys($index) as $key) {
					$bindings .= $this->params[$key][1];
					$args[] = & $this->params[$key][0];
				}

				$args[1] = $bindings;

				if ( ! empty($args[1])) {
					\call_user_func_array('mysqli_stmt_bind_param', $args);
				}
			}
			
			if ( ! \mysqli_stmt_execute($this->stmt)) {
				throw new Panic('Failed to execute statement');
			}

			#
			# to avoid complications with statements not getting closed before
			# new ones are executed we fetch the result set imediatly
			#

			$this->resultset = [];
			$result = \mysqli_stmt_get_result($this->stmt);
			while ($data = mysqli_fetch_assoc($result)) {
				$this->resultset[] = $data;
			}
		}
		catch (\Exception $exception) {
			$message = $exception->getMessage();
			$message .= "\n".$this->formatQuery($this->query);
			throw new Panic($message, 500, $exception);
		}

		return $this;
	}
1267293
public function exec(): void
    {
        $this->queryExecuted = false;
        $sql = $this->getSQL();
        $adapter = $this->getAdapter();

        $adapter->prepare($sql);
        $bindings = $this->getBindings();

        try {
            foreach ($bindings->getBindings() as $bind) {
	            $adapter->getStatement()->bindValue($bind->getParameter(), $bind->getValue(), $bind->getType());
            }

	        $adapter->getStatement()->execute();

            Log::sql("{$this->adapter}>>>\n{$this->debug()}");
        } catch (PDOException $e) {
            // more descriptive error handling when query fails

            switch ($e->getCode()) {
                case 'HY093': // PDO miss match parameter count
                    //Log::debug("[{$e->getCode()}] Tried and failed to execute SQL query:\n{$sql}");
                    //Log::debug('BINDINGS', $bindings->getAsArray());
	                $exception = new QueryException("[{$e->getCode()}] Query bindings parameter miss match: {$e->getMessage()}", (int) $e->getCode(), $e);
                    break;

                default:
                    //Log::debug("[{$e->getCode()}] Tried and failed to execute SQL query:\n{$this->debug()}");
	                $exception = new QueryException("[{$e->getCode()}] Tried and failed to execute SQL query: {$e->getMessage()}", (int) $e->getCode(), $e);
                    break;
            }

            $exception->setAdapter($adapter->getConfigKey());
	        $exception->setSql($this->debug());
	        $exception->setBindings($bindings);
	        $exception->setWasPrepared(true);
            throw $exception;
        }

        $this->queryExecuted = true;
    }
875815
public function getSqlQueriesToExecute()
    {
        $queries = array();
        $classNames = array();

        foreach ($this->componentsWithUpdateFile as $componentName => $componentUpdateInfo) {
            foreach ($componentUpdateInfo as $file => $fileVersion) {
                require_once $file; // prefixed by PIWIK_INCLUDE_PATH

                $className = $this->getUpdateClassName($componentName, $fileVersion);
                if (!class_exists($className, false)) {
                    throw new \Exception("The class $className was not found in $file");
                }

                if (in_array($className, $classNames)) {
                    continue; // prevent from getting updates from Piwik\Columns\Updater multiple times
                }

                $classNames[] = $className;

                /** @var Updates $update */
                $update = StaticContainer::getContainer()->make($className);
                $migrationsForComponent = $update->getMigrations($this);
                foreach ($migrationsForComponent as $index => $migration) {
                    $migration = $this->keepBcForOldMigrationQueryFormat($index, $migration);
                    $queries[] = $migration;
                }
                $this->hasMajorDbUpdate = $this->hasMajorDbUpdate || call_user_func(array($className, 'isMajorUpdate'));
            }
        }
        return $queries;
    }
4498
public function execute(): void
	{
		$migrations = $this->getOutstanding();

		if(empty($migrations))
		{
			$this->write('<blue>There are no outstanding migrations.</blue>');

			return;
		}

		$batch = $this->builder()->max('batch') + 1;

		foreach($migrations as $migration)
		{
			$this->runMigration($migration, 'up', $batch);
		}

		$this->write('Ran the following migrations:' . PHP_EOL);

		$this->outputMigrationList($migrations);
	}
1309685
public function exec()
    {
        $schema = true;
        //
        $data = $this->splite(Translator::ListAll());
        //
        $this->show($data);
    }
110191
function exec($statement) {

		if (self::$logQueries) {
			$start = microtime(true);
			$result = parent::exec($statement);
			$time = microtime(true) - $start;
			$this->logQuery((string) $statement, $time);
			return $result;
		}
		if (self::$printQueries) {
			$this->printQuery((string) $statement);
		}

		return parent::exec($statement);
	}
1296780
public function runMigrations()
    {
        // Check we havy any
        if (!file_exists(DIR_MIGRATIONS)) {
            return 0;
        }

        // Have DB already?
        new MigrationEntityRepository;

        // Check we have DB structure and any migration applied
        $migrated_files = [];
        if (SQL::getInstance()->getTables()) {
            $migrated_files = MigrationEntityRepository::getInstance()->getPairs('filename', 'filename');
        }

        $existing_files = FileSystem::scanDirs(DIR_MIGRATIONS);
        if (!$existing_files) {
            return 0;
        }

        $to_migrate = [];
        // Filters migrations that are already done
        foreach ($existing_files as $file) {
            if (isset($migrated_files[$file['name']])) {
                continue;
            }

            $to_migrate[] = $file['name'];
        }

        // Run new migrations
        foreach ($to_migrate as $file) {
            $this->runMigrationFile($file);

            $this->setMigrationFileAsCompleted($file);
        }

        return count($to_migrate);
    }
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;
        }
    }
537515
function execQueryString($sql, $params = null)
    {
        if (!is_array($params) && !is_null($params)) {
            $params = array($params);
        }

        $stmt = $this->prepare($sql);
        $stmt->execute($params);
        return $stmt;
    }
1022107
def db_exec(self, query, args=None):
        
        if args is None:
            self.db_query(query)
        else:
            self.db_query(query, args)

        self.db.commit()
692390
function ExecuteSql()
    {
        $versionCompare = version_compare($this->installedVersion, $this->manifest->Version());
       
        if ($versionCompare > 0)
        {
            $bundle = $this->manifest->BundleName();
            throw new \Exception("Error instaling bundle $bundle: Previously installed version is greater than curren code version. Please re-install the bundle.");
        }
        else if ($versionCompare === 0)
        {
            return;
        }
        $engineFolder = $this->FindEngineFolder();
        if (!$engineFolder)
        {
            return;
        }
        $this->ExecuteScripts($engineFolder);       
    }