代码之家  ›  专栏  ›  技术社区  ›  Data Monk

清除创建表列布局

  •  0
  • Data Monk  · 技术社区  · 14 年前

    我有一系列这样的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
        )
    );
    

    准确的布局比创建一个干净的外观来提高可读性更不重要。(阅读:请不要燃烧格式本身)-笑-

    编写这个脚本的好方法是什么(我看着你,珀尔神…)

    3 回复  |  直到 14 年前
        1
  •  2
  •   Prix Winteroo    14 年前

    嗯,嗯,我不能说它对你所有的文件都有效,但是像这样的事情会起作用…

    #!/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 
    );
    
        2
  •  1
  •   cjm    14 年前

    我也没试过,但CPAN试过了 SQL::Beautify SQL::QueryBuilder::Pretty .

        3
  •  0
  •   BT.    14 年前

    http://www.dpriver.com/pp/sqlformat.htm

    不是脚本。但我现在不想编写任何代码。

    对于任何语言中的此类内容,请查找格式化程序或“prebuild junk”的单词“pretty”。