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
|
2013-06-30 14:54:45 -04:00
|
|
|
include DirectoryHelper
|
2013-02-05 14:16:51 -05:00
|
|
|
|
|
|
|
def initialize
|
|
|
|
@table_data = {}
|
|
|
|
end
|
|
|
|
|
|
|
|
def json_output_stream
|
2013-06-30 14:54:45 -04:00
|
|
|
@json_output_stream ||= File.new( File.join( tmp_directory('export'), 'tables.json' ), 'w+b' )
|
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
|
|
|
|
|
|
|
@schema_data = {
|
|
|
|
schema: {
|
|
|
|
source: args[:source],
|
|
|
|
version: args[:version]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
end
|
|
|
|
|
|
|
|
def write_table(table_name, columns)
|
|
|
|
@table_data[table_name] ||= {}
|
|
|
|
@table_data[table_name][:fields] = columns.map(&:name)
|
|
|
|
@table_data[table_name][:rows] ||= []
|
|
|
|
|
|
|
|
row_count = 0
|
|
|
|
begin
|
|
|
|
rows = yield(row_count)
|
|
|
|
if rows
|
|
|
|
row_count += rows.size
|
|
|
|
@table_data[table_name][:rows] << rows
|
|
|
|
end
|
|
|
|
|
|
|
|
# TODO: write to multiple files as needed.
|
|
|
|
# one file per table? multiple files per table?
|
|
|
|
|
2013-03-04 19:42:44 -05:00
|
|
|
end while rows && rows.size > 0
|
2013-02-05 14:16:51 -05:00
|
|
|
|
|
|
|
@table_data[table_name][:rows].flatten!(1)
|
|
|
|
@table_data[table_name][:row_count] = @table_data[table_name][:rows].size
|
|
|
|
end
|
|
|
|
|
|
|
|
def finish
|
|
|
|
@schema_data[:schema][:table_count] = @table_data.keys.count
|
2013-04-26 21:45:53 -04:00
|
|
|
json_output_stream.write( Oj.dump(@schema_data.merge(@table_data),
|
|
|
|
:mode => :compat) )
|
2013-02-05 14:16:51 -05:00
|
|
|
json_output_stream.close
|
|
|
|
|
2013-06-30 14:54:45 -04:00
|
|
|
@filenames = [File.join( tmp_directory('export'), 'tables.json' )]
|
2013-02-05 14:16:51 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def filenames
|
|
|
|
@filenames ||= []
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|
2013-04-26 21:45:53 -04:00
|
|
|
end
|