"Удаление" из дерева элементов в заданном диапазоне (включительно) с "закрытием" дыры
@param \T4\Dbal\Connection $connection
@param string $table
@param int $lft
@param int $rgt
344292
protected function removeFromTreeByLftRgt(Connection $connection, $table, $lft, $rgt)
    {
        $query = (new Query())
            ->update()
            ->table($table)
            ->values([
                '__lft' => 'CASE WHEN __lft>:rgt THEN __lft - (:width + 1) ELSE __lft END',
                '__rgt' => 'CASE WHEN __rgt>:rgt THEN __rgt - (:width + 1) ELSE __rgt END',
            ])
            ->params([':rgt' => $rgt, ':width' => $rgt - $lft]);
        $connection->execute($query);
    }
463706
public function rollback(ConnectionInterface $connection)
    {
        $connectionId = $connection->getName();

        if ($this->transactionLevel > 1) {
            array_pop($this->pendingEvents[$connectionId][$this->transactionLevel]);
        } else {
            unset($this->pendingEvents[$connectionId]);
        }

        $this->transactionLevel--;
    }
500330
public function getTableMetadata(
        Connection $connection,
        string $databaseName,
        string $tableName
    ): TableMetadata {
        // Get top-level table information
        $tableStatement = $connection
            ->createQueryBuilder()
            ->select([
                'tables.TABLE_NAME AS name',
                'tables.ENGINE AS engine',
                'tables.TABLE_COLLATION AS collation',
                'tables.TABLE_ROWS AS row_count',
                'charset.CHARACTER_SET_NAME AS charset'
            ])
            ->from('information_schema.TABLES', 'tables')
            ->leftJoin(
                'tables',
                'information_schema.COLLATION_CHARACTER_SET_APPLICABILITY',
                'charset',
                'tables.TABLE_COLLATION = charset.COLLATION_NAME'
            )
            ->where('TABLE_NAME = :table_name')
            ->setParameter('table_name', $tableName)
            ->execute();

        $tableRow = $tableStatement->fetch(\PDO::FETCH_ASSOC);

        // Get column information
        $columnsStatement = $connection
            ->createQueryBuilder()
            ->select([
                'columns.COLUMN_NAME AS name',
                'columns.COLUMN_TYPE AS type',
                'columns.CHARACTER_MAXIMUM_LENGTH AS max_length',
                '"PRI" = columns.COLUMN_KEY AS is_primary_key',
                '"YES" = columns.IS_NULLABLE AS is_nullable',
                '(
                    SELECT COUNT(*) 
                    FROM   INFORMATION_SCHEMA.STATISTICS 
                    WHERE  TABLE_SCHEMA = :schema 
                    AND    TABLE_NAME = :table_name 
                    AND    COLUMN_NAME = columns.COLUMN_NAME
                ) AS is_indexed'
            ])
            ->from('information_schema.COLUMNS', 'columns')
            ->where('TABLE_SCHEMA = :schema')
            ->andWhere('TABLE_NAME = :table_name')
            ->setParameters([
                'schema' => $databaseName,
                'table_name' => $tableName
            ])
            ->execute();

        // Build column metadata
        $columnMetadataList = [];
        foreach ($columnsStatement->fetchAll(\PDO::FETCH_ASSOC) as $columnsRow) {
            $columnMetadataList[] = new ColumnMetadata(
                $databaseName,
                $tableName,
                $columnsRow['name'],
                $columnsRow['type'],
                is_null($columnsRow['max_length']) ? null : intval($columnsRow['max_length']),
                boolval($columnsRow['is_primary_key']),
                boolval($columnsRow['is_nullable']),
                boolval($columnsRow['is_indexed'])
            );
        }

        return new TableMetadata(
            $databaseName,
            $tableName,
            $tableRow['engine'],
            $tableRow['collation'],
            $tableRow['charset'],
            intval($tableRow['row_count']),
            $columnMetadataList
        );
    }
680306
public function initConnection(Connection $connection)
    {
        /** @var $pdo PDO */
        $pdo = $connection->getWrappedConnection();
        $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
        $params = $connection->getParams();
        if (!isset($params['charset'])) {
            throw new RuntimeException("No connection charset specified");
        }
        $pdo->exec('SET NAMES ' . $pdo->quote($params['charset']));
    }
