2013-06-30 14:54:45 -04:00
|
|
|
require_dependency 'directory_helper'
|
|
|
|
|
2013-02-05 14:16:51 -05:00
|
|
|
module Export
|
|
|
|
|
|
|
|
class SchemaArgumentsError < RuntimeError; end
|
|
|
|
|
|
|
|
class JsonEncoder
|
2014-01-29 00:49:01 -05:00
|
|
|
attr_accessor :stream_creator
|
|
|
|
|
2013-06-30 14:54:45 -04:00
|
|
|
include DirectoryHelper
|
2013-02-05 14:16:51 -05:00
|
|
|
|
2014-01-29 00:49:01 -05:00
|
|
|
def initialize(stream_creator = nil)
|
|
|
|
@stream_creator = stream_creator
|
|
|
|
@stream_creator ||= lambda do |filename|
|
|
|
|
File.new(filename, 'w+b' )
|
|
|
|
end
|
|
|
|
|
|
|
|
@schema_data = {
|
|
|
|
schema: {}
|
|
|
|
}
|
|
|
|
|
|
|
|
@table_info = {}
|
2013-02-05 14:16:51 -05:00
|
|
|
end
|
|
|
|
|
2014-01-29 00:49:01 -05:00
|
|
|
|
|
|
|
def write_json(name, data)
|
|
|
|
filename = File.join( tmp_directory('export'), "#{name}.json")
|
|
|
|
filenames << filename
|
|
|
|
stream = stream_creator.call(filename)
|
|
|
|
Oj.to_stream(stream, data, :mode => :compat)
|
|
|
|
stream.close
|
2013-02-05 14:16:51 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def write_schema_info(args)
|
2013-03-04 19:42:44 -05:00
|
|
|
raise SchemaArgumentsError unless args[:source].present? && args[:version].present?
|
2013-02-05 14:16:51 -05:00
|
|
|
|
2014-01-29 00:49:01 -05:00
|
|
|
@schema_data[:schema][:source] = args[:source]
|
|
|
|
@schema_data[:schema][:version] = args[:version]
|
2013-02-05 14:16:51 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def write_table(table_name, columns)
|
2014-01-29 00:49:01 -05:00
|
|
|
rows ||= []
|
2013-02-05 14:16:51 -05:00
|
|
|
|
2014-01-29 00:49:01 -05:00
|
|
|
while true
|
|
|
|
current_rows = yield(rows.count)
|
|
|
|
break unless current_rows && current_rows.size > 0
|
|
|
|
rows.concat current_rows
|
|
|
|
end
|
2013-02-05 14:16:51 -05:00
|
|
|
|
2014-01-29 00:49:01 -05:00
|
|
|
# TODO still way too big a chunk, needs to be split up
|
|
|
|
write_json(table_name, rows)
|
2013-02-05 14:16:51 -05:00
|
|
|
|
2014-01-29 00:49:01 -05:00
|
|
|
@table_info[table_name] ||= {
|
|
|
|
fields: columns.map(&:name),
|
|
|
|
row_count: rows.size
|
|
|
|
}
|
2013-02-05 14:16:51 -05:00
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
def finish
|
2014-01-29 00:49:01 -05:00
|
|
|
@schema_data[:schema][:table_count] = @table_info.keys.count
|
|
|
|
write_json("schema", @schema_data.merge(@table_info))
|
2013-02-05 14:16:51 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def filenames
|
|
|
|
@filenames ||= []
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|
2013-04-26 21:45:53 -04:00
|
|
|
end
|