Last Updated: February 25, 2016
·
848
· erickbrower

Ruby vs Clojure: Get a List of DB Tables

Here's a bite-sized example from some code I was just working on. In the test suite for a Clojure web service, I needed a quick function to query for a list of all the tables in the Postgres DB so I could truncate them as part of a fixture. Here's the Clojure:

(ns example
  (:require [korma.core :refer [exec-raw]]))

(def all-tables
  (map #(:table_name %) 
       (exec-raw [(str "SELECT table_name "
                       "FROM information_schema.tables "
                       "WHERE table_schema='public' "
                       "AND table_type='BASE TABLE'")] :results)))

And for comparison, here's how that might look in Ruby:

require 'activerecord'

def all_tables
  query = <<-SQL
  SELECT table_name 
  FROM information_schema.tables 
  WHERE table_schema='public' AND table_type='BASE TABLE'
  SQL
  results = ActiveRecord::Base.connection.execute query
  results.map { |r| r[:table_name] }
end

Notice the similarities? The Ruby is read top to bottom, but the Clojure is read from the inside out. The flow is essentially:

  1. Create a sql query string
  2. Execute it against a database
  3. Apply this anonymous function to each of the results
  4. Implicitly return the new collection

Even read start to end, I think the Clojure code explains itself pretty well. "Map this function over the collection of stuff that this query returns". Of course Ruby wins at simplicity, but Clojure continues to surprise me with how expressive it can be. Once you get used to all those parentheses. :)