move db init/open functions into a single file

This commit is contained in:
Jeremy Latt 2014-03-01 15:02:24 -08:00
parent 542744d52a
commit b421971b61
3 changed files with 34 additions and 31 deletions

View File

@ -2,12 +2,10 @@ package main
import ( import (
"code.google.com/p/go.crypto/bcrypt" "code.google.com/p/go.crypto/bcrypt"
"database/sql"
"encoding/base64" "encoding/base64"
"flag" "flag"
"fmt" "fmt"
"github.com/jlatt/ergonomadic/irc" "github.com/jlatt/ergonomadic/irc"
_ "github.com/mattn/go-sqlite3"
"log" "log"
"os" "os"
) )
@ -21,27 +19,6 @@ func genPasswd(passwd string) {
fmt.Println(encoded) fmt.Println(encoded)
} }
func initDB(config *irc.Config) {
os.Remove(config.Database())
db, err := sql.Open("sqlite3", config.Database())
if err != nil {
log.Fatal(err)
}
defer db.Close()
_, err = db.Exec(`
CREATE TABLE channel (
name TEXT NOT NULL UNIQUE,
flags TEXT NOT NULL,
key TEXT NOT NULL,
topic TEXT NOT NULL,
user_limit INTEGER DEFAULT 0)`)
if err != nil {
log.Fatal(err)
}
}
func main() { func main() {
conf := flag.String("conf", "ergonomadic.json", "ergonomadic config file") conf := flag.String("conf", "ergonomadic.json", "ergonomadic config file")
initdb := flag.Bool("initdb", false, "initialize database") initdb := flag.Bool("initdb", false, "initialize database")
@ -59,7 +36,7 @@ func main() {
} }
if *initdb { if *initdb {
initDB(config) irc.InitDB(config.Database())
return return
} }

32
irc/database.go Normal file
View File

@ -0,0 +1,32 @@
package irc
import (
"database/sql"
_ "github.com/mattn/go-sqlite3"
"log"
"os"
)
func InitDB(path string) {
os.Remove(path)
db := OpenDB(path)
defer db.Close()
_, err := db.Exec(`
CREATE TABLE channel (
name TEXT NOT NULL UNIQUE,
flags TEXT NOT NULL,
key TEXT NOT NULL,
topic TEXT NOT NULL,
user_limit INTEGER DEFAULT 0)`)
if err != nil {
log.Fatal(err)
}
}
func OpenDB(path string) *sql.DB {
db, err := sql.Open("sqlite3", path)
if err != nil {
log.Fatal(err)
}
return db
}

View File

@ -7,7 +7,6 @@ import (
"database/sql" "database/sql"
"encoding/binary" "encoding/binary"
"fmt" "fmt"
_ "github.com/mattn/go-sqlite3"
"log" "log"
"net" "net"
"os" "os"
@ -36,17 +35,12 @@ type Server struct {
} }
func NewServer(config *Config) *Server { func NewServer(config *Config) *Server {
db, err := sql.Open("sqlite3", config.Database())
if err != nil {
log.Fatal(err)
}
server := &Server{ server := &Server{
channels: make(ChannelNameMap), channels: make(ChannelNameMap),
clients: make(ClientNameMap), clients: make(ClientNameMap),
commands: make(chan Command, 16), commands: make(chan Command, 16),
ctime: time.Now(), ctime: time.Now(),
db: db, db: OpenDB(config.Database()),
idle: make(chan *Client, 16), idle: make(chan *Client, 16),
motdFile: config.MOTD, motdFile: config.MOTD,
name: config.Name, name: config.Name,