Skip to content

Use DateTimeColumn #407

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

Merged
merged 4 commits into from
May 16, 2025
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: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
- Enh #396: Remove `getCacheKey()` and `getCacheTag()` methods from `Schema` class (@Tigrov)
- Enh #403, #404: Use `DbArrayHelper::arrange()` instead of `DbArrayHelper::index()` method (@Tigrov)
- New #397: Realize `Schema::loadResultColumn()` method (@Tigrov)
- New #407: Use `DateTimeColumn` class for datetime column types (@Tigrov)

## 1.3.0 March 21, 2024

Expand Down
10 changes: 6 additions & 4 deletions src/Column/ColumnDefinitionBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@ final class ColumnDefinitionBuilder extends AbstractColumnDefinitionBuilder
'bpchar',
'character varying',
'varchar',
'time',
'timetz',
'timestamp',
'timestamptz',
'time',
'timetz',
'interval',
];

Expand Down Expand Up @@ -97,10 +97,12 @@ protected function getDbType(ColumnInterface $column): string
ColumnType::TEXT => 'text',
ColumnType::BINARY => 'bytea',
ColumnType::UUID => 'uuid',
ColumnType::DATETIME => 'timestamp',
ColumnType::TIMESTAMP => 'timestamp',
ColumnType::DATE => 'date',
ColumnType::DATETIME => 'timestamp',
ColumnType::DATETIMETZ => 'timestamptz',
ColumnType::TIME => 'time',
ColumnType::TIMETZ => 'timetz',
ColumnType::DATE => 'date',
ColumnType::STRUCTURED => 'jsonb',
ColumnType::JSON => 'jsonb',
default => 'varchar',
Expand Down
17 changes: 9 additions & 8 deletions src/Column/ColumnFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
* columns?: array<string, ColumnInterface>,
* comment?: string|null,
* computed?: bool|string,
* dbTimezone?: string,
* db_type?: string|null,
* default_value?: mixed,
* dimension?: int|string,
Expand Down Expand Up @@ -88,16 +89,16 @@ final class ColumnFactory extends AbstractColumnFactory
'varchar' => ColumnType::STRING,
'text' => ColumnType::TEXT,
'bytea' => ColumnType::BINARY,
'date' => ColumnType::DATE,
'abstime' => ColumnType::DATETIME,
'timestamp' => ColumnType::DATETIME,
'timestamp without time zone' => ColumnType::DATETIME,
'timestamp with time zone' => ColumnType::DATETIMETZ,
'timestamptz' => ColumnType::DATETIMETZ,
'time' => ColumnType::TIME,
'time without time zone' => ColumnType::TIME,
'time with time zone' => ColumnType::TIME,
'timetz' => ColumnType::TIME,
'timestamp' => ColumnType::TIMESTAMP,
'timestamp without time zone' => ColumnType::TIMESTAMP,
'timestamp with time zone' => ColumnType::TIMESTAMP,
'timestamptz' => ColumnType::TIMESTAMP,
'abstime' => ColumnType::TIMESTAMP,
'time with time zone' => ColumnType::TIMETZ,
'timetz' => ColumnType::TIMETZ,
'date' => ColumnType::DATE,
'interval' => ColumnType::STRING,
'box' => ColumnType::STRING,
'circle' => ColumnType::STRING,
Expand Down
92 changes: 48 additions & 44 deletions tests/ColumnTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@

namespace Yiisoft\Db\Pgsql\Tests;

use DateTimeImmutable;
use DateTimeZone;
use PHPUnit\Framework\Attributes\DataProviderExternal;
use Throwable;
use Yiisoft\Db\Constant\ColumnType;
use Yiisoft\Db\Exception\Exception;
Expand All @@ -20,25 +23,30 @@
use Yiisoft\Db\Pgsql\Column\IntegerColumn;
use Yiisoft\Db\Pgsql\Column\StructuredColumn;
use Yiisoft\Db\Pgsql\Connection;
use Yiisoft\Db\Pgsql\Tests\Provider\ColumnProvider;
use Yiisoft\Db\Pgsql\Tests\Support\TestTrait;
use Yiisoft\Db\Query\Query;
use Yiisoft\Db\Schema\Column\ColumnInterface;
use Yiisoft\Db\Schema\Column\DoubleColumn;
use Yiisoft\Db\Schema\Column\JsonColumn;
use Yiisoft\Db\Schema\Column\StringColumn;
use Yiisoft\Db\Tests\AbstractColumnTest;
use Yiisoft\Db\Tests\Common\CommonColumnTest;
use Yiisoft\Db\Tests\Support\Assert;

