GithubHelp home page GithubHelp logo

laminas / laminas-db Goto Github PK

View Code? Open in Web Editor NEW
118.0 24.0 66.0 6.91 MB

Database abstraction layer, SQL abstraction, result set abstraction, and RowDataGateway and TableDataGateway implementations

Home Page: https://docs.laminas.dev/laminas-db/

License: BSD 3-Clause "New" or "Revised" License

Shell 0.15% PHP 99.85%
tablegateway database database-adapter sql sql-abstraction resultset resultset-abstraction rowdatagateway database-abstraction-layer

laminas-db's Introduction

laminas-db

Build Status

🇷🇺 Русским гражданам

Мы, участники Laminas, родились и живем в разных странах. У многих из нас есть друзья, родственники и коллеги как в России, так и в Украине. Некоторые из нас родились в России. Некоторые из нас живут в России. У некоторых бабушки и дедушки сражались с фашистами во Второй мировой войне. Здесь никто не поддерживает фашизм.

У одного из нас есть украинская родственница, которая спаслась из дома вместе с сыном. Поезд задержался из-за бомбежки на дороге впереди. У нас есть друзья, которые прячутся в бомбоубежищах. Мы с тревогой ждем весточки от них после воздушных налетов, которые беспорядочно наносят удары и попадают по больницам, школам, детским садам и домам. Мы не берем это из каких-либо СМИ. Мы наблюдаем это напрямую.

Вы доверяете нам достаточно, чтоб использовать наши программы, и мы просим вас довериться нам вновь. Мы нуждаемся в помощи. Выходите и протестуйте против этой бесполезной войны. Остановите кровопролитие. Скажите "Нет войне!"

🇺🇸 To Citizens of Russia

We at Laminas come from all over the world. Many of us have friends, family and colleagues in both Russia and Ukraine. Some of us were born in Russia. Some of us currently live in Russia. Some have grandparents who fought Nazis in World War II. Nobody here supports fascism.

One team member has a Ukrainian relative who fled her home with her son. The train was delayed due to bombing on the road ahead. We have friends who are hiding in bomb shelters. We anxiously follow up on them after the air raids, which indiscriminately fire at hospitals, schools, kindergartens and houses. We're not taking this from any media. These are our actual experiences.

You trust us enough to use our software. We ask that you trust us to say the truth on this. We need your help. Go out and protest this unnecessary war. Stop the bloodshed. Say "stop the war!"

Laminas\Db is a component that abstract the access to a Database using an object oriented API to build the queries. Laminas\Db consumes different storage adapters to access different database vendors such as MySQL, PostgreSQL, Oracle, IBM DB2, Microsoft Sql Server, PDO, etc.

Contributing

Please be sure to read the contributor's guide for general information on contributing. This section outlines specifics for laminas-db.

Test suites

The phpunit.xml.dist file defines two test suites, "unit test" and "integration test". You can run one or the other using the --testsuite option to phpunit:

$ ./vendor/bin/phpunit --testsuite "unit test" # unit tests only
$ ./vendor/bin/phpunit --testsuite "integration test" # integration tests only

Unit tests do not require additional functionality beyond having the appropriate database extensions present and loaded in your PHP binary.

Integration tests

To run the integration tests, you need databases. The repository includes a Vagrantfile which allows you to fire up a vagrant box with several of our target databases, including:

  • MySQL
  • PostgreSQL
  • SQL Server

To start up vagrant:

$ vagrant up

Copy phpunit.xml.dist to phpunit.xml, and change the following ENV var declaration values to "true":

  • TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL
  • TESTS_LAMINAS_DB_ADAPTER_DRIVER_SQLSRV
  • TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL
  • TESTS_LAMINAS_DB_ADAPTER_DRIVER_SQLITE_MEMORY

From there, you can run the integration tests:

$ ./vendor/bin/phpunit --testsuite "integration test"

laminas-db's People

Contributors

akrabat avatar bakura10 avatar dasprid avatar evandotpro avatar ezimuel avatar freeaqingme avatar froschdesign avatar ghostwriter avatar kabel avatar koopzington avatar leftbrained avatar localheinz avatar maks3w avatar marc-mabe avatar marcelto avatar michalbundyra avatar micheh avatar mikaelkael avatar mwillbanks avatar ocramius avatar oleksandrbonar avatar ralphschindler avatar renovate[bot] avatar romulobusatto avatar samsonasik avatar sgehrig avatar thinkscape avatar tptrixtop avatar turrsis avatar weierophinney avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laminas-db's Issues

Refactor of `Zend\Db\Sql` for 3.0.0

