Swoole 5.1 adds more database coroutine client support

In 5.1the version, support for a variety of database coroutine clients has been added, and all PDOare provided in the form of interfaces. Old business codes can be switched to coroutine mode with one click without any changes, and can be executed concurrently asynchronously and non-blockingly.

include:

  1. pdo_pgsql
  2. pdo_odbc
  3. pdo_sqlite
  4. pdo_ociOracledatabase)

Open method

Added 4compilation parameters and Runtime Hookoptions to enable these coroutine clients.

compile options

  • --with-swoole-odbc,relyunixodbc-dev
  • --with-swoole-pgsql,relylibpq-dev
  • --with-swoole-sqlite,relylibsqlite3-dev
  • --with-swoole-oracle,relyoracle-instantclient

Runtime HookOptions

  • SWOOLE_HOOK_PDO_PGSQL
  • SWOOLE_HOOK_PDO_ODBC
  • SWOOLE_HOOK_PDO_SQLITE
  • SWOOLE_HOOK_PDO_ORACLE

These options are included in SWOOLE_HOOK_ALL, or one of the clients can be enabled individually.

PDO_PGSQL

In the previous version, Swoole\Coroutine\PostgreSQLthe client was provided. Since it is brand new API, users need to be compatible PHP-FPMwith and Swoole, and it is not widely used.

go (function () {
     $pg = new  Swoole\Coroutine\PostgreSql ();
     $conn = $pg -> connect ( "host=127.0.0.1 port=5432 dbname=test user=test password=" );
     $result = $pg -> query ( $conn , 'SELECT * FROM test;' );
     $arr = $pg -> fetchAll ( $result );
     var_dump ( $arr );
});

5.1Added in the version Runtime Hook PDO_PGSQL, you can directly use FPMthe historical code under .

go (function () {
     $pdo = new  PDO ( "pgsql:host= {$host} ;port= {$port} ;dbname= {$dbname} " , $user , $password );
     $statement = $pdo - > query ( 'select * from user where id =1 limit 1' );
     var_dump ( $statement -> fetch (PDO:: FETCH_ASSOC ));
});

PDO_ODBC

ODBCOpen Database Connectivity) is a standardized technology that provides a unified interface for multiple database management systems. It was proposed by Microsoft to achieve heterogeneity and enable applications to access multiple different types of data sources. ODBCThe standard defines what applications make requests API, and what drivers provide in response to requests APIODBCIt is an open, cross-platform technology that can be used in a variety of operating systems and programming languages.

Most relational databases support ODBCdrivers, including:

  1. Microsoft SQL Server
  2. Oracle
  3. IBM DB2
  4. MySQL
  5. PostgreSQL
  6. SQLite
  7. Teradata
  8. Microsoft Access
  9. SAP Sybase Adaptive Server Enterprise (ASE)
  10. Informix

These databases use ODBCdrivers to provide access interfaces, allowing developers to use the same code to access data when using different databases.

5.1This version supports PDO_ODBCcoroutine support, and ODBCcan support almost all databases, so that these databases can also run in Swoolecoroutine mode.

LinuxYou need to install the library under unixodbcto supportodbc

sudo apt install unixodbc-dev

Unlike other database drivers, odbcyou need to use odbcinstthe tool to register the database first. The configuration file needs to be implemented Linuxbelow /etc/odbcinst.ini.

odbcinst.ini

[mysql] 
Driver =libmaodbc.so
 Description =MariaDB Connector/ODBC(Unicode)
 Threading = 0 
UsageCount = 1

The configuration file is placed in /etc/odbcinst.iniDriver=libmaodbc.sowhich tells odbcto use this dynamic link library as the driver layer.

To support other more database types, you need to install ODBCthe driver of the database. For example, MySQL ODBCthe driver can useodbc-mariadb

sudo apt install odbc-mariadb

After successful execution, it will be installed libmaodbc.soin the system library directory.

mysql_odbc.ini

To register a database ODBC, you need to write a configuration file, including the database’s host address, user name, password and other information.

[mysql-test] 
Description = MySQL test database
 Trace = On 
TraceFile = stderr
 Driver = mysql
 SERVER = 127.0 . 0.1 
USER = root
 PASSWORD = root
 PORT = 3306 
DATABASE = test

Then use odbcinstthe tool to register the database:

odbcinst -i -d -f ~/mysql-odbc.ini

Can be isqlexecuted using toolsSQL

htf@swoole-12:/etc$ isql mysql-test
+---------------------------------------------+
| Connected! |
| |
| sql-statement |
| help [tablename] |
| quit |
| |
+---------------------------------------------+
SQL> show tables
+------------------------------------------------- ----------------+
| Tables_in_test |
+------------------------------------------------- ----------------+
| ckl |
| custom |
| firmware |
| numbers |
| userinfo |
+------------------------------------------------- ----------------+
SQLRowCount returns 5
5 rows fetched
SQL>

code

Co\ run (function () {
     $pdo = new  PDO ( 'odbc:mysql-test' );
     $statement = $pdo -> prepare ( 'show tables' );
     $statement -> execute ();
     var_dump ( count ( $statement -> fetchAll (PDO:: FETCH_COLUMN )), 1 );
});

PDO_SQLITE