920651
public static function createInsert(Connection $connection, $table, $values){
		if(!($values instanceof Traversable || (is_array($values) && !empty($values))))
			throw new InvalidArgumentException('Argument 3 must be a non-empty array or Traversable.');

		$obj = new self($connection);
		$obj->type = Manager::STMT_INSERT;
		$obj->source = $table;
		$obj->values = $values instanceof Traversable ? iterator_to_array($values) : $values;
		return $obj;
	}
760656
public function onMessage($connection, $data)
    {
        $uri  = parse_url($_SERVER['REQUEST_URI']);
        $path = isset($uri['path']) ? $uri['path'] : '/';

        $file = $this->root . $path;

        if (!is_file($file)) {
            $this->app->worker($connection, $data);
        } else {
            $this->sendFile($connection, $file);
        }
    }
270629
public function initConnection(Connection $connection)
    {
        /** @var $pdo PDO */
        $pdo = $connection->getWrappedConnection();
        $this->fkSupported = version_compare('3.6.19', $pdo->getAttribute(PDO::ATTR_SERVER_VERSION)) < 0;
        $pdo->exec($this->buildEnableForeignKeysQuery());
    }
1118369
static public function setdown($db=null, $table=null) {
		$self = get_called_class();
		if (is_null($db) || is_null($table))
			$df = $self::resolveConfiguration();
		if (!is_object($db=(is_string($db=($db?:$df['db']))?\Base::instance()->get($db):$db)))
			trigger_error(self::E_CONNECTION,E_USER_ERROR);
		if (strlen($table=strtolower($table?:$df['table']))==0)
			trigger_error(self::E_NO_TABLE,E_USER_ERROR);
		if (isset($df) && !empty($df['fieldConf']))
			$fields = $df['fieldConf'];
		else
			$fields = array();
		$deletable = array();
		$deletable[] = $table;
		foreach ($fields as $key => $field) {
			$field = static::resolveRelationConf($field);
			if (array_key_exists('has-many',$field)) {
				if (!is_array($relConf = $field['has-many']))
					continue;
				$rel = $relConf[0]::resolveConfiguration();
				// check if foreign conf matches m:m
				if (array_key_exists($relConf[1],$rel['fieldConf']) && !is_null($relConf[1])
					&& key($rel['fieldConf'][$relConf[1]]) == 'has-many') {
					// compute mm table name
					$deletable[] = isset($relConf[2]) ? $relConf[2] :
						static::getMMTableName(
							$rel['table'], $relConf[1], $table, $key,
							$rel['fieldConf'][$relConf[1]]['has-many']);
				}
			}
		}

		if($db instanceof Jig) {
			/** @var Jig $db */
			$dir = $db->dir();
			foreach ($deletable as $item)
				if(file_exists($dir.$item))
					unlink($dir.$item);
		} elseif($db instanceof SQL) {
			/** @var SQL $db */
			$schema = new Schema($db);
			$tables = $schema->getTables();
			foreach ($deletable as $item)
				if(in_array($item, $tables))
					$schema->dropTable($item);
		} elseif($db instanceof Mongo) {
			/** @var Mongo $db */
			foreach ($deletable as $item)
				$db->selectCollection($item)->drop();
		}
	}
788113
protected function expandTreeBeforeLft(Connection $connection, $table, $lft, $width)
    {
        $query = (new Query())
            ->update()
            ->table($table)
            ->values([
                '__lft' => 'CASE WHEN __lft>=:lft THEN __lft + (:width + 1) ELSE __lft END',
                '__rgt' => 'CASE WHEN __rgt>=:lft THEN __rgt + (:width + 1) ELSE  __rgt END',
            ])
            ->where('__lft>=:lft OR __rgt>=:lft')
            ->order('__lft DESC')
            ->params([':lft' => $lft, ':width' => $width]);
        $connection->execute($query);
    }
996745
public function batchInsert(\Phalcon\Db\Adapter $connection, $tableName, $fields)
    {
        $migrationData = $this->migrationsDir . '/' . $this->version . '/' . $tableName . '.dat';
        if (file_exists($migrationData)) {
            $connection->begin();
            $batchHandler = fopen($migrationData, 'r');
            while (($line = fgets($batchHandler)) !== false) {
                $connection->insert($tableName, explode('|', rtrim($line)), $fields, false);
                unset($line);
            }
            fclose($batchHandler);
            $connection->commit();
        }
    }
1038833
static function remove_bindings(\fenrir\system\MysqlDatabaseSignature $db, $table, array $bindings) {
		foreach ($bindings as $key) {
			$db->prepare
				(
					"
						ALTER TABLE `$table`
						 DROP FOREIGN KEY `$key`
					"
				)
				->execute();
		}
	}
1115566
public function onClientConnect($connection)
    {
        $connection->id = self::generateConnectionId();
        // 保存该连接的内部通讯的数据包报头，避免每次重新初始化
        $connection->gatewayHeader = array(
            'local_ip'      => ip2long($this->lanIp),
            'local_port'    => $this->lanPort,
            'client_ip'     => ip2long($connection->getRemoteIp()),
            'client_port'   => $connection->getRemotePort(),
            'gateway_port'  => $this->_gatewayPort,
            'connection_id' => $connection->id,
            'flag'          => 0,
        );
        // 连接的 session
        $connection->session                       = '';
        // 该连接的心跳参数
        $connection->pingNotResponseCount          = -1;
        // 该链接发送缓冲区大小
        $connection->maxSendBufferSize             = $this->sendToClientBufferSize;
        // 保存客户端连接 connection 对象
        $this->_clientConnections[$connection->id] = $connection;

        // 如果用户有自定义 onConnect 回调，则执行
        if ($this->_onConnect) {
            call_user_func($this->_onConnect, $connection);
        }

        $this->sendToWorker(GatewayProtocol::CMD_ON_CONNECTION, $connection);
    }
1010718
public function onClientClose($connection)
    {
        // 尝试通知 worker，触发 Event::onClose
        $this->sendToWorker(GatewayProtocol::CMD_ON_CLOSE, $connection);
        unset($this->_clientConnections[$connection->id]);
        // 清理 uid 数据
        if (!empty($connection->uid)) {
            $uid = $connection->uid;
            unset($this->_uidConnections[$uid][$connection->id]);
            if (empty($this->_uidConnections[$uid])) {
                unset($this->_uidConnections[$uid]);
            }
        }
        // 清理 group 数据
        if (!empty($connection->groups)) {
            foreach ($connection->groups as $group) {
                unset($this->_groupConnections[$group][$connection->id]);
                if (empty($this->_groupConnections[$group])) {
                    unset($this->_groupConnections[$group]);
                }
            }
        }
        // 触发 onClose
        if ($this->_onClose) {
            call_user_func($this->_onClose, $connection);
        }
    }
1355649
public function toSql(Connection $connection, Grammar $grammar)
    {
        $this->addImpliedCommands();

        $statements = [];

        // Each type of command has a corresponding compiler function on the schema
        // grammar which is used to build the necessary SQL statements to build
        // the blueprint element, so we'll just call that compilers function.
        foreach ($this->commands as $command) {
            $method = 'compile' . ucfirst($command->name);

            if (method_exists($grammar, $method)) {
                if (!is_null($sql = $grammar->{$method}($this, $command, $connection))) {
                    $statements = array_merge($statements, (array) $sql);
                }
            }
        }

        return $statements;
    }
420054
private function saveMigration(Connection $connection, string $class): void
    {
        $format = $connection->getSchemaManager()->getDatabasePlatform()->getDateTimeFormatString();
        $now    = (new DateTimeImmutable())->format($format);
        $connection->insert(static::MIGRATIONS_TABLE, [
            static::MIGRATIONS_COLUMN_CLASS       => $class,
            static::MIGRATIONS_COLUMN_MIGRATED_AT => $now,
        ]);
    }
867145
protected function assertDatabaseMissing($table, array $data, $connection = null)
    {
        return $this->notSeeInDatabase($table, $data, $connection);
    }
172071
private function setPreferredCharsetCollation(Connection $connection)
    {
        // Let's get the currently configured connection charset and collation
        $connectionParams = $connection->getParams();
        $connectionCharset = isset($connectionParams['character_set']) ? $this->characterSetCollationResolver->normalizeCharacterSet($connectionParams['character_set']) : '';
        $connectionCollation = isset($connectionParams['collation']) ? $this->characterSetCollationResolver->normalizeCollation($connectionParams['collation']) : '';
        try {
            list($characterSet, $collation) = $this->characterSetCollationResolver->resolveCharacterSetAndCollation($connection);
        } catch (CharacterSetCollationException $x) {
            // Unsupported character set and/or collation
            return $connection;
        }
        if ($connectionCharset === $characterSet && $connectionCollation === $collation) {
            // No changes required
            return $connection;
        }

        return $this->reconfigureCharacterSetCollation($connection, $characterSet, $collation);
    }