This is a task for refactoring Zend\Db\Sql using the type hints of PHP 7.2. You must work on the 3.0.0 branch.

If you change the API you should report it in the /3.0.0.md file.

Note: it's quite difficult to provide this code refactor without changing other classes. That means you should provide the refactoring without pass all the unit tests. In this phase is only important to have the unit tests running, so we you must focus only on fatal/parse errors.


Originally posted by @ezimuel at zendframework/zend-db#362

Some of AbstractPlatform inheritors are preventing \PDO disconnect

Some of Zend\Db\Adapter\Platform\AbstractPlatform inheritors (Mysql, Oracle, Postgresql, Sqlite, SqlServer) holding the reference of \PDO object (even if DriverInterface passed into constructor, because quote methods are reassigning resource reference of connection to local variable resource). This causing problems when you using Platform class and want to disconnect the \PDO instance with disconnect method of the ConnectionInterface.

We found that problem when noticed ~40k+ TCP connections on 3306 port stucked in CLOSE_WAIT state after disconnecting and exec another php script and exit original script.

Code to reproduce the issue

        $testConnection = function() {
            $mypid = getmypid();
            $lsof = shell_exec("lsof -i -P -n | grep 3306 | grep $mypid");
            echo ($lsof === null ? 'no connection' : 'connection established') . PHP_EOL;
        };

        // take your adapter with mysql driver inside
        $db = self::$infrastructure->db();

        $testConnection();

        $db->getDriver()->getConnection()->connect();

        $testConnection();

        $db->getDriver()->getConnection()->disconnect();

        $testConnection();

        $db->getDriver()->getConnection()->connect();

        $testConnection();

        $db->getPlatform()->quoteValue('test');
        $db->getDriver()->getConnection()->disconnect();

        $testConnection(); // are still connected? yes :(

Expected results

Connection is disconnected even when using quoteValue method of platform object

Actual results

Connection established


Originally posted by @jadrovski at zendframework/zend-db#387

Refactor of `Zend\Db\ResultSet` for 3.0.0

This is a task for refactoring Zend\Db\ResultSet using the type hints of PHP 7.2. You must work on the 3.0.0 branch.

If you change the API you should report it in the /3.0.0.md file.

Note: it's quite difficult to provide this code refactor without changing other classes. That means you should provide the refactoring without pass all the unit tests. In this phase is only important to have the unit tests running, so we you must focus only on fatal/parse errors.


Originally posted by @ezimuel at zendframework/zend-db#364

Reconnect on lost DB connection with PDO_MYSQL

I am using php for long running scripts as a RabbitMq message comsumer. Messages can have DB access implemented as ZF3 / zend-db Tablegateway. The DB connection used is PDO_MYSQL.
In case DB connection is killed (MYSQL_CONNECTION_TIMEOUT or other), AbstractTableGateway throws an error (HY000 - 2006 - MySQL server has gone away) when trying to execute a statement against the closed connection.

I expect that Tablegateway / Adapter / db Driver is smart enough to handle lost connection and reconnect or at least handle "unconnected" state and connect (again).

Code to reproduce the issue

  • use some Tablegateway connected via PDO_MYSQL in a long running loop
  • while the loop runs, go to the MySQL-Server and kill the connection manually
  • you will get "HY000 - 2006 - MySQL server has gone away" in Tablegateway / Adapter / db Driver.

Expected results

when the DB connection is lost the DB managing objects should be able to connect again to the DB again as they did initially.

Actual results

  • when the DB connection is lost the DB managing objects are not able to connect again. An error is thrown: "HY000 - 2006 - MySQL server has gone away" in Tablegateway / Adapter / db Driver.

Originally posted by @finalJustize at zendframework/zend-db#302

Broader PDO fetch-style range

I encountered a situation Where I want to fetch multiple columns with the same name where aliases are not an option, so I set the fetchmode to \PDO::FETCH_NAMED which resulted in the Exception\InvalidArgumentException "The fetch mode must be one of the PDO::FETCH_* constants.", which \PDO::FETCH_NAMED is.

I've attempted to fix this by editing the condition so that all the fetch styles listed in http://php.net/manual/en/pdostatement.fetch.php

I hope that this PR is to the required standards :D


Originally posted by @chris-kruining at zendframework/zend-db#296

Connection::getLastGeneratedValue should throw exception when unable to get an Id

When trying to get and Id for a record by using the Connection::getLastGeneratedValue method you would expect that an exception is thrown when trying to do something that is not possible or when the database fails to return an ID because this is an exceptional situation.

