Skip to content

Commit

Permalink
feature: improve error handling of special binding including infiles
Browse files Browse the repository at this point in the history
  • Loading branch information
g105b committed Feb 10, 2024
1 parent d0f07b5 commit 3c27070
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 23 deletions.
3 changes: 2 additions & 1 deletion src/Connection/Driver.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,12 @@ protected function connect():void {
Connection::ATTR_ERRMODE => Connection::ERRMODE_EXCEPTION,
];

if($this->settings->getSchema() === Settings::DRIVER_MYSQL) {
if($this->settings->getDriver() === Settings::DRIVER_MYSQL) {
$options[Connection::MYSQL_ATTR_INIT_COMMAND]
= "SET SESSION collation_connection='"
. $this->settings->getCollation()
. "'";
$options[Connection::MYSQL_ATTR_LOCAL_INFILE] = true;
}

$this->connection = new Connection(
Expand Down
54 changes: 32 additions & 22 deletions src/Query/SqlQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,9 @@
/** @SuppressWarnings(PHPMD.ExcessiveClassComplexity) */
class SqlQuery extends Query {
const SPECIAL_BINDINGS = [
"limit",
"offset",
"groupBy",
"orderBy",
"field" => ["groupBy", "orderBy"],
"int" => ["limit", "offset"],
"string" => ["infileName"],
];

/** @param array<string, mixed>|array<mixed> $bindings */
Expand Down Expand Up @@ -71,10 +70,10 @@ public function execute(array $bindings = []):ResultSet {
$lastInsertId = $pdo->lastInsertId();
}
catch(PDOException $exception) {
$code = $exception->getCode();
throw new PreparedStatementException(
$exception->getMessage() . " (Code $code)",
previous: $exception
$exception->getMessage() . " (" . $exception->getCode(),
0,
$exception
);
}
}
Expand Down Expand Up @@ -108,24 +107,35 @@ public function injectSpecialBindings(
string $sql,
array $bindings
):string {
foreach(self::SPECIAL_BINDINGS as $special) {
$specialPlaceholder = ":" . $special;
foreach(self::SPECIAL_BINDINGS as $type => $specialList) {
foreach($specialList as $special) {
$specialPlaceholder = ":" . $special;

if(!array_key_exists($special, $bindings)) {
continue;
}
if(!array_key_exists($special, $bindings)) {
continue;
}

$replacement = $this->escapeSpecialBinding(
$bindings[$special],
$special
);
if($type !== "string") {
$replacement = $this->escapeSpecialBinding(
$bindings[$special],
$special
);
}

$sql = str_replace(
$specialPlaceholder,
$replacement,
$sql
);
unset($bindings[$special]);
if($type === "field") {
$replacement = "`" . $bindings[$special] . "`";
}
elseif($type === "string") {
$replacement = "'" . $bindings[$special] . "'";
}

$sql = str_replace(
$specialPlaceholder,
$replacement,
$sql
);
unset($bindings[$special]);
}
}

foreach($bindings as $key => $value) {
Expand Down

0 comments on commit 3c27070

Please sign in to comment.