nimblog/src/modules/db.nim

58 lines
1.5 KiB
Nim
Raw Normal View History

2022-05-13 15:01:32 +00:00
# Everything related to database reads and writes goes in this file
2022-04-13 15:14:13 +00:00
import tables
import std/[os, db_sqlite, strutils, streams]
2022-04-13 20:22:52 +00:00
import formatter
2022-04-13 15:14:13 +00:00
2022-04-13 21:42:12 +00:00
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
2022-04-13 15:14:13 +00:00
proc createDb(dbSettings: Table): bool =
2022-04-13 21:42:12 +00:00
if not fileExists("data/blog.db"):
2022-04-13 15:14:13 +00:00
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"])
2022-04-13 21:42:12 +00:00
db = connectDb()
2022-04-13 15:14:13 +00:00
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))
2022-04-13 20:22:52 +00:00
logPrint("Ran SQL command from schema", "Info")
2022-04-13 15:14:13 +00:00
db.close()
return true
2022-04-13 21:42:12 +00:00
export createDb, checkUser, createUser