But at this moment the method returns null when you use it incorrectly or false when getting the ID from the database fails combined with PHP type system this can cause new errors that are hard to trace.

Code to reproduce the issue

Example combined with PostgreSQL database.

$connection = Zend\Db\Adapter\Driver\Pdo\Connection;

$connection->getLastGeneratedValue(); // will always return null

$connection->getLastGeneratedValue('incorrect_seq_name'); // will always return false

Expected results

At this moment the method is not defensive enough and it is easy to make mistakes with it. I would expect it to throw an exception that will explain what is going wrong. It's possible that an migration goes wrong and a sequence is not created causing this code to always return false what can be a valid value.


Originally posted by @rjd22 at zendframework/zend-db#343

Zend\Db\Adapter\AdapterServiceFactory always invoke Zend\Db\Adapter\Adapter

I created my own Db\Adapter\AdapterServiceFactory so I could be able to call my own Db\Adapter.

namespace RVMvp\Db\Adapter;

use Interop\Container\ContainerInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Db\Adapter\AdapterServiceFactory as ZendAdapterServiceFactory;

class AdapterServiceFactory extends ZendAdapterServiceFactory
{
    public function createService(ServiceLocatorInterface $container)
    {
        return $this($container, Adapter::class);
    }
}

It should create a service of RVMvp\Db\Adapter\Adapter but keep creating Zend\Db\Adapter\Adapter.

This is happening because the invokable method is calling directly the Zend\Db\Adapter\Adapter instead of the requested name provided on createService method:

namespace Zend\Db\Adapter;

use Interop\Container\ContainerInterface;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class AdapterServiceFactory implements FactoryInterface
{
    /**
     * Create db adapter service
     *
     * @param ContainerInterface $container
     * @param string $requestedName
     * @param array $options
     * @return Adapter
     */
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $config = $container->get('config');
        return new Adapter($config['db']); // HERE IT'S CALLING DIRECTLY
    }

    /**
     * Create db adapter service (v2)
     *
     * @param ServiceLocatorInterface $container
     * @return Adapter
     */
    public function createService(ServiceLocatorInterface $container)
    {
        return $this($container, Adapter::class);
    }
}

I did my workaround adding the invokable method to my own AdapterServiceFactory:

public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
 {
        $config = $container->get('config');
        return new $requestedName($config['db']); // CHANGED TO REQUESTED NAME
 }

I'm suggesting a bugfix so we don't need to override the invokable method.


Originally posted by @raivirtual at zendframework/zend-db#353

Added IbmDb2 db2_pclose to disconnect

Updated the disconnect method to choose db2_pclose or db2_close based on the resource's connectionParameter for persistence.

The public function connect() creates either persistent or non persistent db2 connections based on a connection parameter.

This update uses the same logic in the public function disconnect() to close the connection. Previously persistent connections would not have been closed with the db2_close() call, because they need the db2_pclose() call.


Originally posted by @JargonMan at zendframework/zend-db#333

Memory Leak Issue When Connecting Via DB2 Connect

Provide a narrative description of what you are trying to accomplish.

There appears to be a memory leak issue when connecting to a DB2 database via the DB2 Connect driver while using the Zend DB package.

OS: Ubuntu 18.04.1 LTS
PHP Version: PHP 7.2.19-0ubuntu0.18.04.2 (cli) (built: Aug 12 2019 19:34:28) ( NTS )
DB2 Connect Version: 11.1

Explanation of Diagnosis:
When I run a similar process with a simple PDO object, I do not get the same memory allocation issues. Here is the PDO code I was using to check:

$conn = new PDO('ibm:MYDEVENV', 'MYUSERNAME', 'MYPASSWORD');
$result = $conn->query('select ACCT_UNIT from MYLIBRARY.MYTABLE where MYVALUE = 113;');
if (!$result) {
	var_dump($conn->errorInfo());
}
while ($row = $result->fetch()) {
	var_dump($row);
}

The outcome is as expected:

array(2) {
  ["ACCT_UNIT"]=>
  string(15) "113            "
  [0]=>
  string(15) "113            "
}

When this database connection and query are run using Zend-Db package, a memory allocation error is thrown. See below:

Code to reproduce the issue

