Skip to content

Instantly share code, notes, and snippets.

@jar-o
Created September 26, 2016 23:30
Show Gist options
  • Save jar-o/5a4412ad7a60fc0bca644c35f672ed5f to your computer and use it in GitHub Desktop.
Save jar-o/5a4412ad7a60fc0bca644c35f672ed5f to your computer and use it in GitHub Desktop.
A::Moose::Role::ToSql - convert a moose object into a CREATE TABLE statement, more-or-less
package A::Moose::Role::ToSql;
use Moose::Role;
use JSON;
sub sql_table {
my $self = shift;
my %ok_types = (
Str => 'character varying(255)',
Int => 'integer',
Bool => 'integer',
DateTimeType => 'timestamp without time zone',
HashRef => 'text',
NonNegInt => 'integer',
);
my $table_name = lc ref $self;
$table_name =~ s/::/_/g;
my @sql_table;
push @sql_table, ' id SERIAL PRIMARY KEY';
for my $attr ( $self->meta->get_all_attributes ) {
my ($n, $p) = (
$attr->type_constraint->name,
$attr->type_constraint->parent->name
);
$n =~ s/Maybe\[(.+)\]/$1/;
my ($ntype, $type) = ( exists $ok_types{$n} ? $n : $p,
$ok_types{ $n } // $ok_types{ $p });
unless ($type) {
# print "Can't convert attr " . $attr->name . '(' .
# $attr->type_constraint->name . ")\n";
next;
}
$n = $attr->name;
my $field = " $n " . $ok_types{$ntype};
push @sql_table, $field;
}
return "CREATE TABLE $table_name (\n". join(",\n", @sql_table) . "\n);";
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment