我有一系列看起来像这样的SQL脚本:
CREATE TABLE table_one
(
column_one int not null,
column_two varchar(100) not null,
column_three_four_five int,
column_six decimal(16,4) null,
PRIMARY KEY ( column_one, column_three_four_five)
);
我想清理布局以便于扫描,如下所示:
CREATE TABLE table_one
(
column_one int not null,
column_two varchar(100) not null,
column_three_four_five int,
column_six decimal(16,4) null,
PRIMARY KEY
(
column_one,
column_three_four_five
)
);
确切的布局不如创建干净的外观以提高可读性那么重要。 (阅读:请不要激活格式化本身)-grin -
什么是编写脚本的好方法(我在看着你,Perl众神......)?
答案 0 :(得分:2)
嗯,不能说它会适用于你的所有文件但这样的事情可以胜任...
#!/usr/bin/perl
use strict;
use warnings;
my $default_padding = 30;
my $my_file = 'data.sql';
my $my_new_file = 'data_new.sql';
open (my $fh, '<', $my_file) or die $!;
my @sql = <$fh>;
close($fh);
open (my $fhsave, '>>', $my_new_file) or die $!;
foreach my $line (@sql) {
print $fhsave "$line" if ($line !~ /^\s+/);
$line =~ s/\s+/ /ig;
print $fhsave sprintf(" %-*s %s\n", $default_padding, $1, $2) if ($line =~ /^\s+(.+?)\s+(.+)/);
}
close ($fhsave);
示例文件data.sql
CREATE TABLE table_one
(
column_one int not null,
column_two varchar(100) not null,
column_three_four_five int,
column_six decimal(16,4) null
);
输出:
CREATE TABLE table_one
(
column_one int not null,
column_two varchar(100) not null,
column_three_four_five int,
column_six decimal(16,4) null
);
答案 1 :(得分:1)
我没有尝试过任何一个,但CPAN有SQL::Beautify和SQL::QueryBuilder::Pretty。
答案 2 :(得分:0)