$configArray = array(
    'driver' => 'pdo_ibm',
    'dsn' => 'ibm:MYDEVENV',
    'platform' => 'IbmDb2',
    'platform_options' => [
        'quote_identifiers' => false,
    ],
    'driver_options' => [
        'isDefaultTableAdapter' => true,
        'i5_naming' => 'DB2_I5_NAMING_ON',
        'autocommit' => 'DB_AUTOCOMMIT_OFF',
        'i5_lib' => 'MYLIBRARY'
    ],
    'username' => 'MYUSERNAME',
    'password' => 'MYPASSWORD',
);
$adapter = new \Zend\Db\Adapter\Adapter($configArray);
$sql = 'select ACCT_UNIT from MYLIBRARY.MYTABLE where MYFIELD = :MYVALUE';
$parameters = ['MYVALUE' => 113];
try {
       $result = $adapter->query($sql, $parameters);

       if ($result instanceof ResultSet)
       {
            $arrayResults = $result->toArray();

            if (sizeof($arrayResults) === 1)
                return $arrayResults[0];
            else {
                $arrayResults[] = array('ACCT_UNIT'=>'0000');
                return $arrayResults[0];
             }
        }
} catch (\Exception $e) {
       $this->appLogger->crit($e);
       $errorMessage = $e->getMessage();
       throw new \Exception ($errorMessage);
}

Expected results

The query should return the value it was passed as a parameter inside an associative array:
["ACCT_UNIT" => "113"]

Actual results

I received the following error:

mmap() failed: [12] Cannot allocate memory
PHP Fatal error:  Out of memory (allocated 2097152) (tried to allocate 140346646331424 bytes) in /tmp/vendor/zendframework/zend-db/src/Adapter/Driver/Pdo/Connection.php on line 425

Originally posted by @StoneMorKnight at zendframework/zend-db#394

zend-db documentation addition

Provide a narrative description of what you are trying to accomplish:

  • Are you fixing a bug?

    • Detail how the bug is invoked currently.
    • Detail the original, incorrect behavior.
    • Detail the new, expected behavior.
    • Base your feature on the master branch, and submit against that branch.
    • Add a regression test that demonstrates the bug, and proves the fix.
    • Add a CHANGELOG.md entry for the fix.
  • Are you creating a new feature?

    • Why is the new feature needed? What purpose does it serve?
    • How will users use the new feature?
    • Base your feature on the develop branch, and submit against that branch.
    • Add only one feature per pull request; split multiple features over multiple pull requests
    • Add tests for the new feature.
    • Add documentation for the new feature.
    • Add a CHANGELOG.md entry for the new feature.
  • Is this related to quality assurance?

  • Is this related to documentation?


Originally posted by @spengilley at zendframework/zend-db#347

WIP: Refactor of `Zend\Db\Exception` for 3.0.0

This is a task for refactoring Zend\Db\Exception using the type hints of PHP 7.2. You must work on the 3.0.0 branch.

If you change the API you should report it in the /3.0.0.md file.

Note: it's quite difficult to provide this code refactor without changing other classes. That means you should provide the refactoring without pass all the unit tests. In this phase is only important to have the unit tests running, so we you must focus only on fatal/parse errors.


Originally posted by @ezimuel at zendframework/zend-db#366

Reconnect on lost DB connection

This functionality allow to enable & configure reconnect functionality using options parameter in adapter.

When you are creating adapter for mysqli:

$adapter = new Adapter([
    'driver' => 'Mysqli',
    'database' => '',
    'username' => '',
    'password' => '',
    'options' => [
        'reconnect_tries' => 3
    ]
]);

You can specify reconnect_tries and if during your work connect will be lost adapter will try automatically reconnect to server.

Fix for #302


Originally posted by @tptrixtop at zendframework/zend-db#307

Refactor of `Zend\Db\Metadata` for 3.0.0

This is a task for refactoring Zend\Db\Metadata using the type hints of PHP 7.2. You must work on the 3.0.0 branch.

If you change the API you should report it in the /3.0.0.md file.

Note: it's quite difficult to provide this code refactor without changing other classes. That means you should provide the refactoring without pass all the unit tests. In this phase is only important to have the unit tests running, so we you must focus only on fatal/parse errors.


Originally posted by @ezimuel at zendframework/zend-db#365

Refactor of `Zend\Db\Metadata` for 3.0.0

This PR provides changes described in #365

A few questions came up while refactoring. Some feedback is appreciated:

  • Setter returns are inconsistent (e.g. ColumnObject and ConstraintKeyObject). Since there are fluent setters, possibility is that they are being used. Therefore I recommend to unify and make all setters fluent. If that is okay, I'll provide the changes in this scope.
  • Unsure where class constants of ConstraintKeyObject and AbstractSource are used. Currently the visibility is defined as public. If they are not needed elsewhere, private or protected might be more suitable.
  • The $table parameter of loadConstraintData() and loadConstraintReferences() in class Zend\Db\Metadata\Source\AbstractSource is unused. Version 3.0 might be a good time to remove it (causing BC). Should I include this change in this scope?

