ikto / pgi
简单的 PostgreSQL OOP 接口
v1.0.0
2021-06-04 20:59 UTC
Requires
- php: >=7.0
- ext-json: *
- ext-pgsql: *
Requires (Dev)
- phpunit/phpunit: ~6.0
This package is not auto-updated.
Last update: 2024-09-21 13:34:19 UTC
README
简短描述
这个库受到 Perl DBI 模块的影响。它是数据库依赖的(与 PostgreSQL 绑定),但仍试图保持简单。尽可能简单。
如果你出于某种原因不想使用 ORM 或类似的东西,这可能是一个不错的选择。使用这个库,你不需要直接与 PHP API 交互。它提供了错误异常,这使得代码比直接与 PHP API 交互写得更干净。
但要注意。它不会阻止你如果想要伤害自己的话 :)
功能
- 数据库级别错误的异常处理。
- 嵌套事务机制(使用保存点)。
- 数据库和 PHP 之间自动双向数据转换。例如,带时区的时间戳 表示为 DateTime。
需求(环境)
- PHP 7.0 或更高版本
- pgsql 扩展
如何使用
这里有一些示例。
use IKTO/PgI; // Connecting to the database. $dbh = PgI::connect('host=127.0.0.1 port=5432 dbname=pgi_test', 'postgres', 'postgres'); // Inserting a row into database table. if (!$dbh->doQuery('INSERT INTO "message" (name, data) VALUES ($1, $2)', [], ['Welcome!', 'Hello, this is a test!'])) { throw new \RuntimeException('Something went wrong'); } // Updating rows in db. $count = $dbh->doQuery('UPDATE "record" SET "published" = $1 WHERE "published" = $2 AND "date" < $3', [], [false, true, DateTime::createFromFormat('Y-m-d', '2013-11-21')]); echo sprintf("We've unpublished %d records", $count); // Deleting records from db. $count = $dbh->doQuery('DELETE FROM "record" WHERE "published" = $1', [], [false]); echo sprintf("We've removed %d unpublished records", $count); // Selecting the latest record as associative array. $record = $dbh->selectRowAssoc('SELECT * FROM "record" WHERE "published" = $1 ORDER BY "date" DESC LIMIT 1', [], [true]); // Selecting the array of available record IDs. $ids = $dbh->selectColArray('SELECT "id" FROM "record" ORDER BY "id" ASC'); // Getting the next sequence value. $id = $dbh->getSeqNextValue('record_id_seq'); // Using transactions. try { $dbh->beginWork(); $id = $dbh->getSeqNextValue('record_id_seq'); $dbh->doQuery('INSERT INTO "record" (id, date, published) VALUES ($1, NOW(), $2)', [], [$id, false]); $dbh->doQuery('INSERT INTO "message" (id_record, name, data) VALUES ($1, $2, $3)', [], [$id, 'Hello', 'This is a test']); $dbh->doQuery('UPDATE "record" SET "published" = $1 WHERE "id" = $2', [], [true, $id]); $dbh->commit(); } catch (\Exception $e) { $dbh->rollback(); }
待续...