DbObject: introduce loadOptional

This prevents useless queries (e.g. exists() && load())
This commit is contained in:
Thomas Gelf 2023-03-07 11:17:37 +01:00
parent 2ade848f4d
commit 903f2c825f
1 changed files with 42 additions and 4 deletions

View File

@ -560,7 +560,7 @@ abstract class DbObject
/** /**
* Unique key name * Unique key name
* *
* @return string * @return string|array
*/ */
public function getKeyName() public function getKeyName()
{ {
@ -713,8 +713,7 @@ abstract class DbObject
*/ */
protected function loadFromDb() protected function loadFromDb()
{ {
$select = $this->db->select()->from($this->table)->where($this->createWhere()); $properties = $this->db->fetchRow($this->prepareObjectQuery());
$properties = $this->db->fetchRow($select);
if (empty($properties)) { if (empty($properties)) {
if (is_array($this->getKeyName())) { if (is_array($this->getKeyName())) {
@ -735,6 +734,11 @@ abstract class DbObject
return $this->setDbProperties($properties); return $this->setDbProperties($properties);
} }
public function prepareObjectQuery()
{
return $this->db->select()->from($this->table)->where($this->createWhere());
}
/** /**
* @param object|array $row * @param object|array $row
* @param Db $db * @param Db $db
@ -1313,6 +1317,40 @@ abstract class DbObject
return $obj; return $obj;
} }
/**
* @param $id
* @param DbConnection $connection
* @return static
*/
public static function loadOptional($id, DbConnection $connection): ?DbObject
{
if ($prefetched = static::getPrefetched($id)) {
return $prefetched;
}
/** @var DbObject $obj */
$obj = new static();
if (self::$dbObjectStore !== null && $obj->hasUuidColumn()) {
$table = $obj->getTableName();
assert($connection instanceof Db);
$uuid = UuidLookup::findUuidForKey($id, $table, $connection, self::$dbObjectStore->getBranch());
if ($uuid) {
return self::$dbObjectStore->load($table, $uuid);
}
return null;
}
$obj->setConnection($connection)->setKey($id);
$properties = $connection->getDbAdapter()->fetchRow($obj->prepareObjectQuery());
if (empty($properties)) {
return null;
}
$obj->setDbProperties($properties);
return $obj;
}
/** /**
* @param DbConnection $connection * @param DbConnection $connection
* @param \Zend_Db_Select $query * @param \Zend_Db_Select $query
@ -1448,7 +1486,7 @@ abstract class DbObject
)); ));
} }
public static function loadWithUniqueId(UuidInterface $uuid, DbConnection $connection) public static function loadWithUniqueId(UuidInterface $uuid, DbConnection $connection): ?DbObject
{ {
$db = $connection->getDbAdapter(); $db = $connection->getDbAdapter();
$obj = new static; $obj = new static;