From 0da78f77ebe4d97c9babc92836ab3147256a7305 Mon Sep 17 00:00:00 2001 From: alyx Date: Fri, 24 May 2024 20:19:42 -0400 Subject: JSONL + CSV DBs --- visitors.php | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 52 insertions(+), 9 deletions(-) diff --git a/visitors.php b/visitors.php index 5707482..e6c106a 100644 --- a/visitors.php +++ b/visitors.php @@ -67,7 +67,7 @@ $config['use_path_info'] = false; // The path to the database file, in one of 3 formats. // // *.json - use a JSON array -// *.jsonl - use newline-delimited JSON objects +// *.jsonl - use newline-delimited JSON objects (jsonlines) // *.csv - use CSV // *.db, *.sqlite, *.sqlite3 - use Sqlite3 @@ -105,23 +105,19 @@ abstract class Database { } // notes: `id` is not stable -final class JsonDatabase extends Database { - private string $file; - private array $data; +abstract class FileDatabase extends Database { + protected string $file; + protected array $data; public function __construct(string $file) { if (file_exists($file)) - $this->data = json_decode(file_get_contents($file), associative: true); + $this->data = $this->load($file); else $this->data = array(); $this->file = $file; } - private function save() { - file_put_contents($this->file, json_encode($this->data)); - } - protected function _append_row(array $db_row) { array_unshift($this->data, $db_row); $this->save(); @@ -147,4 +143,51 @@ final class JsonDatabase extends Database { return true; } + + abstract protected function save(); + abstract protected function load(string $file): array; +} + +// notes: `id` is not stable +final class JsonDatabase extends FileDatabase { + protected function save() { + file_put_contents($this->file, json_encode($this->data)); + } + + protected function load(string $file): array { + return json_decode(file_get_contents($file), associative: true); + } +} + +// notes: `id` is not stable +final class JsonlDatabase extends FileDatabase { + protected function save() { + $fp = fopen($this->file, 'w'); + foreach($data as $row) { + fwrite($fp, json_encode($row)."\n"); + } + fclose($fp); + } + + protected function load(string $file): array { + return array_map(fn($s) => json_decode($s, associative: true), file($file)); + } +} + + +// notes: `id` is not stable +final class CsvDatabase extends FileDatabase { + private const array KEY_ORDER = ['name', 'message', 'email', 'website', 'timestamp']; + + protected function save() { + $fp = fopen($this->file, 'w'); + foreach($this->data as $row) { + fputcsv($fp, array_map(fn($k) => $row[$k]??'', self::KEY_ORDER)); + } + fclose($fp); + } + + protected function load(string $file): array { + return array_map(fn($s) => array_combine(self::KEY_ORDER, str_getcsv($s)), file($file)); + } } -- cgit v1.2.3-70-g09d2