Skip to content

Commit

Permalink
Distinguish between executeStatement and executeQuery
Browse files Browse the repository at this point in the history
  • Loading branch information
mvorisek committed May 27, 2022
1 parent 05339b9 commit 6d3e0e2
Show file tree
Hide file tree
Showing 16 changed files with 111 additions and 61 deletions.
4 changes: 2 additions & 2 deletions docs/persistence/sql/advanced.rst
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ When it's time to execute you can specify your PDO manually::

With queries you might need to select mode first::

$stmt = $query->mode('delete')->execute($pdo);
$stmt = $query->mode('delete')->executeStatement($pdo);

The :php:meth:`Expresssion::execute` is a convenient way to prepare query,
bind all parameters and get `Doctrine\DBAL\Result`, but if you wish to do it manually,
Expand All @@ -47,7 +47,7 @@ by switching to DSQL::
$c = new Connection(['connection' => $pdo]);

$user_ids = $c->dsql()->table('expired_users')->field('user_id');
$c->dsql()->table('user')->where('id', 'in', $user_ids)->set('active', 0)->mode('update')->execute();
$c->dsql()->table('user')->where('id', 'in', $user_ids)->set('active', 0)->mode('update')->executeStatement();

// Native Laravel Database Query Builder
// $user_ids = DB::table('expired_users')->lists('user_id');
Expand Down
6 changes: 3 additions & 3 deletions docs/persistence/sql/expressions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -175,14 +175,14 @@ you can simply change the value of :php:attr:`$connection` property::

$expr->connection = $pdo_dbh;

Finally, you can pass connection class into :php:meth:`execute` directly.
Finally, you can pass connection class into :php:meth:`executeQuery` directly.

.. php:method:: execute($connection = null)
.. php:method:: executeQuery($connection = null)
Executes expression using current database connection or the one you
specify as the argument::

$stmt = $expr->execute($pdo_dbh);
$stmt = $expr->executeQuery($pdo_dbh);

returns `Doctrine\DBAL\Result`.

Expand Down
12 changes: 6 additions & 6 deletions docs/persistence/sql/queries.rst
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,11 @@ to re-use your query efficiently::
if ($row) {
$query
->set('revision', $query->expr('revision + 1'))
->mode('update')->execute();
->mode('update')->executeStatement();
} else {
$query
->set('revision', 1)
->mode('insert')->execute();
->mode('insert')->executeStatement();
}

The example above will perform a select query first:
Expand Down Expand Up @@ -665,10 +665,10 @@ Set value to a field

Example::

$q->table('user')->set('name', 'john')->mode('insert')->execute();
$q->table('user')->set('name', 'john')->mode('insert')->executeStatement();
// insert into user (name) values (john)

$q->table('log')->set('date', $q->expr('now()'))->mode('insert')->execute();
$q->table('log')->set('date', $q->expr('now()'))->mode('insert')->executeStatement();
// insert into log (date) values (now())

Method can be executed several times on the same Query object.
Expand Down Expand Up @@ -782,8 +782,8 @@ Other Methods
->option('calc_found_rows') // for default select mode
->option('ignore', 'insert') // for insert mode;

$q->execute(); // select calc_found_rows `name` from `test`
$q->mode('insert')->execute(); // insert ignore into `test` (`name`) values (`name` = 'John')
$q->executeQuery(); // select calc_found_rows `name` from `test`
$q->mode('insert')->executeStatement(); // insert ignore into `test` (`name`) values (`name` = 'John')

.. php:method:: _set_args($what, $alias, $value)
Expand Down
6 changes: 3 additions & 3 deletions docs/persistence/sql/quickstart.rst
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ DSQL classes are mindful about your SQL vendor and it's quirks, so when you're
building sub-queries with :php:meth:`Query::dsql`, you can avoid some nasty
problems::

$sqlite_c->dsql()->table('user')->mode('truncate')->execute();
$sqlite_c->dsql()->table('user')->mode('truncate')->executeStatement();

