Class: ActiveRecord::Tasks::SpannerDatabaseTasks

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record/tasks/spanner_database_tasks.rb

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ SpannerDatabaseTasks

Returns a new instance of SpannerDatabaseTasks.



12
13
14
15
# File 'lib/active_record/tasks/spanner_database_tasks.rb', line 12

def initialize config
  config = config.symbolize_keys
  @connection = ActiveRecordSpannerAdapter::Connection.new config
end

Instance Method Details

#charsetObject



41
42
43
# File 'lib/active_record/tasks/spanner_database_tasks.rb', line 41

def charset
  nil
end

#collationObject



45
46
47
# File 'lib/active_record/tasks/spanner_database_tasks.rb', line 45

def collation
  nil
end

#createObject



17
18
19
20
21
22
23
24
25
# File 'lib/active_record/tasks/spanner_database_tasks.rb', line 17

def create
  @connection.create_database
rescue Google::Cloud::Error => error
  if error.instance_of? Google::Cloud::AlreadyExistsError
    raise ActiveRecord::DatabaseAlreadyExists
  end

  raise error
end

#dropObject



27
28
29
# File 'lib/active_record/tasks/spanner_database_tasks.rb', line 27

def drop
  @connection.database.drop
end

#purgeObject



31
32
33
34
35
36
37
38
39
# File 'lib/active_record/tasks/spanner_database_tasks.rb', line 31

def purge
  begin
    drop
  rescue ActiveRecord::NoDatabaseError # rubocop:disable Lint/HandleExceptions
    # ignored; create the database
  end

  create
end

#structure_dump(filename, _extra_flags) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/active_record/tasks/spanner_database_tasks.rb', line 49

def structure_dump filename, _extra_flags
  file = File.open filename, "w"
  ignore_tables = ActiveRecord::SchemaDumper.ignore_tables

  if ignore_tables.any?
    index_regx = /^CREATE(.*)INDEX(.*)ON (#{ignore_tables.join "|"})\(/
    table_regx = /^CREATE TABLE (#{ignore_tables.join "|"})/
  end

  @connection.database.ddl(force: true).each do |statement|
    next if ignore_tables.any? &&
            (table_regx =~ statement || index_regx =~ statement)
    file.write statement
    file.write ";\n"
  end
ensure
  file.close
end

#structure_load(filename, _extra_flags) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/active_record/tasks/spanner_database_tasks.rb', line 68

def structure_load filename, _extra_flags
  statements = File.read(filename).split(/;/).map(&:strip).reject(&:empty?)
  ddls = statements.select { |s| s =~ /^(CREATE|ALTER|DROP|GRANT|REVOKE|ANALYZE)/ }
  @connection.execute_ddl ddls

  client = @connection.spanner.client @connection.instance_id,
                                      @connection.database_id
  dmls = statements.reject { |s| s =~ /^(CREATE|ALTER|DROP|GRANT|REVOKE|ANALYZE)/ }

  client.transaction do |tx|
    dmls.each { |dml| tx.execute_query dml }
  end
end