diff options
author | Evgeny Zinoviev <me@ch1p.io> | 2022-05-26 21:18:29 +0300 |
---|---|---|
committer | Evgeny Zinoviev <me@ch1p.io> | 2022-05-27 01:04:47 +0300 |
commit | cf0b9f036b3e3eb218610e7eeececda1320d9f50 (patch) | |
tree | 39e6d1853aecb3fb77036a941a4c6df12a0ce793 /localwebsite/engine/database.php | |
parent | c3ed2483ea508141431be74f29f7c209271897cd (diff) |
auth
Diffstat (limited to 'localwebsite/engine/database.php')
-rw-r--r-- | localwebsite/engine/database.php | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/localwebsite/engine/database.php b/localwebsite/engine/database.php index 186d2ef..33f36cf 100644 --- a/localwebsite/engine/database.php +++ b/localwebsite/engine/database.php @@ -7,13 +7,19 @@ class database { protected SQLite3 $link; public function __construct(string $db_path) { + $will_create = !file_exists($db_path); $this->link = new SQLite3($db_path); + if ($will_create) + setperm($db_path); $this->link->enableExceptions(true); $this->upgradeSchema(); } protected function upgradeSchema() { $cur = $this->getSchemaVersion(); + if ($cur == self::SCHEMA_VERSION) + return; + if ($cur < 1) { $this->link->exec("CREATE TABLE users ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -77,4 +83,49 @@ class database { return $this->link->querySingle($this->prepareQuery($sql, ...$params), true); } + protected function performInsert(string $command, string $table, array $fields): SQLite3Result { + $names = []; + $values = []; + $count = 0; + foreach ($fields as $k => $v) { + $names[] = $k; + $values[] = $v; + $count++; + } + + $sql = "{$command} INTO `{$table}` (`" . implode('`, `', $names) . "`) VALUES (" . implode(', ', array_fill(0, $count, '?')) . ")"; + array_unshift($values, $sql); + + return call_user_func_array([$this, 'query'], $values); + } + + public function insert(string $table, array $fields): SQLite3Result { + return $this->performInsert('INSERT', $table, $fields); + } + + public function replace(string $table, array $fields): SQLite3Result { + return $this->performInsert('REPLACE', $table, $fields); + } + + public function insertId(): int { + return $this->link->lastInsertRowID(); + } + + public function update($table, $rows, ...$cond): SQLite3Result { + $fields = []; + $args = []; + foreach ($rows as $row_name => $row_value) { + $fields[] = "`{$row_name}`=?"; + $args[] = $row_value; + } + $sql = "UPDATE `$table` SET " . implode(', ', $fields); + if (!empty($cond)) { + $sql .= " WHERE " . $cond[0]; + if (count($cond) > 1) + $args = array_merge($args, array_slice($cond, 1)); + } + return $this->query($sql, ...$args); + } + + }
\ No newline at end of file |