Switch from SQLite to PostgreSQL

This commit is contained in:
Gregory Trolliet 2020-11-22 15:09:31 +01:00
parent 69de37562f
commit 44226c4809
4 changed files with 23 additions and 11 deletions

25
db.php
View file

@ -1,4 +1,6 @@
<?php
class DataBase
{
const DEFAULT_DURATION = '+7 day';
@ -18,15 +20,18 @@ class DataBase
public function init()
{
require_once 'dbconfig.php';
$dsn = 'pgsql:dbname=' . $dbname
. ';host=' . $host
. ';port=' . $port;
try {
$this->db = new PDO('sqlite:test.db');
$this->db = new PDO($dsn, $username, $password);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo $e->getMessage();
return null;
}
$stmt = $this->db->prepare('PRAGMA foreign_keys = 1;');
$stmt->execute();
}
public function isInit()
@ -38,18 +43,18 @@ class DataBase
{
$stmt = $this->db->prepare("
CREATE TABLE IF NOT EXISTS clouds(
id_cloud INTEGER PRIMARY KEY,
id_cloud serial PRIMARY KEY,
code TEXT NOT NULL UNIQUE,
size INTEGER NOT NULL DEFAULT 3,
text TEXT,
delete_t TIMESTAMP DEFAULT
(datetime('now', '" . self::DEFAULT_DURATION . "'))
(CURRENT_TIMESTAMP + INTERVAL '" . self::DEFAULT_DURATION . "')
);
");
$stmt->execute();
$stmt = $this->db->prepare("
CREATE TABLE IF NOT EXISTS words(
id_word INTEGER PRIMARY KEY,
id_word serial PRIMARY KEY,
word TEXT NOT NULL,
count INT DEFAULT 1,
cloud_id INT NOT NULL,
@ -107,7 +112,7 @@ class DataBase
$stmt->execute();
}
}
public function getWords(string $id)
public function getWordsList(string $id)
{
$stmt = $this->db->prepare("
SELECT *
@ -132,7 +137,7 @@ class DataBase
public function getWordsPercentage(string $id)
{
$words = $this->getWords($id);
$words = $this->getWordsList($id);
$total = 0;
foreach ($words as $word) {
$total += $word[1];
@ -144,9 +149,9 @@ class DataBase
return $words;
}
public function getWordsMax(string $id)
public function getWordsRelative(string $id)
{
$words = $this->getWords($id);
$words = $this->getWordsList($id);
$max = 0;
foreach ($words as $word) {
$max = max($max, $word[1]);

7
dbconfig.php Normal file
View file

@ -0,0 +1,7 @@
<?php
$host = 'localhost';
$dbname = 'simplewordscloud';
$username = 'raghnarok';
$password = 'pLkXCTEdCy6roOlnqqSjzuacRBI2UmLjYa7CbMjh';
$port = '5432';

View file

@ -12,7 +12,7 @@ if (!isset($_GET['id'])) {
}
$id = $_GET['id'];
if ($words = $db->getWordsMax($id)) {
if ($words = $db->getWordsRelative($id)) {
echo json_encode($words);
} else {
echo json_encode('No id');

BIN
test.db

Binary file not shown.