Created
August 22, 2016 22:45
-
-
Save githoov/e749c3d14dcc3827dfacf3976ec3673d to your computer and use it in GitHub Desktop.
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 ruby | |
require 'json' | |
require 'optparse' | |
@file_path = '' | |
@separator = '' | |
@table_name = '' | |
OptionParser.new do |opts| | |
opts.on('-f', '--file=file_path', 'fully qualified path to file') {|file_path| @file_path = file_path} | |
opts.on('-s', '--separator=separator', 'separator') {|separator| @separator = separator} | |
opts.on('-t', '--table_name=table_name', 'name of final table') {|table_name| @table_name = table_name} | |
end.parse!(ARGV) | |
# helpers | |
class String | |
def is_integer? | |
/\A[-+]?\d+\z/ === self | |
end | |
def is_number? | |
true if Float(self) rescue false | |
end | |
end | |
def infer_type(object) | |
case | |
when | |
begin | |
JSON.parse(object).is_a?(Hash) | |
rescue => e | |
end | |
then 'variant' | |
when object.is_number? | |
then 'number' | |
when object.is_integer? | |
then 'integer' | |
when (object.is_a?(TrueClass) || object.is_a?(FalseClass)) | |
then 'boolean' | |
else 'varchar' | |
end | |
end | |
def split_to_cols(line, separator) | |
return line.split(separator) | |
end | |
def generate_create(table_name, column_names, data_types) | |
"create table #{table_name} (#{column_names.zip(data_types).map{|pair| pair.join(' ')}.join(', ')});" | |
end | |
begin | |
lines = File.open(@file_path).map(&:strip).first(2) | |
column_names = split_to_cols(lines[0], @separator) | |
data_types = split_to_cols(lines[1], @separator).map{|x| infer_type(x)} | |
puts generate_create(@table_name, column_names, data_types) | |
rescue => e | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment