Monday, September 6, 2010

Testing sequel to access PostgreSQL

# seq01pg.rb

require 'rubygems'
require 'sequel'

class SequelTest

  def initialize
    
    @db =  Sequel.postgres('mydb', :host=>'localhost', :user=>'socrateos', :password=>'secret')
    
    unless(@db.table_exists?(:table1))
      @db.create_table :table1 do
        primary_key :id
        String :title
      end
    end
  
    unless(record_exists?(:table1, :title, 'test1'))
      @db[:table1].insert(:id => 1, :title => 'test1')
    end
  
    unless(record_exists?(:table1, :title, 'test2'))
      @db[:table1].insert(:id => 2, :title => 'test2')
    end
 
    unless(record_exists?(:table1, :title, 'test3'))
      @db[:table1].insert(:id => 3, :title => 'test3')
    end
  
  end

  def record_exists?(table, field, value)
    rows = @db[table].where(field => value)
    return (rows.count>0)
  end
  
  def show_all
    p "Database type:" + @db.database_type.to_s
    @db.fetch('select * from table1') do |row|
      p row
    end
  end
 
end

app = SequelTest.new
app.show_all


Run it:
$ ruby seq01pg.rb 
"Database type:postgres"
{:title=>"test1", :id=>1}
{:title=>"test2", :id=>2}
{:title=>"test3", :id=>3}

No comments:

Post a Comment