Gem Version Dependency Status Code Climate Test Coverage Build Status

SqlQuery

Ruby gem to load SQL queries from .sql.erb templates using ERB.

It makes working with pure SQL easier with syntax highlighting. Let's you clean your Ruby code from SQL strings.

Installation

Add this line to your application's Gemfile:

gem 'sql_query'

And then execute:

$ bundle

Or install it yourself as:

$ gem install sql_query

Usage

Create SQL query in file in app/sql_queries directory

# app/sql_queries/get_player_by_email.sql.erb
SELECT *
FROM players
WHERE email = <%= quote @email %>

You can use SQL like this:

> query = SqlQuery.new(sql_name: :get_player_by_email, email: '[email protected]')

> query.execute
   (0.6ms)  SELECT * FROM players WHERE email = '[email protected]'
=> []

> query.explain
=> EXPLAIN for:
SELECT *
FROM players
WHERE email = '[email protected]'

                        QUERY PLAN
----------------------------------------------------------
 Seq Scan on players  (cost=0.00..2.14 rows=1 width=5061)
   Filter: ((email)::text = '[email protected]'::text)
(2 rows)

> query.sql
=> "SELECT *\nFROM players\nWHERE email = '[email protected]'\n"

>  query.pretty_sql
=> SELECT *
FROM players
WHERE email = '[email protected]'

Methods

  • execute - executes query and returns result data.

  • explain - runs explain for SQL from template

  • sql - returns SQL string

  • pretty_sql - returns SQL string prettier to read in console

  • prepared_for_logs - returns sql string without new lines and multiple whitespaces.

Contributing

  1. Fork it ( https://github.com/[my-github-username]/sql_query/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request