nulib/php/src/db/sqlite/SqliteStorage.php

83 lines
2.1 KiB
PHP

<?php
namespace nulib\db\sqlite;
use nulib\cl;
use nulib\db\CapacitorChannel;
use nulib\db\CapacitorStorage;
/**
* Class SqliteStorage
*/
class SqliteStorage extends CapacitorStorage {
function __construct($sqlite) {
$this->db = Sqlite::with($sqlite);
}
protected Sqlite $db;
function db(): Sqlite {
return $this->db;
}
const PRIMARY_KEY_DEFINITION = [
"id_" => "integer primary key autoincrement",
];
protected function tableExists(string $tableName): bool {
$found = $this->db->get([
# depuis la version 3.33.0 le nom officiel de la table est sqlite_schema,
# mais le nom sqlite_master est toujours valable pour le moment
"select name from sqlite_master ",
"where" => ["name" => $tableName],
]);
return $found !== null;
}
function _getMigration(CapacitorChannel $channel): _sqliteMigration {
$migrations = cl::merge([
"0init" => [$this->_createSql($channel)],
], $channel->getMigration());
return new _sqliteMigration($migrations, $channel->getName());
}
function channelExists(string $name, ?array &$row=null): bool {
$row = $this->db->one([
"select",
"from" => static::CHANNELS_TABLE,
"where" => ["name" => $name],
]);
return $row !== null;
}
function getChannels(): iterable {
return $this->db->all([
"select",
"from" => static::CHANNELS_TABLE,
]);
}
protected function _addToChannelsSql(CapacitorChannel $channel): array {
$sql = parent::_addToChannelsSql($channel);
$sql[0] = "insert or ignore";
return $sql;
}
protected function _afterCreate(CapacitorChannel $channel): void {
$db = $this->db;
if (!$this->tableExists(static::CHANNELS_TABLE)) {
# ne pas créer si la table existe déjà, pour éviter d'avoir besoin d'un
# verrou en écriture
$db->exec($this->_createChannelsSql());
}
if (!$this->channelExists($channel->getName())) {
# ne pas insérer si la ligne existe déjà, pour éviter d'avoir besoin d'un
# verrou en écriture
$db->exec($this->_addToChannelsSql($channel));
}
}
function close(): void {
$this->db->close();
}
}