117 lines
1.9 KiB
Go
117 lines
1.9 KiB
Go
package database
|
|
|
|
import (
|
|
"database/sql"
|
|
"fmt"
|
|
|
|
_ "github.com/mattn/go-sqlite3"
|
|
)
|
|
|
|
var DB *sql.DB
|
|
|
|
// TODO: Change DB Structure
|
|
func InitDB(filepath string) (err error) {
|
|
DB, err = sql.Open("sqlite3", filepath)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
if DB == nil {
|
|
panic("DB couldn't be initialized")
|
|
}
|
|
|
|
handleError(initObjectTable())
|
|
handleError(initCollectionTable())
|
|
handleError(initActorTable())
|
|
handleError(initUserTable())
|
|
|
|
return
|
|
}
|
|
|
|
func initObjectTable() (err error) {
|
|
statement, err := DB.Prepare(`CREATE TABLE IF NOT EXISTS object (
|
|
id TEXT PRIMARY KEY,
|
|
type TEXT,
|
|
attributedTo TEXT,
|
|
content TEXT,
|
|
published INTEGER,
|
|
toActor TEXT
|
|
)`)
|
|
if err != nil {
|
|
return
|
|
}
|
|
statement.Exec()
|
|
|
|
return
|
|
}
|
|
|
|
func initCollectionTable() (err error) {
|
|
statement, err := DB.Prepare(`CREATE TABLE IF NOT EXISTS collection (
|
|
id TEXT PRIMARY KEY
|
|
)`)
|
|
if err != nil {
|
|
return
|
|
}
|
|
statement.Exec()
|
|
|
|
statement, err = DB.Prepare(`CREATE TABLE IF NOT EXISTS collectionObject (
|
|
collectionId TEXT,
|
|
objectId TEXT,
|
|
PRIMARY KEY (collectionId, objectId)
|
|
)`)
|
|
if err != nil {
|
|
return
|
|
}
|
|
statement.Exec()
|
|
|
|
return
|
|
}
|
|
|
|
func initActorTable() (err error) {
|
|
statement, err := DB.Prepare(`CREATE TABLE IF NOT EXISTS actor (
|
|
id TEXT PRIMARY KEY,
|
|
type TEXT,
|
|
name TEXT,
|
|
preferredUsername TEXT,
|
|
summary TEXT,
|
|
inbox TEXT,
|
|
outbox TEXT,
|
|
followers TEXT,
|
|
following TEXT,
|
|
liked TEXT
|
|
)`)
|
|
if err != nil {
|
|
return
|
|
}
|
|
statement.Exec()
|
|
|
|
return
|
|
}
|
|
|
|
func initUserTable() (err error) {
|
|
statement, err := DB.Prepare(`CREATE TABLE IF NOT EXISTS user (
|
|
id TEXT PRIMARY KEY,
|
|
password TEXT,
|
|
actor TEXT
|
|
)`)
|
|
if err != nil {
|
|
return
|
|
}
|
|
statement.Exec()
|
|
|
|
statement, err = DB.Prepare(`CREATE TABLE IF NOT EXISTS session (
|
|
token TEXT PRIMARY KEY,
|
|
userId TEXT
|
|
)`)
|
|
if err != nil {
|
|
return
|
|
}
|
|
statement.Exec()
|
|
|
|
return
|
|
}
|
|
|
|
func handleError(err error) {
|
|
if err != nil {
|
|
panic(fmt.Sprintf("Could not execute Database Query: %s", err))
|
|
}
|
|
}
|