use function str_repeat;
use function stream_get_contents;

/**
* @group pgsql
*
* @psalm-suppress PropertyNotSetInConstructor
*/
final class ColumnTest extends AbstractColumnTest
final class ColumnTest extends CommonColumnTest
{
use TestTrait;

protected const COLUMN_BUILDER = ColumnBuilder::class;

private function insertTypeValues(Connection $db): void
{
$db->createCommand()->insert(
Expand All @@ -49,6 +57,8 @@ private function insertTypeValues(Connection $db): void
'char_col3' => null,
'float_col' => 1.234,
'blob_col' => "\x10\x11\x12",
'timestamp_col' => '2023-07-11 14:50:23',
'timestamp_default' => new DateTimeImmutable('2023-07-11 14:50:23'),
'bool_col' => false,
'bit_col' => 0b0110_0100, // 100
'varbit_col' => 0b1_1100_1000, // 456
Expand All @@ -64,12 +74,14 @@ private function insertTypeValues(Connection $db): void
)->execute();
}

private function assertResultValues(array $result): void
private function assertTypecastedValues(array $result): void
{
$this->assertSame(1, $result['int_col']);
$this->assertSame(str_repeat('x', 100), $result['char_col']);
$this->assertSame(1.234, $result['float_col']);
$this->assertSame("\x10\x11\x12", stream_get_contents($result['blob_col']));
$this->assertEquals(new DateTimeImmutable('2023-07-11 14:50:23', new DateTimeZone('UTC')), $result['timestamp_col']);
$this->assertEquals(new DateTimeImmutable('2023-07-11 14:50:23'), $result['timestamp_default']);
$this->assertFalse($result['bool_col']);
$this->assertSame(0b0110_0100, $result['bit_col']);
$this->assertSame(0b1_1100_1000, $result['varbit_col']);
Expand All @@ -93,11 +105,11 @@ public function testQueryWithTypecasting(): void

$result = $query->one();

$this->assertResultValues($result);
$this->assertTypecastedValues($result);

$result = $query->all();

$this->assertResultValues($result[0]);
$this->assertTypecastedValues($result[0]);

$db->close();
}
Expand All @@ -112,11 +124,11 @@ public function testCommandWithPhpTypecasting(): void

$result = $command->queryOne();

$this->assertResultValues($result);
$this->assertTypecastedValues($result);

$result = $command->queryAll();

$this->assertResultValues($result[0]);
$this->assertTypecastedValues($result[0]);

$db->close();
}
Expand Down Expand Up @@ -190,43 +202,19 @@ public function testPhpTypeCast(): void
{
$db = $this->getConnection(true);
$schema = $db->getSchema();
$tableSchema = $schema->getTableSchema('type');
$columns = $schema->getTableSchema('type')->getColumns();

$this->insertTypeValues($db);

$query = (new Query($db))->from('type')->one();

$intColPhpTypeCast = $tableSchema->getColumn('int_col')?->phpTypecast($query['int_col']);
$charColPhpTypeCast = $tableSchema->getColumn('char_col')?->phpTypecast($query['char_col']);
$floatColPhpTypeCast = $tableSchema->getColumn('float_col')?->phpTypecast($query['float_col']);
$blobColPhpTypeCast = $tableSchema->getColumn('blob_col')?->phpTypecast($query['blob_col']);
$boolColPhpTypeCast = $tableSchema->getColumn('bool_col')?->phpTypecast($query['bool_col']);
$bitColPhpTypeCast = $tableSchema->getColumn('bit_col')?->phpTypecast($query['bit_col']);
$varbitColPhpTypeCast = $tableSchema->getColumn('varbit_col')?->phpTypecast($query['varbit_col']);
$numericColPhpTypeCast = $tableSchema->getColumn('numeric_col')?->phpTypecast($query['numeric_col']);
$intArrayColPhpType = $tableSchema->getColumn('intarray_col')?->phpTypecast($query['intarray_col']);
$numericArrayColPhpTypeCast = $tableSchema->getColumn('numericarray_col')?->phpTypecast($query['numericarray_col']);
$varcharArrayColPhpTypeCast = $tableSchema->getColumn('varchararray_col')?->phpTypecast($query['varchararray_col']);
$textArray2ColPhpType = $tableSchema->getColumn('textarray2_col')?->phpTypecast($query['textarray2_col']);
$jsonColPhpType = $tableSchema->getColumn('json_col')?->phpTypecast($query['json_col']);
$jsonBColPhpType = $tableSchema->getColumn('jsonb_col')?->phpTypecast($query['jsonb_col']);
$jsonArrayColPhpType = $tableSchema->getColumn('jsonarray_col')?->phpTypecast($query['jsonarray_col']);

$this->assertSame(1, $intColPhpTypeCast);
$this->assertSame(str_repeat('x', 100), $charColPhpTypeCast);
$this->assertSame(1.234, $floatColPhpTypeCast);
$this->assertSame("\x10\x11\x12", stream_get_contents($blobColPhpTypeCast));
$this->assertFalse($boolColPhpTypeCast);
$this->assertSame(0b0110_0100, $bitColPhpTypeCast);
$this->assertSame(0b1_1100_1000, $varbitColPhpTypeCast);
$this->assertSame(33.22, $numericColPhpTypeCast);
$this->assertSame([1, -2, null, 42], $intArrayColPhpType);
$this->assertSame([null, 1.2, -2.2, null, null], $numericArrayColPhpTypeCast);
$this->assertSame(['', 'some text', '""', '\\\\', '[",","null",true,"false","f"]', null], $varcharArrayColPhpTypeCast);
$this->assertNull($textArray2ColPhpType);
$this->assertSame([['a' => 1, 'b' => null, 'c' => [1, 3, 5]]], $jsonColPhpType);
$this->assertSame(['1', '2', '3'], $jsonBColPhpType);
$this->assertSame([[[',', 'null', true, 'false', 'f']]], $jsonArrayColPhpType);
$result = [];

foreach ($columns as $columnName => $column) {
$result[$columnName] = $column->phpTypecast($query[$columnName]);
}

$this->assertTypecastedValues($result);

$db->close();
}
Expand Down Expand Up @@ -430,32 +418,48 @@ public function testColumnInstance()
$db->close();
}

