From f50139f7ce6944a2bbeec2fb08d16d32d2d24ea1 Mon Sep 17 00:00:00 2001 From: techno-express Date: Mon, 8 Feb 2021 13:16:36 -0500 Subject: [PATCH] Code cleanup, refactor for PHP 8 compatibility, and bug fixes discovered in doing so - bug fixes, prior to PHP 8, `**@**` silenced errors which this library used to return `**false**` instead, that is not no longer possible with PHP 8 - Linux and Windows CI tests move to GitHub Actions - General code style fixes - merged bug fix https://github.com/ezSQL/ezsql/pull/199 - fixed tests in issue https://github.com/ezSQL/ezsql/issues/200, and corrections for PR https://github.com/ezSQL/ezsql/pull/201 --- .github/install_mssql.sh | 72 ++++++++++++++++ .github/workflows/ezsql-linux.yml | 56 +++++++++++++ .github/workflows/ezsql-windows.yml | 65 +++++++++++++++ .travis.yml | 40 --------- README.md | 6 +- appveyor.yml | 114 -------------------------- lib/Database.php | 12 ++- lib/Database/ez_mysqli.php | 35 ++++---- lib/Database/ez_pdo.php | 53 ++++++++---- lib/Database/ez_pgsql.php | 16 +++- lib/Database/ez_sqlite3.php | 2 +- lib/Database/ez_sqlsrv.php | 100 ++++++++++++----------- lib/ezQuery.php | 16 +++- lib/ezsqlModel.php | 87 +++++++++++++++++++- lib/ezsqlModelInterface.php | 65 --------------- tests/ConfigTest.php | 16 ++-- tests/DInjectorTest.php | 4 +- tests/DatabaseTest.php | 2 +- tests/EZTestCase.php | 2 +- tests/ezSchemaTest.php | 2 +- tests/ezsqlModelTest.php | 2 +- tests/mysqli/mysqliTest.php | 4 +- tests/pdo/pdo_mysqlTest.php | 19 +++-- tests/pdo/pdo_pgsqlTest.php | 26 ++++-- tests/pdo/pdo_sqliteTest.php | 4 +- tests/pdo/pdo_sqlsrvTest.php | 25 ++++-- tests/sqlsrv/sqlsrvTest.php | 8 +- unsupported/install_sql.sh | 122 ---------------------------- 28 files changed, 495 insertions(+), 480 deletions(-) create mode 100644 .github/install_mssql.sh create mode 100644 .github/workflows/ezsql-linux.yml create mode 100644 .github/workflows/ezsql-windows.yml delete mode 100644 .travis.yml delete mode 100644 appveyor.yml delete mode 100644 unsupported/install_sql.sh diff --git a/.github/install_mssql.sh b/.github/install_mssql.sh new file mode 100644 index 0000000..64b19ba --- /dev/null +++ b/.github/install_mssql.sh @@ -0,0 +1,72 @@ +#!/bin/bash -e + +# Use the following variables to control your install: + +# Password for the SA user (required) +MSSQL_SA_PASSWORD='!Passw0rd' + +# Product ID of the version of SQL server you're installing +# Must be evaluation, developer, express, web, standard, enterprise, or your 25 digit product key +# Defaults to developer +MSSQL_PID='evaluation' + +# Install SQL Server Agent (recommended) +SQL_INSTALL_AGENT='y' + +# Install SQL Server Full Text Search (optional) +# SQL_INSTALL_FULLTEXT='y' + +# Create an additional user with sysadmin privileges (optional) +SQL_INSTALL_USER='ez_test' +SQL_INSTALL_USER_PASSWORD='ezTest' +SQL_INSTALL_DATABASE='ez_test' + +if [ -z $MSSQL_SA_PASSWORD ] +then + echo Environment variable MSSQL_SA_PASSWORD must be set for unattended install + exit 1 +fi + +echo Adding Microsoft repositories... +sudo curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add - +sudo curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add - +repoargs="$(curl https://packages.microsoft.com/config/ubuntu/18.04/mssql-server-2019.list)" +sudo add-apt-repository "${repoargs}" + +echo Running apt-get update -y... +sudo apt-get update -y + +echo Installing SQL Server... +sudo apt-get install -y mssql-server + +echo Running mssql-conf setup... +sudo MSSQL_SA_PASSWORD=$MSSQL_SA_PASSWORD \ + MSSQL_PID=$MSSQL_PID \ + /opt/mssql/bin/mssql-conf -n setup accept-eula + +# Configure firewall to allow TCP port 1433: +echo Configuring UFW to allow traffic on port 1433... +sudo ufw allow 1433/tcp +sudo ufw reload + +# Restart SQL Server after installing: +echo Restarting SQL Server... +sudo systemctl restart mssql-server + +# Optional new user creation: +if [ ! -z $SQL_INSTALL_USER ] && [ ! -z $SQL_INSTALL_USER_PASSWORD ] +then + echo Creating user $SQL_INSTALL_USER + sqlcmd \ + -S localhost \ + -U SA \ + -P $MSSQL_SA_PASSWORD \ + -Q "CREATE DATABASE ez_test" + sqlcmd \ + -S localhost \ + -U SA \ + -P $MSSQL_SA_PASSWORD \ + -Q "CREATE LOGIN [$SQL_INSTALL_USER] WITH PASSWORD=N'$SQL_INSTALL_USER_PASSWORD', DEFAULT_DATABASE=[$SQL_INSTALL_DATABASE], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF; ALTER SERVER ROLE [sysadmin] ADD MEMBER [$SQL_INSTALL_USER]" +fi + +echo Done! diff --git a/.github/workflows/ezsql-linux.yml b/.github/workflows/ezsql-linux.yml new file mode 100644 index 0000000..edcf375 --- /dev/null +++ b/.github/workflows/ezsql-linux.yml @@ -0,0 +1,56 @@ +# GitHub Action for PHP with extensions +name: Linux + +on: + push: + branches: + - master + pull_request: + branches: + - master + +jobs: + linux: + name: Linux (PHP ${{ matrix.php-versions }} CI) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + operating-system: [ubuntu-latest] + php-versions: ['7.4', '8.0'] + + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup PHP, with composer and extensions + uses: shivammathur/setup-php@v2 #https://github.com/shivammathur/setup-php + with: + php-version: ${{ matrix.php-versions }} + extensions: mbstring, fileinfo, mysqli, pdo_mysql, pgsql, pdo_pgsql, sqlite3, pdo_sqlite, sqlsrv, pdo_sqlsrv, xdebug + coverage: xdebug + - name: Start MySQL + run: sudo systemctl start mysql.service + - name: Setup MySQL Database + run: | + mysql -uroot -h127.0.0.1 -proot -e "CREATE DATABASE IF NOT EXISTS ez_test;" + mysql -uroot -h127.0.0.1 -proot -e "CREATE USER ez_test@localhost IDENTIFIED BY 'ezTest'; GRANT ALL ON ez_test.* TO ez_test@localhost; FLUSH PRIVILEGES;" + - name: Start PostgreSql + run: | + sudo systemctl start postgresql.service + pg_isready + - name: Create additional user + run: | + sudo -u postgres psql --command="CREATE USER ez_test PASSWORD 'ezTest'" --command="\du" + - name: Setup PostgreSql Database + run: | + sudo -u postgres createdb --owner=ez_test ez_test + - name: Setup SQLServer Database + run: | + chmod +x "${GITHUB_WORKSPACE}/.github/install_mssql.sh" + "${GITHUB_WORKSPACE}/.github/install_mssql.sh" + - name: Install dependencies + run: composer update + - name: Test with phpunit + run: vendor/bin/phpunit --coverage-clover=coverage.xml + - name: Submit code coverage + run: bash <(curl -s https://codecov.io/bash) diff --git a/.github/workflows/ezsql-windows.yml b/.github/workflows/ezsql-windows.yml new file mode 100644 index 0000000..1bb2273 --- /dev/null +++ b/.github/workflows/ezsql-windows.yml @@ -0,0 +1,65 @@ +# GitHub Action for PHP with extensions +name: Windows + +on: + push: + branches: + - master + pull_request: + branches: + - master + +jobs: + windows: + name: Windows (PHP ${{ matrix.php-versions }} CI) + runs-on: windows-latest + strategy: + fail-fast: false + matrix: + operating-system: [windows-latest] + php-versions: ['7.1', '7.2'] + + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup PHP, with composer and extensions + uses: shivammathur/setup-php@v2 #https://github.com/shivammathur/setup-php + with: + php-version: ${{ matrix.php-versions }} + extensions: mbstring, fileinfo, mysqli, pdo_mysql, pgsql, pdo_pgsql, sqlite3, pdo_sqlite, sqlsrv, pdo_sqlsrv, xdebug + coverage: xdebug + - name: Chocolatey Install MySQL + run: choco install mysql --version=5.7.18 -y -f + - name: Setup MySQL Database + run: | + mysql -u root -e "CREATE DATABASE IF NOT EXISTS ez_test;" + mysql -u root -e "CREATE USER ez_test@localhost IDENTIFIED BY 'ezTest'; GRANT ALL ON ez_test.* TO ez_test@localhost; FLUSH PRIVILEGES;" + - name: Chocolatey Uninstall PostgreSql 13 + run: choco uninstall postgresql13 -y -f + - name: Chocolatey Install PostgreSql 9 + run: choco install postgresql9 --params '/Password:root' -y -f + - name: Setup PostgreSql Database + run: | + $env:Path += ";C:\Program Files\PostgreSQL\9.6\bin" + $env:PGPASSWORD = "root" + psql -U postgres --command="\conninfo" + psql -U postgres -c "CREATE USER ez_test WITH PASSWORD 'ezTest';" --command="\du" + createdb --owner=ez_test ez_test + [Environment]::SetEnvironmentVariable("Path", $env:Path, [EnvironmentVariableTarget]::Machine) + - name: Chocolatey Install SQLServer + run: choco install sql-server-express -ia "/IACCEPTSQLSERVERLICENSETERMS /Q /ACTION=install /INSTANCEID=MSSQLSERVER /INSTANCENAME=MSSQLSERVER /UPDATEENABLED=FALSE /TCPENABLED=1 /SECURITYMODE=SQL /SAPWD=Password12!" -o -y -f + - name: Setup SQLServer Database + run: | + sqlcmd -L + New-NetFirewallRule -DisplayName "SQLServer default instance" -Direction Inbound -LocalPort 1433 -Protocol TCP -Action Allow + New-NetFirewallRule -DisplayName "SQLServer Browser service" -Direction Inbound -LocalPort 1434 -Protocol UDP -Action Allow + sqlcmd -S localhost,1433 -U sa -P Password12! -Q "CREATE DATABASE ez_test" + sqlcmd -S localhost,1433 -U sa -P Password12! -d ez_test -Q "CREATE LOGIN ez_test WITH PASSWORD=N'ezTest', DEFAULT_DATABASE=ez_test, CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF; ALTER SERVER ROLE [sysadmin] ADD MEMBER ez_test" + - name: Install dependencies + run: composer update + - name: Test with phpunit + run: vendor\bin\phpunit --coverage-clover=coverage.xml + - name: Submit code coverage + uses: codecov/codecov-action@v1 + with: + file: ./coverage.xml # optional diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 4a011dc..0000000 --- a/.travis.yml +++ /dev/null @@ -1,40 +0,0 @@ -language: php - -# Versions of PHP you want your project run with. -php: - - 7.1 - - 7.2 - - 7.4 - - 8.0 - -matrix: - allow_failures: - - php: 8.0 - fast_finish: true - -env: - - MYSQL_HOST=127.0.0.1 MYSQL_USER=root - -services: - - mysql - - postgresql - -# Commands to be run before your environment runs. -before_script: - - composer install --no-interaction --no-progress --prefer-dist -# - composer require phpstan/phpstan "0.11.3" - - mysql -e 'CREATE DATABASE IF NOT EXISTS ez_test;' - - mysql -e "CREATE USER ez_test@localhost IDENTIFIED BY 'ezTest'; GRANT ALL ON ez_test.* TO ez_test@localhost; FLUSH PRIVILEGES;" - - psql -c 'CREATE DATABASE ez_test;' -U postgres - - psql -c "CREATE USER ez_test WITH PASSWORD 'ezTest';" -U postgres -# - mysql -e 'GRANT ALL PRIVILEGES ON ez_test.* TO ez_test@localhost;' -# - mysql -e "SET PASSWORD FOR 'ez_test'@'localhost' = PASSWORD('ezTest')" - -after_success: - - bash <(curl -s https://codecov.io/bash) - - travis_retry php vendor/bin/php-coveralls - -# Commands you want to run that will verify your build. -script: - - vendor/bin/phpunit --coverage-clover=coverage.xml -# - vendor/bin/phpstan analyse lib tests --level=1 diff --git a/README.md b/README.md index 526839b..46268f5 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@ # **ezsql** -[![Build Status](https://travis-ci.org/ezSQL/ezsql.svg?branch=master)](https://travis-ci.org/ezSQL/ezsql) -[![Build status](https://ci.appveyor.com/api/projects/status/6s8oqnoxa2i5k04f?svg=true)](https://ci.appveyor.com/project/jv2222/ezsql) +[![Windows](https://github.com/ezSQL/ezsql/workflows/Windows/badge.svg)](https://github.com/ezSQL/ezsql/actions?query=workflow%3AWindows) +[![Linux](https://github.com/ezSQL/ezsql/workflows/Linux/badge.svg)](https://github.com/ezSQL/ezsql/actions?query=workflow%3ALinux) [![codecov](https://codecov.io/gh/ezSQL/ezSQL/branch/master/graph/badge.svg)](https://codecov.io/gh/ezSQL/ezSQL) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/aad1f6aaaaa14f60933e75615da900b8)](https://www.codacy.com/app/techno-express/ezsql?utm_source=github.com&utm_medium=referral&utm_content=ezSQL/ezsql&utm_campaign=Badge_Grade) [![Maintainability](https://api.codeclimate.com/v1/badges/6f6107f25e9de7bf4272/maintainability)](https://codeclimate.com/github/ezSQL/ezsql/maintainability) -[![Total Downloads](https://poser.pugx.org/jv2222/ezsql/downloads)](https://packagist.org/packages/jv2222/ezsql) +[![Total Downloads](https://poser.pugx.org/ezSQL/ezsql/downloads)](https://packagist.org/packages/ezSQL/ezsql) ***A class to make it very easy to deal with database connections.*** diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index 2804ddc..0000000 --- a/appveyor.yml +++ /dev/null @@ -1,114 +0,0 @@ -build: false -platform: - - x64 -clone_folder: c:\projects\php-project-workspace - -## Build matrix for lowest and highest possible targets -environment: - matrix: - - php_ver_target: 7.3.11 - MYSQL_DATABASE: ez_test - MYSQL_HOST: localhost - MYSQL_USER: root - MYSQL_PASSWORD: Password12! - MYSQL_PATH: C:\Program Files\MySQL\MySQL Server 5.7 - -services: - - mssql2014 - - mysql - - postgresql - -## Set up environment variables -init: - - SET COMPOSER_NO_INTERACTION=1 - - SET PHP=1 # This var is connected to PHP install cache - - SET ANSICON=121x90 (121x90) - -## Install PHP and composer, and run the appropriate composer command Get the MSSQL DLL's and XDEBUG -install: - # Enable Windows Update service, needed to install vcredist2015 (dependency of php) - - IF EXIST c:\tools\php73 (SET PHP=0) - - ps: Set-Service wuauserv -StartupType Manual - - choco config set cacheLocation %LOCALAPPDATA%\Temp\Chocolatey - - choco install -y php --version %php_ver_target% - - choco install -y sqlite - - choco install -y composer - - refreshenv - - composer install --no-interaction --no-progress --prefer-dist - - cd C:\tools\php73 - # Get the MSSQL DLL's - - ps: >- - If ($env:PHP -eq "1") { - $DLLVersion = "5.6.1" - cd C:\tools\php73\ext - $source = "http://windows.php.net/downloads/pecl/releases/sqlsrv/$($DLLVersion)/php_sqlsrv-$($DLLVersion)-7.3-nts-vc15-x64.zip" - $destination = "C:\tools\php73\ext\php_sqlsrv-$($DLLVersion)-7.3-nts-vc15-x64.zip" - Invoke-WebRequest $source -OutFile $destination - 7z x -y php_sqlsrv-$($DLLVersion)-7.3-nts-vc15-x64.zip > $null - $source = "http://windows.php.net/downloads/pecl/releases/pdo_sqlsrv/$($DLLVersion)/php_pdo_sqlsrv-$($DLLVersion)-7.3-nts-vc15-x64.zip" - $destination = "C:\tools\php73\ext\php_pdo_sqlsrv-$($DLLVersion)-7.3-nts-vc15-x64.zip" - Invoke-WebRequest $source -OutFile $destination - 7z x -y php_pdo_sqlsrv-$($DLLVersion)-7.3-nts-vc15-x64.zip > $null - Remove-Item C:\tools\php73\ext* -include .zip - Invoke-WebRequest "https://xdebug.org/files/php_xdebug-2.7.2-7.3-vc15-nts-x86_64.dll" -OutFile "C:\tools\php73\ext\php_xdebug-2.7.2-7.3-vc15-nts-x86_64.dll" - cd C:\tools\php73 - } - - IF %PHP%==1 echo date.timezone="UTC" >> php.ini - - IF %PHP%==1 echo extension_dir=ext >> php.ini - - IF %PHP%==1 echo extension=php_fileinfo.dll >> php.ini - - ps: >- - If ($env:php_ver_target -eq "5.6") { - Add-Content php.ini "`nextension=php_sqlsrv_nts.dll" - Add-Content php.ini "`nextension=php_pdo_sqlsrv_nts.dll" - Add-Content php.ini "`n" - } Else { - Add-Content php.ini "`nextension=php_sqlsrv.dll" - Add-Content php.ini "`nextension=php_pdo_sqlsrv.dll" - Add-Content php.ini "`n" - } - - IF %PHP%==1 echo extension=php_pgsql.dll >> php.ini - - IF %PHP%==1 echo extension=php_pdo_pgsql.dll >> php.ini - - IF %PHP%==1 echo extension=php_sqlite3.dll >> php.ini - - IF %PHP%==1 echo extension=php_pdo_sqlite.dll >> php.ini - - IF %PHP%==1 echo extension=php_mysqli.dll >> php.ini - - IF %PHP%==1 echo extension=php_pdo_mysql.dll >> php.ini - - IF %PHP%==1 echo [xdebug] >> php.ini - - IF %PHP%==1 echo zend_extension=php_xdebug-2.7.2-7.3-vc15-nts-x86_64.dll >> php.ini - - IF %PHP%==1 echo zend.assertions=1 >> php.ini - - IF %PHP%==1 echo assert.exception=On >> php.ini - - IF %PHP%==1 echo xdebug.remote_enable=1 >> php.ini - - IF %PHP%==1 echo xdebug.remote_autostart=1 >> php.ini - - IF %PHP%==1 echo xdebug.profiler_enable=off >> php.ini - - cd c:\projects\php-project-workspace - - composer self-update -# - composer require phpstan/phpstan "0.11.3" - -build_script: - # postgres - - SET PGUSER=postgres - - SET PGPASSWORD=Password12! - - PATH=C:\Program Files\PostgreSQL\9.6\bin\;%PATH% - - createdb ez_test - - psql -c "CREATE USER ez_test WITH PASSWORD 'ezTest';" - # sqlserver - - sqlcmd -S localhost,1433 -U sa -P Password12! -Q "CREATE DATABASE ez_test" - - sqlcmd -S localhost,1433 -U sa -P Password12! -d ez_test -Q "CREATE LOGIN ez_test WITH PASSWORD=N'ezTest', DEFAULT_DATABASE=ez_test, CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF; ALTER SERVER ROLE [sysadmin] ADD MEMBER ez_test" - -before_test: - - SET PATH=%MYSQL_PATH%\bin;%PATH% - - mysqladmin --host=%MYSQL_HOST% --user=%MYSQL_USER% --password=%MYSQL_PASSWORD% create %MYSQL_DATABASE% - # mysql - - mysql -u root -p"Password12!" -e "CREATE DATABASE IF NOT EXISTS ez_test;" - - mysql -u root -p"Password12!" -e "GRANT ALL PRIVILEGES ON ez_test.* TO ez_test@localhost IDENTIFIED BY 'ezTest'"; - - mysql -u root -p"Password12!" -e "FLUSH PRIVILEGES;" - -on_success: - - ps: | - $env:PATH = 'C:\msys64\usr\bin;' + $env:PATH - Invoke-WebRequest -Uri 'https://codecov.io/bash' -OutFile codecov.sh - bash codecov.sh -f "coverage.xml" - -## Run the actual test -test_script: - - cd c:\projects\php-project-workspace - - vendor\bin\phpunit --coverage-clover=coverage.xml diff --git a/lib/Database.php b/lib/Database.php index b512608..914d068 100644 --- a/lib/Database.php +++ b/lib/Database.php @@ -18,11 +18,14 @@ class Database private static $instances = []; private function __construct() - { } + { + } private function __clone() - { } - private function __wakeup() - { } + { + } + public function __wakeup() + { + } /** * Initialize and connect a vendor database. @@ -30,6 +33,7 @@ private function __wakeup() * @param mixed $vendor - SQL driver * @param mixed $setting - SQL connection parameters * @param mixed $tag - Store the instance for later use + * @return Database\ez_pdo|Database\ez_pgsql|Database\ez_sqlsrv|Database\ez_sqlite3|Database\ez_mysqli */ public static function initialize(?string $vendor = null, ?array $setting = null, ?string $tag = null) { diff --git a/lib/Database/ez_mysqli.php b/lib/Database/ez_mysqli.php index 16b9326..2ec89af 100644 --- a/lib/Database/ez_mysqli.php +++ b/lib/Database/ez_mysqli.php @@ -18,7 +18,7 @@ class ez_mysqli extends ezsqlModel implements DatabaseInterface /** * Database connection handle - * @var resource + * @var \mysqli */ private $dbh; @@ -132,19 +132,13 @@ public function connect( */ public function select($name = '', $charset = '') { - $this->_connected = false; $name = empty($name) ? $this->database->getName() : $name; - if (!$this->dbh) { - // Must have an active database connection - $this->register_error(\FAILED_CONNECTION . ' in ' . __FILE__ . ' on line ' . __LINE__); - } elseif (!\mysqli_select_db($this->dbh, $name)) { + try { // Try to connect to the database - // Try to get error supplied by mysql if not use our own - if (!$str = \mysqli_error($this->dbh)) { - $str = 'Unexpected error while trying to select database'; + if (($this->dbh === null) || ($this->_connected === false) || !\mysqli_select_db($this->dbh, $name)) { + throw new Exception("Error Processing Request", 1); } - $this->register_error($str . ' in ' . __FILE__ . ' on line ' . __LINE__); - } else { + $this->database->setName($name); if ($charset == '') { $charset = $this->database->getCharset(); @@ -162,10 +156,21 @@ public function select($name = '', $charset = '') \mysqli_query($this->dbh, 'SET NAMES \'' . $encoding . '\''); } } - $this->_connected = true; - } - return $this->_connected; + return true; + } catch (\Throwable $e) { + $str = \FAILED_CONNECTION; + // Must have an active database connection + if ($this->dbh && $this->_connected) { + // Try to get error supplied by mysql if not use our own + if (!$str = \mysqli_error($this->dbh)) { + $str = 'Unexpected error while trying to select database'; + } + } + + $this->register_error($str . ' in ' . __FILE__ . ' on line ' . __LINE__); + return false; + } } // select /** @@ -225,7 +230,7 @@ private function fetch_prepared_result(&$stmt, $query) } // Binds variables to a prepared statement for result storage - \call_user_func_array([$stmt, 'bind_result'], $variables); + \call_user_func_array([$stmt, 'bind_result'], \array_values($variables)); $i = 0; // Store Query Results diff --git a/lib/Database/ez_pdo.php b/lib/Database/ez_pdo.php index 8b80dbb..f379058 100644 --- a/lib/Database/ez_pdo.php +++ b/lib/Database/ez_pdo.php @@ -19,7 +19,7 @@ class ez_pdo extends ezsqlModel implements DatabaseInterface /** * Database connection handle - * @var resource + * @var \PDO */ private $dbh; @@ -239,14 +239,18 @@ public function query_prepared(string $query, array $param = null, $isSelect = f { $stmt = $this->dbh->prepare($query); $result = false; - if ($stmt && $stmt->execute($param)) { + if ($stmt && $stmt->execute(\array_values($param))) { $result = $stmt->rowCount(); // Store Query Results $num_rows = 0; - while ($row = @$stmt->fetch(\PDO::FETCH_ASSOC)) { - // Store results as an objects within main array - $this->last_result[$num_rows] = (object) $row; - $num_rows++; + try { + while ($row = @$stmt->fetch(\PDO::FETCH_ASSOC)) { + // Store results as an objects within main array + $this->last_result[$num_rows] = (object) $row; + $num_rows++; + } + } catch (\Throwable $ex) { + // } $this->num_rows = $num_rows; @@ -300,10 +304,14 @@ private function processResult(string $query, $result = null, bool $isSelect = f // Store Query Results $num_rows = 0; - while ($row = @$result->fetch(\PDO::FETCH_ASSOC)) { - // Store results as an objects within main array - $this->last_result[$num_rows] = (object) $row; - $num_rows++; + try { + while ($row = @$result->fetch(\PDO::FETCH_ASSOC)) { + // Store results as an objects within main array + $this->last_result[$num_rows] = (object) $row; + $num_rows++; + } + } catch (\Throwable $ex) { + // } // Log number of rows the query returned @@ -318,9 +326,13 @@ private function processResult(string $query, $result = null, bool $isSelect = f if (!empty($result)) $this->_affectedRows = $result; - // Take note of the insert_id - if (\preg_match("/^(insert|replace)\s+/i", $query)) { - $this->insert_id = @$this->dbh->lastInsertId(); + try { + // Take note of the insert_id + if (\preg_match("/^(insert|replace)\s+/i", $query)) { + $this->insert_id = @$this->dbh->lastInsertId(); + } + } catch (\Throwable $ex) { + // } // Return number of rows affected @@ -346,8 +358,13 @@ private function processQuery(string $query, array $param = null) if (!empty($param) && \is_array($param) && $this->isPrepareOn()) { $this->shortcutUsed = true; $this->_affectedRows = $this->query_prepared($query, $param, false); - } else - $this->_affectedRows = $this->dbh->exec($query); + } else { + try { + $this->_affectedRows = $this->dbh->exec($query); + } catch (\Throwable $ex) { + // + } + } if ($this->processResult($query) === false) return false; @@ -360,7 +377,11 @@ private function processQuery(string $query, array $param = null) $this->shortcutUsed = true; $sth = $this->query_prepared($query, $param, true); } else - $sth = $this->dbh->query($query); + try { + $sth = $this->dbh->query($query); + } catch (\Throwable $ex) { + // + } if ($this->processResult($query, $sth, true) === false) return false; diff --git a/lib/Database/ez_pgsql.php b/lib/Database/ez_pgsql.php index 4f56e16..3d5eed8 100644 --- a/lib/Database/ez_pgsql.php +++ b/lib/Database/ez_pgsql.php @@ -162,9 +162,13 @@ private function processQueryResult(string $query, $result = null) if (!empty($result)) $this->result = $result; - // If there is an error then take note of it.. - if ($str = @\pg_last_error($this->dbh)) { - return $this->register_error($str); + try { + // If there is an error then take note of it.. + if ($str = @\pg_last_error($this->dbh)) { + return $this->register_error($str); + } + } catch (\Throwable $ex) { + return $this->register_error($ex->getMessage()); } // Query was an insert, delete, update, replace @@ -298,7 +302,11 @@ public function query(string $query, bool $use_prepare = false) $this->shortcutUsed = true; $this->result = $this->query_prepared($query, $param); } else { - $this->result = @\pg_query($this->dbh, $query); + try { + $this->result = @\pg_query($this->dbh, $query); + } catch (\Throwable $ex) { + // + } } if ($this->processQueryResult($query) === false) { diff --git a/lib/Database/ez_sqlite3.php b/lib/Database/ez_sqlite3.php index 8c9a7f3..b7dead0 100644 --- a/lib/Database/ez_sqlite3.php +++ b/lib/Database/ez_sqlite3.php @@ -18,7 +18,7 @@ class ez_sqlite3 extends ezsqlModel implements DatabaseInterface /** * Database connection handle - * @var resource + * @var \SQLite3 */ private $dbh; diff --git a/lib/Database/ez_sqlsrv.php b/lib/Database/ez_sqlsrv.php index ccfe580..154f260 100644 --- a/lib/Database/ez_sqlsrv.php +++ b/lib/Database/ez_sqlsrv.php @@ -179,61 +179,65 @@ private function processQueryResult(string $query, $result = null) // Query was an insert, delete, update, replace $this->is_insert = false; - if (\preg_match("/^(insert|delete|update|replace)\s+/i", $query)) { - $this->is_insert = true; - $this->_affectedRows = @\sqlsrv_rows_affected($this->result); - - // Take note of the insert_id - if (\preg_match("/^(insert|replace)\s+/i", $query)) { - $identityResultset = @\sqlsrv_query($this->dbh, "select SCOPE_IDENTITY()"); - - if ($identityResultset != false) { - $identityRow = @\sqlsrv_fetch($identityResultset); - $this->insert_id = $identityRow[0]; + try { + if (\preg_match("/^(insert|delete|update|replace)\s+/i", $query)) { + $this->is_insert = true; + $this->_affectedRows = @\sqlsrv_rows_affected($this->result); + + // Take note of the insert_id + if (\preg_match("/^(insert|replace)\s+/i", $query)) { + $identityResultset = @\sqlsrv_query($this->dbh, "select SCOPE_IDENTITY()"); + + if ($identityResultset != false) { + $identityRow = @\sqlsrv_fetch($identityResultset); + $this->insert_id = $identityRow[0]; + } } - } - // Return number of rows affected - $this->return_val = $this->_affectedRows; - } else { // Query was a select - // Take note of column info - $i = 0; - foreach (@\sqlsrv_field_metadata($this->result) as $field) { - $col = []; - foreach ($field as $name => $value) { - $name = \strtolower($name); - if ($name == "size") { - $name = "max_length"; - } elseif ($name == "type") { - $name = "typeid"; + // Return number of rows affected + $this->return_val = $this->_affectedRows; + } else { // Query was a select + // Take note of column info + $i = 0; + foreach (@\sqlsrv_field_metadata($this->result) as $field) { + $col = []; + foreach ($field as $name => $value) { + $name = \strtolower($name); + if ($name == "size") { + $name = "max_length"; + } elseif ($name == "type") { + $name = "typeid"; + } + + //DEFINED FOR E_STRICT + $col = new \stdClass(); + $col->{$name} = $value; } - //DEFINED FOR E_STRICT - $col = new \stdClass(); - $col->{$name} = $value; + $col->type = $this->get_datatype($col); + $this->col_info[$i++] = $col; + unset($col); } - $col->type = $this->get_datatype($col); - $this->col_info[$i++] = $col; - unset($col); - } - - // Store Query Results - $num_rows = 0; + // Store Query Results + $num_rows = 0; - while ($row = @\sqlsrv_fetch_object($this->result)) { + while ($row = @\sqlsrv_fetch_object($this->result)) { - // Store results as an objects within main array - $this->last_result[$num_rows] = $row; - $num_rows++; - } + // Store results as an objects within main array + $this->last_result[$num_rows] = $row; + $num_rows++; + } - @\sqlsrv_free_stmt($this->result); + @\sqlsrv_free_stmt($this->result); - // Log number of rows the query returned - $this->num_rows = $num_rows; + // Log number of rows the query returned + $this->num_rows = $num_rows; - // Return number of rows selected - $this->return_val = $this->num_rows; + // Return number of rows selected + $this->return_val = $this->num_rows; + } + } catch (\Throwable $ex) { + return false; } return $this->return_val; @@ -300,7 +304,11 @@ public function query(string $query, bool $use_prepare = false) $this->shortcutUsed = true; $this->result = $this->query_prepared($query, $param); } else { - $this->result = @\sqlsrv_query($this->dbh, $query); + try { + $this->result = @\sqlsrv_query($this->dbh, $query); + } catch (\Throwable $ex) { + // + } } if ($this->processQueryResult($query) === false) { diff --git a/lib/ezQuery.php b/lib/ezQuery.php index b94c433..88a76f5 100644 --- a/lib/ezQuery.php +++ b/lib/ezQuery.php @@ -812,7 +812,15 @@ public function get_results( return array(); } - // query call template + // + + /** + * query call template + * + * @param string $query + * @param bool $use_prepare + * @return bool|mixed + */ public function query(string $query, bool $use_prepare = false) { return false; @@ -965,6 +973,12 @@ public function alter(string $table = null, ...$schemas) return false; } + /** + * Does an drop table query if table exists. + * @param $table - database table to erase + * + * @return bool + */ public function drop(string $table = null) { if (empty($table)) diff --git a/lib/ezsqlModel.php b/lib/ezsqlModel.php index 9371019..6de9efc 100644 --- a/lib/ezsqlModel.php +++ b/lib/ezsqlModel.php @@ -174,9 +174,73 @@ public function __construct() } /** - * Use for Calling Non-Existent Functions, handling Getters and Setters + * Magic methods for Calling Non-Existent Functions, handling Getters and Setters. * @method set/get{property} - a property that needs to be accessed * + * @method void setDebug_All($args); + * @method void setTrace($args); + * @method void setDebug_Called($args); + * @method void setVarDump_Called($args); + * @method void setShow_Errors($args); + * @method void setNum_Queries($args); + * @method void setConn_Queries($args); + * @method void setCaptured_Errors($args); + * @method void setCache_Dir($args); + * @method void setUse_Disk_Cache($args); + * @method void setCache_Timeout($args); + * @method void setCache_Queries($args); + * @method void setCache_Inserts($args); + * @method void setNum_Rows($args); + * @method void setDb_Connect_Time($args); + * @method void setSql_Log_File($args); + * @method void setProfile_Times($args); + * @method void setInsert_Id($args); + * @method void setLast_Query($args); + * @method void setLast_Error($args); + * @method void setCol_Info($args); + * @method void setTimers($args); + * @method void setTotal_Query_Time($args); + * @method void setTrace_Log($args); + * @method void setUse_Trace_Log($args); + * @method void setDo_Profile($args); + * @method void setLast_Result($args); + * @method void setFrom_Disk_Cache($args); + * @method void setDebug_Echo_Is_On($args); + * @method void setFunc_Call($args); + * @method void setAll_Func_Calls($args); + * + * @method string getDebug_All(); + * @method string getTrace(); + * @method string getDebug_Called(); + * @method string getVarDump_Called(); + * @method string getShow_Errors(); + * @method string getNum_Queries(); + * @method string getConn_Queries(); + * @method string getCaptured_Errors(); + * @method string getCache_Dir(); + * @method string getUse_Disk_Cache(); + * @method string getCache_Timeout(); + * @method string getCache_Queries(); + * @method string getCache_Inserts(); + * @method string getNum_Rows(); + * @method string getDb_Connect_Time(); + * @method string getSql_Log_File(); + * @method string getProfile_Times(); + * @method string getInsert_Id(); + * @method string getLast_Query(); + * @method string getLast_Error(); + * @method string getCol_Info(); + * @method string getTimers(); + * @method string getTotal_Query_Time(); + * @method string getTrace_Log(); + * @method string getUse_Trace_Log(); + * @method string getDo_Profile(); + * @method string getLast_Result(); + * @method string getFrom_Disk_Cache(); + * @method string getDebug_Echo_Is_On(); + * @method string getFunc_Call(); + * @method string getAll_Func_Calls(); + * * @property-read function * @property-write args * @@ -258,8 +322,8 @@ public function flush() // Get rid of these $this->last_result = null; $this->col_info = array(); - $this->last_query = null; - $this->all_func_calls = array(); + $this->last_query = null; + $this->all_func_calls = array(); $this->from_disk_cache = false; $this->clearPrepare(); } @@ -337,7 +401,7 @@ public function get_col(string $query = null, int $x = 0, bool $use_prepare = fa return $new_array; } - public function get_results(string $query = null, $output = \OBJECT, bool $use_prepare = false) + public function get_results(string $query = null, $output = \OBJECT, bool $use_prepare = false) { // Log how the function was called $this->log_query("\$db->get_results(\"$query\", $output, $use_prepare)"); @@ -664,16 +728,31 @@ public function secureReset() $this->secureOptions = null; } + /** + * Returns `true` if the database connection is established. + * + * @return bool + */ public function isConnected() { return $this->_connected; } // isConnected + /** + * Returns the `number` of affected rows of a query. + * + * @return int + */ public function affectedRows() { return $this->_affectedRows; } // affectedRows + /** + * Returns the last query `result`. + * + * @return object + */ public function queryResult() { return $this->last_result; diff --git a/lib/ezsqlModelInterface.php b/lib/ezsqlModelInterface.php index 74b8be7..171e5f2 100644 --- a/lib/ezsqlModelInterface.php +++ b/lib/ezsqlModelInterface.php @@ -2,71 +2,6 @@ namespace ezsql; -/** - * @method void setDebug_All($args); - * @method void setTrace($args); - * @method void setDebug_Called($args); - * @method void setVarDump_Called($args); - * @method void setShow_Errors($args); - * @method void setNum_Queries($args); - * @method void setConn_Queries($args); - * @method void setCaptured_Errors($args); - * @method void setCache_Dir($args); - * @method void setUse_Disk_Cache($args); - * @method void setCache_Timeout($args); - * @method void setCache_Queries($args); - * @method void setCache_Inserts($args); - * @method void setNum_Rows($args); - * @method void setDb_Connect_Time($args); - * @method void setSql_Log_File($args); - * @method void setProfile_Times($args); - * @method void setInsert_Id($args); - * @method void setLast_Query($args); - * @method void setLast_Error($args); - * @method void setCol_Info($args); - * @method void setTimers($args); - * @method void setTotal_Query_Time($args); - * @method void setTrace_Log($args); - * @method void setUse_Trace_Log($args); - * @method void setDo_Profile($args); - * @method void setLast_Result($args); - * @method void setFrom_Disk_Cache($args); - * @method void setDebug_Echo_Is_On($args); - * @method void setFunc_Call($args); - * @method void setAll_Func_Calls($args); - * - * @method string getDebug_All(); - * @method string getTrace(); - * @method string getDebug_Called(); - * @method string getVarDump_Called(); - * @method string getShow_Errors(); - * @method string getNum_Queries(); - * @method string getConn_Queries(); - * @method string getCaptured_Errors(); - * @method string getCache_Dir(); - * @method string getUse_Disk_Cache(); - * @method string getCache_Timeout(); - * @method string getCache_Queries(); - * @method string getCache_Inserts(); - * @method string getNum_Rows(); - * @method string getDb_Connect_Time(); - * @method string getSql_Log_File(); - * @method string getProfile_Times(); - * @method string getInsert_Id(); - * @method string getLast_Query(); - * @method string getLast_Error(); - * @method string getCol_Info(); - * @method string getTimers(); - * @method string getTotal_Query_Time(); - * @method string getTrace_Log(); - * @method string getUse_Trace_Log(); - * @method string getDo_Profile(); - * @method string getLast_Result(); - * @method string getFrom_Disk_Cache(); - * @method string getDebug_Echo_Is_On(); - * @method string getFunc_Call(); - * @method string getAll_Func_Calls(); - */ interface ezsqlModelInterface { /** diff --git a/tests/ConfigTest.php b/tests/ConfigTest.php index b824dd7..5cd8f0e 100644 --- a/tests/ConfigTest.php +++ b/tests/ConfigTest.php @@ -45,7 +45,7 @@ public function testErrorMysqli() } $this->expectException(\Exception::class); - $this->expectExceptionMessageMatches('/[Missing configuration details to connect to database]/'); + $this->expectExceptionMessageRegExp('/[Missing configuration details to connect to database]/'); $settings = Config::initialize('mysqli', [self::TEST_DB_USER, self::TEST_DB_PASSWORD]); } @@ -88,7 +88,7 @@ public function testErrorPdo() $dsn = 'mysql:host=' . self::TEST_DB_HOST . ';dbname=' . self::TEST_DB_NAME . ';port=3306'; $this->expectException(\Exception::class); - $this->expectExceptionMessageMatches('/[Missing configuration details to connect to database]/'); + $this->expectExceptionMessageRegExp('/[Missing configuration details to connect to database]/'); $settings = Config::initialize('pdo', [$dsn]); } @@ -102,7 +102,7 @@ public function test__callPdo() $dsn = 'mysql:host=' . self::TEST_DB_HOST . ';dbname=' . self::TEST_DB_NAME . ';port=3306'; $this->expectException(\Exception::class); - $this->expectExceptionMessageMatches('/[does not exist]/'); + $this->expectExceptionMessageRegExp('/[does not exist]/'); $settings = new Config('pdo', [$dsn, self::TEST_DB_USER, self::TEST_DB_PASSWORD]); $settings->getNotAnProperty(); } @@ -145,7 +145,7 @@ public function testErrorPgsql() } $this->expectException(\Exception::class); - $this->expectExceptionMessageMatches('/[Missing configuration details to connect to database]/'); + $this->expectExceptionMessageRegExp('/[Missing configuration details to connect to database]/'); $settings = Config::initialize('pgsql', [self::TEST_DB_USER, self::TEST_DB_PASSWORD]); } @@ -185,7 +185,7 @@ public function testErrorSqlsrv() } $this->expectException(\Exception::class); - $this->expectExceptionMessageMatches('/[Missing configuration details to connect to database]/'); + $this->expectExceptionMessageRegExp('/[Missing configuration details to connect to database]/'); $settings = new Config('sqlsrv', [self::TEST_DB_USER, self::TEST_DB_PASSWORD]); } @@ -224,21 +224,21 @@ public function testErrorSqlite3() } $this->expectException(\Exception::class); - $this->expectExceptionMessageMatches('/[Missing configuration details to connect to database]/'); + $this->expectExceptionMessageRegExp('/[Missing configuration details to connect to database]/'); $settings = new Config('sqlite3', [self::TEST_SQLITE_DB_DIR]); } public function test_construct() { $this->expectException(\Exception::class); - $this->expectExceptionMessageMatches('/[Missing configuration details to connect to database]/'); + $this->expectExceptionMessageRegExp('/[Missing configuration details to connect to database]/'); $settings = new Config('', [self::TEST_DB_USER, self::TEST_DB_PASSWORD, self::TEST_DB_NAME]); } public function test_constructArgs() { $this->expectException(\Exception::class); - $this->expectExceptionMessageMatches('/[Missing configuration details to connect to database]/'); + $this->expectExceptionMessageRegExp('/[Missing configuration details to connect to database]/'); $settings = new Config('mysqli'); } } diff --git a/tests/DInjectorTest.php b/tests/DInjectorTest.php index 849405d..f92cfb6 100644 --- a/tests/DInjectorTest.php +++ b/tests/DInjectorTest.php @@ -52,7 +52,7 @@ public function testAutoWire_Error() { $container = new DInjector(); $this->expectException(ContainerException::class); - $this->expectExceptionMessageMatches('/[is not instantiable]/'); + $this->expectExceptionMessageRegExp('/[is not instantiable]/'); $baz = $container->autoWire('ezsql\Tests\Baz'); } @@ -70,7 +70,7 @@ public function testGet_Error() { $container = new DInjector(); $this->expectException(NotFoundException::class); - $this->expectExceptionMessageMatches('/[does not exists]/'); + $this->expectExceptionMessageRegExp('/[does not exists]/'); $baz = $container->get('Baz'); } } diff --git a/tests/DatabaseTest.php b/tests/DatabaseTest.php index a163c3a..dcdd9b2 100644 --- a/tests/DatabaseTest.php +++ b/tests/DatabaseTest.php @@ -105,7 +105,7 @@ public function testInitialize_Pdo() public function testInitialize_Error() { $this->expectException(\Exception::class); - $this->expectExceptionMessageMatches('/[Missing configuration details]/'); + $this->expectExceptionMessageRegExp('/[Missing configuration details]/'); $mysqli = Database::initialize('', [self::TEST_DB_USER, self::TEST_DB_PASSWORD, self::TEST_DB_NAME]); } } diff --git a/tests/EZTestCase.php b/tests/EZTestCase.php index d0e8172..3600f46 100644 --- a/tests/EZTestCase.php +++ b/tests/EZTestCase.php @@ -42,7 +42,7 @@ abstract class EZTestCase extends \PHPUnit\Framework\TestCase protected $errors; - public function errorHandler($errno, $errstr, $errfile, $errline, $errcontext) + public function errorHandler($errno, $errstr, $errfile, $errline, $errcontext = null) { $this->errors[] = compact("errno", "errstr", "errfile", "errline", "errcontext"); } diff --git a/tests/ezSchemaTest.php b/tests/ezSchemaTest.php index a322f30..d7757f2 100644 --- a/tests/ezSchemaTest.php +++ b/tests/ezSchemaTest.php @@ -104,7 +104,7 @@ public function test__call_Error() $this->assertFalse(column('id', INTR, 32, AUTO, PRIMARY)); $db = mysqlInstance([self::TEST_DB_USER, self::TEST_DB_PASSWORD, self::TEST_DB_NAME]); $this->expectException(\Exception::class); - $this->expectExceptionMessageMatches('/[does not exist]/'); + $this->expectExceptionMessageRegExp('/[does not exist]/'); $this->assertNull(column('id', 'DOS', 32)); } diff --git a/tests/ezsqlModelTest.php b/tests/ezsqlModelTest.php index c01ba64..55c28d0 100644 --- a/tests/ezsqlModelTest.php +++ b/tests/ezsqlModelTest.php @@ -43,7 +43,7 @@ public function testSetCache_Timeout() public function testGetNotProperty() { $this->expectException(\Exception::class); - $this->expectExceptionMessageMatches('/does not exist/'); + $this->expectExceptionMessageRegExp('/does not exist/'); $res = $this->object->getNotProperty(); } diff --git a/tests/mysqli/mysqliTest.php b/tests/mysqli/mysqliTest.php index 9374784..40d2f36 100644 --- a/tests/mysqli/mysqliTest.php +++ b/tests/mysqli/mysqliTest.php @@ -90,7 +90,7 @@ public function testSelect() $this->assertTrue($result); $this->errors = array(); - set_error_handler(array($this, 'errorHandler')); + //set_error_handler(array($this, 'errorHandler')); $this->assertTrue($this->object->select('')); $this->object->disconnect(); $this->assertFalse($this->object->select('notest')); @@ -616,7 +616,7 @@ public function testQuery_prepared() public function test__construct_Error() { - $this->expectExceptionMessageMatches('/[Missing configuration details]/'); + $this->expectExceptionMessageRegExp('/[Missing configuration details]/'); $this->assertNull(new ez_mysqli()); } diff --git a/tests/pdo/pdo_mysqlTest.php b/tests/pdo/pdo_mysqlTest.php index e6f48a4..a6c1c7d 100644 --- a/tests/pdo/pdo_mysqlTest.php +++ b/tests/pdo/pdo_mysqlTest.php @@ -16,7 +16,7 @@ class pdo_mysqlTest extends EZTestCase const TEST_DB_PORT = '3306'; /** - * @var resource + * @var \ezsql\Database\ez_pdo */ protected $object; @@ -288,6 +288,7 @@ public function testWhereGrouping() public function testJoins() { $this->assertTrue($this->object->connect('mysql:host=' . self::TEST_DB_HOST . ';dbname=' . self::TEST_DB_NAME . ';port=' . self::TEST_DB_PORT, self::TEST_DB_USER, self::TEST_DB_PASSWORD)); + $this->object->query('DROP TABLE unit_test'); $this->object->query('CREATE TABLE unit_test(id integer, test_key varchar(50), PRIMARY KEY (ID))'); $this->object->insert('unit_test', array('id' => '1', 'test_key' => 'testing 1')); $this->object->insert('unit_test', array('id' => '2', 'test_key' => 'testing 2')); @@ -301,10 +302,10 @@ public function testJoins() $i = 1; $o = 3; foreach ($result as $row) { - $this->assertEquals($i, $row->child_id); - $this->assertEquals('testing child ' . $i, $row->child_test_key); - $this->assertEquals($o, $row->id); - $this->assertEquals('testing ' . $o, $row->test_key); + $this->assertEquals($o, $row->child_id); + $this->assertEquals('testing child ' . $o, $row->child_test_key); + $this->assertEquals($i, $row->id); + $this->assertEquals('testing ' . $i, $row->test_key); ++$i; --$o; } @@ -316,13 +317,14 @@ public function testJoins() --$o; } - $this->assertEquals(0, $this->object->drop('unit_test')); - $this->assertEquals(0, $this->object->drop('unit_test_child')); + $this->assertEquals(0, $this->object->query('DROP TABLE unit_test')); + $this->assertEquals(0, $this->object->query('DROP TABLE unit_test_child')); } public function testBeginTransactionCommit() { $this->object->connect(); + $this->object->query('DROP TABLE unit_test'); $this->object->query('CREATE TABLE unit_test(id integer, test_key varchar(50), PRIMARY KEY (ID))'); $commit = null; @@ -355,6 +357,7 @@ public function testBeginTransactionCommit() public function testBeginTransactionRollback() { $this->object->connect(); + $this->object->query('DROP TABLE unit_test'); $this->object->query('CREATE TABLE unit_test(id integer, test_key varchar(50), PRIMARY KEY (ID))'); $commit = null; @@ -443,7 +446,7 @@ public function testQuery_prepared() public function test__Construct_Error() { - $this->expectExceptionMessageMatches('/[Missing configuration details]/'); + $this->expectExceptionMessageRegExp('/[Missing configuration details]/'); $this->assertNull(new ez_pdo()); } diff --git a/tests/pdo/pdo_pgsqlTest.php b/tests/pdo/pdo_pgsqlTest.php index f08eef0..7078044 100644 --- a/tests/pdo/pdo_pgsqlTest.php +++ b/tests/pdo/pdo_pgsqlTest.php @@ -18,7 +18,7 @@ class pdo_pgsqlTest extends EZTestCase const TEST_SQLITE_DB = 'ez_test.sqlite'; /** - * @var resource + * @var \ezsql\Database\ez_pdo */ protected $object; @@ -157,6 +157,7 @@ public function testDelete() public function testSelecting() { $this->assertTrue($this->object->connect('pgsql:host=' . self::TEST_DB_HOST . ';dbname=' . self::TEST_DB_NAME . ';port=' . self::TEST_DB_PORT, self::TEST_DB_USER, self::TEST_DB_PASSWORD)); + $this->object->drop('unit_test'); $this->object->query('CREATE TABLE unit_test(id serial, test_key varchar(50), test_value varchar(50), PRIMARY KEY (ID))'); $this->object->insert('unit_test', array('test_key' => 'test 1', 'test_value' => 'testing string 1')); $this->object->insert('unit_test', array('test_key' => 'test 2', 'test_value' => 'testing string 2')); @@ -187,29 +188,35 @@ public function testSelecting() foreach ($result as $row) { $this->assertEquals('testing string 1', $row->test_value); } + + $this->object->drop('unit_test'); } public function testWhereGrouping() { $this->assertTrue($this->object->connect('pgsql:host=' . self::TEST_DB_HOST . ';dbname=' . self::TEST_DB_NAME . ';port=' . self::TEST_DB_PORT, self::TEST_DB_USER, self::TEST_DB_PASSWORD)); - $this->object->query('CREATE TABLE unit_test(id integer, test_key varchar(50), active tinyint(1), PRIMARY KEY (ID))'); - $this->object->insert('unit_test', array('id' => '1', 'test_key' => 'testing 1', 'active' => 1)); - $this->object->insert('unit_test', array('id' => '2', 'test_key' => 'testing 2', 'active' => 0)); - $this->object->insert('unit_test', array('id' => '3', 'test_key' => 'testing 3', 'active' => 1)); - $this->object->insert('unit_test', array('id' => '4', 'test_key' => 'testing 4', 'active' => 1)); - - $result = $this->object->selecting('unit_test', '*', where(eq('active', '1'), grouping(like('test_key', '%1%', _OR), like('test_key', '%3%')))); + $this->object->drop('unit_test_more'); + $this->object->query('CREATE TABLE unit_test_more(id serial, test_key varchar(50), active_data integer, PRIMARY KEY (ID))'); + $this->object->insert('unit_test_more', array('test_key' => 'testing 1', 'active_data' => 1)); + $this->object->insert('unit_test_more', array('test_key' => 'testing 2', 'active_data' => 0)); + $this->object->insert('unit_test_more', array('test_key' => 'testing 3', 'active_data' => 1)); + $this->object->insert('unit_test_more', array('test_key' => 'testing 4', 'active_data' => 1)); + + $result = $this->object->selecting('unit_test_more', '*', where(eq('active_data', 1), grouping(like('test_key', '%1%', _OR), like('test_key', '%3%')))); $i = 1; foreach ($result as $row) { $this->assertEquals($i, $row->id); $this->assertEquals('testing ' . $i, $row->test_key); $i = $i + 2; } + + $this->object->drop('unit_test_more'); } public function testJoins() { $this->assertTrue($this->object->connect('pgsql:host=' . self::TEST_DB_HOST . ';dbname=' . self::TEST_DB_NAME . ';port=' . self::TEST_DB_PORT, self::TEST_DB_USER, self::TEST_DB_PASSWORD)); + $this->object->drop('unit_test'); $this->object->query('CREATE TABLE unit_test(id integer, test_key varchar(50), PRIMARY KEY (ID))'); $this->object->insert('unit_test', array('id' => '1', 'test_key' => 'testing 1')); $this->object->insert('unit_test', array('id' => '2', 'test_key' => 'testing 2')); @@ -237,6 +244,9 @@ public function testJoins() $this->assertEquals($o, $row->parent_id); --$o; } + + $this->object->drop('unit_test'); + $this->object->drop('unit_test_child'); } public function testPosgreSQLDisconnect() diff --git a/tests/pdo/pdo_sqliteTest.php b/tests/pdo/pdo_sqliteTest.php index fc49a5f..d9644c7 100644 --- a/tests/pdo/pdo_sqliteTest.php +++ b/tests/pdo/pdo_sqliteTest.php @@ -17,7 +17,7 @@ class pdo_sqliteTest extends EZTestCase const TEST_SQLITE_DB = './tests/pdo/ez_test.sqlite'; /** - * @var resource + * @var \ezsql\Database\ez_pdo */ protected $object; @@ -219,6 +219,7 @@ public function testSelecting() public function testWhereGrouping() { $this->assertTrue($this->object->connect('sqlite:' . self::TEST_SQLITE_DB, '', '', array(), true)); + $this->object->drop('unit_test'); $this->object->query('CREATE TABLE unit_test(id integer, test_key varchar(50), active tinyint(1), PRIMARY KEY (ID))'); $this->object->insert('unit_test', array('id' => '1', 'test_key' => 'testing 1', 'active' => 1)); $this->object->insert('unit_test', array('id' => '2', 'test_key' => 'testing 2', 'active' => 0)); @@ -239,6 +240,7 @@ public function testWhereGrouping() public function testJoins() { $this->assertTrue($this->object->connect('sqlite:' . self::TEST_SQLITE_DB, '', '', array(), true)); + $this->object->drop('unit_test'); $this->object->query('CREATE TABLE unit_test(id integer, test_key varchar(50), PRIMARY KEY (ID))'); $this->object->insert('unit_test', array('id' => '1', 'test_key' => 'testing 1')); $this->object->insert('unit_test', array('id' => '2', 'test_key' => 'testing 2')); diff --git a/tests/pdo/pdo_sqlsrvTest.php b/tests/pdo/pdo_sqlsrvTest.php index d9a52cb..5861919 100644 --- a/tests/pdo/pdo_sqlsrvTest.php +++ b/tests/pdo/pdo_sqlsrvTest.php @@ -8,7 +8,7 @@ class pdo_sqlsrvTest extends EZTestCase { /** - * @var resource + * @var \ezsql\Database\ez_pdo */ protected $object; @@ -89,8 +89,8 @@ public function testInsert() public function testUpdate() { $this->assertTrue($this->object->connect('sqlsrv:Server=' . self::TEST_DB_HOST . ';Database=' . self::TEST_DB_NAME, self::TEST_DB_USER, self::TEST_DB_PASSWORD)); + $this->object->drop('unit_test'); $this->object->query('CREATE TABLE unit_test(id integer, test_key varchar(50), PRIMARY KEY (ID))'); - $this->assertNotFalse($this->object->insert('unit_test', array('id' => 1, 'test_key' => 'testUpdate() 1'))); $this->object->insert('unit_test', array('id' => 2, 'test_key' => 'testUpdate() 2')); $this->object->insert('unit_test', array('id' => 3, 'test_key' => 'testUpdate() 3')); @@ -163,6 +163,7 @@ public function testDelete() public function testSelecting() { $this->assertTrue($this->object->connect('sqlsrv:Server=' . self::TEST_DB_HOST . ';Database=' . self::TEST_DB_NAME, self::TEST_DB_USER, self::TEST_DB_PASSWORD)); + $this->object->drop('unit_test'); $this->object->query('CREATE TABLE unit_test(id integer, test_key varchar(50), PRIMARY KEY (ID))'); $this->object->insert('unit_test', array('id' => 8, 'test_key' => 'testing 8')); $this->object->insert('unit_test', array('id' => 9, 'test_key' => 'testing 9')); @@ -191,29 +192,34 @@ public function testSelecting() foreach ($result as $row) { $this->assertEquals('testing 8', $row->test_key); } + + $this->object->drop('unit_test'); } public function testWhereGrouping() { $this->assertTrue($this->object->connect('sqlsrv:Server=' . self::TEST_DB_HOST . ';Database=' . self::TEST_DB_NAME, self::TEST_DB_USER, self::TEST_DB_PASSWORD)); - $this->object->query('CREATE TABLE unit_test(id integer, test_key varchar(50), active tinyint(1), PRIMARY KEY (ID))'); - $this->object->insert('unit_test', array('id' => '1', 'test_key' => 'testing 1', 'active' => 1)); - $this->object->insert('unit_test', array('id' => '2', 'test_key' => 'testing 2', 'active' => 0)); - $this->object->insert('unit_test', array('id' => '3', 'test_key' => 'testing 3', 'active' => 1)); - $this->object->insert('unit_test', array('id' => '4', 'test_key' => 'testing 4', 'active' => 1)); + $this->object->query('CREATE TABLE unit_test_other(id integer, test_key varchar(50), active_data integer, PRIMARY KEY (ID))'); + $this->object->insert('unit_test_other', array('id' => 1, 'test_key' => 'testing 1', 'active_data' => 1)); + $this->object->insert('unit_test_other', array('id' => 2, 'test_key' => 'testing 2', 'active_data' => 0)); + $this->object->insert('unit_test_other', array('id' => 3, 'test_key' => 'testing 3', 'active_data' => 1)); + $this->object->insert('unit_test_other', array('id' => 4, 'test_key' => 'testing 4', 'active_data' => 1)); - $result = $this->object->selecting('unit_test', '*', where(eq('active', '1'), grouping(like('test_key', '%1%', _OR), like('test_key', '%3%')))); + $result = $this->object->selecting('unit_test_other', '*', where(eq('active_data', '1'), grouping(like('test_key', '%1%', _OR), like('test_key', '%3%')))); $i = 1; foreach ($result as $row) { $this->assertEquals($i, $row->id); $this->assertEquals('testing ' . $i, $row->test_key); $i = $i + 2; } + + $this->object->drop('unit_test_other'); } public function testJoins() { $this->assertTrue($this->object->connect('sqlsrv:Server=' . self::TEST_DB_HOST . ';Database=' . self::TEST_DB_NAME, self::TEST_DB_USER, self::TEST_DB_PASSWORD)); + $this->object->drop('unit_test'); $this->object->query('CREATE TABLE unit_test(id integer, test_key varchar(50), PRIMARY KEY (ID))'); $this->object->insert('unit_test', array('id' => '1', 'test_key' => 'testing 1')); $this->object->insert('unit_test', array('id' => '2', 'test_key' => 'testing 2')); @@ -241,6 +247,9 @@ public function testJoins() $this->assertEquals($o, $row->parent_id); --$o; } + + $this->object->drop('unit_test'); + $this->object->drop('unit_test_child'); } public function testSQLsrvDisconnect() diff --git a/tests/sqlsrv/sqlsrvTest.php b/tests/sqlsrv/sqlsrvTest.php index 21d1f68..04df061 100644 --- a/tests/sqlsrv/sqlsrvTest.php +++ b/tests/sqlsrv/sqlsrvTest.php @@ -37,7 +37,7 @@ protected function setUp(): void */ protected function tearDown(): void { - $this->object->query('DROP TABLE unit_test'); + $this->object->drop('unit_test'); $this->object = null; } @@ -363,9 +363,9 @@ public function testQuery_prepared() column('prepare_key', VARCHAR, 50) ); - $this->object->insert('prepare_test', ['id' => 1, 'prepare_key' => 'test 2']); - $this->object->query_prepared('INSERT INTO prepare_test( id, prepare_key ) VALUES( ?, ? )', [4, 'test 10']); - $this->object->query_prepared('INSERT INTO prepare_test( id, prepare_key ) VALUES( ?, ? )', [9, 'test 3']); + $this->object->query_prepared('INSERT INTO prepare_test(id, prepare_key ) VALUES( ?, ? )', [1, 'test 2']); + $this->object->query_prepared('INSERT INTO prepare_test(id, prepare_key ) VALUES( ?, ? )', [4, 'test 10']); + $this->object->query_prepared('INSERT INTO prepare_test(id, prepare_key ) VALUES( ?, ? )', [9, 'test 3']); $this->object->query_prepared('SELECT id, prepare_key FROM prepare_test WHERE id = ?', [9]); $query = $this->object->queryResult(); diff --git a/unsupported/install_sql.sh b/unsupported/install_sql.sh deleted file mode 100644 index e2ad2ac..0000000 --- a/unsupported/install_sql.sh +++ /dev/null @@ -1,122 +0,0 @@ -#!/bin/bash -e - -# Use the following variables to control your install: - -# Password for the SA user (required) -MSSQL_SA_PASSWORD='MasterTest' - -# Product ID of the version of SQL server you're installing -# Must be evaluation, developer, express, web, standard, enterprise, or your 25 digit product key -# Defaults to developer -MSSQL_PID='evaluation' - -# Install SQL Server Agent (recommended) -SQL_INSTALL_AGENT='y' - -# Install SQL Server Full Text Search (optional) -# SQL_INSTALL_FULLTEXT='y' - -# Create an additional user with sysadmin privileges (optional) -SQL_INSTALL_USER='ez_test' -SQL_INSTALL_USER_PASSWORD='ezTest' - -if [ -z $MSSQL_SA_PASSWORD ] -then - echo Environment variable MSSQL_SA_PASSWORD must be set for unattended install - exit 1 -fi - -echo Adding Microsoft repositories... -sudo curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add - -repoargs="$(curl https://packages.microsoft.com/config/ubuntu/16.04/mssql-server-2017.list)" -sudo add-apt-repository "${repoargs}" -repoargs="$(curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list)" -sudo add-apt-repository "${repoargs}" - -echo Running apt-get update -y... -sudo apt-get update -y - -echo Installing SQL Server... -sudo apt-get install -y mssql-server - -echo Running mssql-conf setup... -sudo MSSQL_SA_PASSWORD=$MSSQL_SA_PASSWORD \ - MSSQL_PID=$MSSQL_PID \ - /opt/mssql/bin/mssql-conf -n setup accept-eula - -echo Installing mssql-tools and unixODBC developer... -sudo ACCEPT_EULA=Y apt-get install -y mssql-tools unixodbc-dev - -# Add SQL Server tools to the path by default: -echo Adding SQL Server tools to your path... -echo PATH="$PATH:/opt/mssql-tools/bin" >> ~/.bash_profile -echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc - -# Optional SQL Server Agent installation: -if [ ! -z $SQL_INSTALL_AGENT ] -then - echo Installing SQL Server Agent... - sudo apt-get install -y mssql-server-agent -fi - -# Optional SQL Server Full Text Search installation: -if [ ! -z $SQL_INSTALL_FULLTEXT ] -then - echo Installing SQL Server Full-Text Search... - sudo apt-get install -y mssql-server-fts -fi - -# Configure firewall to allow TCP port 1433: -echo Configuring UFW to allow traffic on port 1433... -sudo ufw allow 1433/tcp -sudo ufw reload - -# Optional example of post-installation configuration. -# Trace flags 1204 and 1222 are for deadlock tracing. -# echo Setting trace flags... -# sudo /opt/mssql/bin/mssql-conf traceflag 1204 1222 on - -# Restart SQL Server after installing: -echo Restarting SQL Server... -sudo systemctl restart mssql-server - -# Connect to server and get the version: -counter=1 -errstatus=1 -while [ $counter -le 5 ] && [ $errstatus = 1 ] -do - echo Waiting for SQL Server to start... - sleep 3s - /opt/mssql-tools/bin/sqlcmd \ - -S localhost \ - -U SA \ - -P $MSSQL_SA_PASSWORD \ - -Q "SELECT @@VERSION" 2>/dev/null - errstatus=$? - ((counter++)) -done - -# Display error if connection failed: -if [ $errstatus = 1 ] -then - echo Cannot connect to SQL Server, installation aborted - exit $errstatus -fi - -# Optional new user creation: -if [ ! -z $SQL_INSTALL_USER ] && [ ! -z $SQL_INSTALL_USER_PASSWORD ] -then - echo Creating user $SQL_INSTALL_USER - /opt/mssql-tools/bin/sqlcmd \ - -S localhost \ - -U SA \ - -P $MSSQL_SA_PASSWORD \ - -Q "CREATE LOGIN [$SQL_INSTALL_USER] WITH PASSWORD=N'$SQL_INSTALL_USER_PASSWORD', DEFAULT_DATABASE=[master], CHECK_EXPIRATION=ON, CHECK_POLICY=ON; ALTER SERVER ROLE [sysadmin] ADD MEMBER [$SQL_INSTALL_USER]" - /opt/mssql-tools/bin/sqlcmd \ - -S localhost \ - -U SA \ - -P $MSSQL_SA_PASSWORD \ - -Q "CREATE DATABASE ez_test" -fi - -echo Done!