Strange Symphonies The whole is greater than the sum of its parts

21May/072

ActiveRecord Without Rails

Some of you must be wondering, I must be insane to use ActiveRecord outside of Rails. But there are some very compelling reasons.

  • ActiveRecord is an awesome library for Object Relational Mapping (ORM).
  • Other projects might not involve the use of Rails.
  • You want to experiment with ActiveRecord prior to creating a plugin for your Rails project.
  • A library for ORM is already written (why reinvent the wheel?)
  • Your just very bored.

Whatever the case may be, it's best to be prepared.

Installing ActiveRecord

If you already have Rails installed via RubyGems, then your already set to go. Else install it in the terminal via:

sudo gem install activerecord

Playing with ActiveRecord

Open up a file, and insert the following:

require 'rubygems'
require 'active_record'

ActiveRecord::Base.establish_connection(
  :adapter  => 'mysql',
  :database => 'database',
  :username => 'user',
  :password => 'password',
  :host     => 'localhost')

Now if you are familiar with Rails, this is the same configuration as seen in your database.yml file ( RAILS_ROOT/config/database.yml File). There are more options for how to connect to a database, just check the ActiveRecord::Base.establish_connection documentation.

Moving Database Configuration to Another File

Note: It's not safe to save your database configuration in the same file as you code. In case you distribute your code, and forget to remove your password. That wouldn't be a cool scenario. (Well it would also be pointless if you sent your database configuration file as well).

So lets make a database.yml and dump the information in there.

adapter: mysql
database:  database
username: user
password: password
host:      localhost

Now our previous file that utilizes ActiveRecord will look like such:

require 'rubygems'
require 'active_record'
require 'yaml'

dbconfig = YAML::load(File.open('database.yml'))
ActiveRecord::Base.establish_connection(dbconfig)

Playing with ActiveRecord Safely!

And now your set to playing around with ActiveRecord without Rails!

require 'rubygems'
require 'active_record'
require 'yaml'

dbconfig = YAML::load(File.open('database.yml'))
ActiveRecord::Base.establish_connection(dbconfig)

class User < ActiveRecord::Base
end

puts User.count
# 6

Debugging ActiveRecord SQL Queries

Sometimes you run into problems, and suspect your SQL isn't generated as it's supposed to be. But how do we debug this?

require 'rubygems'
require 'active_record'
require 'yaml'
require 'logger'

dbconfig = YAML::load(File.open('database.yml'))
ActiveRecord::Base.establish_connection(dbconfig)
ActiveRecord::Base.logger = Logger.new(STDERR)

class User < ActiveRecord::Base
end

puts User.count
# SQL (0.000277)   SELECT count(*) AS count_all FROM users
# 6

This will output it to standard error (in which most cases its) your screen. Sadly this can also clutter your screen.

Debugging ActiveRecord SQL Queries to a File

Now if you know your shell well, you can pipe it to a file via:

ruby connect.rb 2&gt;&gt; database.log

But you may forget to pipe it, or what not.

So replace the line containing ActiveRecord::Base.logger with

ActiveRecord::Base.logger = Logger.new(File.open('database.log', 'a'))

Warning: I chose to append ('a') the output to the file. This may result in very large files. You can chose to use overwrite ('w') instead.

From here on you can watch the file with: tail -f database.log [image16x16:terminal].

Funky/Colorized Logs

Note: If you view the database.log file, you'll notice the following. This is because ActiveRecord colorizes output for viewing in a terminal. But when viewed as a normal file, you get garbage.

  ^[[4;36;1mSQL (0.000273)^[[0m   ^[[0;1mSELECT count(*) AS count_all FROM users ^[[0m

To disable colorize logging, enter:

ActiveRecord.colorize_logging = false

Related posts

Tags

Comments (2) Trackbacks (0)
  1. I cant express the aewsome, thank you

  2. Hi Aizat,

    Thanks for this useful article.
    I’m developing an application dedicated to generate statistical reports, I would like that user after saving their stat report they save sql queries too. To do that I wrote the following module:
    module SqlHunter
    class ActiveRecord::ConnectionAdapters::AbstractAdapter

    @@queries = []
    cattr_accessor :queries
    def log_info_with_trace(sql, name, runtime)
    return unless @logger && @logger.debug?
    @@queries << sql
    end
    alias_method_chain :log_info, :trace
    end
    end

    in the controller I wrote that

    sqlfile = File.open("public/advancedStats/#{@dir_name}/advancedStatQuery.sql", 'w')
    @queries = ActiveRecord::ConnectionAdapters::AbstractAdapter::queries
    for query in @queries do
    sqlfile.write("#{query} \n")
    end
    sqlfile.close

    I also modified Rails environment by adding this line:

    ActiveRecord::Base.logger.level = Logger::DEBUG

    This program is working and I can get queries but, all queries. In contrast I need only the specific queries done by one user to generate a stat report.

    Do you have any idea to fix that,
    Thanks,

    mgatri


Leave a comment


No trackbacks yet.