Initial commit

This commit is contained in:
Artem Mamonov
2025-02-06 02:36:10 +01:00
commit acf9b43671
24 changed files with 1946 additions and 0 deletions

32
internal/db/sqlite/db.go Normal file
View File

@@ -0,0 +1,32 @@
package sqlite
import (
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
)
var db *sqlx.DB
func OpenDb(fname string) (*sqlx.DB, error) {
conn, err := sqlx.Open("sqlite3", fname+"?cache=shared&mode=rwc&_journal_mode=WAL")
if err != nil {
return nil, err
}
conn.SetMaxOpenConns(1) // sqlite3 does not support multiple connections
db = conn
return conn, nil
}
func CloseDb() error {
if db != nil {
return db.Close()
}
return nil
}
func GetDb() *sqlx.DB {
return db
}

View File

@@ -0,0 +1,69 @@
package sqlite
import (
"database/sql"
"log"
)
func InitTables() {
// Create tables
q := `
CREATE TABLE IF NOT EXISTS albums (
id TEXT NOT NULL PRIMARY KEY,
name TEXT,
is_active INTEGER DEFAULT 1,
watermarked INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
expire_at DATETIME,
password TEXT,
allow_comments INTEGER DEFAULT 0,
allow_downloads INTEGER DEFAULT 0,
allow_favourite INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS metrics (
album_id TEXT NOT NULL PRIMARY KEY,
views INTEGER DEFAULT 0,
downloads INTEGER DEFAULT 0,
files INTEGER DEFAULT 0,
files_size INTEGER DEFAULT 0,
fav_lists INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS comments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
album_id TEXT,
photo_id TEXT,
message TEXT,
created_at DATETIME
);
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
username TEXT,
password TEXT
);
CREATE TABLE IF NOT EXISTS sessions (
id VARCHAR(36) PRIMARY KEY,
user_id INTEGER,
token TEXT,
expires_at DATETIME
);
`
_, err := db.Exec(q)
if err != nil {
log.Fatalf("%q: %s\n", err, q)
}
// Insert default user if not exists
q = `SELECT * FROM users WHERE username = 'admin'`
row := db.QueryRow(q)
var id int
err = row.Scan(&id)
if err != sql.ErrNoRows {
return
}
q = `INSERT INTO users (username, password) VALUES ('admin', '$2a$14$09LaSuG93OEdVXZMBP.8Ruy4rvP54OeEGBoNP/6DAHMR/K0ITNBYq')`
_, err = db.Exec(q)
if err != nil {
log.Fatalf("%q: %s\n", err, q)
}
}