The above code will work even though SQLite does not support truncate. That's
because DSQL takes care of this.
Expand Down Expand Up @@ -191,15 +191,15 @@ You can actually perform multiple operations::

$q = $c->dsql()->table('employee')->where('emp_no', 1234);
$backup_data = $q->getRows();
$q->mode('delete')->execute();
$q->mode('delete')->executeStatement();

A good practice is to re-use the same query object before you branch out and
perform the action::

$q = $c->dsql()->table('employee')->where('emp_no', 1234);

if ($confirmed) {
$q->mode('delete')->execute();
$q->mode('delete')->executeStatement();
} else {
echo "Are you sure you want to delete " . $q->field('count(*)') . " employees?";
}
Expand Down
4 changes: 2 additions & 2 deletions docs/persistence/sql/transactions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ It is recommended to always use atomic() in your code.
exception, whole transaction will be automatically rolled back::

$c->atomic(function () use ($c) {
$c->dsql('user')->set('balance=balance + 10')->where('id', 10)->mode('update')->execute();
$c->dsql('user')->set('balance=balance - 10')->where('id', 14)->mode('update')->execute();
$c->dsql('user')->set('balance=balance + 10')->where('id', 10)->mode('update')->executeStatement();
$c->dsql('user')->set('balance=balance - 10')->where('id', 14)->mode('update')->executeStatement();
});

atomic() can be nested.
Expand Down
4 changes: 2 additions & 2 deletions docs/sql.rst
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ In short this should allow you to build and execute any SQL statement::
$this->expr("call get_nominal_sheet([], [], '2014-10-01', '2015-09-30', 0)", [
$this->getApp()->system->getId(),
$this->getApp()->system['contractor_id'],
])->execute();
])->executeQuery();

Depending on the statement you can also use your statement to retrieve data::

Expand Down Expand Up @@ -469,7 +469,7 @@ procedure inside Model::init() then set $table property to a temporary table::
$res = $this->expr("call get_nominal_sheet([], [], '2014-10-01', '2015-09-30', 0)", [
$this->getApp()->system->getId(),
$this->getApp()->system['contractor_id'],
])->execute();
])->executeQuery();

$this->addField('date', ['type' => 'date']);
$this->addField('items', ['type' => 'integer']);
Expand Down
6 changes: 3 additions & 3 deletions src/Persistence/Sql.php
Original file line number Diff line number Diff line change
Expand Up @@ -561,7 +561,7 @@ protected function insertRaw(Model $model, array $dataRaw)

