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

65 lines
1.8 KiB
PHP

<?php
namespace nulib\db\sqlite;
use nulib\cl;
use nulib\db\CapacitorChannel;
use nulib\db\CapacitorStorage;
/**
* Class SqliteStorage
*/
class SqliteStorage extends CapacitorStorage {
const GENSERIAL_DEFINITION = "integer primary key autoincrement";
function __construct($sqlite) {
$this->db = Sqlite::with($sqlite);
}
protected Sqlite $db;
function db(): Sqlite {
return $this->db;
}
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());
}
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();
}
}