Sha256: 6960a2673fe34ad2750cfae3fd98a983b31e3f68a1f37be5519eaeb73d1784ce

Contents?: true

Size: 1.41 KB

Versions: 1

Compression:

Stored size: 1.41 KB

Contents

module Simple
  module SQL
    module Reflection
      extend self

      extend Forwardable
      delegate [:ask, :all, :records, :record] => ::Simple::SQL

      def tables(schema: "public")
        if schema == "public"
          sql = <<~SQL
            SELECT table_name AS name, *
            FROM information_schema.tables
            WHERE table_schema=$1
          SQL
        else
          sql = <<~SQL
            SELECT table_schema || '.' || table_name AS name, *
            FROM information_schema.tables
            WHERE table_schema=$1
          SQL
        end
        records = ::Simple::SQL.records sql, schema
        records_by_attr(records, :name)
      end

      def columns(table_name)
        schema, table_name = parse_table_name(table_name)
        records = ::Simple::SQL.records <<~SQL, schema, table_name
          SELECT
            column_name AS name,
            *
          FROM information_schema.columns
          WHERE table_schema=$1 AND table_name=$2
        SQL

        records_by_attr(records, :column_name)
      end

      private

      def parse_table_name(table_name)
        p1, p2 = table_name.split(".", 2)
        if p2
          [ p1, p2 ]
        else
          [ "public", p1 ]
        end
      end

      def records_by_attr(records, attr)
        records.inject({}) do |hsh, record|
          hsh.update record[attr] => OpenStruct.new(record)
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
simple-sql-0.2.6 lib/simple/sql/reflection.rb