class DatabaseStorage implements StorageInterface {
protected $connection;
protected $table;
protected $options = array();
public function __construct(Connection $connection, $table, array $options = array()) {
$this->connection = $connection;
$this->table = $table;
$this->options = $options;
}
public function exists($name) {
return (bool) $this->connection
->queryRange('SELECT 1 FROM {' . $this->connection
->escapeTable($this->table) . '} WHERE name = :name', 0, 1, array(
':name' => $name,
), $this->options)
->fetchField();
}
public function read($name) {
$data = FALSE;
try {
$raw = $this->connection
->query('SELECT data FROM {' . $this->connection
->escapeTable($this->table) . '} WHERE name = :name', array(
':name' => $name,
), $this->options)
->fetchField();
if ($raw !== FALSE) {
$data = $this
->decode($raw);
}
} catch (Exception $e) {
}
return $data;
}
public function write($name, array $data) {
$data = $this
->encode($data);
$options = array(
'return' => Database::RETURN_AFFECTED,
) + $this->options;
return (bool) $this->connection
->merge($this->table, $options)
->key(array(
'name' => $name,
))
->fields(array(
'data' => $data,
))
->execute();
}
public function delete($name) {
$options = array(
'return' => Database::RETURN_AFFECTED,
) + $this->options;
return (bool) $this->connection
->delete($this->table, $options)
->condition('name', $name)
->execute();
}
public function rename($name, $new_name) {
$options = array(
'return' => Database::RETURN_AFFECTED,
) + $this->options;
return (bool) $this->connection
->update($this->table, $options)
->fields(array(
'name' => $new_name,
))
->condition('name', $name)
->execute();
}
public function encode($data) {
return serialize($data);
}
public function decode($raw) {
$data = @unserialize($raw);
return is_array($data) ? $data : FALSE;
}
public function listAll($prefix = '') {
return $this->connection
->query('SELECT name FROM {' . $this->connection
->escapeTable($this->table) . '} WHERE name LIKE :name', array(
':name' => db_like($prefix) . '%',
), $this->options)
->fetchCol();
}
}