Class: DrushDeploy::Database

Inherits:
Object
  • Object
show all
Defined in:
lib/drush_deploy/database.rb

Defined Under Namespace

Classes: ConfigNotFound, Error, FieldNotFound

Constant Summary collapse

STANDARD_KEYS =
%w(driver database username password host port prefix collation).map &:to_sym
MANAGE_KEYS =
%w(driver database username password host port prefix 
admin_username admin_password).map &:to_sym

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Database

Returns a new instance of Database.



30
31
32
33
34
# File 'lib/drush_deploy/database.rb', line 30

def initialize(config)
  @config = config
  @seen_paths = {}
  @db_status = {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args, &block) ⇒ Object



36
37
38
39
40
41
42
# File 'lib/drush_deploy/database.rb', line 36

def method_missing(sym, *args, &block)
  if @config.respond_to?(sym)
    @config.send(sym, *args, &block)
  else
    super
  end
end

Class Method Details

.deep_merge(h1, h2) ⇒ Object



305
306
307
308
# File 'lib/drush_deploy/database.rb', line 305

def self.deep_merge(h1,h2)
  merger = proc { |key,v1,v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 }
  h1.merge(h2, &merger)
end

.deep_update(h1, h2) ⇒ Object

Should split these out



294
295
296
297
298
299
300
301
302
303
# File 'lib/drush_deploy/database.rb', line 294

def self.deep_update(h1,h2)
  h1.inject({}) do |h,(k,v)|
    if Hash === v && Hash === h2[k]
      h[k] = deep_update(v,h2[k])
    else
      h[k] = h2.key?(k) ? h2[k] : v
    end
    h
  end
end

.each_db(databases) ⇒ Object



310
311
312
313
314
315
316
# File 'lib/drush_deploy/database.rb', line 310

def self.each_db(databases)
  databases.each do |site_name,site|
    site.each do |db_name,db|
      yield db,site_name,db_name
    end
  end
end

.url(db) ⇒ Object



318
319
320
321
322
323
# File 'lib/drush_deploy/database.rb', line 318

def self.url(db)
  missing_keys = %w(driver username password host port database).delete_if {|k| db.key? k.to_sym}
  throw FieldNotFound.new missing_keys unless missing_keys.empty?
  
  "#{db[:driver]}://#{db[:username]}:#{db[:password]}@#{db[:host]}:#{db[:port]}/#{db[:database]}"
end

Instance Method Details

#config(*args) ⇒ Object



172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/drush_deploy/database.rb', line 172

def config(*args)
  options = (args.size>0 && args.last.is_a?(Hash)) ? args.pop : {}
  db_name = args[0] || :default
  instance_name = args[1] || :default
  if databases[db_name] && databases[db_name][instance_name]
    conf = databases[db_name][instance_name].dup
  else
    throw ConfigNotFound.new db_name,instance_name
  end
  if options[:admin] && conf[:admin_username]
    conf[:username] = conf[:admin_username]
    conf[:password] = conf[:admin_password]
  end
  conf.merge options
end

#configureObject



44
45
46
47
48
49
# File 'lib/drush_deploy/database.rb', line 44

def configure
  databases_path.find do |val|
    set :databases, load_path( val, databases )
    MANAGE_KEYS.all? {|k| databases.key? k}
  end
end

#copy_database(from, to, conf_name = nil) ⇒ Object



252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/drush_deploy/database.rb', line 252

def copy_database(from,to,conf_name = nil)
  logger.info "Copying database #{from} to #{to}"
  tables = db_tables(nil,conf_name)
  conf = config(conf_name,:database => from, :admin => true)

  remote_sql("CREATE DATABASE #{to};", :config => conf)
  sql = ''
  tables.each do |table|
    sql += <<-END 
      CREATE TABLE #{to}.#{table} LIKE #{from}.#{table};
      INSERT INTO #{to}.#{table} SELECT * FROM #{from}.#{table};
    END
  end
  remote_sql(sql, :config => conf)
  @db_status.delete(to)
end

#db_empty?(db = nil, conf_name = nil) ⇒ Boolean

Returns:

  • (Boolean)


200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/drush_deploy/database.rb', line 200

