Module: DbMod::Statements::Prepared

Includes:
Params
Defined in:
lib/db_mod/statements/prepared.rb

Overview

Provides the def_prepared function which allows DbMod modules to declare prepared SQL statements that will be added to the database connection when DbMod#db_connect is called.

For statements that are not prepared ahead of execution, see def_statement in Statement.

def_prepared


def_prepared accepts two parameters:

  • `name` [Symbol]: The name that will be given to the prepared statement. A method will also be defined on the module with the same name which will call the statement and return the result.

  • `sql` [String]: The SQL statement to be prepared. Parameters may be declared using the $ symbol followed by a number ($1, $2, $3) or a name ($one, $two, $under_scores). The two styles may not be mixed in the same statement. The defined function can then be passed parameters that will be used when the statement is executed.

### example

module MyModule
  include DbMod

  def_prepared :my_prepared, <<-SQL
    SELECT *
      FROM stuff
     WHERE a = $1 AND b = $2
  SQL

  def_prepared :my_named_prepared, <<-SQL
    SELECT *
      FROM stuff
     WHERE a = $a AND b = $b
  SQL
end

include MyModule
db_connect db: 'mydb'
my_prepared(1,2)
my_named_prepared(a: 1, b: 2)

Constant Summary

Constants included from Params

DbMod::Statements::Params::NAMED_OR_NUMBERED, DbMod::Statements::Params::NAMED_PARAM, DbMod::Statements::Params::NUMBERED_PARAM

Class Method Summary collapse

Methods included from Params

parse_named_params!, parse_numbered_params!, parse_params!, valid_named_args!, valid_sql_params!

Class Method Details

.setup(mod) ⇒ Object

Defines a module-specific def_prepared function for a module that has just had DbMod included.

Parameters:

  • mod (Module)

57
58
59
60
61
62
# File 'lib/db_mod/statements/prepared.rb', line 57

def self.setup(mod)
  Prepared.define_def_prepared(mod)
  Prepared.define_prepared_statements(mod)
  Prepared.define_inherited_prepared_statements(mod)
  Prepared.define_prepare_all_statements(mod)
end