I have just started to learn Ruby, quite nice language, but I’m stuck on
connecting to the database (Postgresql)
I have installed some ruby-pg and Ruby/DBI package for my Ubuntu system,
but then what?
I’m having trouble with finding the correct/best documentation on how to
connect and how to perform queries to the database.
Can someone point me in the right dirrection here?
Simple example code could perhaps also be of value to get me started.
I have just started to learn Ruby, quite nice language, but I’m stuck on
connecting to the database (Postgresql)
I have installed some ruby-pg and Ruby/DBI package for my Ubuntu system,
but then what?
You did google for “ruby DBI”? There’s a good introductory article on
kitebird.
However, DBI is a pretty old layer and not well maintained. I think that
most people would either:
(1) use a higher-level abstraction layer such as ActiveRecord,
Datamapper or Sequel. All three of those have good documentation, and
will happily sit on top of a postgres database; or
(2) use the ruby-pg layer directly (look at its documentation for
examples).
Option (2) arguably gives the best performance, but that’s irrelevant
because the time for the database to perform a SQL query will far
outweigh the time to send the request. Option (1) gives you much easier
ways to interact with the database, and also makes it easier for your
code to be database-independent.
On an Ubuntu system, my personal inclination is to ignore the
Ubuntu-provided packages and instead install everything as gems. That
gives you much more control and the ability to install more recent
packages (or specific versions of packages).
Performance, as ruby-pg interfaces directly with libpq. There are also
chances that postgres offers specific functionality only accessible
through a libpq interface. This comes down to the question of what the
specific use case is for interfacing with postgres.
I would personally recommend Sequel, even for performance. Although
ruby-pg is
more low level, it is very hard to fine tune every transaction. Sequel
by
default does a lot of caching in memory and comes with builtin database
connection pool. These can save great effort reimplementing by yourself
and also
boost you application performance. Not to mention Sequel also has got a
memchached plugin already just in case you want it. Using Postgres with
Sequel,
you still have access to bind variable and prepared statement
functionality
coming from ruby-pg, which can be fine tuned to further improve
performance.
Aside from performance, using high level library like Sequel makes your
application more portable and more readable.