db-migrate/db_migrate.nim
2016-01-31 00:18:21 -06:00

74 lines
2.1 KiB
Nim

## DB Migrate
## ==========
##
## Simple tool to manage database migrations.
import json, times, os, docopt
type DbMigrateConfig* = tuple[ driver, sqlDir, connectionString: string ]
proc loadConfig*(filename: string): DbMigrateConfig =
let cfg = json.parseFile(filename)
let config = (
driver: if cfg.hasKey("driver"): cfg["driver"].getStr else: "postres",
sqlDir: if cfg.hasKey("sqlDir"): cfg["sqlDir"].getStr else: "migrations",
connectionString: cfg["connectionString"].getStr)
# Check for migrations directory
# TODO: try/except
if not existsDir config.sqlDir:
echo "SQL directory '" & config.sqlDir &
"' does not exist and will be created."
createDir config.sqlDir
return config
proc createMigration*(config: DBMigrateConfig, migrationName: string): seq[string] =
let timestamp = getTime().getLocalTime().format("yyyyMMddHHmmss")
let filenamePrefix = timestamp & "-" & migrationName
let upFilename = joinPath(config.sqlDir, filenamePrefix & "-up.sql")
let downFilename = joinPath(config.sqlDir, filenamePrefix & "-down.sql")
let scriptDesc = migrationName & " (" & timestamp & ")"
# TODO: try/except and catch errors creating files.
let upFile = open(upFilename, fmWrite)
let downFile = open(downFilename, fmWrite)
upFile.writeLine "-- UP script for " & scriptDesc
downFile.writeLine "-- DOWN script for " & scriptDesc
upFile.close()
downFile.close()
return @[upFilename, downFilename]
when isMainModule:
let doc = """
Usage:
db-migrate [options] create <migration-name>
Options:
-c --config <config-file> Use the given configuration file (defaults to
"database.json").
"""
# Parse arguments
let args = docopt(doc, version = "db-migrate 0.1.0")
echo $args
# Load configuration file
let configFilename =
if args["--config"]: $args["--config"]
else: "database.json"
let config = loadConfig(configFilename)
# Execute commands
if args["create"]:
let filesCreated = createMigration(config, $args["<migration-name>"])
echo "Created new migration files:"
for filename in filesCreated: echo "\t" & filename