Created
April 5, 2017 06:54
-
-
Save modeverv/80fe277cc3f0eca139775a5cf2b9d49c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/ruby | |
# coding: utf-8 | |
############################################################# | |
## | |
## csvを受け取りsqlを生成します | |
## csvの形式 | |
## 文字コード:utf-8 | |
## 内容: | |
## テーブル物理名,カラム物理名 | |
## | |
############################################################# | |
targetfile = ARGV[0] | |
outputfile = ARGV[1] | |
if targetfile.nil? || targetfile.empty? || outputfile.nil? || outputfile.empty? | |
puts <<-EOF | |
USAGE ruby makeSQL.rb <targetfilepath> | |
EOF | |
exit | |
end | |
SQL_ALTER_TABLE = <<-EOF | |
-- テーブル定義を変更 | |
ALTER TABLE %TABLE% ALTER COLUMN %COLUMN% TYPE text; | |
EOF | |
SQL_FUNCTION = <<-EOF | |
-- トリガー関数を定義 | |
CREATE OR REPLACE FUNCTION %TABLE%_trigger_func_%COLUMN%() | |
RETURNS trigger AS | |
$BODY$ | |
BEGIN | |
NEW.%COLUMN% := encode(pgp_sym_encrypt(NEW.%COLUMN%,'hoge'),'base64'); | |
RETURN NEW; | |
END ;$BODY$ | |
LANGUAGE plpgsql VOLATILE | |
COST 100; | |
EOF | |
SQL_TRRIGER = <<-EOF | |
-- トリガー関数を設定 | |
CREATE TRIGGER encrypt_%TABLE%_%COLUMN% BEFORE INSERT OR UPDATE OF %COLUMN% | |
ON %TABLE% FOR EACH ROW | |
EXECUTE PROCEDURE public.%TABLE%_trigger_func_%COLUMN%(); | |
EOF | |
bufs = [] | |
open(targetfile,"r") do |rio| | |
open(outputfile,"w") do |wio| | |
rio.each do |line| | |
table,column = line.split(",").map{|e| e.strip } | |
unless table.nil? || column.nil? || table.empty? || column.empty? | |
buf = "\n-- #{"#"*80}\n-- #{table}の#{column}についてSQLを生成します" | |
wio.puts buf | |
bufs << buf | |
sql = SQL_ALTER_TABLE.gsub("%TABLE%",table).gsub("%COLUMN%",column) | |
wio.puts sql | |
wio.puts "" | |
bufs << sql | |
sql = SQL_FUNCTION.gsub("%TABLE%",table).gsub("%COLUMN%",column) | |
wio.puts sql | |
wio.puts "" | |
bufs << sql | |
sql = SQL_TRRIGER.gsub("%TABLE%",table).gsub("%COLUMN%",column) | |
wio.puts sql | |
wio.puts "" | |
bufs << sql | |
end | |
end | |
end | |
end | |
puts bufs.join("\n") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment