ActiveQuery
SQL & Ruby
Ideal for reports, large queries, separating SQL from code logic, query optimization, command and query responsibility segregation (CQRS)
Ruby is a great language for writing DSLs, but we don't need a new one. SQL is already a mature DSL. (Don't agree? Wait until this extra syntax layer breaks down and you start wrestling with a (raw-sql) function.) ~ Kris Jenkins (yesql)
-- name: find_product
-- example with params
SELECT * FROM products
WHERE units_in_stock > :units
AND product_name LIKE ':name';
-- name: insert_category
INSERT INTO categories (category_id, category_name, description)
VALUES(<%= rand 248...599 %>, 'books', 'ruby books');
ActiveQuery.users_by_country # return raw sql
# You use symbols as params
ActiveQuery.run(:users_by_country) # run query as full-scan
# async call, stream the results Postgres only
ActiveQuery.async_run(:all_users) {|u| puts u["name"] }
Installation
Add this line to your application's Gemfile:
gem 'activequery'
And then execute:
$ bundle
Or install it yourself as:
$ gem install activequery
Usage
Create template dir inside your app
mkdir -p app/sqltemplates
touch app/sqltemplates/my_query.sql
Add created path to config For Rails users:
activequery rails
Configure:
ActiveQuery.configure do |config|
config.template_path = "."
config.adapter = :postgres
config.connection = "dbname=rails6pg_development user=dev"
end
TODO:
- [x] Ruby On Rails easy integration
- [x] PostgreSQL Adapter
- [x] Ruby erb inside sql template files
- [x] Async/Stream results (ideal for realtime reporting/analytics)
- [x] Named parameters
- [ ] ?-style positional parameters
- [ ] class: MyClass param to create or extend ruby class with
- [ ] Import/Export to Materialized Views
- [ ] Retrieving SQL templates from custom stores (Redis, Riak)
- [ ] Add connection pooling. (If you use this with Rails ActiveRecord has its own connection pool)
- [ ] Add Actors/Workers
- [ ] MySQL and SQLite providers
- [ ] Generate CRUD
Dev Notes:
# create demo database (sudo su postgres)
rake db:create
rake db:import
rake db:drop
# tests
rake test:unit
rake test:integration
rake test:system
rake test:bench
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/mtunjic/activequery.
License
The gem is available as open source under the terms of the MIT License.