try {
$model->hook(self::HOOK_BEFORE_INSERT_QUERY, [$insert]);
$c = $insert->execute()->rowCount();
$c = $insert->executeStatement();
} catch (SqlException $e) {
throw (new Exception('Unable to execute insert query', 0, $e))
->addMoreInfo('model', $model)
Expand Down Expand Up @@ -594,7 +594,7 @@ protected function updateRaw(Model $model, $idRaw, array $dataRaw): void
$model->hook(self::HOOK_BEFORE_UPDATE_QUERY, [$update]);

try {
$c = $update->execute()->rowCount();
$c = $update->executeStatement();
} catch (SqlException $e) {
throw (new Exception('Unable to update due to query error', 0, $e))
->addMoreInfo('model', $model)
Expand Down Expand Up @@ -632,7 +632,7 @@ protected function deleteRaw(Model $model, $idRaw): void
$model->hook(self::HOOK_BEFORE_DELETE_QUERY, [$delete]);

try {
$c = $delete->execute()->rowCount();
$c = $delete->executeStatement();
} catch (SqlException $e) {
throw (new Exception('Unable to delete due to query error', 0, $e))
->addMoreInfo('model', $model)
Expand Down
20 changes: 17 additions & 3 deletions src/Persistence/Sql/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -325,15 +325,29 @@ public function connection()
}

/**
* Execute Expression by using this connection.
* Execute Expression by using this connection and return result.
*/
public function execute(Expression $expr): DbalResult
public function executeQuery(Expression $expr): DbalResult
{
if ($this->connection === null) {
throw new Exception('DBAL connection is not set');
}

return $expr->execute($this->connection);
return $expr->executeQuery($this->connection);
}

/**
* Execute Expression by using this connection and return affected rows.
*
* @phpstan-return int<0, max>
*/
public function executeStatement(Expression $expr): int
{
if ($this->connection === null) {
throw new Exception('DBAL connection is not set');
}

return $expr->executeStatement($this->connection);
}

/**
Expand Down
48 changes: 42 additions & 6 deletions src/Persistence/Sql/Expression.php
Original file line number Diff line number Diff line change
Expand Up @@ -532,15 +532,29 @@ function ($matches) use ($params, &$numParams, &$i, &$j) {

/**
* @param DbalConnection|Connection $connection
*
* @return DbalResult|int<0, max>
*
* @deprecated Expression::execute() is deprecated and will be removed in v4.0, use Expression::executeQuery() or Expression::executeStatement() instead
*/
public function execute(object $connection = null): DbalResult
public function execute(object $connection = null, bool $fromExecuteStatement = null)
{
if ($connection === null) {
$connection = $this->connection;
}

if ($fromExecuteStatement === null) {
'trigger_error'('Method is deprecated. Use executeQuery() or executeStatement() instead', \E_USER_DEPRECATED);

$fromExecuteStatement = false;
}

if (!$connection instanceof DbalConnection) {
return $connection->execute($this);
if ($fromExecuteStatement) {
return $connection->executeStatement($this);
}

return $connection->executeQuery($this);
}

[$sql, $params] = $this->updateRenderBeforeExecute($this->render());
Expand Down Expand Up @@ -600,7 +614,11 @@ public function execute(object $connection = null): DbalResult
}
}

$result = $statement->execute(); // @phpstan-ignore-line
if ($fromExecuteStatement) {
$result = $statement->executeStatement();
} else {
$result = $statement->executeQuery();
}

return $result;
} catch (DbalException $e) {
Expand All @@ -620,6 +638,24 @@ public function execute(object $connection = null): DbalResult
}
}

/**
* @param DbalConnection|Connection $connection
*/
public function executeQuery(object $connection = null): DbalResult
{
return $this->execute($connection, false); // @phpstan-ignore-line
}

/**
* @param DbalConnection|Connection $connection
*
* @phpstan-return int<0, max>
*/
public function executeStatement(object $connection = null): int
{
return $this->execute($connection, true); // @phpstan-ignore-line
}

// {{{ Result Querying

/**
Expand Down Expand Up @@ -667,7 +703,7 @@ public function getRowsIterator(): \Traversable
{
// DbalResult::iterateAssociative() is broken with streams with Oracle database
// https://github.com/doctrine/dbal/issues/5002
$iterator = $this->execute()->iterateAssociative();
$iterator = $this->executeQuery()->iterateAssociative();

foreach ($iterator as $row) {
yield array_map(function ($v) {
Expand All @@ -685,7 +721,7 @@ public function getRows(): array
{
// DbalResult::fetchAllAssociative() is broken with streams with Oracle database
// https://github.com/doctrine/dbal/issues/5002
$result = $this->execute();
$result = $this->executeQuery();

$rows = [];
while (($row = $result->fetchAssociative()) !== false) {
Expand All @@ -704,7 +740,7 @@ public function getRows(): array
*/
public function getRow(): ?array
{
$row = $this->execute()->fetchAssociative();
$row = $this->executeQuery()->fetchAssociative();

if ($row === false) {
return null;
Expand Down
2 changes: 1 addition & 1 deletion src/Schema/Migrator.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ public function dropIfExists(): self
if ($this->getDatabasePlatform() instanceof OraclePlatform) {
$dropTriggerSql = $this->getDatabasePlatform()->getDropAutoincrementSql($this->table->getName())[1];
try {
$this->connection->expr($dropTriggerSql)->execute();
$this->connection->expr($dropTriggerSql)->executeStatement();
} catch (Exception $e) {
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/Schema/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ protected function setUp(): void
if ($this->db->getDatabasePlatform() instanceof MySQLPlatform) {
$this->db->connection->expr(
'SET SESSION auto_increment_increment = 1, SESSION auto_increment_offset = 1'
)->execute();
)->executeStatement();
}

$this->db->connection->connection()->getConfiguration()->setSQLLogger(
Expand Down Expand Up @@ -296,7 +296,7 @@ public function setDb(array $dbData, bool $importData = true): void
$query->set($idColumnName, $id);
}

$query->mode('insert')->execute();
$query->mode('insert')->executeStatement();
}
});
}
Expand Down
2 changes: 1 addition & 1 deletion tests/JoinSqlTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ public function testJoinSaving2(): void
],
], $this->getDb(['user', 'contact']));

