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

83 lines
2.2 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",
];
function _getMigration(CapacitorChannel $channel): _sqliteMigration {
return new _sqliteMigration(cl::merge([
$this->_createSql($channel),
], $channel->getMigration()), $channel->getName());
}
function _getCreateSql(CapacitorChannel $channel): string {
$query = new _sqliteQuery($this->_createSql($channel));
return self::format_sql($channel, $query->getSql());
}
function tableExists(string $tableName): bool {
$name = $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 $name !== null;
}
function channelExists(string $name): bool {
return null !== $this->db->get([
"select name",
"from" => static::CHANNELS_TABLE,
"where" => ["name" => $name],
]);
}
protected function _addToChannelsSql(CapacitorChannel $channel): array {
return cl::merge(parent::_createChannelsSql(), [
"suffix" => "on conflict ignore",
]);
}
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
$this->_addToChannelsSql($channel);
}
}
function _exists(CapacitorChannel $channel): bool {
return $this->tableExists($channel->getTableName());
}
function close(): void {
$this->db->close();
}
}