Skip to content

feat: MySQL's STR_TO_DATE function implementation #56

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

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
2 changes: 1 addition & 1 deletion .github/workflows/phpunit.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ jobs:
echo "::set-output name=dir::$(composer config cache-files-dir)"

- name: Cache Composer packages
uses: actions/cache@v2
uses: actions/cache@v4
with:
path: ${{ steps.composer-cache.outputs.dir }}
key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/psalm.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
echo "::set-output name=dir::$(composer config cache-files-dir)"

- name: Cache Composer packages
uses: actions/cache@v2
uses: actions/cache@v4
with:
path: ${{ steps.composer-cache.outputs.dir }}
key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
Expand Down
74 changes: 74 additions & 0 deletions src/Processor/Expression/FunctionEvaluator.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,8 @@ public static function evaluate(
return self::sqlInetAton($conn, $scope, $expr, $row, $result);
case 'INET_NTOA':
return self::sqlInetNtoa($conn, $scope, $expr, $row, $result);
case 'STR_TO_DATE':
return self::sqlStrToDate($conn, $scope, $expr, $row, $result);
}

throw new ProcessorException("Function " . $expr->functionName . " not implemented yet");
Expand Down Expand Up @@ -1533,4 +1535,76 @@ private static function getPhpIntervalFromExpression(
throw new ProcessorException('MySQL INTERVAL unit ' . $expr->unit . ' not supported yet');
}
}

/**
* @param array<string, mixed> $row
* @return string|null
*/
private static function sqlStrToDate(
FakePdoInterface $conn,
Scope $scope,
FunctionExpression $expr,
array $row,
QueryResult $result
) : ?string {
$args = $expr->args;

if (\count($args) !== 2) {
throw new ProcessorException("MySQL DATE_FORMAT() function must be called with one argument");
}

$subject = (string) Evaluator::evaluate($conn, $scope, $args[0], $row, $result);
$format = (string) Evaluator::evaluate($conn, $scope, $args[1], $row, $result);

if (strpos($format, '%') === false) {
return null;
}

$date_format_list = [
"%b" => "M", "%c" => "n", "%d" => "d", "%D" => "jS", "%e" => "j",
"%m" => "m", "%M" => "F", "%y" => "y", "%Y" => "Y"
];

$time_format_list = [
"%h" => "h", "%H" => "H", "%i" => "i", "%I" => "h", "%k" => "G",
"%l" => "g", "%r" => "h:i:s A", "%s" => "s", "%S" => "s", "%T" => "H:i:s"
];

$has_date_format = false;
$has_time_format = false;
preg_match_all("/(?:%[a-zA-Z])/u", $format, $matches);
foreach ($matches[0] as $match) {
$has_date_format = $has_date_format || in_array($match, array_keys($date_format_list));
$has_time_format = $has_time_format || in_array($match, array_keys($time_format_list));
}


$format = \str_replace(
array_keys($date_format_list + $time_format_list),
array_values($date_format_list + $time_format_list),
$format
);

if ($has_date_format && $has_time_format) {
$time = \DateTimeImmutable::createFromFormat($format, $subject);
if($time !== false) {
return $time->format('Y-m-d G:i:s');
}
}

if ($has_date_format) {
$time = \DateTimeImmutable::createFromFormat($format, $subject);
if($time !== false) {
return $time->format('Y-m-d');
}
}

if ($has_time_format) {
$time = \DateTimeImmutable::createFromFormat($format, $subject);
if($time !== false) {
return $time->format('G:i:s');
}
}
return null;
}
}
32 changes: 32 additions & 0 deletions tests/EndToEndTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1242,4 +1242,36 @@ private static function getConnectionToFullDB(bool $emulate_prepares = true, boo

return $pdo;
}

public function testStrToDateInSelectFunction()
{
$pdo = self::getConnectionToFullDB(false);
$query = $pdo->prepare("SELECT STR_TO_DATE('01,5,2013', '%d,%m,%Y') AS date");

$query->execute();

$d = mktime(0, 0, 0, 5, 1, 2013);

$current_date = date('Y-m-d', $d);

$this->assertSame(
[[
'date' => $current_date,
]],
$query->fetchAll(\PDO::FETCH_ASSOC)
);
}

public function testStrToDateInWhereFunction()
{
$pdo = self::getConnectionToFullDB(false);
$query = $pdo->prepare("SELECT id FROM `video_game_characters` WHERE `created_on` = (STR_TO_DATE('26/3/2022', '%d/%m/%Y') - INTERVAL 2 MONTH)");

$query->execute();

$this->assertSame(
[['id' => 16,]],
$query->fetchAll(\PDO::FETCH_ASSOC)
);
}
}
13 changes: 13 additions & 0 deletions tests/SelectParseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -316,4 +316,17 @@ public function testBracketedFirstSelect()

$select_query = \Vimeo\MysqlEngine\Parser\SQLParser::parse($sql);
}

public function testStrToDateFunction()
{
$sql = "SELECT STR_TO_DATE('01,5,2013', '%d,%m,%Y')";
$select_query = \Vimeo\MysqlEngine\Parser\SQLParser::parse($sql);
$this->assertInstanceOf(SelectQuery::class, $select_query);

$strToDateFunction = $select_query->selectExpressions[0];
$this->assertTrue(isset($strToDateFunction->args[0]));
$this->assertTrue(isset($strToDateFunction->args[1]));
$this->assertEquals('01,5,2013', $strToDateFunction->args[0]->value);
$this->assertEquals('%d,%m,%Y', $strToDateFunction->args[1]->value);
}
}
2 changes: 1 addition & 1 deletion tests/fixtures/bulk_character_insert.sql
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@ VALUES
('13','pac man', 'Ms Pac Man’s worse three-quarters', 'hero','yellow circle','atari','1','0','{"magic":0, "speed":0, "strength":0, "weapons":0}', NOW()),
('14','yoshi', 'Green machine', 'hero','dinosaur','super nintendo','1','0','{"magic":0, "speed":1, "strength":0, "weapons":0}', NOW()),
('15','link', 'Zelda? I hardly knew her!', 'hero','not sure','nes','1','0','{"magic":1, "speed":0, "strength":0, "weapons":1}', NOW()),
('16','dude', 'Duuuuuude', 'hero','sure','sega genesis','1','0','{"magic":1, "speed":0, "strength":0, "weapons":1}', NOW())
('16','dude', 'Duuuuuude', 'hero','sure','sega genesis','1','0','{"magic":1, "speed":0, "strength":0, "weapons":1}', '2022-01-26 00:00:00')
Loading