irap/multi-query

mysqli的包装对象,用于将查询合并为一个。

3.0.0 2023-10-26 12:33 UTC

This package is auto-updated.

Last update: 2024-08-26 14:34:14 UTC


README

这是一个简化发送多个PHP Mysqli查询并处理响应的包。这通常可以显著提高性能,通过消除往返时间,这在数据库位于远程主机时尤为明显。

示例用法

基本示例

$db = new mysqli($host, $user, $password, $db_name);

$queries = array(
    "DROP TABLE `table1`",
    "DROP TABLE `table2`",
    "DROP TABLE `table3`"
);

$multiQuery = new iRAP\MultiQuery\MultiQuery($db, $queries);

完整示例

在下面的示例中,我们运行了许多不同的查询,并使用我们在添加查询时获得的索引,以从多查询对象中稍后获取其结果。我们还演示了如何通过检查运行后的对象状态来检查是否发生错误。

$connection = new mysqli('host', 'user', 'password', 'db_name');

$queries = array(
    'SELECT * FROM `table1`',
    'SHOW TABLES`',
    'SELECT * FROM `table2`'
);

$select1QueryIndex = 0;
$showTablesQueryIndex = 1;
$select2QueryIndex = 2;

$multiQuery = new iRAP\MultiQuery\MultiQuery($connection, $queries);


if ($multiQuery->hasErrors())
{
    $errors = $multiQuery->getErrors();
    // do something with the errors array such as use them in an
    // exception message....
}
else
{
    $tablesResult = $multiQuery->getResult($showTablesQueryIndex);

    if ($tablesResult === FALSE)
    {
        throw new Exception("Failed to fetch tables");
    }
    else
    {
        $tables = array();

        while (($row = $tablesResult->fetch_array()) !== null)
        {
            $tables[] = $row[0];
        }

        print "tables: " . implode(", ", $tables);
    }
}

合并结果示例

如果您已使用单独的表(例如,所有表都具有相同的结构)来分区您的数据,那么您可能想使用get_merged_result()方法将所有查询结果合并为一个。

# // Example 2 - Fetch data from two tables that have exactly the same structure
# // e.g. a case of partitioning data using table names like "dataset1", "dataset2"

$queries = array(
    'SELECT * FROM `table1`',
    'SELECT * FROM `table2`'
);

$multiQuery2 = new iRAP\MultiQuery\MultiQuery($connection, $queries);
$mergedResult = $multiQuery2->getMergedResult();
print "merged result: " . print_r($mergedResult, true) . PHP_EOL;

事务

此包还包括一个类,用于帮助处理MySQL事务。以下是使用此类的示例

$queries = array(
    'DELETE FROM `myTable` WHERE id = ' . $id,
    'INSERT INTO `myTable` SELECT * FROM `myTable2` WHERE id = ' . $id
);

$transaction = new iRAP\MultiQuery\Transaction($mysqli, $queries);

if (!$transaction->wasSuccessful())
{
    throw new Exception("Failed to reset the record in xyz");
}

如果事务对象中的任何查询失败,事务将自动检测并回滚。默认情况下,如果事务失败,对象将不会重试,但您可以配置它进行重试。以下是相同的示例,但这次我们将它设置为在事务运行时最多重试5次,并在每次尝试之间等待3秒。如果您不设置,默认的睡眠时间为1秒。

$queries = array(
    'DELETE FROM `myTable` WHERE id = ' . $id,
    ... # more quries here.
);

$transaction = new iRAP\MultiQuery\Transaction(
    $mysqli,
    $queries,
    $attempts=5,
    $sleepPeriod=3
);
...