Module: AppQuery

Defined in:
lib/app_query.rb,
lib/app_query/base.rb,
lib/app_query/version.rb,
lib/app_query/tokenizer.rb,
lib/app_query/render_helpers.rb

Overview

AppQuery provides a way to work with raw SQL queries using ERB templating, parameter binding, and CTE manipulation.

Examples:

Using the global function

AppQuery("SELECT * FROM users WHERE id = $1").select_one(binds: [1])
AppQuery("SELECT * FROM users WHERE id = :id").select_one(binds: {id: 1})

Loading queries from files

# Loads from app/queries/invoices.sql
AppQuery[:invoices].select_all

Configuration

AppQuery.configure do |config|
  config.query_path = "db/queries"
end

CTE manipulation

AppQuery(<<~SQL).select_all(select: "select * from articles where id = 1")
  WITH articles AS(...)
  SELECT * FROM articles
  ORDER BY id
SQL

Defined Under Namespace

Modules: RenderHelpers Classes: Base, Configuration, Error, Q, Result, Tokenizer, UnrenderedQueryError

Constant Summary collapse

VERSION =
"0.4.0"

Class Method Summary collapse

Class Method Details

.[](query_name, **opts) ⇒ Q

Loads a query from a file in the configured query path.

Examples:

Load a simple query

AppQuery[:invoices]  # loads app/queries/invoices.sql

Load from a subdirectory

AppQuery["reports/weekly"]  # loads app/queries/reports/weekly.sql

Load with explicit extension

AppQuery["invoices.sql.erb"]  # loads app/queries/invoices.sql.erb

Parameters:

  • query_name (String, Symbol)

    the query name or path (without extension)

  • opts (Hash)

    additional options passed to AppQuery::Q#initialize

Returns:

  • (Q)

    a new query object loaded from the file



87
88
89
90
91
# File 'lib/app_query.rb', line 87

def self.[](query_name, **opts)
  filename = File.extname(query_name.to_s).empty? ? "#{query_name}.sql" : query_name.to_s
  full_path = (Pathname.new(configuration.query_path) / filename).expand_path
  Q.new(full_path.read, name: "AppQuery #{query_name}", filename: full_path.to_s, **opts)
end

.configurationConfiguration

Returns the current configuration.

Returns:



47
48
49
# File 'lib/app_query.rb', line 47

def self.configuration
  @configuration ||= AppQuery::Configuration.new
end

.configure {|Configuration| ... } ⇒ Object

Yields the configuration for modification.

Examples:

AppQuery.configure do |config|
  config.query_path = "db/queries"
end

Yields:



59
60
61
# File 'lib/app_query.rb', line 59

def self.configure
  yield configuration if block_given?
end

.reset_configuration!void

This method returns an undefined value.

Resets configuration to default values.



66
67
68
69
70
# File 'lib/app_query.rb', line 66

def self.reset_configuration!
  configure do |config|
    config.query_path = "app/queries"
  end
end