Question

I've read all sequel's docs, but I could not find a way to create a database, assuming that I can do that.

I'm running a rake task as such:

require 'rubygems'
require 'bundler/setup'

require 'pg'
require 'sequel'

require 'yaml'
require 'erb'


namespace :db do

  task :connect do

  end


  task :create => :connect do

    puts db_config

    Sequel.connect(db_config['production']){ |db|

      db.create_table :user do
        primary_key :id

        String :name
        String :email

      end

      user = db[:user]


      user.insert(:name => 'Roland', :email => 'rolandjitsu@gmail.com')
    }

  end

  task :drop => :connect do

  end

end

def db_config
  YAML.load(ERB.new(File.read('config/database.yml')).result)
end

But obviously that will not create the database if it does not exist, so I am a bit unsure what I can do about it. When I run the task I get:

PG::ConnectionBad: FATAL:  database "pulsr" does not exist

And the database.yml file:

production: &production
  adapter: postgres
  host: localhost
  encoding: unicode
  database: pulsr
  username:
  password:

development:
  <<: *production

Does anyone know what I can do to create the database? Will that be a manual process as starting the postgresql server?

Was it helpful?

Solution 2

You can create a database with the CREATE DATABASE command.

When using postgresql, to create a database you first connect to the template1 database as a user with correct priveliges then issue the CREATE DATABASE command.

If you have shell access you can use the handy createdb shell command instead.

OTHER TIPS

You can do this with Sequel without having to resort to command line tools, which may not be available to you on every system on which your script is used.

Typically you will specify the 'postgres' database in order to fulfill the 'database' parameter requirement.

production = db_config['production']

Sequel.connect(production.merge('database' => 'postgres')) do |db|
  db.execute "DROP DATABASE IF EXISTS #{production['database']}"
  db.execute "CREATE DATABASE #{production['database']}"
end

Sequel.connect(production) do |db|
  # ...
end

This is how ActiveRecord does it, too.

Yes, this is a manual process. The database is part of the configuration where sequel should connect to, so it has to be there before sequel starts.

echo "create database REMOTE_TESTS" | mysql -u root

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top