├── .editorconfig ├── .gitignore ├── LICENSE ├── README-zh.md ├── README.md ├── composer.json ├── examples ├── bind.php ├── prepare.php └── query.php └── src ├── Mysql.php ├── MysqlStatement.php └── SwPDO.php /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | end_of_line = lf 6 | indent_size = 2 7 | indent_style = space 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | trim_trailing_whitespace = false 13 | 14 | [*.php] 15 | indent_size = 4 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .buildpath 2 | .settings/ 3 | .project 4 | *.patch 5 | .idea/ 6 | .git/ 7 | runtime/ 8 | vendor/ 9 | temp/ 10 | *.lock -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README-zh.md: -------------------------------------------------------------------------------- 1 | # SwPDO 2 | 3 | [![Latest Version](https://img.shields.io/github/release/swlib/swpdo.svg?style=flat-square)](https://github.com/swlib/swpdo/releases) 4 | [![Build Status](https://travis-ci.org/swlib/swpdo.svg?branch=master)](https://github.com/swlib/swpdo/releases) 5 | [![Php Version](https://img.shields.io/badge/php-%3E=7.1-brightgreen.svg?maxAge=2592000)](https://secure.php.net/) 6 | [![Swoole Version](https://img.shields.io/badge/swoole-%3E=2.1.2-brightgreen.svg?maxAge=2592000)](https://github.com/swoole/swoole-src) 7 | [![SwPDO License](https://img.shields.io/hexpm/l/plug.svg?maxAge=2592000)](https://github.com/swlib/swpdo/blob/master/LICENSE) 8 | 9 | ## 简介 10 | 11 | 0成本迁移PDO到Swoole协程客户端. 12 | 13 | ## 安装 14 | 15 | 最好的安装方法是通过 [Composer](http://getcomposer.org/) 包管理器 : 16 | 17 | ```shell 18 | composer require swlib/saber 19 | ``` 20 | 21 |
22 | 23 | ## 协程调度 24 | 25 | Swoole底层实现协程调度, **业务层无需感知**, 开发者可以无感知的**用同步的代码编写方式达到异步IO的效果和超高性能**,避免了传统异步回调所带来的离散的代码逻辑和陷入多层回调中导致代码无法维护. 26 | 27 | 需要在`onRequet`, `onReceive`, `onConnect`等事件回调函数中使用, 或是使用go关键字包裹 (`swoole.use_shortname`默认开启). 28 | 29 |
30 | 31 | ## 例子 32 | 33 | > 由于PDO使用了多引擎, PHP层面难以用类实现构造函数返回不同的实例. 34 | 35 | 除了构造函数有所不同, 其它使用方法完全一样 36 | 37 | #### query 38 | 39 | ```php 40 | $options = [ 41 | 'mysql:host=127.0.0.1;dbname=test;charset=UTF8', 42 | 'root', 43 | 'root' 44 | ]; 45 | $sql = 'select * from `user` LIMIT 1'; 46 | 47 | //PDO 48 | $pdo = new \PDO(...$options); 49 | $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //strong type 50 | $pdo_both = $pdo->query($sql)->fetch(); 51 | $pdo_assoc = $pdo->query($sql)->fetch(\PDO::FETCH_ASSOC); 52 | $pdo_object = $pdo->query($sql)->fetch(\PDO::FETCH_OBJ); 53 | $pdo_number = $pdo->query($sql)->fetch(\PDO::FETCH_NUM); 54 | 55 | //SwPDO 56 | $swpdo = SwPDO::construct(...$options); //default is strong type 57 | $swpdo_both = $swpdo->query($sql)->fetch(); 58 | $swpdo_assoc = $swpdo->query($sql)->fetch(\PDO::FETCH_ASSOC); 59 | $swpdo_object = $swpdo->query($sql)->fetch(\PDO::FETCH_OBJ); 60 | $swpdo_number = $swpdo->query($sql)->fetch(\PDO::FETCH_NUM); 61 | 62 | var_dump($pdo_both === $swpdo_both); 63 | var_dump($pdo_assoc === $swpdo_assoc); 64 | var_dump($pdo_object == $swpdo_object); 65 | var_dump($pdo_number === $swpdo_number); 66 | //output: true true true true 67 | ``` 68 | 69 | #### prepare 70 | 71 | ```php 72 | //PDO 73 | $pdo = new \PDO(...$options); 74 | $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //strong type 75 | $statement = $pdo->prepare($sql); 76 | $statement->execute(); 77 | $pdo_fetch = $statement->fetch(\PDO::FETCH_ASSOC); 78 | $statement->execute(); 79 | $pdo_fetch_all = $statement->fetchAll(); 80 | $statement->execute(); 81 | $pdo_fetch_all_column = $statement->fetchAll(\PDO::FETCH_COLUMN, 1); 82 | $statement->execute(); 83 | $pdo_fetch_column = $statement->fetchColumn(); 84 | $statement->execute(); 85 | 86 | //SwPDO 87 | $swpdo = SwPDO::construct(...$options); 88 | $statement = $swpdo->prepare($sql); 89 | $statement->execute(); 90 | $swpdo_fetch = $statement->fetch(\PDO::FETCH_ASSOC); 91 | $statement->execute(); 92 | $swpdo_fetch_all = $statement->fetchAll(); 93 | $statement->execute(); 94 | $swpdo_fetch_all_column = $statement->fetchAll(\PDO::FETCH_COLUMN, 1); 95 | $statement->execute(); 96 | $swpdo_fetch_column = $statement->fetchColumn(); 97 | $statement->execute(); 98 | 99 | var_dump($pdo_fetch === $swpdo_fetch); //true 100 | var_dump($pdo_fetch_all === $swpdo_fetch_all); //true 101 | var_dump($pdo_fetch_all_column === $swpdo_fetch_all_column); //true 102 | var_dump($pdo_fetch_column === $swpdo_fetch_column); //true 103 | ``` 104 | 105 | ### bind 106 | 107 | ```php 108 | //PDO 109 | $pdo = new \PDO(...$options); 110 | $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //strong type 111 | $statement = $pdo->prepare($sql); 112 | $statement->execute(['id' => 1]); 113 | $pdo_bind_exec = $statement->fetch(\PDO::FETCH_ASSOC); 114 | 115 | $statement->bindValue(':id', 1); 116 | $statement->execute(); 117 | $pdo_bind_val = $statement->fetch(\PDO::FETCH_ASSOC); 118 | 119 | $statement->bindParam(':id', $id); 120 | $statement->execute(); 121 | $pdo_bind_param = $statement->fetch(\PDO::FETCH_ASSOC); 122 | 123 | //SwPDO 124 | $swpdo = SwPDO::construct(...$options); 125 | $statement = $swpdo->prepare($sql); 126 | $statement->execute(['id' => 1]); 127 | $swpdo_bind_exec = $statement->fetch(\PDO::FETCH_ASSOC); 128 | 129 | $statement->bindValue(':id', 1); 130 | $statement->execute(); 131 | $swpdo_bind_val = $statement->fetch(\PDO::FETCH_ASSOC); 132 | 133 | $statement->bindParam(':id', $id); 134 | $statement->execute(); 135 | $swpdo_bind_param = $statement->fetch(\PDO::FETCH_ASSOC); 136 | 137 | var_dump($pdo_bind_exec === $swpdo_bind_exec); //true 138 | var_dump($pdo_bind_val === $swpdo_bind_val); //true 139 | var_dump($pdo_bind_param === $swpdo_bind_param); //true 140 | ``` 141 | 142 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SwPDO 2 | 3 | [![Latest Version](https://img.shields.io/github/release/swlib/swpdo.svg?style=flat-square)](https://github.com/swlib/swpdo/releases) 4 | [![Build Status](https://travis-ci.org/swlib/swpdo.svg?branch=master)](https://github.com/swlib/swpdo/releases) 5 | [![Php Version](https://img.shields.io/badge/php-%3E=7.1-brightgreen.svg?maxAge=2592000)](https://secure.php.net/) 6 | [![Swoole Version](https://img.shields.io/badge/swoole-%3E=2.1.2-brightgreen.svg?maxAge=2592000)](https://github.com/swoole/swoole-src) 7 | [![SwPDO License](https://img.shields.io/hexpm/l/plug.svg?maxAge=2592000)](https://github.com/swlib/swpdo/blob/master/LICENSE) 8 | 9 | ## Introduction 10 | 11 | Traditional PDO to Swoole Coroutine migration plan without cost. 12 | 13 | [中文文档](README-zh.md) 14 | 15 | ## Install 16 | 17 | The best way to install: [Composer](http://getcomposer.org/) : 18 | 19 | ```shell 20 | composer require swlib/swpdo 21 | ``` 22 | 23 |
24 | 25 | ## Coroutine 26 | 27 | The bottom layer of Swoole implements coroutine scheduling, **and the business layer does not need to be aware**. Developers can use synchronization code writing methods to achieve the effect and ultra-high performance of asynchronous IO without perception, avoiding the discrete code logic and trapping caused by traditional asynchronous callbacks. Too many callback layers causes the code too difficult to maintain. 28 | 29 | It needs to be used in event callback functions such as `onRequet`, `onReceive`, and `onConnect`, or wrapped using the go keyword (`swoole.use_shortname` is on by default). 30 | 31 |
32 | 33 | ## Example 34 | 35 | > Because PDO uses multiple engines, it is difficult at the PHP level to return different instances with class - implemented constructors. 36 | 37 | **Except that the constructor is different, all methods use in the same way.** 38 | 39 | #### query 40 | 41 | ```php 42 | $options = [ 43 | 'mysql:host=127.0.0.1;dbname=test;charset=UTF8', 44 | 'root', 45 | 'root' 46 | ]; 47 | $sql = 'select * from `user` LIMIT 1'; 48 | 49 | //PDO 50 | $pdo = new \PDO(...$options); 51 | $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //strong type 52 | $pdo_both = $pdo->query($sql)->fetch(); 53 | $pdo_assoc = $pdo->query($sql)->fetch(\PDO::FETCH_ASSOC); 54 | $pdo_object = $pdo->query($sql)->fetch(\PDO::FETCH_OBJ); 55 | $pdo_number = $pdo->query($sql)->fetch(\PDO::FETCH_NUM); 56 | 57 | //SwPDO 58 | $swpdo = SwPDO::construct(...$options); //default is strong type 59 | $swpdo_both = $swpdo->query($sql)->fetch(); 60 | $swpdo_assoc = $swpdo->query($sql)->fetch(\PDO::FETCH_ASSOC); 61 | $swpdo_object = $swpdo->query($sql)->fetch(\PDO::FETCH_OBJ); 62 | $swpdo_number = $swpdo->query($sql)->fetch(\PDO::FETCH_NUM); 63 | 64 | var_dump($pdo_both === $swpdo_both); 65 | var_dump($pdo_assoc === $swpdo_assoc); 66 | var_dump($pdo_object == $swpdo_object); 67 | var_dump($pdo_number === $swpdo_number); 68 | //output: true true true true 69 | ``` 70 | 71 | #### prepare 72 | 73 | ```php 74 | //PDO 75 | $pdo = new \PDO(...$options); 76 | $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //strong type 77 | $statement = $pdo->prepare($sql); 78 | $statement->execute(); 79 | $pdo_fetch = $statement->fetch(\PDO::FETCH_ASSOC); 80 | $statement->execute(); 81 | $pdo_fetch_all = $statement->fetchAll(); 82 | $statement->execute(); 83 | $pdo_fetch_all_column = $statement->fetchAll(\PDO::FETCH_COLUMN, 1); 84 | $statement->execute(); 85 | $pdo_fetch_column = $statement->fetchColumn(); 86 | $statement->execute(); 87 | 88 | //SwPDO 89 | $swpdo = SwPDO::construct(...$options); 90 | $statement = $swpdo->prepare($sql); 91 | $statement->execute(); 92 | $swpdo_fetch = $statement->fetch(\PDO::FETCH_ASSOC); 93 | $statement->execute(); 94 | $swpdo_fetch_all = $statement->fetchAll(); 95 | $statement->execute(); 96 | $swpdo_fetch_all_column = $statement->fetchAll(\PDO::FETCH_COLUMN, 1); 97 | $statement->execute(); 98 | $swpdo_fetch_column = $statement->fetchColumn(); 99 | $statement->execute(); 100 | 101 | var_dump($pdo_fetch === $swpdo_fetch); //true 102 | var_dump($pdo_fetch_all === $swpdo_fetch_all); //true 103 | var_dump($pdo_fetch_all_column === $swpdo_fetch_all_column); //true 104 | var_dump($pdo_fetch_column === $swpdo_fetch_column); //true 105 | ``` 106 | 107 | ### bind 108 | 109 | ```php 110 | //PDO 111 | $pdo = new \PDO(...$options); 112 | $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //strong type 113 | $statement = $pdo->prepare($sql); 114 | $statement->execute(['id' => 1]); 115 | $pdo_bind_exec = $statement->fetch(\PDO::FETCH_ASSOC); 116 | 117 | $statement->bindValue(':id', 1); 118 | $statement->execute(); 119 | $pdo_bind_val = $statement->fetch(\PDO::FETCH_ASSOC); 120 | 121 | $statement->bindParam(':id', $id); 122 | $statement->execute(); 123 | $pdo_bind_param = $statement->fetch(\PDO::FETCH_ASSOC); 124 | 125 | //SwPDO 126 | $swpdo = SwPDO::construct(...$options); 127 | $statement = $swpdo->prepare($sql); 128 | $statement->execute(['id' => 1]); 129 | $swpdo_bind_exec = $statement->fetch(\PDO::FETCH_ASSOC); 130 | 131 | $statement->bindValue(':id', 1); 132 | $statement->execute(); 133 | $swpdo_bind_val = $statement->fetch(\PDO::FETCH_ASSOC); 134 | 135 | $statement->bindParam(':id', $id); 136 | $statement->execute(); 137 | $swpdo_bind_param = $statement->fetch(\PDO::FETCH_ASSOC); 138 | 139 | var_dump($pdo_bind_exec === $swpdo_bind_exec); //true 140 | var_dump($pdo_bind_val === $swpdo_bind_val); //true 141 | var_dump($pdo_bind_param === $swpdo_bind_param); //true 142 | ``` 143 | 144 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "swlib/swpdo", 3 | "type": "library", 4 | "keywords": [ 5 | "php", 6 | "swoole", 7 | "pdo", 8 | "mysql" 9 | ], 10 | "description": "Swoole Coroutine SQL component like PDO", 11 | "license": "Apache-2.0", 12 | "authors": [ 13 | { 14 | "name": "twosee", 15 | "email": "twose@qq.com" 16 | } 17 | ], 18 | "require": { 19 | "php": ">=7.0" 20 | }, 21 | "autoload": { 22 | "classmap": [ 23 | "src/SwPDO.php" 24 | ], 25 | "psr-4": { 26 | "Swlib\\SwPDO\\": "src" 27 | } 28 | }, 29 | "repositories": { 30 | "packagist": { 31 | "type": "composer", 32 | "url": "https://packagist.phpcomposer.com" 33 | } 34 | }, 35 | "require-dev": { 36 | "eaglewu/swoole-ide-helper": "dev-master", 37 | "phpunit/phpunit": "~7" 38 | }, 39 | "scripts": { 40 | "test": "./vendor/bin/phpunit -c phpunit.xml" 41 | } 42 | } -------------------------------------------------------------------------------- /examples/bind.php: -------------------------------------------------------------------------------- 1 | 5 | * Date: 2018/4/7 下午11:53 6 | */ 7 | 8 | use Swlib\SwPDO; 9 | 10 | require __DIR__ . '/../vendor/autoload.php'; 11 | 12 | go(function () { 13 | $options = [ 14 | 'mysql:host=127.0.0.1;dbname=test;charset=UTF8', 15 | 'root', 16 | 'root' 17 | ]; 18 | $sql = 'select * from `user` where id=:id'; 19 | $id = 1; 20 | 21 | //PDO 22 | $pdo = new \PDO(...$options); 23 | $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //strong type 24 | $statement = $pdo->prepare($sql); 25 | $statement->execute(['id' => 1]); 26 | $pdo_bind_exec = $statement->fetch(\PDO::FETCH_ASSOC); 27 | 28 | $statement->bindValue(':id', 1); 29 | $statement->execute(); 30 | $pdo_bind_val = $statement->fetch(\PDO::FETCH_ASSOC); 31 | 32 | $statement->bindParam(':id', $id); 33 | $statement->execute(); 34 | $pdo_bind_param = $statement->fetch(\PDO::FETCH_ASSOC); 35 | 36 | //SwPDO 37 | $swpdo = SwPDO::construct(...$options); 38 | $statement = $swpdo->prepare($sql); 39 | $statement->execute(['id' => 1]); 40 | $swpdo_bind_exec = $statement->fetch(\PDO::FETCH_ASSOC); 41 | 42 | $statement->bindValue(':id', 1); 43 | $statement->execute(); 44 | $swpdo_bind_val = $statement->fetch(\PDO::FETCH_ASSOC); 45 | 46 | $statement->bindParam(':id', $id); 47 | $statement->execute(); 48 | $swpdo_bind_param = $statement->fetch(\PDO::FETCH_ASSOC); 49 | 50 | var_dump($pdo_bind_exec === $swpdo_bind_exec); //true 51 | var_dump($pdo_bind_val === $swpdo_bind_val); //true 52 | var_dump($pdo_bind_param === $swpdo_bind_param); //true 53 | }); -------------------------------------------------------------------------------- /examples/prepare.php: -------------------------------------------------------------------------------- 1 | 5 | * Date: 2018/4/7 下午11:53 6 | */ 7 | 8 | use Swlib\SwPDO; 9 | 10 | require __DIR__ . '/../vendor/autoload.php'; 11 | 12 | go(function () { 13 | $options = [ 14 | 'mysql:host=127.0.0.1;dbname=test;charset=UTF8', 15 | 'root', 16 | 'root' 17 | ]; 18 | $sql = 'select * from `user`'; 19 | 20 | //PDO 21 | $pdo = new \PDO(...$options); 22 | $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //strong type 23 | $statement = $pdo->prepare($sql); 24 | $statement->execute(); 25 | $pdo_fetch = $statement->fetch(\PDO::FETCH_ASSOC); 26 | $statement->execute(); 27 | $pdo_fetch_all = $statement->fetchAll(); 28 | $statement->execute(); 29 | $pdo_fetch_all_column = $statement->fetchAll(\PDO::FETCH_COLUMN, 1); 30 | $statement->execute(); 31 | $pdo_fetch_column = $statement->fetchColumn(); 32 | $statement->execute(); 33 | 34 | //SwPDO 35 | $swpdo = SwPDO::construct(...$options); 36 | $statement = $swpdo->prepare($sql); 37 | $statement->execute(); 38 | $swpdo_fetch = $statement->fetch(\PDO::FETCH_ASSOC); 39 | $statement->execute(); 40 | $swpdo_fetch_all = $statement->fetchAll(); 41 | $statement->execute(); 42 | $swpdo_fetch_all_column = $statement->fetchAll(\PDO::FETCH_COLUMN, 1); 43 | $statement->execute(); 44 | $swpdo_fetch_column = $statement->fetchColumn(); 45 | $statement->execute(); 46 | 47 | var_dump($pdo_fetch === $swpdo_fetch); 48 | var_dump($pdo_fetch_all === $swpdo_fetch_all); 49 | var_dump($pdo_fetch_all_column === $swpdo_fetch_all_column); 50 | var_dump($pdo_fetch_column === $swpdo_fetch_column); 51 | }); -------------------------------------------------------------------------------- /examples/query.php: -------------------------------------------------------------------------------- 1 | 5 | * Date: 2018/4/7 下午4:08 6 | */ 7 | 8 | use Swlib\SwPDO; 9 | 10 | require __DIR__ . '/../vendor/autoload.php'; 11 | 12 | go(function () { 13 | $options = [ 14 | 'mysql:host=127.0.0.1;dbname=test;charset=UTF8', 15 | 'root', 16 | 'root' 17 | ]; 18 | $sql = 'select * from `user` LIMIT 1'; 19 | 20 | //PDO 21 | $pdo = new \PDO(...$options); 22 | $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //strong type 23 | $pdo_both = $pdo->query($sql)->fetch(); 24 | $pdo_assoc = $pdo->query($sql)->fetch(\PDO::FETCH_ASSOC); 25 | $pdo_object = $pdo->query($sql)->fetch(\PDO::FETCH_OBJ); 26 | $pdo_number = $pdo->query($sql)->fetch(\PDO::FETCH_NUM); 27 | 28 | //SwPDO 29 | $swpdo = SwPDO::construct(...$options); //default is strong type 30 | $swpdo_both = $swpdo->query($sql)->fetch(); 31 | $swpdo_assoc = $swpdo->query($sql)->fetch(\PDO::FETCH_ASSOC); 32 | $swpdo_object = $swpdo->query($sql)->fetch(\PDO::FETCH_OBJ); 33 | $swpdo_number = $swpdo->query($sql)->fetch(\PDO::FETCH_NUM); 34 | 35 | var_dump($pdo_both === $swpdo_both); //true 36 | var_dump($pdo_assoc === $swpdo_assoc); //true 37 | var_dump($pdo_object == $swpdo_object); //true 38 | var_dump($pdo_number === $swpdo_number); //true 39 | }); -------------------------------------------------------------------------------- /src/Mysql.php: -------------------------------------------------------------------------------- 1 | 5 | * Date: 2018/4/7 下午4:11 6 | */ 7 | 8 | namespace Swlib\SwPDO; 9 | 10 | use BadMethodCallException; 11 | use InvalidArgumentException; 12 | use PDO; 13 | 14 | class Mysql 15 | { 16 | private static $default_options = [ 17 | 'host' => '', 18 | 'port' => 3306, 19 | 'user' => '', 20 | 'password' => '', 21 | 'database' => '',//数据库名称 22 | 'charset' => 'utf8mb4', //指定字符集 23 | 'timeout' => 1.000, //可选:连接超时时间(非查询超时时间),默认为SW_MYSQL_CONNECT_TIMEOUT(1.0) 24 | 'strict_type' => true //开启严格类型模式 25 | ]; 26 | 27 | /** @var \Swoole\Coroutine\Mysql */ 28 | public $client; 29 | 30 | public $inTransaction = false; 31 | 32 | public static function construct(array $options) 33 | { 34 | $mysql = new self(); 35 | static $keyMap = [ 36 | 'dbname' => 'database' 37 | ]; 38 | foreach ($keyMap as $pdoKey => $swpdoKey) { 39 | if (isset($options[$pdoKey])) { 40 | $options[$swpdoKey] = $options[$pdoKey]; 41 | unset($options[$pdoKey]); 42 | } 43 | } 44 | $options = $options + self::$default_options; 45 | $mysql->client = new \Swoole\Coroutine\Mysql(); 46 | $mysql->client->connect($options); 47 | 48 | return $mysql; 49 | } 50 | 51 | public function beginTransaction() 52 | { 53 | $this->client->begin(); 54 | $this->inTransaction = true; 55 | } 56 | 57 | public function rollBack() 58 | { 59 | $this->client->rollback(); 60 | $this->inTransaction = false; 61 | } 62 | 63 | public function commit() 64 | { 65 | $this->client->commit(); 66 | $this->inTransaction = true; 67 | } 68 | 69 | public function inTransaction() 70 | { 71 | return $this->client->connect_errno; 72 | } 73 | 74 | public function lastInsertId() 75 | { 76 | return $this->client->insert_id; 77 | } 78 | 79 | public function errorCode() 80 | { 81 | $this->client->errno; 82 | } 83 | 84 | public function errorInfo() 85 | { 86 | return $this->client->errno; 87 | } 88 | 89 | public function exec(string $statement): int 90 | { 91 | $this->query($statement); 92 | 93 | return $this->client->affected_rows; 94 | } 95 | 96 | public function query(string $statement, float $timeout = 1.000) 97 | { 98 | return new MysqlStatement($this, $statement, ['timeout' => $timeout]); 99 | } 100 | 101 | private function rewriteToPosition(string $statement) 102 | { 103 | 104 | } 105 | 106 | public function prepare(string $statement, array $driver_options = []) 107 | { 108 | //rewriting :name to ? style. 109 | if (strpos($statement, ':') !== false) { 110 | $i = 0; 111 | $bindKeyMap = []; 112 | $statement = preg_replace_callback( 113 | '/:(\w+)\b/', 114 | function ($matches) use (&$i, &$bindKeyMap) { 115 | $bindKeyMap[$matches[1]] = $i++; 116 | 117 | return '?'; 118 | }, 119 | $statement 120 | ); 121 | } 122 | $stmt_obj = $this->client->prepare($statement); 123 | if ($stmt_obj) { 124 | $stmt_obj->bindKeyMap = $bindKeyMap ?? []; 125 | return new MysqlStatement($this, $stmt_obj, $driver_options); 126 | } else { 127 | return false; 128 | } 129 | } 130 | 131 | public function getAttribute(int $attribute) 132 | { 133 | switch ($attribute) { 134 | case PDO::ATTR_AUTOCOMMIT: 135 | return true; 136 | case PDO::ATTR_CASE: 137 | case PDO::ATTR_CLIENT_VERSION: 138 | case PDO::ATTR_CONNECTION_STATUS: 139 | return $this->client->connected; 140 | case PDO::ATTR_DRIVER_NAME: 141 | case PDO::ATTR_ERRMODE: 142 | return 'Swoole Style'; 143 | case PDO::ATTR_ORACLE_NULLS: 144 | case PDO::ATTR_PERSISTENT: 145 | case PDO::ATTR_PREFETCH: 146 | case PDO::ATTR_SERVER_INFO: 147 | return $this->serverInfo['timeout'] ?? self::$default_options['timeout']; 148 | case PDO::ATTR_SERVER_VERSION: 149 | case PDO::ATTR_TIMEOUT: 150 | default: 151 | throw new InvalidArgumentException('Not implemented yet!'); 152 | } 153 | } 154 | 155 | public function quote() 156 | { 157 | throw new BadMethodCallException(<< 5 | * Date: 2018/4/7 下午7:49 6 | */ 7 | 8 | namespace Swlib\SwPDO; 9 | 10 | use PDO; 11 | use Swoole\Coroutine\Mysql\Statement; 12 | 13 | class MysqlStatement 14 | { 15 | 16 | private $parent; 17 | /** 18 | * @var Statement | string 19 | */ 20 | public $statement; 21 | public $timeout; 22 | 23 | public $bindMap = []; 24 | 25 | public $cursor = -1; 26 | public $cursor_orientation = PDO::FETCH_ORI_NEXT; 27 | public $result_set = []; 28 | 29 | public function __construct(Mysql $parent, $statement, array $driver_options = []) 30 | { 31 | $this->parent = $parent; 32 | $this->statement = $statement; 33 | $this->timeout = $driver_options['timeout'] ?? 1.000; 34 | } 35 | 36 | public function errorCode() 37 | { 38 | return $this->statement->errno; 39 | } 40 | 41 | public function errorInfo() 42 | { 43 | return $this->statement->error; 44 | } 45 | 46 | public function rowCount() 47 | { 48 | return $this->statement->affected_rows; 49 | } 50 | 51 | public function bindParam($parameter, &$variable) 52 | { 53 | if (!is_string($parameter) && !is_int($parameter)) { 54 | return false; 55 | } 56 | $parameter = ltrim($parameter, ':'); 57 | $this->bindMap[$parameter] = &$variable; 58 | 59 | return true; 60 | } 61 | 62 | public function bindValue($parameter, $variable) 63 | { 64 | if (!is_string($parameter) && !is_int($parameter)) { 65 | return false; 66 | } 67 | if (is_object($variable)) { 68 | if (!method_exists($variable, '__toString')) { 69 | return false; 70 | } else { 71 | $variable = (string)$variable; 72 | } 73 | } 74 | $parameter = ltrim($parameter, ':'); 75 | $this->bindMap[$parameter] = $variable; 76 | 77 | return true; 78 | } 79 | 80 | private function afterExecute() 81 | { 82 | $this->cursor = -1; 83 | $this->bindMap = []; 84 | } 85 | 86 | public function execute(array $input_parameters = [], ?float $timeout = null) 87 | { 88 | if (!empty($input_parameters)) { 89 | foreach ($input_parameters as $key => $value) { 90 | $this->bindParam($key, $value); 91 | } 92 | } 93 | $input_parameters = []; 94 | if (!empty($this->statement->bindKeyMap)) { 95 | foreach ($this->statement->bindKeyMap as $name_key => $num_key) { 96 | $input_parameters[$num_key] = $this->bindMap[$name_key]; 97 | } 98 | } else { 99 | $input_parameters = $this->bindMap; 100 | } 101 | $r = $this->statement->execute($input_parameters, $timeout ?? $this->timeout); 102 | $this->result_set = ($ok = $r !== false) ? $r : []; 103 | $this->afterExecute(); 104 | 105 | return $ok; 106 | } 107 | 108 | private function __executeWhenStringQueryEmpty() 109 | { 110 | if (is_string($this->statement) && empty($this->result_set)) { 111 | $this->result_set = $this->parent->client->query($this->statement); 112 | $this->afterExecute(); 113 | } 114 | } 115 | 116 | private static function transBoth($raw_data) 117 | { 118 | $temp = []; 119 | foreach ($raw_data as $row) { 120 | $row_set = []; 121 | $i = 0; 122 | foreach ($row as $key => $value) { 123 | $row_set[$key] = $value; 124 | $row_set[$i++] = $value; 125 | } 126 | $temp[] = $row_set; 127 | } 128 | 129 | return $temp; 130 | } 131 | 132 | private static function transStyle( 133 | $raw_data, 134 | int $fetch_style = PDO::FETCH_BOTH, 135 | $fetch_argument = null, 136 | array $ctor_args = [] 137 | ) { 138 | if (!is_array($raw_data)) { 139 | return false; 140 | } 141 | if (empty($raw_data)) { 142 | return $raw_data; 143 | } 144 | $result_set = []; 145 | switch ($fetch_style) { 146 | case PDO::FETCH_BOTH: 147 | $result_set = self::transBoth($raw_data); 148 | break; 149 | case PDO::FETCH_COLUMN: 150 | $result_set = array_column( 151 | is_numeric($fetch_argument) ? self::transBoth($raw_data) : $raw_data, 152 | $fetch_argument 153 | ); 154 | break; 155 | case PDO::FETCH_OBJ: 156 | foreach ($raw_data as $row) { 157 | $result_set[] = (object)$row; 158 | } 159 | break; 160 | case PDO::FETCH_NUM: 161 | foreach ($raw_data as $row) { 162 | $result_set[] = array_values($row); 163 | } 164 | break; 165 | case PDO::FETCH_ASSOC: 166 | default: 167 | return $raw_data; 168 | } 169 | 170 | return $result_set; 171 | } 172 | 173 | public function fetch( 174 | int $fetch_style = PDO::FETCH_BOTH, 175 | int $cursor_orientation = PDO::FETCH_ORI_NEXT, 176 | int $cursor_offset = 0, 177 | $fetch_argument = null 178 | ) { 179 | $this->__executeWhenStringQueryEmpty(); 180 | switch ($cursor_orientation) { 181 | case PDO::FETCH_ORI_ABS: 182 | $this->cursor = $cursor_offset; 183 | break; 184 | case PDO::FETCH_ORI_REL: 185 | $this->cursor += $cursor_offset; 186 | break; 187 | case PDO::FETCH_ORI_NEXT: 188 | default: 189 | $this->cursor++; 190 | } 191 | 192 | if (isset($this->result_set[$this->cursor])) { 193 | $result = $this->result_set[$this->cursor]; 194 | unset($this->result_set[$this->cursor]); 195 | } else { 196 | $result = false; 197 | } 198 | 199 | if (empty($result)) { 200 | return $result; 201 | } else { 202 | return self::transStyle([$result], $fetch_style, $fetch_argument)[0]; 203 | } 204 | } 205 | 206 | /** 207 | * Returns a single column from the next row of a result set or FALSE if there are no more rows. 208 | * 209 | * @param int $column_number 210 | * 0-indexed number of the column you wish to retrieve from the row. 211 | * If no value is supplied, PDOStatement::fetchColumn() fetches the first column. 212 | * 213 | * @return bool|mixed 214 | */ 215 | public function fetchColumn(int $column_number = 0) 216 | { 217 | $this->__executeWhenStringQueryEmpty(); 218 | return $this->fetch(PDO::FETCH_COLUMN, PDO::FETCH_ORI_NEXT, 0, $column_number); 219 | } 220 | 221 | public function fetchAll(int $fetch_style = PDO::FETCH_BOTH, $fetch_argument = null, array $ctor_args = []) 222 | { 223 | $this->__executeWhenStringQueryEmpty(); 224 | $result_set = self::transStyle($this->result_set, $fetch_style, $fetch_argument, $ctor_args); 225 | $this->result_set = []; 226 | 227 | return $result_set; 228 | } 229 | 230 | } 231 | -------------------------------------------------------------------------------- /src/SwPDO.php: -------------------------------------------------------------------------------- 1 | 5 | * Date: 2018/4/7 下午4:04 6 | */ 7 | 8 | namespace Swlib; 9 | 10 | class SwPDO 11 | { 12 | 13 | /** 14 | * SwPDO constructor. 15 | * @param string $dsn 16 | * @param string $username 17 | * @param string $password 18 | * @param array $driver_options 19 | * 20 | * @return SwPDO\Mysql 21 | */ 22 | public static function construct( 23 | string $dsn, 24 | string $username = '', 25 | string $password = '', 26 | array $driver_options = [] 27 | ) { 28 | $dsn = explode(':', $dsn); 29 | $driver = ucwords(array_shift($dsn)); 30 | $dsn = explode(';', implode(':', $dsn)); 31 | $options = []; 32 | foreach ($dsn as $kv) { 33 | $kv = explode('=', $kv); 34 | if ($kv) { 35 | $options[$kv[0]] = $kv[1] ?? ''; 36 | } 37 | } 38 | $authorization = [ 39 | 'user' => $username, 40 | 'password' => $password, 41 | ]; 42 | $options = $driver_options + $authorization + $options; 43 | $class = SwPDO::class . "\\$driver"; 44 | 45 | return $class::construct($options); 46 | } 47 | 48 | public static function getAvailableDrivers() 49 | { 50 | return ['MySQL']; 51 | } 52 | 53 | } --------------------------------------------------------------------------------