Add initial data tables (#2)
This commit is contained in:
62
src/lib/Data.php
Normal file
62
src/lib/Data.php
Normal file
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
/**
|
||||
* A centralized place for data access for the application
|
||||
*/
|
||||
class Data {
|
||||
|
||||
/**
|
||||
* Obtain a new connection to the database
|
||||
* @return SQLite3 A new connection to the database
|
||||
*/
|
||||
private static function getConnection(): SQLite3 {
|
||||
$db = new SQLite3("../data/{${DATABASE_NAME}}");
|
||||
$db->exec('PRAGMA foreign_keys = ON;');
|
||||
return $db;
|
||||
}
|
||||
|
||||
public static function ensureDb(): void {
|
||||
$db = self::getConnection();
|
||||
$tables = $db->query("SELECT name FROM sqlite_master WHERE type = 'table'")->fetchArray(SQLITE3_NUM);
|
||||
if (!array_search('frc_user', $tables)) {
|
||||
$query = <<<SQL
|
||||
CREATE TABLE frc_user (
|
||||
id INTEGER NOT NULL PRIMARY KEY,
|
||||
email TEXT NOT NULL,
|
||||
password TEXT NOT NULL,
|
||||
salt TEXT NOT NULL)
|
||||
SQL;
|
||||
$db->exec($query);
|
||||
$db->exec('CREATE INDEX idx_user_email ON frc_user (email)');
|
||||
}
|
||||
if (!array_search('feed', $tables)) {
|
||||
$query = <<<SQL
|
||||
CREATE TABLE feed (
|
||||
id INTEGER NOT NULL PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL,
|
||||
url TEXT NOT NULL,
|
||||
checked_on TEXT,
|
||||
FOREIGN KEY (user_id) REFERENCES frc_user (id))
|
||||
SQL;
|
||||
$db->exec($query);
|
||||
}
|
||||
if (!array_search('item', $tables)) {
|
||||
$query = <<<SQL
|
||||
CREATE TABLE item (
|
||||
id INTEGER NOT NULL PRIMARY KEY,
|
||||
feed_id INTEGER NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
published_on TEXT NOT NULL,
|
||||
updated_on TEXT,
|
||||
content TEXT NOT NULL,
|
||||
is_encoded INTEGER NOT NULL,
|
||||
is_read INTEGER NOT NULL,
|
||||
is_bookmarked INTEGER NOT NULL,
|
||||
FOREIGN KEY (feed_id) REFERENCES feed (id))
|
||||
SQL;
|
||||
$db->exec($query);
|
||||
}
|
||||
$db->close();
|
||||
}
|
||||
}
|
||||
|
||||
Data::ensureDb();
|
||||
Reference in New Issue
Block a user