$this->db->connection->dsql()->table('contact')->where('id', 2)->mode('delete')->execute();
$this->db->connection->dsql()->table('contact')->where('id', 2)->mode('delete')->executeStatement();

$m_u2->unload();
$m_u2 = $m_u->createEntity();
Expand Down
2 changes: 1 addition & 1 deletion tests/Persistence/Sql/ConnectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,6 @@ public function testException4(): void
);

$this->expectException(\Atk4\Data\Persistence\Sql\Exception::class);
$q->execute();
$q->executeQuery();
}
}
16 changes: 8 additions & 8 deletions tests/Persistence/Sql/WithDb/SelectTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ public function testExpression(): void
public function testOtherQueries(): void
{
// truncate table
$this->q('employee')->mode('truncate')->execute();
$this->q('employee')->mode('truncate')->executeStatement();
$this->assertSame(
'0',
$this->q('employee')->field(new Expression('count(*)'))->getOne()
Expand All @@ -167,10 +167,10 @@ public function testOtherQueries(): void
// insert
$this->q('employee')
->setMulti(['id' => 1, 'name' => 'John', 'surname' => 'Doe', 'retired' => true])
->mode('insert')->execute();
->mode('insert')->executeStatement();
$this->q('employee')
->setMulti(['id' => 2, 'name' => 'Jane', 'surname' => 'Doe', 'retired' => false])
->mode('insert')->execute();
->mode('insert')->executeStatement();
$this->assertSame(
[['id' => '1', 'name' => 'John'], ['id' => '2', 'name' => 'Jane']],
$this->q('employee')->field('id')->field('name')->order('id')->getRows()
Expand All @@ -180,7 +180,7 @@ public function testOtherQueries(): void
$this->q('employee')
->where('name', 'John')
->set('name', 'Johnny')
->mode('update')->execute();
->mode('update')->executeStatement();
$this->assertSame(
[['id' => '1', 'name' => 'Johnny'], ['id' => '2', 'name' => 'Jane']],
$this->q('employee')->field('id')->field('name')->order('id')->getRows()
Expand All @@ -191,11 +191,11 @@ public function testOtherQueries(): void
$this->q('employee')
->setMulti(['name' => 'Peter', 'surname' => 'Doe', 'retired' => true])
->where('id', 1)
->mode('update')->execute();
->mode('update')->executeStatement();
} else {
$this->q('employee')
->setMulti(['id' => 1, 'name' => 'Peter', 'surname' => 'Doe', 'retired' => true])
->mode('replace')->execute();
->mode('replace')->executeStatement();
}

// In SQLite replace is just like insert, it just checks if there is
Expand All @@ -217,7 +217,7 @@ public function testOtherQueries(): void
// delete
$this->q('employee')
->where('retired', true)
->mode('delete')->execute();
->mode('delete')->executeStatement();
$this->assertSame(
[['id' => '2', 'name' => 'Jane']],
$this->q('employee')->field('id')->field('name')->getRows()
Expand All @@ -227,7 +227,7 @@ public function testOtherQueries(): void
public function testEmptyGetOne(): void
{
// truncate table
$this->q('employee')->mode('truncate')->execute();
$this->q('employee')->mode('truncate')->executeStatement();
$this->expectException(Exception::class);
$this->q('employee')->field('name')->getOne();
}
Expand Down
Loading

0 comments on commit 6d3e0e2

Please sign in to comment.