#!/usr/bin/env ruby require 'builder/builder.rb' module Prick::SubCommand def self.build(database, username, schema, builddir: "schema", force: false, timer: nil, dump: nil) Timer.on! if timer time "Prick::Command#build" do begin super_conn = PgConn.new # Used to create new databases (doesn't make a # difference right now as the mikras user is # still a superuser) conn = nil builder = nil time "Load build object" do if super_conn.rdbms.exist? database conn = PgConn.new(database, username) exist = true else super_conn.rdbms.create database, owner: username conn = PgConn.new(database, username) exist = false end builder = Prick::Build::Builder.new(conn, builddir) if exist if force # Drop all schemas but re-creates the public schema super_conn.rdbms.empty!(database) else # Find schemas to refresh. This includes all schemas in the # database refresh_schemas = conn.schema.list # Find existing keep-schemas (but exclude target schema) keep_schemas = builder.keep_schemas.select { |s| conn.schema.exist?(s) && (schema.nil? || schema != s) } # Remove keep-schemas from list of schemas refresh_schemas -= keep_schemas # Eliminate keep schemas from build pool builder.pool.delete_schema(keep_schemas) # Drop refresh schemes refresh_schemas.each { |schema| conn.schema.drop(schema, cascade: true) } end end # Delete schemas after target scheme if present builder.pool.delete_schema(builder.pool.after_schema(schema)) if schema end case dump when :nodes; builder.nodes.reject { |node| node.is_a?(Build::BuildNode) }.map &:dump when :allnodes; builder.nodes.map &:dump when :batches; builder.dump when nil; else raise Prick::Error, "Illegal dump type: #{dump.inspect}" end && exit time "Execute build object" do builder.execute conn end rescue Prick::Error => ex $stderr.puts ex.message exit 1 rescue ::Command::Error => ex $stderr.puts ex.message exit 1 ensure super_conn&.terminate conn&.terminate end end end end