gpt4 book ai didi

php - 如何从打开的连接确定 SQLite 文件名?

转载 作者:行者123 更新时间:2023-12-01 18:29:45 25 4
gpt4 key购买 nike

PHP SQLite3 类不包含文件名信息,或者提供了获取 SQLite 引擎打开的主文件的方法。

如何确定文件名?

这在单元测试中可能很有趣,以确保客户端使用的文件与配置中的预期文件匹配。

最佳答案

如果 SQLite3 类没有提供属性或方法来返回此信息,SQLite 有一个 PRAGMA 语句来获取或设置内部数据或修改库行为。

PRAGMA database_list;

它将返回一行,其中包含 seq、name、file 字段,分别包含序列 id、数据库的内部名称和文件路径:

0|main|/path/to/yourdatabasefile.db

一些细节值得注意。

  • 一个 SQLite 库可以使用多个文件。
  • 该路径将是规范的,因此遵循符号链接(symbolic link)。

单元测试用例示例:

测试当前$client连接文件是否匹配$config->databaseFilename:

/**
* Tests the SQLite client connection
*/
function testClient () {
$client = ...
$config = ...
$row = $client->query("PRAGMA database_list")->fetchArray(SQLITE3_ASSOC);
$this->assertEquals(
[
'seq' => 0,
'name' => 'main',
'file' => realpath($config->databaseFilename)
],
$row,
"The query PRAGMA database_list didn't return what we expected: one database opened by the client, the file returned by the database matching our configuration file."
);
}

要测试查询是否返回预期结果,一种有效的方法是比较两个数组,一个与预期结果,一个与 fetchArray 返回的行进行比较。

默认情况下,fetchArray 将每个字段值存储两次,一次使用数字索引,一次使用关联键。这里我们关注包含正确信息的字段,因此我们使用 SQLITE3_ASSOC 参数仅获取关联内容。如果您想测试顺序,请使用 fetchArray(SQLITE3_NUM):

    $row = $client->query("PRAGMA database_list")->fetchArray(SQLITE3_NUM);
$this->assertEquals(
[0, 'main', realpath($config->databaseFilename)]
$row,
"The query PRAGMA database_list didn't return what we expected: one database opened by the client, the file returned by the database matching our configuration file."
);

realpath函数用于获取规范路径。

引用文献:

关于php - 如何从打开的连接确定 SQLite 文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21656492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com