morpheusv2

A Matrix client written in Go-QT
git clone git://archive.git.mtrnord.blog/Nordgedanken/morpheusv2.git
Log | Files | Refs | README | LICENSE

db.go (2175B)


      1 // Copyright © 2018 MTRNord <info@nordgedanken.de>
      2 //
      3 // Licensed under the Apache License, Version 2.0 (the "License");
      4 // you may not use this file except in compliance with the License.
      5 // You may obtain a copy of the License at
      6 //
      7 //     http://www.apache.org/licenses/LICENSE-2.0
      8 //
      9 // Unless required by applicable law or agreed to in writing, software
     10 // distributed under the License is distributed on an "AS IS" BASIS,
     11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12 // See the License for the specific language governing permissions and
     13 // limitations under the License.
     14 
     15 package sqlite
     16 
     17 import (
     18 	"database/sql"
     19 	"fmt"
     20 	_ "github.com/mattn/go-sqlite3" // Go-sqlite3 side effect import needed to use SQLite3 databases
     21 	"github.com/shibukawa/configdir"
     22 	"log"
     23 	"path/filepath"
     24 )
     25 
     26 // Init prepares the DB by opening it and creating the required tables if needed
     27 func (s *SQLite) Init() (err error) {
     28 	log.Println("Start setting up DB")
     29 	var openErr error
     30 
     31 	// Open the data.db file. It will be created if it doesn't exist.
     32 	configDirs := configdir.New("Nordgedanken", "Morpheusv2")
     33 	filePath := filepath.ToSlash(configDirs.QueryFolders(configdir.Global)[0].Path)
     34 
     35 	log.Println("DBFilePath: ", filePath+"/data.db")
     36 	s.db, openErr = sql.Open("sqlite3", filePath+"/data.db")
     37 	if openErr != nil {
     38 		err = openErr
     39 		return
     40 	}
     41 
     42 	log.Println("Creating DB Tables if needed")
     43 	createTables := `CREATE TABLE IF NOT EXISTS users (id varchar not null primary key, display_name text, avatar text, access_token text, own integer);
     44 					CREATE TABLE IF NOT EXISTS messages (id varchar not null primary key, author_id varchar, message text, timestamp datetime, pure_event text);
     45 					CREATE TABLE IF NOT EXISTS rooms (id varchar not null primary key, room_aliases text, room_name text, room_avatar text, room_topic text, room_messages text);
     46 					`
     47 	_, execErr := s.db.Exec(createTables)
     48 	if execErr != nil {
     49 		err = fmt.Errorf("DB EXEC ERR: %s", execErr)
     50 		return
     51 	}
     52 	log.Println("Finished setting DB Setup")
     53 	return
     54 }
     55 
     56 // Open returns the in Init() created db variable
     57 func (s *SQLite) Open() *sql.DB {
     58 	if s.db != nil {
     59 		return s.db
     60 	}
     61 	return nil
     62 }