bash shell代码如下:
#!/bin/bash
#Find all tablename in VIEWS files
views=$(cat $1 | awk -F " " '
{
print $3;
}
');
for table_name in `echo $views`
do
echo "-----------------$table_name";
table_columns_sql=$(sed -e :a -e 'N;s/\r\n//;ta' $2 | sed -e 's/go/\n/ig' | grep -i "create table $table_name " | awk -F "\\\)lock allpages" '{print $1}' | awk -F ",\t\tCONSTRAINT" '{print $1}' | sed -e "s/create\ table\ $table_name\ (//ig");
table_pk=$(echo $table_columns_sql | awk -F " " '{print $1}');
#===== View ======
table_columns_type=$(echo $table_columns_sql | sed -e 's/ , /,\n/ig' | sed -e 's/null//ig' | sed -e 's/not//ig' | sed -e '/^$/d');
echo "CREATE OR REPLACE view $table_name as
select * from dblink('dbname=xxxx user=xxxx password=xxxx',
'select * from $table_name')
as t1(
$table_columns_type
);";
#===== View insert ======
table_columns=$(echo $table_columns_type | sed -e 's/ , /,\n/ig' | awk -F " " '{
if(NR>1){
printf("|| \047,\047 || case when NEW.%s is not null then \047\047\047\047 || NEW.%s || \047\047\047\047 else \047\047\047\047\047\047 end\n\t",$1,$1)
};
}');
echo "CREATE OR REPLACE RULE "$table_name"_i AS
ON INSERT TO $table_name DO INSTEAD
SELECT dblink_exec('dbname=xxxx user=xxxx password=xxxx'::text,
'INSERT INTO $table_name VALUES ('
|| case when NEW.$table_pk is not null then '''' || NEW.$table_pk || '''' else '''''' end
$table_columns|| ');'
);
";
#===== View update ======
table_columns=$(echo $table_columns_type | sed -e 's/ , /,\n/ig' | awk -F " " '{
if(NR>1){
printf("|| \047chrcssm=\047 || case when NEW.%s is not null then \047\047\047\047 || NEW.%s || \047\047\047,\047 ELSE \047%s,\047 end\n\t",$1,$1,$1)
};
}');
echo "CREATE OR REPLACE RULE "$table_name"_u AS
ON UPDATE TO $table_name DO INSTEAD
SELECT dblink_exec('dbname=xxxx user=xxxx password=xxxx'::text,
'UPDATE $table_name SET '
$table_columns|| ' WHERE $table_pk=''' || OLD.$table_pk || ''';'
);
";
#===== View delete ======
echo "CREATE OR REPLACE RULE "$table_name"_d AS
ON DELETE TO $table_name DO INSTEAD
SELECT dblink_exec('dbname=xxxx user=xxxx password=xxxx'::text,
'DELETE FROM $table_name WHERE $table_pk=''' || OLD.$table_pk || ''';'
);
";
done
阅读(1507) | 评论(0) | 转发(0) |