Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Schema\TestCase::getConnection() method #1026

Merged
merged 2 commits into from
Jul 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion phpstan.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ parameters:

# TODO these rules are generated, this ignores should be fixed in the code
# for src/Schema/TestCase.php
- '~^Call to an undefined method Atk4\\Data\\Persistence::getConnection\(\)\.$~'
- '~^Call to an undefined method Atk4\\Data\\Persistence::dsql\(\)\.$~'
# for src/Field/SqlExpressionField.php
- '~^Call to an undefined method Atk4\\Data\\Model::expr\(\)\.$~'
Expand Down
9 changes: 9 additions & 0 deletions src/Persistence/Sql/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Doctrine\DBAL\Platforms\SqlitePlatform;
use Doctrine\DBAL\Platforms\SQLServerPlatform;
use Doctrine\DBAL\Result as DbalResult;
use Doctrine\DBAL\Schema\AbstractSchemaManager;

/**
* Class for establishing and maintaining connection with your database.
Expand Down Expand Up @@ -441,4 +442,12 @@ public function getDatabasePlatform(): AbstractPlatform
{
return $this->getConnection()->getDatabasePlatform();
}

/**
* @phpstan-return AbstractSchemaManager<AbstractPlatform>
*/
public function createSchemaManager(): AbstractSchemaManager
{
return $this->getConnection()->createSchemaManager();
}
}
2 changes: 1 addition & 1 deletion src/Schema/Migrator.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ protected function getDatabasePlatform(): AbstractPlatform
*/
protected function createSchemaManager(): AbstractSchemaManager
{
return $this->getConnection()->getConnection()->createSchemaManager();
return $this->getConnection()->createSchemaManager();
}

public function table(string $tableName): self
Expand Down
42 changes: 24 additions & 18 deletions src/Schema/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
use Doctrine\DBAL\Platforms\OraclePlatform;
use Doctrine\DBAL\Platforms\SqlitePlatform;
use Doctrine\DBAL\Platforms\SQLServerPlatform;
use Doctrine\DBAL\Schema\AbstractSchemaManager;

