require "rexml/document" =begin structure = [ { "tablename" => "table1", "colums" => [ { "name" => "col1", "datatype" => "text", "null" => "0", "autoincrement" => "1", "relation" => nil, "comment" => "com", }, { "name" => "item_id", "datatype" => "string", "null" => "0", "autoincrement" => "1", "relation" => {"table" => "items", "column" => "id"}, "comment" => "has_many", }, { "name" => "col3", "datatype" => "integer", "null" => "0", "autoincrement" => "1", "relation" => nil, "comment" => "", }, ], "comment" => "user has many actions" }, ] =end class Sqld4r_parser @@trans_map = { "INTEGER" => "integer", "DECIMAL" => "integer", "FLOAT" => "float", "DOUBLE" => "float", "CHAR" => "string", "VARCHAR" => "string", "MEDIUMTEXT" => "text", "BINARY" => "binary", "VARBINARY" => "binary", "BLOB" => "binary", "DATE" => "date", "TIME" => "time", "DATETIME" => "datetime", "YEAR" => "date", "TIMESTAMP" => "timestamp", "ENUM" => "string", "SET" => "boolean", } def initialize super() @structure = [] self end def parse(filepath) doc = REXML::Document.new File.new(filepath) doc.elements.each("sql/table") do |table| #puts table.attributes["name"] @structure << table_hash(table) end @structure end def table_hash(table_elem) buffer_hash = {} buffer_hash["tablename"] = table_elem.attributes["name"] begin buffer_hash["comment"] = table_elem.elements["comment"].text rescue buffer_hash["comment"] = "" end buffer_hash["colums"] = [] table_elem.elements.each("row") do |row| buffer_hash["colums"] << colums_hash(row) end return buffer_hash end =begin INTEGER { "name" => "col2", "datatype" => "integer", "null" => "0", "autoincrement" => "1", "relation" => {"table" => "users", "column" => "id"}, "comment" => "has_many", }, =end def colums_hash(row) rowbuffer_hash = {} rowbuffer_hash["name"] = row.attributes["name"] rowbuffer_hash["null"] = row.attributes["null"] rowbuffer_hash["autoincrement"] = row.attributes["autoincrement"] rowbuffer_hash["datatype"] = @@trans_map[row.elements["datatype"].text] begin rowbuffer_hash["relation"] = {"table" => row.elements["relation"].attributes["table"], "column" => row.elements["relation"].attributes["row"]} rescue rowbuffer_hash["relation"] = nil end begin rowbuffer_hash["comment"] = row.elements["comment"].text rescue rowbuffer_hash["comment"] = "" end return rowbuffer_hash end end