Eql

Build Status Code Climate Version Eye Inline docs Gem Version

Eql provides an ability to create raw DB queries via ERB templates.

Installation

Add this line to your application's Gemfile:

gem 'eql'

Usage

Simple usage

# queries/insert.sql.erb
<% each do |item| %>
  INSERT INTO items (category, name)
    VALUES (<%= item.values_at(:category, :name).map { |i| quote(i) }.join(', ') %>)
    ON CONFILICT (category, name) DO NOTHING;
<% end %>
b = Eql.new('queries')
b.execute(:insert, [{category: 'cars', name: 'BMW'}, {category: 'cars', name: 'AUDI'}])

Inline templates

b = Eql.template <<-ERB
  SELECT products
    FROM customer c
      LEFT JOIN products p ON (c.id = p.customer_id)
    WHERE c.id = <%= quote(id) %>
ERB
b.execute_params(id: 74)

Usage with Rails

# config/initializers/eql.rb

Eql.configure do |config|
  config.path = Rails.root.join('app/queries')
  config.adapter = :active_record
  config.cache_templates = !Rails.env.development?
end
# app/queries/fresh_items.sql.erb
SELECT *
  FROM items
  WHERE outdated IS DISTINCT FROM TRUE
  LIMIT <%= limit %>
  outdated = Eql.execute(:fresh_items, limit: 10)

Create your own adapter

class BashAdapter < Eql::Adapters::Base
  def self.match?(conn)
    conn == :my_bash
  end

  def command
    "bash << eof\n" \
      "#{render}\n" \
    "eof\n"
  end


  def execute
    `#{command}`
  end
end

Eql.register_adapter(:my_bash, BashAdapter)

b = Eql.new(nil, :my_bash)
b.template <<-COMMAND
  mkdir -p <%= folder %>
  find . -name *.rb -not *_spec.rb -type f -exec mv {} <%= folder %> \;
  ls folder/*
COMMAND
b.execute_params(folder: 'units')

Adapters

Now implemented only ActiveRecord adapter. Please, fill free to contribute on a new adapter.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/zoer/eql.

License

The gem is available as open source under the terms of the MIT License.