/** @dataProvider \Yiisoft\Db\Pgsql\Tests\Provider\ColumnProvider::predefinedTypes */
#[DataProviderExternal(ColumnProvider::class, 'predefinedTypes')]
public function testPredefinedType(string $className, string $type, string $phpType)
{
parent::testPredefinedType($className, $type, $phpType);
}

/** @dataProvider \Yiisoft\Db\Pgsql\Tests\Provider\ColumnProvider::dbTypecastColumns */
#[DataProviderExternal(ColumnProvider::class, 'dbTypecastColumns')]
public function testDbTypecastColumns(ColumnInterface $column, array $values)
{
parent::testDbTypecastColumns($column, $values);
}

/** @dataProvider \Yiisoft\Db\Pgsql\Tests\Provider\ColumnProvider::phpTypecastColumns */
#[DataProviderExternal(ColumnProvider::class, 'phpTypecastColumns')]
public function testPhpTypecastColumns(ColumnInterface $column, array $values)
{
parent::testPhpTypecastColumns($column, $values);
}

/** @dataProvider \Yiisoft\Db\Pgsql\Tests\Provider\ColumnProvider::phpTypecastArrayColumns */
#[DataProviderExternal(ColumnProvider::class, 'dbTypecastArrayColumns')]
public function testArrayColumnDbTypecast(ColumnInterface $column, array $values): void
{
$arrayCol = (new ArrayColumn())->column($column);

foreach ($values as [$dimension, $expected, $value]) {
$arrayCol->dimension($dimension);
$dbValue = $arrayCol->dbTypecast($value);

$this->assertInstanceOf(ArrayExpression::class, $dbValue);
$this->assertSame($arrayCol, $dbValue->getType());
$this->assertEquals($value, $dbValue->getValue());
}
}

#[DataProviderExternal(ColumnProvider::class, 'phpTypecastArrayColumns')]
public function testPhpTypecastArrayColumn(ColumnInterface $column, array $values): void
{
$arrayCol = ColumnBuilder::array($column);

foreach ($values as [$dimension, $expected, $value]) {
$arrayCol->dimension($dimension);
$this->assertSame($expected, $arrayCol->phpTypecast($value));

Assert::arraysEquals($expected, $arrayCol->phpTypecast($value));
}
}

