Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@

namespace Cycle\Database\Tests\Feature\Common\Connection;

use Cycle\Database\Exception\StatementException\ConnectionException;
use Cycle\Testing\Database\Attribute\ExceptDriver;
use Cycle\Testing\Database\Driver;
use Cycle\Testing\Database\Mock\WrapDriverInterface;
use Testo\Assert;
use Testo\Test;

Expand All @@ -32,4 +34,37 @@ public function testReconnectionOnBeginTransaction(): void
$this->database->commit();
Assert::same($driver->getTransactionLevel(), 0);
}

#[Test]
public function testFailedReconnectionOnBeginTransactionLeavesNoTransaction(): void
{
$driver = $this->wrapDriver();
$driver->exceptionOnTransactionBegin = 2;

try {
$driver->beginTransaction();
Assert::fail('The second failure has to reach the caller.');
} catch (ConnectionException) {
}

Assert::same($driver->disconnectCalls, 1);
Assert::same($driver->getTransactionLevel(), 0);
}

#[Test]
public function testBeginTransactionWithoutReconnectFailsAtOnce(): void
{
$driver = $this->db(driverConfig: ['reconnect' => false])->getDriver();
\assert($driver instanceof WrapDriverInterface);
$driver->exceptionOnTransactionBegin = 1;

try {
$driver->beginTransaction();
Assert::fail('The failure has to reach the caller.');
} catch (ConnectionException) {
}

Assert::same($driver->disconnectCalls, 0);
Assert::same($driver->getTransactionLevel(), 0);
}
}
12 changes: 12 additions & 0 deletions tests/Feature/Common/Schema/AlterColumnTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,18 @@ public function testDropColumn(): void
SchemaAssert::sameAsInDb($schema);
}

#[Test]
public function testDropEnumColumn(): void
{
$this->sampleSchema('table');

$schema = $this->schema('table');
$schema->dropColumn('status');
$schema->save();

Assert::false($this->schema('table')->hasColumn('status'));
}

#[Test]
public function testDropMultipleColumns(): void
{
Expand Down
20 changes: 20 additions & 0 deletions tests/Feature/MySQL/Schema/CharsetCollationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,26 @@ public function testChangeCollation(): void
Assert::same($titleColumn->getCollation(), 'ascii_bin');
}

#[Test]
public function testChangeCharset(): void
{
$schema = $this->schema('table');
$schema->primary('id');
$schema->string('title', size: 255)->charset('ascii');
$schema->save();

$schema = $this->schema('table');
$schema->column('title')->charset('latin1')->collation('latin1_bin');

Assert::count($schema->getComparator()->alteredColumns(), 1);

$schema->save();

$titleColumn = $this->schema('table')->column('title');
\assert($titleColumn instanceof MySQLColumn);
Assert::same($titleColumn->getCharset(), 'latin1');
}

#[Test]
public function testTextColumnWithCharsetAndCollation(): void
{
Expand Down
26 changes: 26 additions & 0 deletions tests/Feature/MySQL/Schema/CreateTableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@

namespace Cycle\Database\Tests\Feature\MySQL\Schema;

use Cycle\Database\Exception\SchemaException;
use Cycle\Database\Tests\Feature\Common\Schema\CreateTableTest as CommonClass;
use Cycle\Testing\Database\Assert\SchemaAssert;
use Cycle\Testing\Database\Attribute\OnlyDriver;
use Cycle\Testing\Database\Driver;
use Testo\Assert;
use Testo\Expect;
use Testo\Test;

#[OnlyDriver(Driver::MySQL)]
Expand All @@ -35,4 +37,28 @@ public function testMultipleColumnsWithJson(): void
Assert::same($schema->column('status')->getEnumValues(), ['active', 'disabled']);
Assert::same($schema->column('data')->getAbstractType(), 'json');
}

#[Test]
public function testEngineIsChosenAtCreation(): void
{
$schema = $this->schema('table');
$schema->setEngine('MyISAM');
$schema->primary('id');
$schema->save();

Assert::same($this->schema('table')->getEngine(), 'MyISAM');
}

#[Test]
public function testEngineOfAnExistingTableIsRejected(): never
{
$schema = $this->schema('table');
$schema->primary('id');
$schema->save();

Expect::exception(SchemaException::class)
->withMessage('Table engine can be set only at moment of creation');

$this->schema('table')->setEngine('MyISAM');
}
}
39 changes: 39 additions & 0 deletions tests/Feature/MySQL/Schema/DefaultValueTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@

namespace Cycle\Database\Tests\Feature\MySQL\Schema;

use Cycle\Database\Injection\Fragment;
use Cycle\Database\Tests\Feature\Common\Schema\DefaultValueTest as CommonClass;
use Cycle\Testing\Database\Attribute\OnlyDriver;
use Cycle\Testing\Database\Driver;
use Testo\Assert;
use Testo\Expect;
use Testo\Test;

Expand Down Expand Up @@ -47,4 +49,41 @@ public function testJsonDefaultValueEmpty(): void
Expect::exception(\Cycle\Database\Driver\MySQL\Exception\MySQLException::class)->withMessageContaining('Column table.target of type text/blob/json can not have non empty default value');
parent::testJsonDefaultValueEmpty();
}

#[Test]
public function testBitDefaultIsReadAsFragment(): void
{
$this->database->execute("CREATE TABLE `table` (id INT PRIMARY KEY, flags BIT(4) DEFAULT b'101')");

$default = $this->schema('table')->column('flags')->getDefaultValue();

Assert::instanceOf($default, Fragment::class);
Assert::same((string) $default, "b'101'");
}

#[Test]
public function testZeroTimestampDefaultIsReadAsEpoch(): void
{
$this->database->execute("SET SESSION sql_mode = ''");
try {
$this->database->execute(
"CREATE TABLE `table` (id INT PRIMARY KEY, at TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00')",
);
} finally {
$this->database->execute('SET SESSION sql_mode = DEFAULT');
}

$default = $this->schema('table')->column('at')->getDefaultValue();

Assert::instanceOf($default, \DateTimeInterface::class);
Assert::same($default->getTimestamp(), 0);
}

#[Test]
public function testMariaDbNowDefaultIsTheCurrentTimestamp(): void
{
$column = $this->schema('table')->datetime('at')->defaultValue('current_timestamp()');

Assert::equals($column->getDefaultValue(), new Fragment('CURRENT_TIMESTAMP'));
}
}
18 changes: 18 additions & 0 deletions tests/Feature/Postgres/Driver/CursorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -132,4 +132,22 @@ public function testCursorWithHoldSurvivesCommit(): void
Assert::count($remaining, 4);
Assert::same($remaining[3]['name'], \md5('4'));
}

#[Test]
public function testCursorAbandonedAfterRollbackClosesQuietly(): void
{
$this->fillRows(3);

$this->database->begin();
$gen = $this->database->cursor(
$this->database->select()->from('sample_table')->orderBy('id'),
new PostgresCursorOptions(chunkSize: 1),
);
$gen->rewind();
$this->database->rollback();

unset($gen);

Assert::same($this->database->select()->from('sample_table')->count(), 3);
}
}
12 changes: 12 additions & 0 deletions tests/Feature/Postgres/Driver/DriverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Cycle\Database\Tests\Feature\Postgres\Driver;

use Cycle\Database\Driver\Postgres\PostgresDriver;
use Cycle\Database\Tests\Feature\Common\Driver\DriverTest as CommonClass;
use Cycle\Testing\Database\Attribute\OnlyDriver;
use Cycle\Testing\Database\Driver;
Expand All @@ -28,4 +29,15 @@ public function testSchemaPathAfterReconnect(): void

Assert::same($ref->getValue($db->getDriver()), ['custom']);
}

#[Test]
public function testUserSchemaResolvesToTheConnectionUser(): void
{
$driver = $this->database->getDriver();
\assert($driver instanceof PostgresDriver);

$user = $driver->query('SELECT current_user')->fetchColumn();

Assert::same($driver->parseSchemaAndTable('$user.users'), [$user, 'users']);
}
}
39 changes: 39 additions & 0 deletions tests/Feature/Postgres/Schema/AlterColumnTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,45 @@ public function testAddSerialColumn(): void
SchemaAssert::sameAsInDb($schema);
}

#[Test]
public function testPrimaryTypesOnExistingColumnsChangeTheIntegerSize(): void
{
$schema = $this->schema('table');
$schema->integer('id');
$schema->integer('small');
$schema->bigInteger('regular');
$schema->integer('big');
$schema->save();

$schema = $this->schema('table');
$schema->column('small')->smallPrimary();
$schema->column('regular')->primary();
$schema->column('big')->bigPrimary();
$schema->save();

$columns = $this->schema('table')->getColumns();
Assert::same($columns['small']->getInternalType(), 'smallint');
Assert::same($columns['regular']->getInternalType(), 'integer');
Assert::same($columns['big']->getInternalType(), 'bigint');
}

