Executes the task for MySQL databases.
765952
protected function _mysql()
	{
		$this->_msg( 'Changing typeid to not allow NULL values', 0 );
		$this->_status( '' );

		foreach ( $this->_mysql as $table => $stmt ) {
			$this->_msg( sprintf ( 'Checking table "%1$s": ', $table ), 1 );

			if ( $this->_schema->tableExists( $table ) === true
				&& $this->_schema->columnExists( $table, 'typeid' ) === true
				&& $this->_schema->getColumnDetails( $table, 'typeid' )->isNullable() === true )
			{
				$this->_executeList( $stmt );
				$this->_status( 'migrated' );
			} else {
				$this->_status( 'OK' );
			}
		}
	}
395410
public function execute() {
        global $DB, $CFG;

        require_once($CFG->dirroot . '/auth/mnet/auth.php');
        $mnetplugin = new \auth_plugin_mnet();
        $mnetplugin->keepalive_client();

        $random100 = rand(0,100);
        if ($random100 < 10) {
            $longtime = time() - DAYSECS;
            $DB->delete_records_select('mnet_session', "expires < ?", [$longtime]);
        }
    }
767314
def execute(self, query, *parameters, **kwargs):
        """"""
        cursor = self._cursor()
        try:
            self._execute(cursor, query, parameters, kwargs)

        except:
            raise

        finally:
            cursor.close()
1353572
public function execute() {
        global $DB, $CFG;
        if (!empty($CFG->enablebadges)) {
            require_once($CFG->libdir . '/badgeslib.php');
            $total = 0;

            $courseparams = array();
            if (empty($CFG->badges_allowcoursebadges)) {
                $coursesql = '';
            } else {
                $coursesql = ' OR EXISTS (SELECT c.id FROM {course} c WHERE c.visible = :visible AND c.startdate < :current'
                        . '     AND c.id = b.courseid) ';
                $courseparams = array('visible' => true, 'current' => time());
            }

            $sql = 'SELECT b.id
                      FROM {badge} b
                     WHERE (b.status = :active OR b.status = :activelocked)
                       AND (b.type = :site ' . $coursesql . ')';
            $badgeparams = [
                'active' => BADGE_STATUS_ACTIVE,
                'activelocked' => BADGE_STATUS_ACTIVE_LOCKED,
                'site' => BADGE_TYPE_SITE
            ];
            $params = array_merge($badgeparams, $courseparams);
            $badges = $DB->get_fieldset_sql($sql, $params);

            mtrace('Started reviewing available badges.');
            foreach ($badges as $bid) {
                $badge = new \badge($bid);

                if ($badge->has_criteria()) {
                    if (debugging()) {
                        mtrace('Processing badge "' . $badge->name . '"...');
                    }

                    $issued = $badge->review_all_criteria();

                    if (debugging()) {
                        mtrace('...badge was issued to ' . $issued . ' users.');
                    }
                    $total += $issued;
                }
            }

            mtrace('Badges were issued ' . $total . ' time(s).');
        }
    }
901811
public function execute() {
        global $DB;
        if (is_enabled_auth('ldap')) {
            $auth = get_auth_plugin('ldap');
            $users = $DB->get_records('user', array('auth' => 'ldap'));
            foreach ($users as $user) {
                $auth->sync_roles($user);
            }
        }
    }
1145953
public function execute()
    {
        $this->result_set = new \FreeFW\Model\ResultSet();
        switch ($this->type) {
            case self::QUERY_SELECT:
                $model            = \FreeFW\DI\DI::get($this->main_model);
                $this->result_set = $this->strategy->select($model, $this->conditions);
                return true;
                break;
            case self::QUERY_DELETE:
                $model = \FreeFW\DI\DI::get($this->main_model);
                return $this->strategy->delete($model, $this->conditions);
                break;
            default:
                var_dump('error query execute');
                die;
        }
        return false;
    }
184262
public function execute()
    {
        if (method_exists($this, 'setUp')) {
            call_user_func_array([$this, 'setUp'], [$this->request]);
        }
        call_user_func_array([$this, $this->action], [$this->request]);
    }
379220
public function execute()
    {
        $this->label = str_replace(array(
            '#dbName#',
            '#nbQueries#',
            '#totalDuration#'
        ), array(
            $this->dbName,
            count($this->payload) - 1,
            round($this->totalDuration, 2)
        ), $this->label);
        
        $this->firephp->fb(array(
            $this->label,
            $this->payload
        ), \FirePHP::TABLE);
    }
