Run sql script from Ruby - ruby

Using DBI::DatabaseHandle#execute or DBI::DatabaseHandle#prepare it's not possible to run an sql script (with mutiple sql statments). It fails with the following error :
ERROR: cannot insert multiple commands into a prepared statement
I tried to use the "unprepared" way using DBI::DatabaseHandle#do (the doc says it "goes straight to the DBD‘s implementation") but it keeps throwing the same error.
code snippet:
require 'dbd/pg'
require 'dbi'
DBI.connect("dbi:pg:database=dbname", db_user, db_password, db_params) do |dbh|
schema = IO::read(schema_file)
dbh.do(schema)
end
I'm using
ruby 1.8.6 (2007-09-24 patchlevel 111) [i386-mswin32]
dbi-0.4.3
dbd-pg-0.3.9
pg-0.9.0-x86-mswin32
Thank you!

Use either a function or just run multiple prepared queries.

Running multiple queries using DatabaseHandle#do is a missing feature in DBD-Pg. See Ruby/DBI feature 28001.
Note that Pg, the native postgresql Ruby driver on which DBD-Pg is based, allows running multiple queries.
Example:
require 'pg'
require 'dbd/pg'
require 'dbi'
# Pg Succeeds
PGconn.new({:host=>host,:user=>user,:password=>password,:dbname=>dbname}) do |conn|
conn.exec("select 1; select 1;")
end
# DBD-Pg Fails with: ERROR: cannot insert multiple commands ...
DBI::connect("dbi:pg:database=#{dbname};host=#{host};", user, password) do |dbh|
dbh.do("select 1; select 1;")
end

Related

ActiveRecord Schema Dump without rails

In rails you can setup a rails app, assign the right db driver (I need firebird/fb) and then do a rake db:schema:dump pretty much out of the box.
I'm trying to do a version control for my database schema. How can I just make a ruby script that requires activerecord and fb libraries and achieve the same thing. I dont' need an entire rails app. All I want is a consistent script to extract the schema.
Looking at the source of the db:schema:dump task, the following code should get you started:
require 'active_record'
require 'active_record/schema_dumper'
require 'activerecord-fb-adapter'
filename = './schema.rb'
ActiveRecord::Base.establish_connection(
adapter: 'fb',
database: 'db/development.fdb',
username: 'SYSDBA',
password: 'masterkey',
host: 'localhost',
encoding: 'UTF-8',
create: true
)
File.open(filename, "w:utf-8") do |file|
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
end
I just happen to have been working on something similar except for the firebird/fb part.
require "yaml"
require "active_record"
include ActiveRecord
include ActiveRecord::Tasks
ActiveRecord::Migrator.migrations_path='./db/migrate'
DatabaseTasks.db_dir = './db'
db_config_file = "./config/database.yml"
db_config = YAML.load_file(db_config_file)
db_type = 'development'
db_object = db_config[db_type]
#sldbtask = SQLiteDatabaseTasks.new(db_object, './')
unless File.exist?(db_object['database'])
#sldbtask.create
#sldbtask.connection
# try different migation versions
migration_version = 0
ActiveRecord::Migrator.run(:up, ActiveRecord::Migrator.migrations_path, migration_version)
end
unless File.exist?('./db/schema.rb')
#DatabaseTasks.check_schema_file('./db/schema.rb')
File.open('./db/schema.rb', "w:utf-8") do |file|
#sldbtask.establish_connection(db_object)
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
end
end
Of course my adapter is different but it could be modified and it's versatile with a Rails app so you could drop the code part into the root directory. But of course you can rake for that but this just shows that it works. Tou might nave problems with the migration version though. I haven't thoroughly tested it.

require ruby library in serverspec