Originally posted by @arueckauer at zendframework/zend-db#369

1. add return statement to Adapter::getHelpers method;

Class Zend\Db\Adapter\Adapter method getHelpers, you guys forget to return the $functions

  • Are you fixing a bug?
    • Detail how the bug is invoked currently.
    • Detail the original, incorrect behavior.
    • Detail the new, expected behavior.
    • Base your feature on the master branch, and submit against that branch.
    • Add a regression test that demonstrates the bug, and proves the fix.
    • Add a CHANGELOG.md entry for the fix.

Originally posted by @darluc at zendframework/zend-db#319

Documentation code blocks

When i read the docs i found some unstyled code blocks and this turn codes unreadable, please consider two things.
image

i make some change, if you can change this.
image
image

Adding the JOIN_FULL_OUTER class constant, since there are DBMS' out …

…there which can't handle an unqualified OUTER JOIN. An example of that can be found in PostgreSQL (See: https://www.postgresql.org/docs/11/sql-select.html).

Provide a narrative description of what you are trying to accomplish:

  • Are you fixing a bug?

    • Detail how the bug is invoked currently.
    • Detail the original, incorrect behavior.
    • Detail the new, expected behavior.
    • Base your feature on the master branch, and submit against that branch.
    • Add a regression test that demonstrates the bug, and proves the fix.
    • Add a CHANGELOG.md entry for the fix.
  • Are you creating a new feature?

    • Why is the new feature needed? What purpose does it serve?
    • How will users use the new feature?
    • Base your feature on the develop branch, and submit against that branch.
    • Add only one feature per pull request; split multiple features over multiple pull requests
    • Add tests for the new feature.
    • Add documentation for the new feature.
    • Add a CHANGELOG.md entry for the new feature.
  • Is this related to quality assurance?

  • Is this related to documentation?


Originally posted by @galvao at zendframework/zend-db#351

WIP: Refactor `Zend\Db\Adapter\Profiler` for 3.0.0

This is a task for refactoring Zend\Db\Adapter\Profiler using the type hints of PHP 7.2. You must work on the 3.0.0 branch.

If you change the API you should report it in the /3.0.0.md file.

Note: it's quite difficult to provide this code refactor without changing other classes. That means you should provide the refactoring without pass all the unit tests. In this phase is only important to have the unit tests running, so we you must focus only on fatal/parse errors.


Originally posted by @ezimuel at zendframework/zend-db#367

Add mysqli connection flags to mysqli_real_connect

The Mysqli driver doesn't allow setting of flags passed into mysqli_real_connect.

  • Are you fixing a bug?
    • Detail how the bug is invoked currently.

In some instances (like MySQL and PHP on Azure) MYSQLI_SSL_CLIENT needs to be set.

'params' => [
    'host' => 'xxxx.mysql.database.azure.com',
    'port' => 3306,
    'user' => 'xxxx@xxxxx',
    'password' => 'xxxxx',
    'dbname' => 'xxxx',
    'charset' => 'utf8',
    'use_ssl' => true,
    'ssl_ca' => 'xxxxx/certs/BaltimoreCyberTrustRoot.crt.pem',
    'driver_options' => [ ]
]
  • Detail the original, incorrect behavior.

This calls $this->resource->ssl_set($clientKey, $clientCert, $caCert, $caPath, $cipher); to configure the SSL options, but no flag is set on mysqli_real_connect. Connection to Azure subsequently fails with 'SSL connection is required'

  • Detail the new, expected behavior.

Driver should allow connecting as illustrated in azure documentation at https://docs.microsoft.com/en-us/azure/mysql/howto-configure-ssl .

Added 'flags' config key to driver_options to support the setting of flags into mysqli_real_connect. This lets users supply MYSQLI_CLIENT_SSL and other connection flags as indicated on http://www.php.net/manual/en/mysqli.real-connect.php

'params' => [
    'host' => 'xxxx.mysql.database.azure.com',
    'port' => 3306,
    'user' => 'xxxx@xxxxx',
    'password' => 'xxxxx',
    'dbname' => 'xxxx',
    'charset' => 'utf8',
    'use_ssl' => true,
    'ssl_ca' => 'xxxxx/certs/BaltimoreCyberTrustRoot.crt.pem',
    'driver_options' => [ 
        'flags' => MYSQLI_CLIENT_SSL 
    ]
]

Originally posted by @kris-sum at zendframework/zend-db#314

Boolean values in the Mysql Statements cause execute to silently fail

