Skip to content
This repository has been archived by the owner on Jan 24, 2024. It is now read-only.

Integrate mysql datetime precision. #74

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
10 changes: 2 additions & 8 deletions src/Driver/Driver.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ abstract class Driver implements DriverInterface, LoggerAwareInterface
use LoggerAwareTrait;

// DateTime format to be used to perform automatic conversion of DateTime objects.
protected const DATETIME = 'Y-m-d H:i:s';
protected const DATETIME = 'Y-m-d H:i:s.u';

// Driver specific PDO options
protected const DEFAULT_PDO_OPTIONS = [
Expand Down Expand Up @@ -605,13 +605,7 @@ protected function bindParameters(PDOStatement $statement, iterable $parameters)
*/
protected function formatDatetime(DateTimeInterface $value): string
{
try {
$datetime = new DateTimeImmutable('now', $this->getTimezone());
} catch (Throwable $e) {
throw new DriverException($e->getMessage(), $e->getCode(), $e);
}

return $datetime->setTimestamp($value->getTimestamp())->format(static::DATETIME);
return (clone $value)->setTimezone($this->getTimezone())->format(static::DATETIME);
}

/**
Expand Down
22 changes: 22 additions & 0 deletions src/Driver/MySQL/Schema/MySQLColumn.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Spiral\Database\Driver\DriverInterface;
use Spiral\Database\Exception\DefaultValueException;
use Spiral\Database\Exception\SchemaException;
use Spiral\Database\Injection\Fragment;
use Spiral\Database\Injection\FragmentInterface;
use Spiral\Database\Schema\AbstractColumn;
Expand Down Expand Up @@ -265,4 +266,25 @@ protected function formatDatetime(string $type, $value)

return parent::formatDatetime($type, $value);
}

/**
* Set column type as datetime with specific size (precision).
*
* @param int $size
* @return self|$this
*
* @throws SchemaException
*/
public function datetime(int $size = 0): AbstractColumn
{
$this->type('datetime');

if ($size > 6) {
throw new SchemaException('Invalid size (precision) value; must be between 0 and 6.');
}

$this->size = (int)$size;

return $this;
}
}