#[Test]
public function testChangeDecimalPrecision(): void
{
$schema = $this->schema('table');
$schema->integer('id');
$schema->decimal('amount', 10, 2);
$schema->save();

$schema = $this->schema('table');
$schema->decimal('amount', 12, 4);
$schema->save();

$column = $this->schema('table')->column('amount');
Assert::same($column->getPrecision(), 12);
Assert::same($column->getScale(), 4);
}

#[Test]
public function testAddCustomColumnTypeWithOptions(): void
{
Expand Down
20 changes: 20 additions & 0 deletions tests/Feature/Postgres/Schema/EnumIntrospectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,26 @@ public function testCompositePrimaryKeyWithEmulatedEnum(): void
Assert::same($schema->getIndexes(), []);
}

#[Test]
public function testNativeEnumWithDefaultReadInBulk(): void
{
$driver = $this->database->getDriver();

$driver->execute("CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy')");
$driver->execute(
"CREATE TABLE mixed_enums (
id serial NOT NULL,
current_mood mood NOT NULL DEFAULT 'ok',
CONSTRAINT mixed_enums_pkey PRIMARY KEY (id)
)",
);

$schema = $this->database->getSchemas(['mixed_enums'])['mixed_enums'];

Assert::same($schema->column('current_mood')->getEnumValues(), ['sad', 'ok', 'happy']);
Assert::same($schema->column('current_mood')->getDefaultValue(), 'ok');
}

#[AfterTest]
public function tearDown(): void
{
Expand Down
42 changes: 42 additions & 0 deletions tests/Feature/SQLServer/Schema/AlterColumnTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,46 @@ public function testChangeDatetimeSize(): void
SchemaAssert::sameAsInDb($schema);
Assert::same($this->fetchSchema($schema)->column('datetime')->getSize(), 7);
}

#[Test]
public function testMakeEnumNotNullable(): void
{
$schema = $this->sampleSchema('table');
$schema->enum('status', ['active', 'disabled'])->nullable(false)->defaultValue('active');
$schema->save();

$column = $this->fetchSchema($schema)->column('status');
Assert::false($column->isNullable());
Assert::same($column->getEnumValues(), ['active', 'disabled']);
}

#[Test]
public function testChangeDecimalPrecision(): void
{
$schema = $this->sampleSchema('table');
$schema->decimal('amount', 10, 2);
$schema->save();

$schema = $this->schema('table');
$schema->decimal('amount', 12, 4);
$schema->save();

$column = $this->schema('table')->column('amount');
Assert::same($column->getPrecision(), 12);
Assert::same($column->getScale(), 4);
}

#[Test]
public function testAddDefaultToExistingColumn(): void
{
$schema = $this->sampleSchema('table');
$schema->integer('counter')->nullable(true);
$schema->save();

$schema = $this->schema('table');
$schema->integer('counter')->nullable(true)->defaultValue(5);
$schema->save();

Assert::same($this->schema('table')->column('counter')->getDefaultValue(), 5);
}
}
10 changes: 10 additions & 0 deletions tests/Unit/Config/ConfigTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use Cycle\Database\Driver\MySQL\MySQLDriver;
use Cycle\Database\Driver\SQLite\SQLiteDriver;
use Cycle\Database\Exception\ConfigException;
use Cycle\Database\Tests\Unit\Stub\DecoratedDriver;
use Testo\Assert;
use Testo\Expect;
use Testo\Test;
Expand Down Expand Up @@ -259,6 +260,15 @@ public function testGetDriver(): void
Assert::instanceOf($config->getDriver('test2'), MySQLDriver::class);
}

public function returnsADriverWithoutANameAsCreated(): void
{
$config = new DatabaseConfig([
'connections' => ['test' => new SQLiteDriverConfig(driver: DecoratedDriver::class)],
]);

Assert::instanceOf($config->getDriver('test'), DecoratedDriver::class);
}

public function testDriverNames(): void
{
$config = new DatabaseConfig(
Expand Down
7 changes: 7 additions & 0 deletions tests/Unit/Config/PostgresDriverConfigTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,11 @@ public function testSetState(): void
Assert::same($recoveredConfig->readonlySchema, $readonlySchema);
Assert::same($recoveredConfig->readonly, $readonly);
}

public function fallsBackToTheDefaultSchemaForAnEmptyList(): void
{
$config = new PostgresDriverConfig(new DsnConnectionConfig('dsn'), schema: []);

Assert::same($config->schema, [PostgresDriverConfig::DEFAULT_SCHEMA]);
}
}
Loading
Loading