def db_empty?(db = nil, conf_name = nil)
  conf = config(conf_name)
  conf[:database] = db if db
  db = conf[:database]
  if @db_status[db].nil?
    throw FieldNotFound.new 'database' unless conf[:database]
    logger.info "Fetching status of db #{conf[:database]}"
    sql = %q{SELECT count(*) FROM information_schema.tables 
             WHERE table_schema = '%{database}' LIMIT 1} % conf
    conf[:database] = 'information_schema'
    res = remote_sql(sql, :config => conf, :capture => true)
    @db_status[db] = res.split(/\n/)[1].to_i == 0
  end
  @db_status[db]
end

#db_exists?(db = nil, conf_name = nil) ⇒ Boolean

Returns:

  • (Boolean)


226
227
228
229
230
231
232
233
234
# File 'lib/drush_deploy/database.rb', line 226

def db_exists?(db = nil, conf_name = nil)
  conf = config(conf_name,:admin => true)
  conf[:database] = db if db
  throw FieldNotFound.new 'database' unless conf[:database]
  logger.info "Checking existence of #{conf[:database]}"
  sql = %q{SELECT COUNT(*) FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = '%{database}';} % conf
  conf[:database] = 'information_schema'
  remote_sql(sql, :config => conf, :capture => true).split(/\n/)[1].to_i != 0
end

#db_tables(db = nil, conf_name = nil) ⇒ Object



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/drush_deploy/database.rb', line 236

def db_tables(db = nil, conf_name = nil)
  conf = config(conf_name,:admin => true)
  conf[:database] = db if db
  db = conf[:database]
  throw FieldNotFound.new 'database' unless conf[:database]
  logger.info "Fetching table list of #{conf[:database]}"
  db_tables_query = %q{SELECT table_name FROM information_schema.tables
                       WHERE table_schema = '%{database}'
                         AND table_type = 'BASE TABLE'};
  sql = db_tables_query % conf
  conf[:database] = 'information_schema'
  tables = remote_sql(sql, :config => conf, :capture => true).split(/\n/)[1..-1] || []
  @db_status[db] = tables.size == 0
  tables
end

#db_versions(db = nil, conf_name = nil) ⇒ Object



216
217
218
219
220
221
222
223
224
# File 'lib/drush_deploy/database.rb', line 216

def db_versions(db = nil, conf_name = nil)
  conf = config(conf_name,:admin => true)
  conf[:database] = db if db
  throw FieldNotFound.new 'database' unless conf[:database]
  logger.info "Getting list of databases versions"
  sql = %q{SELECT SCHEMA_NAME FROM information_schema.SCHEMATA
           WHERE SCHEMA_NAME REGEXP '%{database}_[0-9]+';} % conf
  (remote_sql(sql, :config => conf, :capture => true).split(/\n/)[1..-1] || []).sort.reverse
end

#drop_database(db, conf_name = nil) ⇒ Object



286
287
288
289
290
291
# File 'lib/drush_deploy/database.rb', line 286

def drop_database(db,conf_name = nil)
  logger.info "Dropping database #{db}"
  conf = config(conf_name,:database => db, :admin => true)
  remote_sql("DROP DATABASE #{db};", :config => conf)
  @db_status[db] = false
end

#load_path(path, databases = {}) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/drush_deploy/database.rb', line 51

def load_path(path,databases = {})
  unless @seen_paths[path]
    logger.info "Trying to load database setting from #{path.inspect}"
    if path !~ /^[\/~]/
      path = latest_release+"/"+path
    end
    if path =~ /.php$/
      @seen_paths[path] = load_php_path path
    elsif path =~ /.yml$/
      @seen_paths[path] = load_yml_path path
    else
      throw Error.new "Unknown file type: #{path}"
    end
  end
  DrushDeploy::Database.deep_merge(@seen_paths[path],databases)
end

#load_php_path(path) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/drush_deploy/database.rb', line 68

def load_php_path(path)
  prefix = ''
  if path.sub!(/^~/,'')
    prefix = "getenv('HOME')." 
  end

  script = <<-END.gsub(/^ */,'')
    <?php
    $filename = #{prefix}'#{path}';
    if( file_exists($filename) ) {
      require_once($filename);
      if( isset($databases) ) {
        print serialize($databases);
      }
    } 
  END

  tmp = capture('mktemp').strip
  put script, tmp, :once => true
  resp = capture "#{remote_drush} php-script '#{tmp}' && rm -f '#{tmp}'"
  
  settings = {}
  unless resp.empty?
    resp = DrushDeploy::Configuration.unserialize_php(resp)
    if resp != []
      settings = resp
    end
  end
  settings
