Matrix/utils/database/databaseConnector.go
2020-10-17 12:07:39 +02:00

164 lines
2.7 KiB
Go

package database
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
)
var DB *sql.DB
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(initDeviceTable())
handleError(initKeyTable())
handleError(initEventTable())
handleError(initRoomTable())
handleError(initTransactionTable())
handleError(initUserTable())
return
}
func initDeviceTable() (err error) {
statement, err := DB.Prepare(`CREATE TABLE IF NOT EXISTS device (
id TEXT PRIMARY KEY,
name TEXT,
accessToken TEXT,
userId TEXT
)`)
if err != nil {
return
}
statement.Exec()
return
}
func initKeyTable() (err error) {
statement, err := DB.Prepare(`CREATE TABLE IF NOT EXISTS key (
id TEXT PRIMARY KEY,
type TEXT,
key TEXT,
deviceId TEXT
)`)
if err != nil {
return
}
statement.Exec()
return
}
func initEventTable() (err error) {
statement, err := DB.Prepare(`CREATE TABLE IF NOT EXISTS event (
id TEXT PRIMARY KEY,
roomId TEXT,
txnId TEXT,
sender TEXT,
origin TEXT,
timestamp INTEGER,
eventType TEXT,
stateKey TEXT,
content TEXT,
depth INTEGER,
hash TEXT,
signature TEXT
)`)
if err != nil {
return
}
statement.Exec()
statement, err = DB.Prepare(`CREATE TABLE IF NOT EXISTS parent (
eventId TEXT,
parentId TEXT,
PRIMARY KEY (eventId, parentId)
)`)
if err != nil {
return
}
statement.Exec()
statement, err = DB.Prepare(`CREATE TABLE IF NOT EXISTS authEvent (
eventId TEXT,
authEventId TEXT,
PRIMARY KEY (eventId, authEventId)
)`)
if err != nil {
return
}
statement.Exec()
return
}
func initRoomTable() (err error) {
statement, err := DB.Prepare(`CREATE TABLE IF NOT EXISTS room (
id TEXT PRIMARY KEY,
version TEXT,
visibility TEXT,
name TEXT,
topic TEXT,
isDirect INT,
federated INT
)`)
if err != nil {
return
}
statement.Exec()
statement, err = DB.Prepare(`CREATE TABLE IF NOT EXISTS roomMember (
userId TEXT,
roomId TEXT,
server TEXT,
PRIMARY KEY (userId, roomId)
)`)
if err != nil {
return
}
statement.Exec()
return
}
func initTransactionTable() (err error) {
statement, err := DB.Prepare(`CREATE TABLE IF NOT EXISTS txn (
id TEXT PRIMARY KEY,
origin TEXT,
timestamp INTEGER
)`)
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,
name TEXT,
password 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))
}
}