SQLiteA lightweight, open source, embedded relational database management system. Its main advantages are that it is small, fast, has support for transactions, and is portable. Here are SQLitesome of the advantages:

  1. Occupies few resources: SQLiteIt is an embedded database that does not require installation or maintenance. It is stored in the file system of the local operating system in the form of a file and does not need to run a database server process independently. Therefore, it takes up very little resources and can run on resource-constrained embedded devices and mobile devices.
  2. Fast: SQLiteIt is a very fast relational database that can easily handle small and medium-sized data sets. Compared with other traditional relational databases, its read and write speeds are relatively fast.
  3. Support for transactions: SQLiteThe support for transactions is very good compared to other lightweight databases, and supports the Acid attribute to prevent data loss or corruption.
  4. Portability: SQLite’s file format is operating system independent, which enables users to migrate their database files from one operating system to another.

Consider using it in the following situations SQLite:

  1. Local data storage: SQLitesuitable for storing local data in applications, such as user personal data, local settings and cache in mobile applications.
  2. Small and medium-sized data storage: SQLitesuitable for storing small and medium-sized data sets, such as the data of small enterprises or single users, rather than situations where the application scenario is complex or the data set is very large.
  3. Offline data read and write operations are required: Since SQLitethe file format of is independent of the operating system, data can be stored as files and read and written offline.
  4. Rapid prototyping: Because it SQLiteis easy to use and manage, it is suitable for rapid prototyping to test and optimize the application in real production.

5.1The version provides sqlitecoroutine client support for embedded databases, and also uses PDOas the interface layer.

compile options

./configure --enable-swoole-sqlite

need to depend on

libsqlite3-dev

Code example

go (function() {
     $db = new  PDO ( 'sqlite::memory:' );
     $db -> exec ( 'create table test (id int)' );
     $stmt = $db -> prepare ( 'insert into test values(?)' );
     $i = 2024 ;
     $stmt -> execute ([ $i ]);
     $stmt = $db -> prepare ( 'select id from test where id = ?' );
     $stmt -> execute ([ $i ]);
     var_dump ( $stmt -> fetch (PDO:: FETCH_ASSOC )[ 'id' ] == $i );
});

PDO_OCI

OracleThe database is a large-scale relational database developed by Oracle Corporation in the United States. It is used by many large enterprises around the world Oracle. Databases are used in the core systems of many commercial projects such as e-commerce platforms, banks, finance, and telecommunications Oracle.

The following are some features and functions of Oracle database:

  1. High performance: OracleThe database can handle a large number of concurrent user requests and quickly process large-scale data.
  2. Scale: OracleThe database supports large-scale database clusters and complex aggregation operations, making it very popular in large enterprises and business-critical applications.
  3. Redundant backup: OracleThe database provides powerful redundant backup and recovery functions, supporting online backup and recovery, incremental backup and recovery, point-in-time recovery, etc.
  4. Security: OracleThe database provides features for encryption, data masking, access control, and authentication of the database.
  5. Flexibility: OracleThe database supports multiple data types and programming languages, and provides powerful storage, indexing and query functions.
  6. High availability: OracleThe database has high availability and supports master-slave synchronization, automatic failover and fault tolerance functions. These functions can ensure the continuity and stability of the system.
  7. Performance optimization: OracleThe database provides rich performance optimization functions and supports various tuning technologies to ensure that the database runs stably under high load.

5.1Version provides native pdo_ocicoroutine client implementation. The database can be connected and operated concurrently in a coroutine environment Oracle.

compile options

You need to add --with-swoole-oracle=instantclient,/path/to/instant/client/libparameters to enable PDO_OCIthe coroutine client.

OracleYou can download the client driver from the official website

apt install -y libaio-dev
apt install -y libaio1
wget -nv https://download.oracle.com/otn_software/linux/instantclient/instantclient-basiclite-linuxx64.zip
unzip instantclient-basiclite-linuxx64.zip && rm instantclient-basiclite-linuxx64.zip
wget -nv https://download.oracle.com/otn_software/linux/instantclient/instantclient-sdk-linuxx64.zip
unzip instantclient-sdk-linuxx64.zip && rm instantclient-sdk-linuxx64.zip
mv instantclient_*_* ./instantclient
rm ./instantclient/sdk/include/ldap.h
# fix debug build warning: zend_signal: handler was replaced for signal (2) after startup
echo DISABLE_INTERRUPT=on > ./instantclient/network/admin/sqlnet.ora
mv ./instantclient /usr/local/
echo '/usr/local/instantclient' > /etc/ld.so.conf.d/oracle-instantclient.conf
ldconfig

Code example

Co\ run (function () {
     $db = new  PDO ( 'oci:dbname=127.0.0.1:' . $ORACLE_PORT . '/' . $ORACLE_SERVICE_NAME . ';charset=AL32UTF8' , $ORACLE_USER , $ORACLE_PASSWORD );
     $ db -> setAttribute (PDO:: ATTR_CASE , PDO:: CASE_LOWER );
     $db -> exec ( "create table test (id int)" );
     for ( $i = 0 ; $i < 10 ; $i ++) {
         go (function () use ($ db , $ i ){
            $ stmt = $ db -> prepare (" insert  into  test  values ​​(?)");
             $stmt -> execute ([ $i ]);
             $stmt = $db -> prepare ( "select id from test where id = ? " );
             $stmt -> execute ([ $i ]);
             var_dump ( $stmt -> fetch (PDO:: FETCH_ASSOC )[ 'id' ] == $i );
        });
    }
});

Conclusion

In 5.1the version, support for more database coroutine clients has been added, allowing Swoolemultiple databases to be supported in coroutine mode.

Use is selected on the interface PDO APIto maintain PHP-FPMcompatibility with . There is no need to modify the code and there is no additional learning cost.

The implementation uses native APIswoole::coroutine::async, based on scalable AIOthread pool and coroutine scheduling API.

This method is more secure and robust and can be directly used in production environments.