Expand Down
21 changes: 11 additions & 10 deletions tests/Provider/ColumnFactoryProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use Yiisoft\Db\Pgsql\Column\BooleanColumn;
use Yiisoft\Db\Pgsql\Column\IntegerColumn;
use Yiisoft\Db\Pgsql\Column\StructuredColumn;
use Yiisoft\Db\Schema\Column\DateTimeColumn;
use Yiisoft\Db\Schema\Column\DoubleColumn;
use Yiisoft\Db\Schema\Column\JsonColumn;
use Yiisoft\Db\Schema\Column\StringColumn;
Expand Down Expand Up @@ -55,16 +56,16 @@ public static function dbTypes(): array
['varchar', ColumnType::STRING, StringColumn::class],
['text', ColumnType::TEXT, StringColumn::class],
['bytea', ColumnType::BINARY, BinaryColumn::class],
['date', ColumnType::DATE, StringColumn::class],
['time', ColumnType::TIME, StringColumn::class],
['time without time zone', ColumnType::TIME, StringColumn::class],
['time with time zone', ColumnType::TIME, StringColumn::class],
['timetz', ColumnType::TIME, StringColumn::class],
['timestamp', ColumnType::TIMESTAMP, StringColumn::class],
['timestamp without time zone', ColumnType::TIMESTAMP, StringColumn::class],
['timestamp with time zone', ColumnType::TIMESTAMP, StringColumn::class],
['timestamptz', ColumnType::TIMESTAMP, StringColumn::class],
['abstime', ColumnType::TIMESTAMP, StringColumn::class],
['abstime', ColumnType::DATETIME, DateTimeColumn::class],
['timestamp', ColumnType::DATETIME, DateTimeColumn::class],
['timestamp without time zone', ColumnType::DATETIME, DateTimeColumn::class],
['timestamp with time zone', ColumnType::DATETIMETZ, DateTimeColumn::class],
['timestamptz', ColumnType::DATETIMETZ, DateTimeColumn::class],
['time', ColumnType::TIME, DateTimeColumn::class],
['time without time zone', ColumnType::TIME, DateTimeColumn::class],
['time with time zone', ColumnType::TIMETZ, DateTimeColumn::class],
['timetz', ColumnType::TIMETZ, DateTimeColumn::class],
['date', ColumnType::DATE, DateTimeColumn::class],
['interval', ColumnType::STRING, StringColumn::class],
['box', ColumnType::STRING, StringColumn::class],
['circle', ColumnType::STRING, StringColumn::class],
Expand Down
27 changes: 27 additions & 0 deletions tests/Provider/ColumnProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

namespace Yiisoft\Db\Pgsql\Tests\Provider;

use DateTimeImmutable;
use DateTimeZone;
use Yiisoft\Db\Expression\Expression;
use Yiisoft\Db\Pgsql\Column\ArrayColumn;
use Yiisoft\Db\Pgsql\Column\ArrayLazyColumn;
Expand All @@ -16,6 +18,7 @@
use Yiisoft\Db\Pgsql\Column\StructuredLazyColumn;
use Yiisoft\Db\Pgsql\Data\LazyArray;
use Yiisoft\Db\Pgsql\Data\StructuredLazyArray;
use Yiisoft\Db\Schema\Column\DateTimeColumn;
use Yiisoft\Db\Schema\Column\DoubleColumn;
use Yiisoft\Db\Schema\Column\JsonColumn;
use Yiisoft\Db\Schema\Column\StringColumn;
Expand Down Expand Up @@ -125,6 +128,8 @@ public static function phpTypecastColumns(): array

public static function phpTypecastArrayColumns()
{
$utcTimezone = new DateTimeZone('UTC');

return [
// [column, values]
[
Expand Down Expand Up @@ -170,6 +175,28 @@ public static function phpTypecastArrayColumns()
[2, [["\x10\x11"], ['', null]], '{{\x1011},{"",}}'],
],
],
[
new DateTimeColumn(),
[
[
1,
[
new DateTimeImmutable('2025-04-19 14:11:35', $utcTimezone),
new DateTimeImmutable('2025-04-19 00:00:00', $utcTimezone),
null,
],
'{2025-04-19 14:11:35,2025-04-19 00:00:00,}',
],
[
2,
[
[new DateTimeImmutable('2025-04-19 14:11:35', $utcTimezone)],
[new DateTimeImmutable('2025-04-19 00:00:00', $utcTimezone), null],
],
'{{2025-04-19 14:11:35},{2025-04-19 00:00:00,}}',
],
],
],
[
new JsonColumn(),
[
Expand Down
3 changes: 3 additions & 0 deletions tests/Provider/QueryBuilderProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,9 @@ public static function buildColumnDefinition(): array
$values['datetime()'][0] = 'timestamp(0)';
$values['datetime(6)'][0] = 'timestamp(6)';
$values['datetime(null)'][0] = 'timestamp';
$values['datetimeWithTimezone()'][0] = 'timestamptz(0)';
$values['datetimeWithTimezone(6)'][0] = 'timestamptz(6)';
$values['datetimeWithTimezone(null)'][0] = 'timestamptz';
$values['array()'][0] = 'varchar[]';
$values['structured()'][0] = 'jsonb';
$values['json()'][0] = 'jsonb';
Expand Down
Loading