Class: BqFakeView

Inherits:
Object
  • Object
show all
Defined in:
lib/bq_fake_view.rb,
lib/bq_fake_view/version.rb

Defined Under Namespace

Classes: CastError, FieldNotFound

Constant Summary collapse

VERSION =
"0.1.2"

Instance Method Summary collapse

Constructor Details

#initialize(auth) ⇒ BqFakeView

Returns a new instance of BqFakeView.



11
12
13
14
15
# File 'lib/bq_fake_view.rb', line 11

def initialize(auth)
  @bigquery = Google::Apis::BigqueryV2::BigqueryService.new
  @bigquery.authorization = auth
  @bigquery
end

Instance Method Details

#create_view(project_id, dataset_id, name, rows, schema) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/bq_fake_view.rb', line 17

def create_view(project_id, dataset_id, name, rows, schema)
  query = view_query(rows, schema)

  @bigquery.insert_table(project_id, dataset_id, Google::Apis::BigqueryV2::Table.new({
    table_reference: {
      project_id: project_id,
      dataset_id: dataset_id,
      table_id: name,
    },
    view: {
      query: query
    },
  }))
end

#sql_from_hash(row, schema) ⇒ Object



39
40
41
42
43
44
45
46
47
# File 'lib/bq_fake_view.rb', line 39

def sql_from_hash(row, schema)
  cols = row.map do |k, v|
    field = schema.find { |f| f[:name].to_s == k.to_s }
    raise FieldNotFound, "#{k} is not found from schema" unless field
    "#{cast_to_sql_value(v, field[:type])} as #{k}"
  end

  "SELECT #{cols.join(", ")}"
end

#view_query(rows, schema) ⇒ Object



32
33
34
35
36
37
# File 'lib/bq_fake_view.rb', line 32

def view_query(rows, schema)
  subqueries = rows.map do |r|
    "(#{sql_from_hash(r, schema)})"
  end
  "SELECT * FROM #{subqueries.join(", ")}"
end