From b1686b1d466662368182d7cf9600ed0848e0c4c7 Mon Sep 17 00:00:00 2001 From: Matt Baer Date: Tue, 13 Nov 2018 13:04:52 -0500 Subject: [PATCH] Add --init-db flag to create schema in app Part of T530 --- README.md | 10 +++++----- app.go | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 62d9d66..0cbff1a 100644 --- a/README.md +++ b/README.md @@ -49,12 +49,12 @@ Now extract the files from the archive, change into the directory, and do the fo # 1) Log into MySQL and run: # CREATE DATABASE writefreely; # -# 2) Import the schema with: -mysql -u YOURUSERNAME -p writefreely < schema.sql - -# 3) Configure your blog +# 2) Configure your blog ./writefreely --config +# 3) Import the schema with: +./writefreely --init-db + # 4) Generate data encryption keys ./writefreely --gen-keys @@ -82,7 +82,7 @@ Ready to hack on your site? Here's a quick overview. go get github.com/writeas/writefreely/cmd/writefreely ``` -Create your database, import the schema, and configure your site [as shown above](#quick-start). Then generate the remaining files you'll need: +Configure your site, create your database, and import the schema [as shown above](#quick-start). Then generate the remaining files you'll need: ```bash make install # Generates encryption keys; installs LESS compiler diff --git a/app.go b/app.go index 97207e7..7adc513 100644 --- a/app.go +++ b/app.go @@ -6,10 +6,12 @@ import ( "fmt" _ "github.com/go-sql-driver/mysql" "html/template" + "io/ioutil" "net/http" "os" "os/signal" "regexp" + "strings" "syscall" "time" @@ -126,6 +128,7 @@ func Serve() { createConfig := flag.Bool("create-config", false, "Creates a basic configuration and exits") doConfig := flag.Bool("config", false, "Run the configuration process") genKeys := flag.Bool("gen-keys", false, "Generate encryption and authentication keys") + createSchema := flag.Bool("init-db", false, "Initialize app database") flag.Parse() debugging = *debugPtr @@ -186,6 +189,44 @@ func Serve() { } os.Exit(errStatus) + } else if *createSchema { + log.Info("Loading configuration...") + cfg, err := config.Load() + if err != nil { + log.Error("Unable to load configuration: %v", err) + os.Exit(1) + } + app.cfg = cfg + connectToDatabase(app) + defer shutdown(app) + + schema, err := ioutil.ReadFile("schema.sql") + if err != nil { + log.Error("Unable to load schema.sql: %v", err) + os.Exit(1) + } + + tblReg := regexp.MustCompile("CREATE TABLE (IF NOT EXISTS )?`([a-z_]+)`") + + queries := strings.Split(string(schema), ";\n") + for _, q := range queries { + if strings.TrimSpace(q) == "" { + continue + } + parts := tblReg.FindStringSubmatch(q) + if len(parts) >= 3 { + log.Info("Creating table %s...", parts[2]) + } else { + log.Info("Creating table ??? (Weird query) No match in: %v", parts) + } + _, err = app.db.Exec(q) + if err != nil { + log.Error("%s", err) + } else { + log.Info("Created.") + } + } + os.Exit(0) } log.Info("Initializing...")