Sha256: abfb514f3fc5323b83575f22de093fdfe6619a6460a5cc97addfc333a08a39bb

Contents?: true

Size: 1.69 KB

Versions: 1

Compression:

Stored size: 1.69 KB

Contents

module Rasti
  module DB
    module TypeConverters
      class Postgres

        CONVERTERS = [
          PostgresTypes::JSON,
          PostgresTypes::JSONB,
          PostgresTypes::HStore,
          PostgresTypes::Array
        ]

        class << self

          def to_db(db, collection_name, attribute_name, value)
            converter, type = find_to_db_converter_and_type db, collection_name, attribute_name
            converter ? converter.to_db(value, type) : value
          end

          def from_db(value)
            converter = find_from_db_converter value.class
            converter ? converter.from_db(value) : value
          end

          private

          def from_db_converters
            @from_db_converters ||= {}
          end

          def to_db_converters
            @to_db_converters ||= {}
          end

          def find_to_db_converter_and_type(db, collection_name, attribute_name)
            key = [db.opts[:database], collection_name].join('.')

            to_db_converters[key] ||= begin
              columns = Hash[db.schema(collection_name)]
              to_db_converters[key] = columns.each_with_object({}) do |(name, schema), hash|
                converter = CONVERTERS.detect { |c| c.to_db? schema[:db_type] }
                hash[name] = [converter, schema[:db_type]] if converter
              end
            end

            to_db_converters[key].fetch(attribute_name, [])
          end

          def find_from_db_converter(klass)
            if !from_db_converters.key?(klass)
              from_db_converters[klass] = CONVERTERS.detect { |c| c.from_db? klass }
            end

            from_db_converters[klass]
          end

        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rasti-db-2.3.1 lib/rasti/db/type_converters/postgres.rb