SQLite boilerplate
This commit is contained in:
parent
44cbd19a8d
commit
88cbeee562
|
@ -3,3 +3,6 @@
|
|||
|
||||
# Binary name built by nimble
|
||||
nimblog
|
||||
|
||||
# Database
|
||||
blog.db
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
# nimblog
|
||||
|
||||
Placeholder text
|
||||
Basic blog written in nim, mostly for learning purposes.
|
||||
|
||||
## How to run
|
||||
|
||||
|
|
|
@ -0,0 +1,15 @@
|
|||
CREATE TABLE users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
displayname TEXT NOT NULL,
|
||||
username TEXT UNIQUE NOT NULL,
|
||||
password TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE posts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
author_id INTEGER NOT NULL,
|
||||
created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
title TEXT NOT NULL,
|
||||
body TEXT NOT NULL,
|
||||
FOREIGN KEY (author_id) REFERENCES users (id)
|
||||
);
|
|
@ -2,7 +2,7 @@ import prologue
|
|||
import prologue/middlewares/staticfile
|
||||
import views
|
||||
|
||||
proc runWebsite(settings: Table) =
|
||||
proc runWebsite(settings: Table[string, bool], dbSettings: Table[string, string]) =
|
||||
let prologueSettings = newSettings(
|
||||
debug = settings["debug"]
|
||||
)
|
||||
|
|
|
@ -0,0 +1,32 @@
|
|||
import tables
|
||||
import std/[os, db_sqlite, strutils, streams]
|
||||
|
||||
proc createDb(dbSettings: Table): bool =
|
||||
if not fileExists(dbSettings["path"]):
|
||||
var userConsent: bool = false
|
||||
while userConsent != true:
|
||||
stdout.write "Did not find database. Create one now? (y/n) "
|
||||
stdout.flushFile()
|
||||
var userInput = readChar(stdin)
|
||||
stdin.flushFile()
|
||||
case userInput
|
||||
of 'y', 'Y':
|
||||
userConsent = true
|
||||
of 'n', 'N':
|
||||
return false
|
||||
else:
|
||||
discard
|
||||
|
||||
let
|
||||
schema = readFile(dbSettings["schema_path"])
|
||||
db = open(dbSettings["path"], "", "", "")
|
||||
for command in schema.split(";"):
|
||||
# Skip "command" if it's just a blank line
|
||||
if command == "\c\n" or command == "\n":
|
||||
continue
|
||||
db.exec(sql(command.strip))
|
||||
echo "Ran command: " & command.strip
|
||||
db.close()
|
||||
return true
|
||||
|
||||
export createDb
|
|
@ -2,14 +2,24 @@ when isMainModule:
|
|||
import tables
|
||||
import modules/blog
|
||||
import modules/env
|
||||
import modules/db
|
||||
|
||||
let settings = {
|
||||
"debug": boolEnvOrDefault("DEBUG", false),
|
||||
"logging": boolEnvOrDefault("NIMBLOG_LOG", true)
|
||||
}.toTable()
|
||||
|
||||
let dbSettings = {
|
||||
"path": "blog.db",
|
||||
"schema_path": "schema.sql"
|
||||
}.toTable()
|
||||
|
||||
if not createDb(dbSettings):
|
||||
echo "Failed to prepare database"
|
||||
quit(QuitFailure)
|
||||
|
||||
try:
|
||||
echo "Starting website"
|
||||
runWebsite(settings)
|
||||
runWebsite(settings=settings, dbSettings=dbSettings)
|
||||
except:
|
||||
echo "Could not run website"
|
||||
|
|
Loading…
Reference in New Issue