end

#load_yml_path(path) ⇒ Object



99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/drush_deploy/database.rb', line 99

def load_yml_path(path)
  prefix = ''
  if path.sub!(/^~/,'')
    prefix = '"$HOME"'
  end

  yaml =  capture("[ ! -e #{prefix}'#{path}' ] || cat #{prefix}'#{path}'")
  if yaml.empty?
    {}
  else
    credentials = YAML.load yaml
    DrushDeploy::Configuration.normalize_value(credentials)
  end
end

#remote_sql(sql, options = {}) ⇒ Object



188
189
190
191
192
193
194
195
196
197
198
# File 'lib/drush_deploy/database.rb', line 188

def remote_sql(sql,options={})
  url = options[:config] ? DrushDeploy::Database.url(options[:config]) : nil
  tmp = capture('mktemp').strip
  put(sql,tmp)
  cmd = %Q{cd '#{latest_release}' && #{remote_drush} sql-cli #{url ? "--db-url='#{url}'" : ''} < '#{tmp}' && rm -f '#{tmp}'}
  if options[:capture]
    capture(cmd)
  else
    run cmd, :once => true
  end
end

#rename_database(from, to, conf_name = nil) ⇒ Object



269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/drush_deploy/database.rb', line 269

def rename_database(from,to,conf_name = nil)
  logger.info "Renaming database #{from} to #{to}"
  conf = config(conf_name,:database => from, :admin => true)
  sql = ''
  if conf[:driver] == :mysql
    sql += "CREATE DATABASE `#{to}`;"
    db_tables(from,conf_name).each do |table|
      sql += "RENAME TABLE `#{from}`.`#{table}` TO `#{to}`.`#{table}`;"
    end
    sql += "DROP DATABASE `#{from}`;"
  else
    sql += "ALTER TABLE #{from} RENAME TO #{to};"
  end
  remote_sql(sql, :config => conf)
  @db_status.delete(to)
end

#update_settings(settings, template = 'sites/default/default.settings.php') ⇒ Object



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/drush_deploy/database.rb', line 114

def update_settings(settings,template = 'sites/default/default.settings.php')
  if template !~ /^[\/~]/
    template = latest_release+"/"+template
  end
  prefix = ''
  if template.sub!(/^~/,'')
    prefix = "getenv('HOME')." 
  end
  script = <<-END.gsub(/^ */,'')
    <?php
    define('DRUPAL_ROOT', '#{latest_release}');
    define('MAINTENANCE_MODE', 'install');

    $template = #{prefix}'#{template}';
    $default = DRUPAL_ROOT.'/sites/default/default.settings.php';
    $backup = '/tmp/default_settings_backup.php';

    $databases = unserialize('#{PHP.serialize(settings)}');
    $comment = 'Generated by drush-deploy';
    $version = explode('.',drush_drupal_version());
    if($version[0] < 7) {
      $vals = $databases['default']['default'];
      $db_url = sprintf('%s://%s:%s@%s:%s/%s',
        $vals['driver'],$vals['username'],$vals['password'],
        $vals['host'], $vals['port'], $vals['database']);
      $settings["db_url"] = array( 'comment' => $comment,
                                      'value' =>  $db_url);
      $settings["db_prefix"] = array( 'comment' => $comment,
                                      'value' =>  $vals['prefix']);
    } else {
      $settings["databases"] = array( 'comment' => $comment,
                                      'value' => $databases );
    }

    require_once(DRUPAL_ROOT.'/includes/bootstrap.inc');
    require_once(DRUPAL_ROOT.'/includes/install.inc');

    $backed_up = false;
    if ($template != $default && file_exists($default)) {
      rename($default,$backup);
      $backed_up = true;
    }
    rename($template,$default);
    drupal_rewrite_settings($settings);
    if ($backed_up) {
      rename($backup,$default);
    }
    __END__
  END

  run %Q{TMP=`mktemp` && sed -n '/^__END__$/ q; p' > $TMP && cd '#{latest_release}' && #{remote_drush} php-script $TMP && rm -f "$TMP"},
      :data => script
end

#updatedbObject



168
169
170
# File 'lib/drush_deploy/database.rb', line 168

def updatedb
  run "cd '#{latest_release}' && #{remote_drush} updatedb --yes", :once => true
end