Skip to content

Commit

Permalink
Add caching for database table exists operations
Browse files Browse the repository at this point in the history
Added:
- Method `DatabaseSource::setTableExists()` to mark table as exists on PDO instance
- Method `DatabaseSource::performTableExists()` to prepare and run actual table lookup

Changed:
- Method `DatabaseSource::createTable()` to mark table exists after creation
- Method `DatabaseSource::tableExists()` to delegate and remember lookup

Fixed:
- Method `DatabaseSource::deleteItem()` to display model class instead of source class
  • Loading branch information
mcaskill committed Oct 2, 2019
1 parent e625f38 commit ac6f81d
Showing 1 changed file with 43 additions and 2 deletions.
45 changes: 43 additions & 2 deletions src/Charcoal/Source/DatabaseSource.php
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,8 @@ public function createTable()
$this->logger->debug($query);
$dbh->query($query);

$this->setTableExists();

return true;
}

Expand Down Expand Up @@ -243,6 +245,27 @@ public function tableExists()
{
$dbh = $this->db();
$table = $this->table();

if (isset($dbh->tableExists, $dbh->tableExists[$table])) {
return $dbh->tableExists[$table];
}

$exists = $this->performTableExists();
$this->setTableExists($exists);

return $exists;
}

/**
* Perform a source table exists operation.
*
* @return boolean TRUE if the table exists, otherwise FALSE.
*/
protected function performTableExists()
{
$dbh = $this->db();
$table = $this->table();

$driver = $dbh->getAttribute(PDO::ATTR_DRIVER_NAME);
if ($driver === self::SQLITE_DRIVER_NAME) {
$query = sprintf('SELECT name FROM sqlite_master WHERE type = "table" AND name = "%s";', $table);
Expand All @@ -254,7 +277,25 @@ public function tableExists()
$sth = $dbh->query($query);
$exists = $sth->fetchColumn(0);

return !!$exists;
return (bool)$exists;
}

/**
* Store a reminder whether the source's database table exists.
*
* @param boolean $exists Whether the table exists or not.
* @return void
*/
protected function setTableExists($exists = true)
{
$dbh = $this->db();
$table = $this->table();

if (!isset($dbh->tableExists)) {
$dbh->tableExists = [];
}

$dbh->tableExists[$table] = $exists;
}

/**
Expand Down Expand Up @@ -637,7 +678,7 @@ public function deleteItem(StorableInterface $item = null)

if (!$model->id()) {
throw new UnexpectedValueException(
sprintf('Can not delete "%s" item. No ID.', get_class($this))
sprintf('Can not delete "%s" item. No ID.', get_class($model))
);
}

Expand Down

0 comments on commit ac6f81d

Please sign in to comment.