Created
March 5, 2014 19:10
-
-
Save jszwedko/9374286 to your computer and use it in GitHub Desktop.
Perl module for use with SQL::Translator to generate Go structs from SQL DDL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
package Custom::Golang; | |
use strict; | |
use SQL::Translator; | |
use String::CamelCase qw(camelize); | |
use Data::Dumper; | |
my %dbi_type_map = ( | |
integer => "int", | |
int => "int", | |
smallint => "int", | |
bigint => "int64", | |
double => "float64", | |
number => "sqlutil.BigRat", | |
decimal => "sqlutil.BigRat", | |
numeric => "sqlutil.BigRat", | |
dec => "sqlutil.BigRat", | |
bit => "int", | |
date => "time.Time", | |
datetime => "time.Time", | |
timestamp => "time.Time", | |
time => "time.Time", | |
char => "string", | |
varchar => "string", | |
varchar2 => "string", | |
binary => "string", | |
varbinary => "string", | |
tinyblob => "string", | |
blob => "string", | |
text => "string" | |
); | |
my %dbi_null_type_map = ( | |
integer => "sql.NullInt64", | |
int => "sql.NullInt64", | |
smallint => "sql.NullInt64", | |
bigint => "sql.NullInt64", | |
double => "sql.NullInt64", | |
number => "sqlutil.NullBigRat", | |
decimal => "sqlutil.NullBigRat", | |
numeric => "sqlutil.NullBigRat", | |
dec => "sqlutil.NullBigRat", | |
bit => "sql.NullInt64", | |
date => "sqlutil.NullTime", | |
datetime => "sqlutil.NullTime", | |
timestamp => "sqlutil.NullTime", | |
time => "sqlutil.NullTime", | |
char => "sql.NullString", | |
varchar => "sql.NullString", | |
varchar2 => "sql.NullString", | |
binary => "sql.NullString", | |
varbinary => "sql.NullString", | |
tinyblob => "sql.NullString", | |
blob => "sql.NullString", | |
text => "sql.NullString" | |
); | |
sub produce { | |
my $transformer = shift; | |
my $schema = $transformer->schema; | |
my $output = ''; | |
for my $table ( $schema->get_tables ) { | |
$output .= join('', "type ", camelize(lc($table->name)), " struct {\n"); | |
for my $c ( $table->get_fields) { | |
$output .= sprintf("%s %s `db:\"%s\"`\n", camelize(lc($c->name)), go_type( $c ), lc($c->name)); | |
} | |
$output .= "}\n"; | |
} | |
return $output; | |
} | |
sub go_type { | |
my $field = shift; | |
my %map = ($field->is_nullable ? %dbi_null_type_map : %dbi_type_map); | |
return $map{lc($field->data_type)}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment