lib/mosql/schema.rb in mosql-0.3.2 vs lib/mosql/schema.rb in mosql-0.4.0

- old
+ new

@@ -68,30 +68,39 @@ rescue KeyError => e raise SchemaError.new("In spec for #{dbname}.#{cname}: #{e}") end end end + + # Lurky way to force Sequel force all timestamps to use UTC. + Sequel.default_timezone = :utc end def create_schema(db, clobber=false) @map.values.each do |dbspec| dbspec.each do |n, collection| next unless n.is_a?(String) meta = collection[:meta] + composite_key = meta[:composite_key] + keys = [] log.info("Creating table '#{meta[:table]}'...") db.send(clobber ? :create_table! : :create_table?, meta[:table]) do collection[:columns].each do |col| opts = {} if col[:source] == '$timestamp' opts[:default] = Sequel.function(:now) end column col[:name], col[:type], opts - if col[:source].to_sym == :_id - primary_key [col[:name].to_sym] + if composite_key and composite_key.include?(col[:name]) + keys << col[:name].to_sym + elsif not composite_key and col[:source].to_sym == :_id + keys << col[:name].to_sym end end + + primary_key keys if meta[:extra_props] type = if meta[:extra_props] == "JSON" "JSON" else @@ -157,10 +166,27 @@ else raise SchemaError.new("Unknown source: #{source}") end end + def transform_primitive(v, type=nil) + case v + when BSON::ObjectId, Symbol + v.to_s + when BSON::Binary + if type.downcase == 'uuid' + v.to_s.unpack("H*").first + else + Sequel::SQL::Blob.new(v.to_s) + end + when BSON::DBRef + v.object_id.to_s + else + v + end + end + def transform(ns, obj, schema=nil) schema ||= find_ns!(ns) obj = obj.dup row = [] @@ -172,22 +198,21 @@ if source.start_with?("$") v = fetch_special_source(obj, source) else v = fetch_and_delete_dotted(obj, source) case v - when BSON::Binary, BSON::ObjectId, Symbol - v = v.to_s - when BSON::DBRef - v = v.object_id.to_s when Hash - v = JSON.dump(v) + v = JSON.dump(Hash[v.map { |k,v| [k, transform_primitive(v)] }]) when Array + v = v.map { |it| transform_primitive(it) } if col[:array_type] v = Sequel.pg_array(v, col[:array_type]) else v = JSON.dump(v) end + else + v = transform_primitive(v, type) end end row << v end @@ -266,10 +291,14 @@ 't' when false 'f' when Sequel::SQL::Function nil + when DateTime, Time + val.strftime("%FT%T.%6N %z") + when Sequel::SQL::Blob + "\\\\x" + [val].pack("h*") else val.to_s.gsub(/([\\\t\n\r])/, '\\\\\\1') end end @@ -288,9 +317,17 @@ def collections_for_mongo_db(db) (@map[db]||{}).keys end def primary_sql_key_for_ns(ns) - find_ns!(ns)[:columns].find {|c| c[:source] == '_id'}[:name] + ns = find_ns!(ns) + keys = [] + if ns[:meta][:composite_key] + keys = ns[:meta][:composite_key] + else + keys << ns[:columns].find {|c| c[:source] == '_id'}[:name] + end + + return keys end end end