Sha256: e1bd4c05f089d90be9277ccb54be9b9ea7924e38c4cb4894f14b5f6afcdf9c68

Contents?: true

Size: 1.65 KB

Versions: 7

Compression:

Stored size: 1.65 KB

Contents

module Rasti
  module DB
    class TypeConverter

      CONVERTIONS = {
        postgres: {
          /^json$/         => ->(value, match) { Sequel.pg_json value },
          /^jsonb$/        => ->(value, match) { Sequel.pg_jsonb value },
          /^hstore$/       => ->(value, match) { Sequel.hstore value },
          /^hstore\[\]$/   => ->(value, match) { Sequel.pg_array value.map { |v| Sequel.hstore v }, 'hstore' },
          /^([a-z]+)\[\]$/ => ->(value, match) { Sequel.pg_array value, match.captures[0] }
        }
      }

      def initialize(db, collection_name)
        @db = db
        @collection_name = collection_name
      end

      def apply_to(attributes)
        convertions = self.class.convertions_for @db, @collection_name

        return attributes if convertions.empty?

        (attributes.is_a?(Array) ? attributes : [attributes]).each do |attrs|
          convertions.each do |name, convertion|
            attrs[name] = convertion[:block].call attrs[name], convertion[:match] if attrs.key? name
          end
        end

        attributes
      end

      @cache ||= {}

      def self.convertions_for(db, collection_name)
        key = [db.database_type, collection_name]
        if !@cache.key?(key)
          columns = Hash[db.schema(collection_name)]
          @cache[key] = columns.each_with_object({}) do |(name, schema), hash| 
            CONVERTIONS.fetch(db.database_type, {}).each do |type, convertion|
              if !hash.key?(name) && match = type.match(schema[:db_type])
                hash[name] = {match: match, block: convertion}
              end
            end
          end
        end
        @cache[key]
      end

    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
rasti-db-0.4.1 lib/rasti/db/type_converter.rb
rasti-db-0.4.0 lib/rasti/db/type_converter.rb
rasti-db-0.3.0 lib/rasti/db/type_converter.rb
rasti-db-0.2.9 lib/rasti/db/type_converter.rb
rasti-db-0.2.8 lib/rasti/db/type_converter.rb
rasti-db-0.2.7 lib/rasti/db/type_converter.rb
rasti-db-0.2.6 lib/rasti/db/type_converter.rb