Skip to content

Commit

Permalink
refactor: change castValue() API
Browse files Browse the repository at this point in the history
  • Loading branch information
kenjis committed Jan 23, 2024
1 parent 64cd791 commit 6d4ce25
Showing 1 changed file with 15 additions and 16 deletions.
31 changes: 15 additions & 16 deletions system/Database/Postgre/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\RawSql;
use InvalidArgumentException;
use LogicException;

/**
* Builder for Postgre
Expand Down Expand Up @@ -348,18 +347,16 @@ protected function _updateBatch(string $table, array $keys, array $values): stri

$sql .= "SET\n";

$this->getFieldTypes($table);

$that = $this;
$sql .= implode(
",\n",
array_map(
static function ($key, $value) use ($alias, $that) {
static function ($key, $value) use ($table, $alias, $that) {
$fieldName = trim($key, '"');

return $key . ($value instanceof RawSql ?
' = ' . $value :
' = ' . $alias . '.' . $that->castValue($fieldName, $value));
' = ' . $alias . '.' . $that->castValue($table, $key, $value));
},
array_keys($updateFields),
$updateFields
Expand All @@ -382,9 +379,7 @@ static function ($key, $value) use ($table, $alias, $that) {
return $value;
}

$fieldName = trim($value, '"');

return $table . '.' . $value . ' = ' . $alias . '.' . $that->castValue($fieldName, $value);
return $table . '.' . $value . ' = ' . $alias . '.' . $that->castValue($table, $value, $value);
},
array_keys($constraints),
$constraints
Expand Down Expand Up @@ -416,23 +411,27 @@ static function ($key, $value) use ($table, $alias, $that) {
/**
* Returns cast value.
*
* @param float|int|string $value Escaped value
* @param string $table Protected Table name.
* @param string $fieldName Field name. May be protected.
* @param float|int|string $value Escaped value
*/
private function castValue(string $fieldName, $value): string
private function castValue(string $table, string $fieldName, $value): string
{
if (! isset($this->QBOptions['fieldTypes'])) {
throw new LogicException(
'You must call getFieldTypes() before calling castValue().'
);
$fieldName = trim($fieldName, $this->db->escapeChar);

if (! isset($this->QBOptions['fieldTypes'][$table])) {
$this->getFieldTypes($table);
}

$type = $this->QBOptions['fieldTypes'][$fieldName] ?? null;
$type = $this->QBOptions['fieldTypes'][$table][$fieldName] ?? null;

return ($type === null) ? $value : $value . '::' . strtoupper($type);
}

/**
* Gets filed types from database meta data.
*
* @param string $table Protected Table name.
*/
private function getFieldTypes(string $table): void
{
Expand All @@ -442,7 +441,7 @@ private function getFieldTypes(string $table): void
$types[$field->name] = $field->type;
}

$this->QBOptions['fieldTypes'] = $types;
$this->QBOptions['fieldTypes'][$table] = $types;
}

/**
Expand Down

0 comments on commit 6d4ce25

Please sign in to comment.