Db: use static instead of self to allow overwrite methods in child classes

This commit is contained in:
Benjamin Renard 2024-09-21 10:08:09 +02:00
parent b1c5878608
commit 3b9bda3195
Signed by: bn8
GPG key ID: 3E2E1CE1907115BC

View file

@ -61,7 +61,7 @@ class Db {
Log :: fatal('Database DSN not configured (%s.dsn)', static :: $config_prefix); Log :: fatal('Database DSN not configured (%s.dsn)', static :: $config_prefix);
if (App::get(static :: $config_prefix.".auto_connect")) if (App::get(static :: $config_prefix.".auto_connect"))
self :: connect(); static :: connect();
} }
@ -70,21 +70,21 @@ class Db {
* @return void * @return void
*/ */
public static function connect() { public static function connect() {
if (self :: $pdo && self :: $fpdo) if (static :: $pdo && static :: $fpdo)
return; return;
$dsn = App::get(static :: $config_prefix.".dsn"); $dsn = App::get(static :: $config_prefix.".dsn");
try { try {
// Connect to database // Connect to database
self :: $pdo = new PDO( static :: $pdo = new PDO(
$dsn, $dsn,
App::get(static :: $config_prefix.".user"), App::get(static :: $config_prefix.".user"),
App::get(static :: $config_prefix.".password"), App::get(static :: $config_prefix.".password"),
App::get(static :: $config_prefix.".options"), App::get(static :: $config_prefix.".options"),
); );
self :: $fpdo = new Query(self :: $pdo); static :: $fpdo = new Query(static :: $pdo);
// Register the debug query handler to log it // Register the debug query handler to log it
self :: $fpdo -> debug = array(self :: class, 'debug_query'); static :: $fpdo -> debug = array(static :: class, 'debug_query');
Log :: trace("DB connection established (DSN: '%s')", $dsn); Log :: trace("DB connection established (DSN: '%s')", $dsn);
} }
@ -103,7 +103,7 @@ class Db {
$error = $q->getMessage(); $error = $q->getMessage();
// Execution time not available in case of execution error // Execution time not available in case of execution error
if (!$error) if (!$error)
self :: $total_query_time += intval(ceil($q->getExecutionTime() * 1000000000)); static :: $total_query_time += intval(ceil($q->getExecutionTime() * 1000000000));
$msg = "# DB query"; $msg = "# DB query";
if ($q->getResult()) if ($q->getResult())
$msg .= sprintf( $msg .= sprintf(
@ -135,7 +135,7 @@ class Db {
* @return void * @return void
*/ */
public static function set_autocommit($value) { public static function set_autocommit($value) {
self :: $pdo -> setAttribute(PDO::ATTR_AUTOCOMMIT, $value); static :: $pdo -> setAttribute(PDO::ATTR_AUTOCOMMIT, $value);
} }
/* /*
@ -153,9 +153,9 @@ class Db {
*/ */
public static function get_one($table, $where, $fields=null, $joins=null) { public static function get_one($table, $where, $fields=null, $joins=null) {
try { try {
$query = self :: $fpdo -> from($table) -> where($where); $query = static :: $fpdo -> from($table) -> where($where);
if ($joins) if ($joins)
self :: apply_joins($query, $joins); static :: apply_joins($query, $joins);
if ($fields) if ($fields)
$query -> select(null) -> select($fields); $query -> select(null) -> select($fields);
if ($query->execute() === false) if ($query->execute() === false)
@ -165,7 +165,7 @@ class Db {
return $return[0]; return $return[0];
} }
catch (Exception $e) { catch (Exception $e) {
self :: _log_simple_select_query_error( static :: _log_simple_select_query_error(
false, $table, $e, $where, $fields, null, null, $joins false, $table, $e, $where, $fields, null, null, $joins
); );
} }
@ -188,9 +188,9 @@ class Db {
$table, $where=null, $fields=null, $order_by=null, $limit=null, $joins=null $table, $where=null, $fields=null, $order_by=null, $limit=null, $joins=null
) { ) {
try { try {
$query = self :: $fpdo -> from($table); $query = static :: $fpdo -> from($table);
if ($joins) if ($joins)
self :: apply_joins($query, $joins); static :: apply_joins($query, $joins);
if ($fields) if ($fields)
$query -> select(null) -> select($fields); $query -> select(null) -> select($fields);
if ($where) if ($where)
@ -204,7 +204,7 @@ class Db {
return $return; return $return;
} }
catch (Exception $e) { catch (Exception $e) {
self :: _log_simple_select_query_error( static :: _log_simple_select_query_error(
false, $table, $e, $where, $fields, $order_by, $limit, $joins false, $table, $e, $where, $fields, $order_by, $limit, $joins
); );
} }
@ -221,9 +221,9 @@ class Db {
*/ */
public static function count($table, $where, $what=null, $joins=null) { public static function count($table, $where, $what=null, $joins=null) {
try { try {
$query = self :: $fpdo -> from($table) -> where($where); $query = static :: $fpdo -> from($table) -> where($where);
if ($joins) if ($joins)
self :: apply_joins($query, $joins); static :: apply_joins($query, $joins);
$query -> select(null) -> select(sprintf("COUNT(%s) as count", $what?$what:"*")); $query -> select(null) -> select(sprintf("COUNT(%s) as count", $what?$what:"*"));
if ($query->execute() === false) if ($query->execute() === false)
return false; return false;
@ -232,7 +232,7 @@ class Db {
return $return[0]["count"]; return $return[0]["count"];
} }
catch (Exception $e) { catch (Exception $e) {
self :: _log_simple_select_query_error( static :: _log_simple_select_query_error(
false, $table, $e, $where, null, null, null, $joins false, $table, $e, $where, null, null, null, $joins
); );
} }
@ -243,7 +243,7 @@ class Db {
* Mapping of JOIN type with corresponding query object method * Mapping of JOIN type with corresponding query object method
* @var array<string,string> * @var array<string,string>
*/ */
private static $join_type_to_query_method = array( protected static $join_type_to_query_method = array(
'LEFT' => 'leftJoin', 'LEFT' => 'leftJoin',
'RIGHT' => 'rightJoin', 'RIGHT' => 'rightJoin',
'INNER' => 'innerJoin', 'INNER' => 'innerJoin',
@ -268,10 +268,10 @@ class Db {
if (!is_array($join) || count($join) != 3) { if (!is_array($join) || count($join) != 3) {
throw new Exception(sprintf("Invalid JOIN clause provided: %s", vardump($join))); throw new Exception(sprintf("Invalid JOIN clause provided: %s", vardump($join)));
} }
if (!array_key_exists(strtoupper($join[0]), self :: $join_type_to_query_method)) { if (!array_key_exists(strtoupper($join[0]), static :: $join_type_to_query_method)) {
throw new Exception(sprintf("Invalid JOIN type '%s'", $join[0])); throw new Exception(sprintf("Invalid JOIN type '%s'", $join[0]));
} }
$method = self :: $join_type_to_query_method[strtoupper($join[0])]; $method = static :: $join_type_to_query_method[strtoupper($join[0])];
call_user_func([$query, $method], sprintf("%s ON %s", $join[1], $join[2])); call_user_func([$query, $method], sprintf("%s ON %s", $join[1], $join[2]));
} }
} }
@ -289,7 +289,7 @@ class Db {
* @param array<array<string>>|null $joins Join specification as array (see apply_joins()) * @param array<array<string>>|null $joins Join specification as array (see apply_joins())
* @return void * @return void
*/ */
private static function _log_simple_select_query_error( protected static function _log_simple_select_query_error(
$multiple, $table, $e, $where=null, $fields=null, $order_by=null, $limit=null, $joins=null $multiple, $table, $e, $where=null, $fields=null, $order_by=null, $limit=null, $joins=null
) { ) {
$msg = "Error occurred getting %s of the table %s"; $msg = "Error occurred getting %s of the table %s";
@ -331,7 +331,7 @@ class Db {
*/ */
public static function insert($table, $values, $want_id=false) { public static function insert($table, $values, $want_id=false) {
try { try {
$id = self :: $fpdo -> insertInto($table) $id = static :: $fpdo -> insertInto($table)
-> values($values) -> values($values)
-> execute(); -> execute();
} }
@ -364,7 +364,7 @@ class Db {
public static function update($table, $changes, $where, $expected_row_changes=null) { public static function update($table, $changes, $where, $expected_row_changes=null) {
if (is_null($expected_row_changes)) $expected_row_changes = 1; if (is_null($expected_row_changes)) $expected_row_changes = 1;
try { try {
$result = self :: $fpdo -> update($table) $result = static :: $fpdo -> update($table)
-> set($changes) -> set($changes)
-> where($where) -> where($where)
-> execute(); -> execute();
@ -401,7 +401,7 @@ class Db {
public static function delete($table, $where, $expected_row_changes=null) { public static function delete($table, $where, $expected_row_changes=null) {
if (is_null($expected_row_changes)) $expected_row_changes = 1; if (is_null($expected_row_changes)) $expected_row_changes = 1;
try { try {
$result = self :: $fpdo -> deleteFrom($table) $result = static :: $fpdo -> deleteFrom($table)
-> where($where) -> where($where)
-> execute(); -> execute();
} }
@ -442,15 +442,15 @@ class Db {
if ($raw_table != $table) if ($raw_table != $table)
Log :: debug("truncate(%s):: Table name cleaned as '%s'", $raw_table, $table); Log :: debug("truncate(%s):: Table name cleaned as '%s'", $raw_table, $table);
try { try {
if (self :: is_sqlite()) { if (static :: is_sqlite()) {
Log :: debug( Log :: debug(
'truncate(%s): Sqlite does not support TRUNCATE SQL query, use DELETE instead.', 'truncate(%s): Sqlite does not support TRUNCATE SQL query, use DELETE instead.',
$table $table
); );
$statement = self :: $pdo -> prepare("DELETE FROM $table"); $statement = static :: $pdo -> prepare("DELETE FROM $table");
} }
else { else {
$statement = self :: $pdo -> prepare("TRUNCATE $table"); $statement = static :: $pdo -> prepare("TRUNCATE $table");
} }
if (!$statement -> execute()) { if (!$statement -> execute()) {
Log :: error("Unknown error occurred truncating the table %s of the database", $table); Log :: error("Unknown error occurred truncating the table %s of the database", $table);
@ -479,7 +479,7 @@ class Db {
} }
public static function date2time($date) { public static function date2time($date) {
self :: set_locale(); static :: set_locale();
$pdate = strptime($date, App::get(static :: $config_prefix.".date_format")); $pdate = strptime($date, App::get(static :: $config_prefix.".date_format"));
return mktime( return mktime(
$pdate['tm_hour'], $pdate['tm_min'], $pdate['tm_sec'], $pdate['tm_hour'], $pdate['tm_min'], $pdate['tm_sec'],
@ -488,12 +488,12 @@ class Db {
} }
public static function time2date($time) { public static function time2date($time) {
self :: set_locale(); static :: set_locale();
return strftime(App::get(static :: $config_prefix.".date_format"), $time); return strftime(App::get(static :: $config_prefix.".date_format"), $time);
} }
public static function datetime2time($date) { public static function datetime2time($date) {
self :: set_locale(); static :: set_locale();
$pdate = strptime($date, App::get(static :: $config_prefix.".datetime_format")); $pdate = strptime($date, App::get(static :: $config_prefix.".datetime_format"));
return mktime( return mktime(
$pdate['tm_hour'], $pdate['tm_min'], $pdate['tm_sec'], $pdate['tm_hour'], $pdate['tm_min'], $pdate['tm_sec'],
@ -502,7 +502,7 @@ class Db {
} }
public static function time2datetime($time) { public static function time2datetime($time) {
self :: set_locale(); static :: set_locale();
return strftime(App::get(static :: $config_prefix.".datetime_format"), $time); return strftime(App::get(static :: $config_prefix.".datetime_format"), $time);
} }
@ -518,12 +518,12 @@ class Db {
if (is_array($datetime_fields)) if (is_array($datetime_fields))
foreach($datetime_fields as $field) foreach($datetime_fields as $field)
if ($row[$field]) if ($row[$field])
$row[$field] = self :: datetime2time($row[$field]); $row[$field] = static :: datetime2time($row[$field]);
// Convert date fields // Convert date fields
if (is_array($date_fields)) if (is_array($date_fields))
foreach($date_fields as $field) foreach($date_fields as $field)
if ($row[$field]) if ($row[$field])
$row[$field] = self :: date2time($row[$field]); $row[$field] = static :: date2time($row[$field]);
return $row; return $row;
} }