So I've been hitting my head on the wall for the entire day on this and I just managed to figure it out.

Although in theory zend-db is properly handling boolean values in the Statement:: bindParametersFromContainer() it appears that there is a bug lying in PHP which is still there in 7.1 and 7.2 (https://bugs.php.net/bug.php?id=38546).

Passing PDO::PARAM_BOOL in the bindParam causes the PDOStatement::execute() to silently return false and not throw any exception, even though PDO::ATTR_ERRMODE is set to PDO::ERRMODE_EXCEPTION

The reason I'm opening this is to bring it to your attention and perhaps discuss if booleans should be treated as integers until a fix is available

Code to reproduce the issue

$sql = new Sql($this->getDbAdapter());

$insert = $sql->insert()
    ->into('Table')
    ->values([ 'field' => true ]);

try {
   $insertStatement = $sql->prepareStatementForSqlObject($insert);
   $result = $insertStatement->execute();
} catch( \Exception $e ) {
   // will never get here
}

// this is false
return ( $result && $result->getAffectedRows() > 0 );

Expected results

The statement should get prepared in the mysql and then get executed. However that is not the case. Looking into mysql's general_log_file one can see the statement being prepared but never executed.

Actual results

PDOStatement::execute() returns false and no exception was thrown thus the only way to detect that the query failed is via the getAffectedRows() but there is absolutely no indication on what went wrong.


Originally posted by @twmobius at zendframework/zend-db#323

Adding schema for Postgres

Postgres sequence can use other schema than public. In this case NEXTVAL and CURRVAL should include Schema name like NEXTVAL("schema"."sequence_name"). In standard approach result of SequenceFeature class was NEXTVAL("schema.sequence_name") which is inproper behavior. I added checking, if the $sequenceName is instance of TableIdentifier. In this case NEXTVAL and CURRVALL is modified.

Provide a narrative description of what you are trying to accomplish:

  • Are you fixing a bug?

    • Detail how the bug is invoked currently.
    • Detail the original, incorrect behavior.
    • Detail the new, expected behavior.
    • Base your feature on the master branch, and submit against that branch.
    • Add a regression test that demonstrates the bug, and proves the fix.
    • Add a CHANGELOG.md entry for the fix.
  • Are you creating a new feature?

    • Why is the new feature needed? What purpose does it serve?
    • How will users use the new feature?
    • Base your feature on the develop branch, and submit against that branch.
    • Add only one feature per pull request; split multiple features over multiple pull requests
    • Add tests for the new feature.
    • Add documentation for the new feature.
    • Add a CHANGELOG.md entry for the new feature.
  • Is this related to quality assurance?

  • Is this related to documentation?


Originally posted by @tkonop at zendframework/zend-db#378

Refactor of `Zend\Db\RowGateway` for 3.0.0

This is a task for refactoring Zend\Db\RowGateway using the type hints of PHP 7.2. You must work on the 3.0.0 branch.

If you change the API you should report it in the /3.0.0.md file.

Note: it's quite difficult to provide this code refactor without changing other classes. That means you should provide the refactoring without pass all the unit tests. In this phase is only important to have the unit tests running, so we you must focus only on fatal/parse errors.


Originally posted by @ezimuel at zendframework/zend-db#363

Bug with zend-db

Bug fix zendframework/zend-db#383 (zendframework/zend-db@c11bffd) causes some big issues on our site.

We have a prepare statement doing

$statement->prepare('SET SESSION group_concat_max_len=:value');
$statement->execute([':value' => 655350]);

from the code in execute function, it now interprets the number as a string instead of an integer
wondering how to interpret the number as a integer again. let me know if you have any questions

Fixes #316 : set return null for HydratingResultSet::current() on no data

Provide a narrative description of what you are trying to accomplish:

  • Are you fixing a bug?
    • Detail how the bug is invoked currently.
      call HydratingResultSet::current() on no data in current record.
    • Detail the original, incorrect behavior.
      it returns false.
    • Detail the new, expected behavior.
      it returns null, the "AbstractResultset" and "ResultSet" class returns null on no data, so it returns null for consistency/fix.
    • Base your feature on the master branch, and submit against that branch.
    • Add a regression test that demonstrates the bug, and proves the fix.
    • Add a CHANGELOG.md entry for the fix.

If this is considered a BC break, I can target to develop. Fixes #316


Originally posted by @samsonasik at zendframework/zend-db#325

AdapterInterface does not define query as a method

Description of what I am trying to accomplish:

  • Given the recommendation here to fall back to manual sql using the adapter in order to accomplish FOR UPDATE statements in MariaDb / MySQL environments, one should still be able to inject an interface into their class objects.
  • The \Zend\Db\Adapter\Adapter implements no such interface which defines a query method

Code to reproduce the issue

class FooBar
{
    /**
     * @var \Zend\Db\Adapter\AdapterInterface
     */
    private $adapter;

    public function  __construct(
        \Zend\Db\Adapter\AdapterInterface $adapter
    ) {
        $this->adapter = $adapter
    }

    public function getRecordById(int $id): \ArrayObject
    {
        /**
         * @var \Zend\Db\ResultSet\ResultSet $resultSet
         */
        $resultSet = $this->adapter->query('SELECT * FROM foo_bar WHERE id = :id FOR UPDATE', ['id' => $id]);
        return $resultSet->current();
    }
}

Expected results

  • AdapterInterface should have query defined so that it is a known accessible method. This will:
    • Allow for DI replacement in applications that may require such things
    • Allow for mocking of the Interface in order to accomplish unit testing of the class

Actual results

Since (in my application) \Zend\Db\Adapter\Adapter is the concrete class that is injected at run time, the method still works. However this leads to:

  • IDE shows an error as it is not a known method of the interface
  • Inability to properly unit test the class since I cannot call ->query on a mocked instance of \Zend\Db\Adapter\AdapterInterface

Originally posted by @dfelton at zendframework/zend-db#398

Incorrect Sql Expression parameters when passing zero in the constructor

I am trying to create an expression that has zero as the parameter value. However, the parameters incorrectly show as empty.

Code to reproduce the issue

$expr = new \Zend\Db\Sql\Expression('?', '0');
print_r($expr->getParameters());

Expected results

It prints "0"

Actual results

It prints empty array

Proposed fix

https://github.com/zendframework/zend-db/blob/master/src/Sql/Expression.php#L59

In Zend\Db\Sql\Expression, update the constructor to explicitly check for '0' when setting parameters

if ($parameters || $parameters === '0') {
     $this->setParameters($parameters);
}

Originally posted by @albertor24 at zendframework/zend-db#381

Refactor of `Zend\Db\TableGateway` for 3.0.0

This is a task for refactoring Zend\Db\TableGateway using the type hints of PHP 7.2. You must work on the 3.0.0 branch.

If you change the API you should report it in the /3.0.0.md file.

Note: it's quite difficult to provide this code refactor without changing other classes. That means you should provide the refactoring without pass all the unit tests. In this phase is only important to have the unit tests running, so we you must focus only on fatal/parse errors.


Originally posted by @ezimuel at zendframework/zend-db#361

3.0.0 sql type hints

Provide a narrative description of what you are trying to accomplish:

  • Are you fixing a bug?

    • Detail how the bug is invoked currently.
    • Detail the original, incorrect behavior.
    • Detail the new, expected behavior.
    • Base your feature on the master branch, and submit against that branch.
    • Add a regression test that demonstrates the bug, and proves the fix.
    • Add a CHANGELOG.md entry for the fix.
  • Are you creating a new feature?

    • Why is the new feature needed? What purpose does it serve?
    • How will users use the new feature?
    • Base your feature on the develop branch, and submit against that branch.
    • Add only one feature per pull request; split multiple features over multiple pull requests
    • Add tests for the new feature.
    • Add documentation for the new feature.
    • Add a CHANGELOG.md entry for the new feature.
  • Is this related to quality assurance?

  • Is this related to documentation?


Originally posted by @guidofaecke at zendframework/zend-db#373

Refactor of `Zend\Db\ResultSet` for 3.0.0

This PR provides changes described in #364

I have two questions from refactoring.

  1. Return type hints for implementations of \Iterator::current() is incomplete due to inconsistent usage. Right now, type hints are only documented in method comment. Either leave it or a change is required to match return types.
  • Iterator::current() documents a mixed (any) type
  • AbstractResultSet::current() documents array|null
  • ResultSet::current() documents array|ArrayObject|null
  • HydratingResultSet::current() documents null|array|bool
  1. ExtractionInterface::extract() expects parameter be of type object. From my understanding HydratingResultSet::toArray() could give provide any of null|array|bool. Not sure if I misunderstand it or if that needs some attention.

Originally posted by @arueckauer at zendframework/zend-db#370

HydratingResultSet current method DocBlock @return

HydratingResultSet current() method is specified in the DocBlock block that is should return an object as seen here:

https://github.com/zendframework/zend-db/blob/ec0e9b51a09fc44f81af77fb949808fb4552c1cf/src/ResultSet/HydratingResultSet.php#L93

The method however could also return a boolean false:

https://github.com/zendframework/zend-db/blob/ec0e9b51a09fc44f81af77fb949808fb4552c1cf/src/ResultSet/HydratingResultSet.php#L103

I am guessing that the best solution for this, as well as possibly other locations to change the boolean false to null and mark the method to return ?object instead


Originally posted by @twmobius at zendframework/zend-db#316

Pdo pgsql: currval of sequence "my_table_id_seq" is not yet defined in this session

Bug Report

Q A
Version(s) 2.11.0

Summary

After upgrade to 2.11.0 I get exception with message Uncaught PDOException: SQLSTATE[55000]: Object not in prerequisite state: 7 ERROR: currval of sequence "my_table_id_seq" is not yet defined in this session.

Imho it is related with #146

How to reproduce

<?php

use Laminas\Db;

$t = '
CREATE TABLE IF NOT EXISTS my_table (
    id SERIAL,
    foo VARCHAR(255) NOT NULL,
    CONSTRAINT my_table_pkey PRIMARY KEY (id)
);
';

$table = new Db\Sql\TableIdentifier('my_table');
$adapter = new Db\Adapter\Adapter([
        'driver'   => 'pdo_pgsql',
        'hostname' => 'localhost',
        'database' => 'my_db',
        'username' => 'my_user',
        'password' => 'my_pass',
        'charset'  => 'utf-8',
]);
$featureSet = new Db\TableGateway\Feature\FeatureSet();
$featureSet->addFeature(new Db\TableGateway\Feature\SequenceFeature('id', 'my_table_id_seq'));

$tableGw = new Db\TableGateway\TableGateway(
    $table,
    $adapter,
    $featureSet
);

$tableGw->insert(['foo' => 'bar']);
$id = $tableGw->getLastInsertValue(); // exception thrown

Expected behavior

Last id is returned.

MySQL SelectDecorator - subselect limit parameter not prefixed (fix included)

When you have a FROM clause that includes a query with a LIMIT in it, and you try to prepare the query, you get following error:

Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in vendor/zendframework/zend-db/src/Adapter/Driver/Pdo/Statement.php:239
Stack trace:
#0 vendor/zendframework/zend-db/src/Adapter/Driver/Pdo/Statement.php(239): PDOStatement->execute()

The reason for this is because the parameter name for the subselect's limit is :limit while in the parameterContainer it is :subselect1limit.

This problem is rectified by modifying line 55 of src/Sql/Platform/Mysql/SelectDecorator.php from:

return [$driver->formatParameterName('limit')];

to

return [$driver->formatParameterName($paramPrefix . 'limit')];

Originally posted by @smartwebproducts at zendframework/zend-db#318

Prepared query wrong number of parameter on 2.9.3

Trying to execute a prepared query with named parameters. Works well with 2.9.2 but fails on 2.9.3.

Code to reproduce the issue

Something like:

$insert = $zdb->sql->insert(self::TABLE);
$insert->values(
    array(
        'name'  => ':name',
        'value'  => ':value'
    )
);
$stmt = $zdb->sql->prepareStatementForSqlObject($insert);

foreach ($values as $k => $v) {
    $stmt->execute(
        array(
            'name' => $k,
            'value' => $v
        )
    );
}

Expected results

Query success.

Actual results

Fails with the following exception:

==> An exception has been thrown in file tests/units/Preferences.php on line xx:
==> PDOException: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in vendor/zendframework/zend-db/src/Adapter/Driver/Pdo/Statement.php:239
==> Stack trace:
==> #0 vendor/zendframework/zend-db/src/Adapter/Driver/Pdo/Statement.php(239): PDOStatement->execute()
==> #1 lib/Preferences.php(310): Zend\Db\Adapter\Driver\Pdo\Statement->execute(Array)
[...]

Array passed to Statement::execute() looks like:

array(
    'name' => 'lang',
    'value' => 'en_US'
)

Thank you.


Originally posted by @trasher at zendframework/zend-db#322

SQL column alias bug

....$select...->join('vendors', 'vendors.id = campaigns_vendors.vendor_id', ['vendor_id'=>'id', 'vendor_daily_limit'=>'daily_limit'], $select::JOIN_LEFT)

When I query this select object I get the following error: "Not a valid magic property for this object"
When I rename the column alias to anything else but 'vendor_daily_limit' the error goes away.
When I print the produced SQL and run it via phpMyadmin or Bench then the query executes perfectly.

Very bizarre error and no indication of what is causing it.


Originally posted by @TradeSharer at zendframework/zend-db#317

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.