Skip to content

Instantly share code, notes, and snippets.

@solisoft
Last active August 27, 2015 07:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save solisoft/2476718a494e20dbfcc2 to your computer and use it in GitHub Desktop.
Save solisoft/2476718a494e20dbfcc2 to your computer and use it in GitHub Desktop.
Migration tool for crystal web frameworks
# prosgres Migration tool for crystal frameworks
# just create a ./db folder and add some migrations files
# ./db/0.sql
# ./db/1.sql
# ...
# ./db/22.sql # and so on ...
#
# Usage :
# require "pg" # I use a modified version solisoft/crystal-pg for now until main repo deployed
# DB = PG.connect("postgres://#{ENV["db_user"]}:#{ENV["db_password"]}@#{ENV["db_host"]}:#{ENV["db_port"]}/#{ENV["db_name"]}")
# require "./pg_migrate"
# migration = PgMigrate.new(DB)
# migration.run
class PgMigrate
def initialize(raw)
@raw = raw
end
def run
puts "Running migrations..."
start = 0 # starting at migration 0
if from_scratch?
# If no versions table then create it
@raw.exec("CREATE TABLE versions( last_version INT )")
else
# Get latest migration's version
start = @raw.exec("SELECT last_version FROM versions LIMIT 1").rows.first.first as Int32 rescue 0
end
m = false # Used to check if at least one migration was done
files = Dir.entries("./db/") - [".", ".."]
files = files.map {|l| l.split(".").first.to_i }.sort
files.each do |f|
if f > start # A new migration ?
m = true
puts ":: Migrating #{f}.sql"
puts @raw.exec_all(File.open("./db/#{f}.sql").read())
# set latest version
@raw.exec_all("TRUNCATE versions; INSERT INTO versions VALUES (#{f});")
end
end
puts ":: Nothing to migrate" unless m
puts "Done"
end
# Check if versions table exists or not
private def from_scratch?
tables = @raw.exec("SELECT * FROM pg_catalog.pg_tables").rows
tables = tables.select {|l| l[0] == "public"}
tables = tables.map {|l| l[1]}
tables.index("versions") == nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment