Class: BigShift::RedshiftTableSchema

Inherits:
Object
  • Object
show all
Defined in:
lib/bigshift/redshift_table_schema.rb

Defined Under Namespace

Classes: Column

Instance Method Summary collapse

Constructor Details

#initialize(schema_name, table_name, redshift_connection) ⇒ RedshiftTableSchema

Returns a new instance of RedshiftTableSchema.


3
4
5
6
7
# File 'lib/bigshift/redshift_table_schema.rb', line 3

def initialize(schema_name, table_name, redshift_connection)
  @schema_name = schema_name
  @table_name = table_name
  @redshift_connection = redshift_connection
end

Instance Method Details

#columnsObject


9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/bigshift/redshift_table_schema.rb', line 9

def columns
  @columns ||= begin
    query = %{
      SELECT "column", "type", "notnull"
      FROM pg_table_def ptd, information_schema.columns isc
      WHERE ptd.schemaname = isc.table_schema
      AND ptd.tablename = isc.table_name
      AND ptd.column = isc.column_name
      AND schemaname = $1
      AND tablename = $2
      ORDER BY ordinal_position
    }.gsub(/\s+/, ' ').strip
    rows = @redshift_connection.exec_params(query, [@schema_name, @table_name])
    if rows.count == 0
      raise sprintf('Table %s for schema %s not found', @table_name.inspect, @schema_name.inspect)
    else
      columns = rows.map do |row|
        name = row['column']
        type = row['type']
        nullable = row['notnull'] == 'f'
        Column.new(name, type, nullable)
      end
      columns
    end
  end
end

#to_big_queryObject


36
37
38
# File 'lib/bigshift/redshift_table_schema.rb', line 36

def to_big_query
  Google::Apis::BigqueryV2::TableSchema.new(fields: columns.map(&:to_big_query))
end