abstract class TestCase extends BaseTestCase
{
Expand All @@ -35,18 +34,18 @@ protected function setUp(): void

$this->db = Persistence::connect($_ENV['DB_DSN'], $_ENV['DB_USER'], $_ENV['DB_PASSWORD']);

if ($this->db->getDatabasePlatform() instanceof SqlitePlatform) {
$this->db->getConnection()->expr(
if ($this->getDatabasePlatform() instanceof SqlitePlatform) {
$this->getConnection()->expr(
'PRAGMA foreign_keys = 1'
)->executeStatement();
}
if ($this->db->getDatabasePlatform() instanceof MySQLPlatform) {
$this->db->getConnection()->expr(
if ($this->getDatabasePlatform() instanceof MySQLPlatform) {
$this->getConnection()->expr(
'SET SESSION auto_increment_increment = 1, SESSION auto_increment_offset = 1'
)->executeStatement();
}

$this->db->getConnection()->getConnection()->getConfiguration()->setSQLLogger(
$this->getConnection()->getConnection()->getConfiguration()->setSQLLogger(
null ?? new class($this) implements SQLLogger { // @phpstan-ignore-line
/** @var \WeakReference<TestCase> */
private $testCaseWeakRef;
Expand All @@ -62,13 +61,23 @@ public function startQuery($sql, array $params = null, array $types = null): voi
return;
}

echo "\n" . $sql . "\n" . (is_array($params) ? print_r(array_map(function ($v) {
if (is_string($v) && strlen($v) > 4096) {
$v = '*long string* (length: ' . strlen($v) . ' bytes, sha256: ' . hash('sha256', $v) . ')';
echo "\n" . $sql . "\n" . (is_array($params) && count($params) > 0 ? substr(print_r(array_map(function ($v) {
if ($v === null) {
$v = 'null';
} elseif (is_bool($v)) {
$v = $v ? 'true' : 'false';
} elseif (is_float($v) && (string) $v === (string) (int) $v) {
$v = $v . '.0';
} elseif (is_string($v)) {
if (strlen($v) > 4096) {
$v = '*long string* (length: ' . strlen($v) . ' bytes, sha256: ' . hash('sha256', $v) . ')';
} else {
$v = '\'' . $v . '\'';
}
}

return $v;
}, $params), true) : '') . "\n\n";
}, $params), true), 6) : '') . "\n\n";
}

public function stopQuery(): void
Expand All @@ -90,17 +99,14 @@ protected function tearDown(): void
parent::tearDown();
}

protected function getDatabasePlatform(): AbstractPlatform
protected function getConnection(): Persistence\Sql\Connection
{
return $this->db->getConnection()->getDatabasePlatform();
return $this->db->getConnection(); // @phpstan-ignore-line
}

/**
* @phpstan-return AbstractSchemaManager<AbstractPlatform>
*/
protected function createSchemaManager(): AbstractSchemaManager
protected function getDatabasePlatform(): AbstractPlatform
{
return $this->db->getConnection()->getConnection()->createSchemaManager();
return $this->getConnection()->getDatabasePlatform();
}

private function convertSqlFromSqlite(string $sql): string
Expand Down Expand Up @@ -243,7 +249,7 @@ public function setDb(array $dbData, bool $importData = true): void

// drop table if already created but only if it was created during this test
foreach ($this->createdMigrators as $migr) {
if ($migr->getConnection() === $this->db->getConnection()) {
if ($migr->getConnection() === $this->getConnection()) {
foreach ($migr->getCreatedTableNames() as $t) {
if ($t === $tableName) {
$migrator->drop();
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->getConnection()->dsql()->table('contact')->where('id', 2)->mode('delete')->executeStatement();
$this->getConnection()->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/ModelNestedArrayTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ protected function setUp(): void
{
parent::setUp();

$this->db->getConnection()->getConnection()->close();
$this->getConnection()->getConnection()->close();

$this->db = new Persistence\Array_([
'user' => [
Expand Down
4 changes: 2 additions & 2 deletions tests/ModelNestedSqlTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,9 @@ public function testSelectSql(): void
$m->setOrder('birthday');

$this->assertSame(
$this->db->getConnection()->dsql()
$this->getConnection()->dsql()
->table(
$this->db->getConnection()->dsql()
$this->getConnection()->dsql()
->table('user')
->field('_id', 'uid')
->field('name')
Expand Down
2 changes: 1 addition & 1 deletion tests/ModelWithCteTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public function testWith(): void
);

if ($this->getDatabasePlatform() instanceof MySQLPlatform) {
$serverVersion = $this->db->getConnection()->getConnection()->getWrappedConnection()->getServerVersion();
$serverVersion = $this->getConnection()->getConnection()->getWrappedConnection()->getServerVersion(); // @phpstan-ignore-line
if (preg_match('~^5\.(?!5\.5-.+?-MariaDB)~', $serverVersion)) {
$this->markTestIncomplete('MySQL Server 5.x does not support WITH clause');
}
Expand Down
6 changes: 3 additions & 3 deletions tests/Persistence/Sql/ExpressionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@
class ExpressionTest extends TestCase
{
/**
* @param mixed ...$args
* @param string|array $template
*/
public function e(...$args): Expression
protected function e($template = [], array $arguments = []): Expression
{
return new Expression(...$args);
return new Expression($template, $arguments);
}

/**
Expand Down
6 changes: 3 additions & 3 deletions tests/Persistence/Sql/QueryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@
class QueryTest extends TestCase
{
/**
* @param string|array ...$args
* @param string|array $template
*/
public function q(...$args): Query
protected function q($template = [], array $arguments = []): Query
{
return new Query(...$args);
return new Query($template, $arguments);
}

public function testConstruct(): void
Expand Down
33 changes: 12 additions & 21 deletions tests/Persistence/Sql/WithDb/SelectTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
namespace Atk4\Data\Tests\Persistence\Sql\WithDb;

use Atk4\Data\Model;
use Atk4\Data\Persistence\Sql\Connection;
use Atk4\Data\Persistence\Sql\Exception;
use Atk4\Data\Persistence\Sql\ExecuteException;
use Atk4\Data\Persistence\Sql\Expression;
Expand All @@ -18,15 +17,10 @@

class SelectTest extends TestCase
{
/** @var Connection */
protected $c;

protected function setUp(): void
{
parent::setUp();

$this->c = $this->db->getConnection();

$model = new Model($this->db, ['table' => 'employee']);
$model->addField('name');
$model->addField('surname');
Expand All @@ -43,14 +37,11 @@ protected function setUp(): void
}

/**
* @param mixed $table
* @param string $alias
* @param string|Expression $table
*/
private function q($table = null, string $alias = null): Query
protected function q($table = null, string $alias = null): Query
{
$q = $this->c->dsql();

// add table to query if specified
$q = $this->getConnection()->dsql();
if ($table !== null) {
$q->table($table, $alias);
}
Expand All @@ -61,9 +52,9 @@ private function q($table = null, string $alias = null): Query
/**
* @param string|array $template
*/
private function e($template = [], array $args = []): Expression
protected function e($template = [], array $arguments = []): Expression
{
return $this->c->expr($template, $args);
return $this->getConnection()->expr($template, $arguments);
}

public function testBasicQueries(): void
Expand Down Expand Up @@ -368,19 +359,19 @@ public function testImportAndAutoincrement(): void
$getLastAiFx = function (): int {
$table = 'test';
$pk = 'myid';
$maxIdExpr = $this->c->dsql()->table($table)->field($this->c->expr('max({})', [$pk]));
$maxIdExpr = $this->q()->table($table)->field($this->e('max({})', [$pk]));
if ($this->getDatabasePlatform() instanceof MySQLPlatform) {
$query = $this->c->dsql()->table('INFORMATION_SCHEMA.TABLES')
->field($this->c->expr('greatest({} - 1, (' . $maxIdExpr->render()[0] . '))', ['AUTO_INCREMENT']))
$query = $this->q()->table('INFORMATION_SCHEMA.TABLES')
->field($this->e('greatest({} - 1, (' . $maxIdExpr->render()[0] . '))', ['AUTO_INCREMENT']))
->where('TABLE_NAME', $table);
} elseif ($this->getDatabasePlatform() instanceof PostgreSQLPlatform) {
$query = $this->c->dsql()->field($this->c->expr('currval(pg_get_serial_sequence([], []))', [$table, $pk]));
$query = $this->q()->field($this->e('currval(pg_get_serial_sequence([], []))', [$table, $pk]));
} elseif ($this->getDatabasePlatform() instanceof SQLServerPlatform) {
$query = $this->c->dsql()->field($this->c->expr('IDENT_CURRENT([])', [$table]));
$query = $this->q()->field($this->e('IDENT_CURRENT([])', [$table]));
} elseif ($this->getDatabasePlatform() instanceof OraclePlatform) {
$query = $this->c->dsql()->field($this->c->expr('{}.CURRVAL', [$table . '_SEQ']));
$query = $this->q()->field($this->e('{}.CURRVAL', [$table . '_SEQ']));
} else {
$query = $this->c->dsql()->table('sqlite_sequence')->field('seq')->where('name', $table);
$query = $this->q()->table('sqlite_sequence')->field('seq')->where('name', $table);
}

return (int) $query->getOne();
Expand Down
Loading