diff --git a/php/src/db/pgsql/Pgsql.php b/php/src/db/pgsql/Pgsql.php index f45ba30..2fef081 100644 --- a/php/src/db/pgsql/Pgsql.php +++ b/php/src/db/pgsql/Pgsql.php @@ -32,6 +32,7 @@ class Pgsql implements IDatabase { protected const OPTIONS = [ "persistent" => true, "force_new" => false, + "serial_support" => true, ]; const CONFIG = null; @@ -171,17 +172,21 @@ class Pgsql implements IDatabase { return true; } + function getLastSerial() { + $db = $this->db(); + $result = @pg_query($db, "select lastval()"); + if ($result === false) return false; + $lastSerial = pg_fetch_row($result)[0]; + pg_free_result($result); + return $lastSerial; + } + function exec($query, ?array $params=null) { $db = $this->db(); $query = new query($query, $params); $result = $query->_exec($db); - if ($query->isInsert()) { - $result = @pg_query($db, "select lastval()"); - if ($result === false) return false; - $lastInsertId = pg_fetch_row($result)[0]; - pg_free_result($result); - return $lastInsertId; - } + $serialSupport = $this->options["serial_support"] ?? true; + if ($serialSupport && $query->isInsert()) return $this->getLastSerial(); $affected_rows = pg_affected_rows($result); pg_free_result($result); return $affected_rows; diff --git a/php/src/db/pgsql/query.php b/php/src/db/pgsql/query.php index c2b76b0..c1c11ba 100644 --- a/php/src/db/pgsql/query.php +++ b/php/src/db/pgsql/query.php @@ -1,15 +1,9 @@ sql; + $bindings = $this->bindings; if (static::DEBUG_QUERIES) { #XXX - error_log($this->sql); + error_log($sql); //error_log(var_export($this->bindings, true)); } - if ($this->bindings !== null) { - #XXX corriger les bindings et la requête *dans le constructeur* - $result = pg_query_params($db, $this->sql, $this->bindings); + if ($bindings !== null) { + # trier d'abord les champ par ordre de longueur, pour éviter les overlaps + $names = array_keys($bindings); + usort($names, function ($a, $b) { + return -cv::compare(strlen(strval($a)), strlen(strval($b))); + }); + $bparams = []; + $number = 1; + foreach ($names as $name) { + $sql = str_replace(":$name", "\$$number", $sql); + $bparams[] = $bindings[$name]; + $number++; + } + $result = pg_query_params($db, $sql, $bparams); } else { - $result = pg_query($db, $this->sql); + $result = pg_query($db, $sql); } if ($result === false) throw PgsqlException::last_error($db); return $result;