定制 v-dem/queasy-db 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

v-dem/queasy-db

Composer 安装命令:

composer require v-dem/queasy-db

包简介

Database access classes, part of QuEasy PHP framework

README 文档

README

Codacy Badge Codacy Badge Total Downloads Latest Stable Version License

QuEasy PHP Framework - Database

Package v-dem/queasy-db

QuEasy DB is a set of database access classes mainly for CRUD operations. Some of the most usual queries can be built automatically (like SELECT by unique field, UPDATE, INSERT and DELETE). Complex queries can be defined in database and/or tables config. Also there's a simple query builder. The main goal is to separate SQL queries out of PHP code and provide an easy way for CRUD operations.

Features

  • QuEasy DB extends PDO class, so any project which uses PDO can be seamlessly moved to use QuEasy DB.
  • Simple CRUD database operations in just one PHP code row.
  • Simple query builder.
  • Separating SQL queries from PHP code.

Requirements

  • PHP version 5.3 or higher

Installation

composer require v-dem/queasy-db

This will also install v-dem/queasy-helper.

Usage

Notes

  • You can use setLogger() method which accepts Psr\Log\LoggerInterface implementation to log all queries, by default Psr\Log\NullLogger is used.
  • By default error mode (PDO::ATTR_ERRMODE) is set to PDO::ERRMODE_EXCEPTION (as in PHP8). If you need to use other error mode and are using Db::trans() method then be sure to manually check errorInfo() and throw an exception inside transaction.
  • For PostgreSQL you may need to add option Db::ATTR_USE_RETURNING => true on initialization to make Db::id() work (it will add RETURNING "id" to each single INSERT statement).
  • All table and column names in auto-generated SQL code are enclosed in double quotes (as per ANSI SQL standard) so check following notes:
  • For MySQL need to set option PDO::MYSQL_ATTR_INIT_COMMAND to SET SQL_MODE = ANSI_QUOTES or run same query after initialization.
  • For MS SQL Server need to run SET QUOTED_IDENTIFIER ON or SET ANSI_DEFAULTS ON query after initialization.

Initialization

$db = new queasy\db\Db(
    [
        'connection' => [
            'dsn' => 'pgsql:host=localhost;dbname=test',
            'user' => 'test_user',
            'password' => 'test_password',
            'options' => [
                ...options...
            ]
        ]
    ]
);

Or PDO-way:

$db = new queasy\db\Db('pgsql:host=localhost;dbname=test', 'test_user', 'test_password', $options);

If DSN is not set then SQLite in-memory database will be used:

$db = new queasy\db\Db();
  • queasy\db\Table instances can be accessed like $db->users

Retrieving records

Get all records from users table
$users = $db->users->all();
Using foreach with users table
foreach ($db->users as $user) {
    // Do something
}
Get single record from users table by id key
$user = $db->users->id[$userId];

It's possible to use select() method to pass PDO options; select() returns PDOStatement instance:

$users = $db->users->id->select($userId, $options);
Select multiple records
$users = $db->users->id[[$userId1, $userId2]];

Using query builder (queasy\db\query\QueryBuidler)

  • Method queasy\db\Table::where() returns queasy\db\query\QueryBuilder instance
Select records using query
$usersFound = $db->users->where('
    "name" LIKE :nameFilter
    AND "is_active" = 1',
    [
        'name' => $nameFilter . '%'
    ]
)->select();
  • QueryBuilder's method select() returns PDOStatement, you can use it as iterator in foreach loop or retrieve records using fetch(), fetchAll() etc
  • select() method accepts $params array where you can use aliases or expressions:
$db->users
    ->where()
    ->select(['count' => $db->expr('count(*)')])
    ->fetch()['count'];

Inserting records

Insert a record into users table using associative array
$db->users[] = [
    'email' => 'john.doe@example.com',
    'password_hash' => sha1('myverystrongpassword')
];
Insert a record into users table by fields order
$db->users[] = [
    'john.doe@example.com',
    sha1('myverystrongpassword')
];
Insert many records into users table using associative array (it will generate single INSERT statement)
$db->users[] = [
    [
        'email' => 'john.doe@example.com',
        'password_hash' => sha1('myverystrongpassword')
    ], [
        'email' => 'mary.joe@example.com',
        'password_hash' => sha1('herverystrongpassword')
    ]
];
Insert many records into users table by order
$db->users[] = [
    [
        'john.doe@example.com',
        sha1('myverystrongpassword')
    ], [
        'mary.joe@example.com',
        sha1('herverystrongpassword')
    ]
];

Also it's possible to use insert() method (in the same way as above) when need to pass PDO options; returns last insert id for single insert and number of inserted rows for multiple inserts:

$userId = $db->users->insert([
    'email' => 'john.doe@example.com',
    'password_hash' => sha1('myverystrongpassword')
], $options);
$insertedRowsCount = $db->users->insert([
    [
        'email' => 'john.doe@example.com',
        'password_hash' => sha1('myverystrongpassword')
    ], [
        'email' => 'mary.joe@example.com',
        'password_hash' => sha1('herverystrongpassword')
    ]
], $options);
  • Second argument ($options) is optional, it will be passed to PDO::prepare()

Updating records

Update a record in users table by id key
$db->users->id[$userId] = [
    'password_hash' => sha1('mynewverystrongpassword')
]
$updatedRowsCount = $db->users->id->update($userId, [
    'password_hash' => sha1('mynewverystrongpassword')
], $options);
  • Third argument ($options) is optional, it will be passed to PDO::prepare()
Update multiple records
$db->users->id[[$userId1, $userId2]] = [
    'is_blocked' => true
]

Deleting records

Delete a record in users table by id key
unset($db->users->id[$userId]);
Delete multiple records
unset($db->users->id[[$userId1, $userId2]]);
$deletedRowsCount = $db->users->id->delete([[$userId1, $userId2]], $options);
  • Second argument ($options) is optional, it will be passed to PDO::prepare()

Other functions

Get last insert id (alias for lastInsertId() method)
$newUserId = $db->id();
Get count of all records in users table
$usersCount = count($db->users);
Using transactions
$db->trans(function() use($db) {
    // Run queries inside a transaction, for example:
    $db->users[] = [
        'john.doe@example.com',
        sha1('myverystrongpassword')
    ];
});
  • On exception transaction is rolled back and exception re-thrown to outer code.
Run custom queries (returns PDOStatement)
$users = $db->run('
    SELECT  *
    FROM    "users"
    WHERE   "name" LIKE concat(\'%\', :searchName, \'%\')',
    [
        ':searchName' => 'John'
    ],
    $options
)->fetchAll();
  • Third argument ($options) is optional, it will be passed to PDO::prepare()
Run query predefined in configuration

This feature can help keep code cleaner and place SQL code outside PHP, somewhere in config files.

$db = new queasy\db\Db(
    [
        'connection' => [
            'dsn' => 'pgsql:host=localhost;dbname=test',
            'user' => 'test_user',
            'password' => 'test_password'
        ],
        'queries' => [
            'searchUsersByName' => [
                'sql' => '
                    SELECT  *
                    FROM    "users"
                    WHERE   "name" LIKE concat(\'%\', :searchName, \'%\')',
                'returns' => Db::RETURN_ALL
            ]
        ]
    ]
);

$users = $db->searchUsersByName([
    'searchName' => 'John'
]);
  • Possible values for returns option are Db::RETURN_STATEMENT (default, returns PDOStatement instance), Db::RETURN_ONE, Db::RETURN_ALL (using PDOStatement::fetchAll() method), Db::RETURN_VALUE

Also it is possible to group predefined queries by tables:

$db = new queasy\db\Db(
    [
        'connection' => [
            'dsn' => 'pgsql:host=localhost;dbname=test',
            'user' => 'test_user',
            'password' => 'test_password'
        ],
        'tables' => [
            'users' => [
                'searchByName' => [
                    'sql' => '
                        SELECT  *
                        FROM    "user_roles"
                        WHERE   "name" LIKE concat(\'%\', :searchName, \'%\')',
                    'returns' => Db::RETURN_ALL
                ]
            ]
        ]
    ]
);

$users = $db->users->searchByName([
    'searchName' => 'John'
]);
Using v-dem/queasy-db together with v-dem/queasy-config and v-dem/queasy-log

config.php:

return [
    'db' => [
        'connection' => [
            'dsn' => 'pgsql:host=localhost;dbname=test',
            'user' => 'test_user',
            'password' => 'test_password'
        ],
        'tables' => [
            'users' => [
                'searchByName' => [
                    'sql' => '
                        SELECT  *
                        FROM    "users"
                        WHERE   "name" LIKE concat(\'%\', :searchName, \'%\')',
                    'returns' => Db::RETURN_ALL
                ]
            ]
        ]
    ],

    'logger' => [
        [
            'class' => queasy\log\ConsoleLogger::class,
            'minLevel' => Psr\Log\LogLevel::DEBUG
        ]
    ]
];

Initializing:

$config = new queasy\config\Config('config.php'); // Can be also INI, JSON or XML

$logger = new queasy\log\Logger($config->logger);

$db = new queasy\db\Db($config->db);
$db->setLogger($logger);

$users = $db->users->searchByName([
    'searchName' => 'John'
]);
  • All queries will be logged with Psr\Log\LogLevel::DEBUG level. Also it's possible to use any other logger class compatible with PSR-3.

v-dem/queasy-db 适用场景与选型建议

v-dem/queasy-db 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 176 次下载、GitHub Stars 达 4, 最近一次更新时间为 2017 年 09 月 03 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「database」 「mysql」 「sqlite」 「postgresql」 「pdo」 「crud」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 v-dem/queasy-db 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 v-dem/queasy-db 我们能提供哪些服务?
定制开发 / 二次开发

基于 v-dem/queasy-db 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 176
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 4
  • 点击次数: 7
  • 依赖项目数: 2
  • 推荐数: 1

GitHub 信息

  • Stars: 4
  • Watchers: 2
  • Forks: 2
  • 开发语言: PHP

其他信息

  • 授权协议: LGPL-3.0-only
  • 更新时间: 2017-09-03