278475
public function execute()
	{
		$this->connect();

		// Take a local copy so that we don't modify the original query and cause issues later
		$sql = $this->replacePrefix((string) $this->sql);

		$count = $this->getCount();

		// Increment the query counter.
		$this->count++;

		// If debugging is enabled then let's log the query.
		if ($this->debug)
		{
			// Add the query to the object queue.
			$this->log(
				Log\LogLevel::DEBUG,
				'{sql}',
				array('sql' => $sql, 'category' => 'databasequery', 'trace' => debug_backtrace())
			);
		}

		// Reset the error values.
		$this->errorNum = 0;
		$this->errorMsg = '';

		// Bind the variables
		if ($this->sql instanceof PreparableInterface)
		{
			$bounded =& $this->sql->getBounded();

			if (\count($bounded))
			{
				// Execute the query. Error suppression is used here to prevent warnings/notices that the connection has been lost.
				$this->cursor = @pg_execute($this->connection, $this->queryName . $count, array_values($bounded));
			}
			else
			{
				// Execute the query. Error suppression is used here to prevent warnings/notices that the connection has been lost.
				$this->cursor = @pg_query($this->connection, $sql);
			}
		}
		else
		{
			// Execute the query. Error suppression is used here to prevent warnings/notices that the connection has been lost.
			$this->cursor = @pg_query($this->connection, $sql);
		}

		// If an error occurred handle it.
		if (!$this->cursor)
		{
			// Check if the server was disconnected.
			if (!$this->connected())
			{
				try
				{
					// Attempt to reconnect.
					$this->connection = null;
					$this->connect();
				}
				catch (ConnectionFailureException $e)
				{
					// If connect fails, ignore that exception and throw the normal exception.
					$this->errorMsg = pg_last_error($this->connection);

					// Only get an error number if we have a non-boolean false cursor, otherwise use default 0
					if ($this->cursor !== false)
					{
						$this->errorNum = (int) pg_result_error_field($this->cursor, PGSQL_DIAG_SQLSTATE);
					}

					// Throw the normal query exception.
					$this->log(
						Log\LogLevel::ERROR,
						'Database query failed (error #{code}): {message}; Failed query: {sql}',
						array('code' => $this->errorNum, 'message' => $this->errorMsg, 'sql' => $sql)
					);

					throw new ExecutionFailureException($sql, $this->errorMsg, $this->errorNum);
				}

				// Since we were able to reconnect, run the query again.
				return $this->execute();
			}

			// The server was not disconnected.
			$this->errorNum = (int) pg_result_error_field($this->cursor, PGSQL_DIAG_SQLSTATE);
			$this->errorMsg = pg_last_error($this->connection);

			// Throw the normal query exception.
			$this->log(
				Log\LogLevel::ERROR,
				'Database query failed (error #{code}): {message}; Failed query: {sql}',
				array('code' => $this->errorNum, 'message' => $this->errorMsg, 'sql' => $sql)
			);

			throw new ExecutionFailureException($sql, $this->errorMsg, $this->errorNum);
		}

		return $this->cursor;
	}
845679
public function execute() {
        global $CFG, $DB;

        $timenow = time();

        // Delete users who haven't completed profile within required period.
        if (!empty($CFG->deleteincompleteusers)) {
            $cuttime = $timenow - ($CFG->deleteincompleteusers * 3600);
            $rs = $DB->get_recordset_sql ("SELECT *
                                               FROM {user}
                                           WHERE confirmed = 1 AND lastaccess > 0
                                               AND lastaccess < ? AND deleted = 0
                                               AND (lastname = '' OR firstname = '' OR email = '')",
                                           array($cuttime));
            foreach ($rs as $user) {
                if (isguestuser($user) or is_siteadmin($user)) {
                    continue;
                }
                if ($user->lastname !== '' and $user->firstname !== '' and $user->email !== '') {
                    // This can happen on MySQL - see MDL-52831.
                    continue;
                }
                delete_user($user);
                mtrace(" Deleted not fully setup user $user->username ($user->id)");
            }
            $rs->close();
        }
    }
