58 lines
1.5 KiB
Nim
58 lines
1.5 KiB
Nim
# Everything related to database reads and writes goes in this file
|
|
|
|
import tables
|
|
import std/[os, db_sqlite, strutils, streams]
|
|
import formatter
|
|
|
|
proc connectDb(dbPath: string = "data/blog.db"): DbConn =
|
|
var db = open(dbPath, "", "", "")
|
|
return db
|
|
|
|
proc createUser(username: string, displayname: string, password: string): bool =
|
|
try:
|
|
var db = connectDb()
|
|
db.exec(sql"INSERT INTO users (username,displayname,password) VALUES (?, ?, ?)", username, displayname, password)
|
|
db.close()
|
|
return true
|
|
except:
|
|
return false
|
|
|
|
proc checkUser(): bool =
|
|
var db = connectDb()
|
|
var response = db.getRow(sql"SELECT * FROM users")
|
|
db.close()
|
|
if response[0] != "":
|
|
return true
|
|
else:
|
|
return false
|
|
|
|
proc createDb(dbSettings: Table): bool =
|
|
if not fileExists("data/blog.db"):
|
|
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 = connectDb()
|
|
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))
|
|
logPrint("Ran SQL command from schema", "Info")
|
|
db.close()
|
|
return true
|
|
|
|
export createDb, checkUser, createUser
|