« blib/lib/auto/share/dist/Cmd-Dwarf/app/lib/Dwarf/Module/SocialMedia/Twitter.pm
↑ Summary
blib/lib/auto/share/dist/Cmd-Dwarf/app/lib/Dwarf/Plugin/JSON.pm »
| 1 | package App::DB::Schema::Dumper; | ||
| 2 | use Dwarf::Pragma; | ||
| 3 | use DBIx::Inspector 0.03; | ||
| 4 | use Carp (); | ||
| 5 | |||
| 6 | sub dump { | ||
| 7 | my $class = shift; | ||
| 8 | my %args = @_==1 ? %{$_[0]} : @_; | ||
| 9 | my $dbh = $args{dbh} or Carp::croak("missing mandatory parameter 'dbh'"); | ||
| 10 | my $namespace = $args{namespace} or Carp::croak("missing mandatory parameter 'namespace'"); | ||
| 11 | my $row_class = $args{base_row_class}; | ||
| 12 | my $dt_rules = $args{dt_rules} || qr/_at$/; | ||
| 13 | |||
| 14 | my $inspector = DBIx::Inspector->new(dbh => $dbh); | ||
| 15 | |||
| 16 | my $ret = "package ${namespace}::Schema;\n"; | ||
| 17 | $ret .= "use Teng::Schema::Declare;\n"; | ||
| 18 | $ret .= "use ${namespace}::Schema::Declare;\n\n"; | ||
| 19 | |||
| 20 | for my $table_info (sort { $a->name cmp $b->name } $inspector->tables) { | ||
| 21 | $ret .= "table {\n"; | ||
| 22 | $ret .= sprintf(" name '%s';\n", $table_info->name); | ||
| 23 | $ret .= sprintf(" pk %s;\n", join ',' , map { q{'}.$_->name.q{'} } $table_info->primary_key); | ||
| 24 | $ret .= sprintf(" row_class '%s';\n", $row_class) if $row_class; | ||
| 25 | |||
| 26 | $ret .= " columns (\n"; | ||
| 27 | for my $col ($table_info->columns) { | ||
| 28 | if ($col->data_type) { | ||
| 29 | my $data_type = $col->data_type; | ||
| 30 | my $pg_type = $col->{PG_TYPE} || $col->{pg_type}; | ||
| 31 | # Pg の char(n) 対策 | ||
| 32 | if ($pg_type && $pg_type =~ /^character\((\d+)\)$/) { | ||
| 33 | if ($1 > 1) { | ||
| 34 | $data_type = "{ pg_type => 1042 }"; | ||
| 35 | } | ||
| 36 | } | ||
| 37 | |||
| 38 | $ret .= sprintf(" { name => '%s', type => %s },\n", $col->name, $data_type); | ||
| 39 | } else { | ||
| 40 | $ret .= sprintf(" '%s',\n", $col->name); | ||
| 41 | } | ||
| 42 | } | ||
| 43 | $ret .= " );\n"; | ||
| 44 | |||
| 45 | my @datetime_columns = grep { $_->name =~ m/$dt_rules/ } $table_info->columns; | ||
| 46 | if (@datetime_columns) { | ||
| 47 | $ret .= " datetime_columns (\n"; | ||
| 48 | for my $col (@datetime_columns) { | ||
| 49 | $ret .= sprintf(" '%s',\n", $col->name); | ||
| 50 | } | ||
| 51 | $ret .= " );\n"; | ||
| 52 | } | ||
| 53 | |||
| 54 | $ret .= "};\n\n"; | ||
| 55 | } | ||
| 56 | $ret .= "1;\n"; | ||
| 57 | return $ret; | ||
| 58 | } | ||
| 59 | |||
| 60 | 1; |