1168991
public function execute() {
        global $DB;
        $started = time();

        $backupid = $this->get_custom_data()->backupid;
        $backuprecordid = $DB->get_field('backup_controllers', 'id', array('backupid' => $backupid), MUST_EXIST);
        mtrace('Processing asynchronous backup for backup: ' . $backupid);

        // Get the backup controller by backup id.
        $bc = \backup_controller::load_controller($backupid);
        $bc->set_progress(new \core\progress\db_updater($backuprecordid, 'backup_controllers', 'progress'));

        // Do some preflight checks on the backup.
        $status = $bc->get_status();
        $execution = $bc->get_execution();

        // Check that the backup is in the correct status and
        // that is set for asynchronous execution.
        if ($status == \backup::STATUS_AWAITING && $execution == \backup::EXECUTION_DELAYED) {
            // Execute the backup.
            $bc->execute_plan();

            // Send message to user if enabled.
            $messageenabled = (bool)get_config('backup', 'backup_async_message_users');
            if ($messageenabled && $bc->get_status() == \backup::STATUS_FINISHED_OK) {
                $asynchelper = new async_helper('backup', $backupid);
                $asynchelper->send_message();
            }

        } else {
            // If status isn't 700, it means the process has failed.
            // Retrying isn't going to fix it, so marked operation as failed.
            $bc->set_status(\backup::STATUS_FINISHED_ERR);
            mtrace('Bad backup controller status, is: ' . $status . ' should be 700, marking job as failed.');

        }

        // Cleanup.
        $bc->destroy();

        $duration = time() - $started;
        mtrace('Backup completed in: ' . $duration . ' seconds');
    }
236337
public function run( $dbtype )
	{
		foreach( $this->_tasks as $taskname => $task ) {
			$this->_runTasks( $dbtype, array( $taskname ) );
		}
	}
1101490
async def execute(self, sql: str, parameters: Iterable[Any] = None) -> None:
        """"""
        if parameters is None:
            parameters = []
        await self._execute(self._cursor.execute, sql, parameters)
129387
public function execute() {
        global $DB;

        $timenow = time();

        \core\session\manager::gc();

        // Cleanup old session linked tokens.
        // Deletes the session linked tokens that are over a day old.
        $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype',
                        array('onedayago' => $timenow - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED));
    }
291915
public function run()
	{
		// Lets make sure we have a database
		if (!$this->taskCreateDb()
				->host($this->host)
				->user($this->user)
				->pass($this->pass)
				->name($this->name)
				->dropTables(true)
			->run()->wasSuccessful()
		){
			throw new RuntimeException('We failed to create the db.');
		}

		// Do we need to uncompress it first?
		if (strpos($this->dump, '.gz') !== false)
		{
			// Create a temp dump file
			$temp_dump = tempnam(sys_get_temp_dir(), 'dump');

			// Decompress the dump file
			if ($fp_out = fopen($temp_dump, 'wb'))
			{
				if ($fp_in = gzopen($this->dump, 'rb'))
				{
					while (!gzeof($fp_in))
					{
						fwrite($fp_out, gzread($fp_in, 1024 * 512));
					}

					fclose($fp_in);
				}
				else
				{
					throw new RuntimeException
					(
						'Failed to open source dump file for reading.'
					);
				}

				gzclose($fp_out);
			}
			else
			{
				throw new RuntimeException
				(
					'Failed to open temp dump file for writing.'
				);
			}

			// Set the dump the deflated version
			$this->dump = $temp_dump;

			// Delete the temp later
			$delete_me = $this->dump;
		}

		// Construct the command to import the dump
		$cmd = 'mysql -h'.$this->host.' -u'.$this->user;
		if (!empty($this->pass)) $cmd .= ' -p'.$this->pass;
		$cmd .= ' '.$this->name.' < '.$this->dump;

		// Run the command
		if (!$this->taskExec($cmd)->run()->wasSuccessful())
		{
			throw new RuntimeException
			(
				'We failed to import your dump. '.
				'HINT: Is the `mysql` binary in your "PATH"?'
			);
		}

		// Delete the deflated temp dump file
		if (isset($delete_me))
		{
			$this->printTaskInfo('Deleting temp dump file.');
			if (!unlink($delete_me))
			{
				return Result::error($this, 'Couldn`t delete temp file.');
			}
		}

		// If we get to here assume everything worked
		return Result::success($this);
	}
580756
public function main()
    {
        // check to make sure task received all correct params
        $this->validate();

        $generatorConfig = $this->getGeneratorConfig();
        $totalNbFiles = 0;

        $dataModels = $this->getDataModels();
        $this->log('Generating PHP files...');

        foreach ($dataModels as $dataModel) {
            $this->log("Datamodel: " . $dataModel->getName(), Project::MSG_VERBOSE);

            foreach ($dataModel->getDatabases() as $database) {

                if ($this->getGeneratorConfig()->getBuildProperty('disableIdentifierQuoting')) {
                    $database->getPlatform()->setIdentifierQuoting(false);
                }

                $this->log(" - Database: " . $database->getName(), Project::MSG_VERBOSE);

                foreach ($database->getTables() as $table) {

                    if (!$table->isForReferenceOnly()) {

                        $nbWrittenFiles = 0;

                        $this->log("  + Table: " . $table->getName(), Project::MSG_VERBOSE);

                        // -----------------------------------------------------------------------------------------
                        // Create Peer, Object, and TableMap classes
                        // -----------------------------------------------------------------------------------------

                        // these files are always created / overwrite any existing files
                        foreach (array('peer', 'object', 'tablemap', 'query') as $target) {
                            $builder = $generatorConfig->getConfiguredBuilder($table, $target);
                            $nbWrittenFiles += $this->build($builder);
                        }

                        // -----------------------------------------------------------------------------------------
                        // Create [empty] stub Peer and Object classes if they don't exist
                        // -----------------------------------------------------------------------------------------

                        // these classes are only generated if they don't already exist
                        foreach (array('peerstub', 'objectstub', 'querystub') as $target) {
                            $builder = $generatorConfig->getConfiguredBuilder($table, $target);
                            $nbWrittenFiles += $this->build($builder, $overwrite = false);
                        }

                        // -----------------------------------------------------------------------------------------
                        // Create [empty] stub child Object classes if they don't exist
                        // -----------------------------------------------------------------------------------------

                        // If table has enumerated children (uses inheritance) then create the empty child stub classes if they don't already exist.
                        if ($col = $table->getChildrenColumn()) {
                            if ($col->isEnumeratedClasses()) {
                                foreach ($col->getChildren() as $child) {
                                    foreach (array('queryinheritance') as $target) {
                                        if (!$child->getAncestor()) {
                                            continue;
                                        }
                                        $builder = $generatorConfig->getConfiguredBuilder($table, $target);
                                        $builder->setChild($child);
                                        $nbWrittenFiles += $this->build($builder, $overwrite = true);
                                    }
                                    foreach (array('objectmultiextend', 'queryinheritancestub') as $target) {
                                        $builder = $generatorConfig->getConfiguredBuilder($table, $target);
                                        $builder->setChild($child);
                                        $nbWrittenFiles += $this->build($builder, $overwrite = false);
                                    }
                                } // foreach
                            } // if col->is enumerated
                        } // if tbl->getChildrenCol


                        // -----------------------------------------------------------------------------------------
                        // Create [empty] Interface if it doesn't exist
                        // -----------------------------------------------------------------------------------------

                        // Create [empty] interface if it does not already exist
                        if ($table->getInterface()) {
                            $builder = $generatorConfig->getConfiguredBuilder($table, 'interface');
                            $nbWrittenFiles += $this->build($builder, $overwrite = false);
                        }

                        // -----------------------------------------------------------------------------------------
                        // Create tree Node classes
                        // -----------------------------------------------------------------------------------------

                        if ($table->treeMode()) {
                            switch ($table->treeMode()) {
                                case 'NestedSet':
                                    foreach (array('nestedsetpeer', 'nestedset') as $target) {
                                        $builder = $generatorConfig->getConfiguredBuilder($table, $target);
                                        $nbWrittenFiles += $this->build($builder);
                                    }
                                    break;

                                case 'MaterializedPath':
                                    foreach (array('nodepeer', 'node') as $target) {
                                        $builder = $generatorConfig->getConfiguredBuilder($table, $target);
                                        $nbWrittenFiles += $this->build($builder);
                                    }

                                    foreach (array('nodepeerstub', 'nodestub') as $target) {
                                        $builder = $generatorConfig->getConfiguredBuilder($table, $target);
                                        $nbWrittenFiles += $this->build($builder, $overwrite = false);
                                    }
                                    break;

                                case 'AdjacencyList':
                                    // No implementation for this yet.
                                default:
                                    break;
                            }
                        } // if Table->treeMode()

                        // ----------------------------------
                        // Create classes added by behaviors
                        // ----------------------------------
                        if ($table->hasAdditionalBuilders()) {
                            foreach ($table->getAdditionalBuilders() as $builderClass) {
                                $builder = new $builderClass($table);
                                $builder->setGeneratorConfig($generatorConfig);
                                $nbWrittenFiles += $this->build($builder, isset($builder->overwrite) ? $builder->overwrite : true);
                            }
                        }

                        $totalNbFiles += $nbWrittenFiles;
                        if ($nbWrittenFiles == 0) {
                            $this->log("\t\t(no change)", Project::MSG_VERBOSE);
                        }
                    } // if !$table->isForReferenceOnly()

                } // foreach table

            } // foreach database

        } // foreach dataModel
        if ($totalNbFiles) {
            $this->log(sprintf("Object model generation complete - %d files written", $totalNbFiles));
        } else {
            $this->log("Object model generation complete - All files already up to date");
        }
    }
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;
    }