I am a newbie in ruby and trying to get my hands dirty in chef. I have written a wrapper cookbook on postgresql community cookbook and wish to test it using test kitchen. Following is the spec.rb file I have written:
require 'serverspec'
require 'pg'
include Serverspec::Helper::Exec
include Serverspec::Helper::DetectOS
RSpec.configure do |c|
c.before :all do
c.path = '/sbin:/usr/sbin'
c.os = backend(Serverspec::Commands::Base).check_os
end
end
describe "Postgresql server" do
it "should connect to database" do
conn = PG::Connection.open(:dbname => "db",:user => "user1",:password => "password")
conn.status == "CONNECTION_OK"
end
end
Through this test I wish to check if the user and database have been created properly.
However this test is unable to resolve the dependency of "pg". Where do I mention this dependency in serverspec?
I have used kitchen verify [node name] to run the test.
Create the Ruby code necessary to install the gem prior to requiring it in your spec_helper.rb file (or on the top of the spec file if it makes more sense):
begin
Gem::Specification.find_by_name('pg')
rescue Gem::LoadError
require 'rubygems/dependency_installer'
Gem::DependencyInstaller.new(Gem::DependencyInstaller::DEFAULT_OPTIONS).install('pg')
end
require 'pg'

'cannot load such file -- mongoid' with rspec with ruby 2

Getting this error
cannot load such file -- mongoid
when trying to run RSpec tests.
I have mongo running in another terminal (mongod)
with ruby 2.0
I've trying including gem 'moped' and bundled but got the same error.
Trying to find out how to fix this error and run my tests.
This is for an open-source project that I've forked and am trying to update.
The test starts with:
require 'spec_helper'
begin
require 'will_paginate/mongoid' # <-- this is the issue
rescue LoadError => error
warn "Error running Sequel specs: #{error.message}"
mongoid_loaded = false
else
Mongoid.database = Mongo::Connection.new.db('will_paginate_test')
class MongoidModel
include Mongoid::Document
end
mongoid_loaded = true
end
describe...
I commented out require 'will_paginate/mongoid' but I then got uninitialized constant Mongoid (NameError)

Using SSPI with Ruby TinyTDS - possible?

After some anguish trying to connect to a SQLServer database with Ruby, I finally discovered TinyTDS and it's fantastic.
However, it requires a username and password to talk to the database. In C# tests in the past, we've used SSPI to supply this, so that any tester can pick up a script and run it and it'll use their Windows Authentication details.
I can't find a way to do this with TDS (beginning to suspect it's not possible with the current version) and hoping someone might prove me wrong, or have another suggestion?
Cheers.
Found the solution.
My install of tiny-tds was version 0.51.
The latest version has SSPI, and so to get that:
gem install tiny_tds --version ">= 0.6.0.rc1"
This comes with no need to specify a username/password and use SSPI by default.
So as an example:
require 'tiny_tds'
sql = "SELECT name from sys.databases"
client = TinyTds::Client.new(:dataserver => "myserver", :database => "mydatabase")
result = client.execute(sql)
results = result.each(:symbolize_keys => true, :as => :array, :cache_rows => true, :empty_sets => true) do |rowset| end
#THIS IS TO OUTPUT IT TO THE CONSOLE
for i in (0..result.fields.length)
printf("%14s", result.fields[i])
end
for j in (0...result.affected_rows)
puts ""
for i in (0...result.fields.length)
printf("%14s",results[j].at(i))
end
end
Will print out a list of the database names, using SSPI to access the database.

Sinatra heroku database access

I have a sinatra ruby app in heroku. I am trying to access the database via the console.When I run the heroku run console , I am getting the following error.
Running console attached to terminal... up, run.10
/app/vendor/ruby-1.9.2/lib/ruby/1.9.1/irb/init.rb:281:in `require':LoadError: no such file to load -- ./console.
When I try to access the record using the following command, I am getting the following error :
irb(main):001:0> Setting.first
NameError: uninitialized constant Object::Setting
from (irb):1
from bin/irb:12:in `<main>'
Can anyone help me in what needs to be done. Am I missing some file or Is there a different way to access the tables in heroku?
The heroku console thing is an old hack for rails apps, but it won't work elsewhere. As you can see from the output, it's trying to load a file called ./console. So, create a console file on your project root, and invoke IRB from it after having connected to your database. For example:
#!/usr/bin/env ruby
require 'irb'
require 'irb/completion'
require 'rubygems'
require 'bundler/setup'
# require something that connects to your database
# or just connect here using ENV['DATABASE_URL']
require 'your_project_setup'
IRB.start

Resources