Skip to content

Commit

Permalink
Let dbname be set in migrate and at server start. (#18)
Browse files Browse the repository at this point in the history
  • Loading branch information
novabyte committed Feb 9, 2017
1 parent d3d7902 commit ad7d3a1
Show file tree
Hide file tree
Showing 10 changed files with 178 additions and 143 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ build/*
data/*
.GITHUB_TOKEN
.idea
install/cloud/**/*.json

### Go ###
# Compiled Object files, Static and Dynamic libs (Shared Objects)
Expand Down
20 changes: 10 additions & 10 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,22 @@ All notable changes to this project are documented below.
The format is based on [keep a changelog](http://keepachangelog.com/) and this project uses [semantic versioning](http://semver.org/).

## [Unreleased]

### Added

- Add verbose command-line flag to enable debug logging and console output.
### Added
- Add `--verbose` flag to enable debug logs in server.
- Database name can now be set in migrations and at server startup. i.e. `nakama --db root@127.0.0.1:26257/mydbname`.
- Improve SQL compatibility.

### Changed
- Update db schema to support 64 characters with device IDs. This enables `SystemInfo.deviceUniqueIdentifier` to be used as a source for device IDs on Windows 10.
- Logout messages now close the connection as well and won't reply.
- Change Logout message type from `TLogout` to `Logout`.
- Update TFriendAdd, TFriendRemove, TFriendBlock to accept UserID as bytes.
- Logout messages now close the server-side connection and won't reply.
- Rename logout protocol message type from `TLogout` to `Logout`.
- Update server protocol for friend messages to use IDs as bytes.

### Fixed

- Fix issue where random handle generator wasn't seeded properly.
- Fix issues in executing Friend, Storage and Group queries.
- Fix sending Close frame message in the Websocket to gracefully close connection.
- Improve various SQL storage, friend, and group queries.
- Send close frame message in the websocket to gracefully close a client connection.
- Build system will now detect modifications to `migrations/...` files and run dependent rules.

## [0.10.0] - 2017-01-14
### Added
Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ build/generated/dashboard/embedded.go: $(shell find dashboard/src dashboard/stat
.PHONY: migration
migration: build/generated/migration/embedded.go

build/generated/migration/embedded.go:
build/generated/migration/embedded.go: $(shell find migrations -type f)
${GOBINDATA} -pkg migration -prefix migrations -o ${BUILDDIR}/generated/migration/embedded.go migrations/...

.PHONY: proto
Expand Down
49 changes: 38 additions & 11 deletions cmd/migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ package cmd
import (
"database/sql"
"flag"
"fmt"
"net/url"
"os"
"time"

Expand Down Expand Up @@ -74,7 +76,7 @@ func MigrationStartupCheck(logger zap.Logger, db *sql.DB) {

func MigrateParse(args []string, logger zap.Logger) {
if len(args) == 0 {
logger.Fatal("Migrate requires commands. Available commands: 'up', 'down', 'redo', 'status'")
logger.Fatal("Migrate requires a subcommand. Available commands are: 'up', 'down', 'redo', 'status'.")
}

migrate.SetTable(migrationTable)
Expand All @@ -97,24 +99,49 @@ func MigrateParse(args []string, logger zap.Logger) {
case "status":
exec = ms.status
default:
logger.Fatal("Unrecognized migrate command. Available commands: 'up', 'down', 'redo', 'status'")
logger.Fatal("Unrecognized migrate subcommand. Available commands are: 'up', 'down', 'redo', 'status'.")
}

ms.parseSubcommand(args[1:])

db, err := sql.Open(dialect, "postgresql://"+ms.DSNS+"/?sslmode=disable")
rawurl := fmt.Sprintf("postgresql://%s?sslmode=disable", ms.DSNS)
url, err := url.Parse(rawurl)
if err != nil {
logger.Fatal("Error connecting to database", zap.Error(err))
logger.Fatal("Bad connection URL", zap.Error(err))
}

dbname := "nakama"
if len(url.Path) > 1 {
dbname = url.Path[1:]
}

url.Path = ""
db, err := sql.Open(dialect, url.String())
if err != nil {
logger.Fatal("Failed to open database", zap.Error(err))
}
if err = db.Ping(); err != nil {
logger.Fatal("Error pinging database", zap.Error(err))
}
ms.db = db

_, err = db.Exec("CREATE DATABASE IF NOT EXISTS nakama; SET DATABASE TO nakama")
_, err = db.Exec(fmt.Sprintf("CREATE DATABASE %s", dbname))
if err != nil {
logger.Fatal("Error creating or selecting database", zap.Error(err))
logger.Info("Database could not be created", zap.Error(err))
} else {
logger.Info("Database created", zap.String("name", dbname))
}
db.Close()

// Append dbname to data source name.
url.Path = fmt.Sprintf("/%s", dbname)
db, err = sql.Open(dialect, url.String())
if err != nil {
logger.Fatal("Failed to open database", zap.Error(err))
}
if err = db.Ping(); err != nil {
logger.Fatal("Error pinging database", zap.Error(err))
}
ms.db = db

exec()
os.Exit(0)
Expand Down Expand Up @@ -204,14 +231,14 @@ func (ms *migrationService) status() {

func (ms *migrationService) parseSubcommand(args []string) {
flags := flag.NewFlagSet("migrate", flag.ExitOnError)
flags.StringVar(&ms.DSNS, "db", "root@localhost:26257", "CockroachDB JDBC connection details")
flags.IntVar(&ms.Limit, "limit", defaultLimit, "CockroachDB JDBC connection details")
flags.StringVar(&ms.DSNS, "db", "root@localhost:26257", "CockroachDB JDBC connection details.")
flags.IntVar(&ms.Limit, "limit", defaultLimit, "Number of migrations to apply forwards or backwards.")

if err := flags.Parse(args); err != nil {
ms.logger.Fatal("Could not parse migration flags")
ms.logger.Fatal("Could not parse migration flags.")
}

if ms.DSNS == "" {
ms.logger.Fatal("Database connection details are required")
ms.logger.Fatal("Database connection details are required.")
}
}
25 changes: 18 additions & 7 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,29 +20,31 @@ import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"

"nakama/cmd"
"nakama/pkg/ga"
"nakama/server"

"github.com/armon/go-metrics"
"github.com/go-yaml/yaml"
_ "github.com/lib/pq"
uuid "github.com/satori/go.uuid"
"github.com/uber-go/zap"
"nakama/cmd"
"nakama/pkg/ga"
"nakama/server"
)

const (
cookieFilename = ".cookie"
)

var (
version string
commitID string
version string
commitID string
verboseLogging bool = true
)

Expand All @@ -55,7 +57,6 @@ func main() {
}
clogger := zap.New(zap.NewTextEncoder(zap.TextNoTime()), options...)


if len(os.Args) > 1 {
// TODO requires Zap to be set to Info level.
switch os.Args[1] {
Expand Down Expand Up @@ -222,7 +223,17 @@ func configureLogger(clogger zap.Logger, config server.Config) (zap.Logger, zap.

func dbConnect(multiLogger zap.Logger, dsns []string) *sql.DB {
// TODO config database pooling
db, err := sql.Open("postgres", "postgresql://"+dsns[0]+"/nakama?sslmode=disable")
rawurl := fmt.Sprintf("postgresql://%s?sslmode=disable", dsns[0])
url, err := url.Parse(rawurl)
if err != nil {
multiLogger.Fatal("Bad connection URL", zap.Error(err))
}

if len(url.Path) < 1 {
url.Path = "/nakama"
}

db, err := sql.Open("postgres", url.String())
if err != nil {
multiLogger.Fatal("Error connecting to database", zap.Error(err))
}
Expand Down
Loading

0 comments on commit ad7d3a1

Please sign in to comment.