Moebius.Query

The main query interface for Moebius. Import this module into your code and query like a champ

Summary

Functions

Executes a given pipeline and returns all results. An alias for to_list/2

Executes a COUNT query based on the assembled pipeline. Analagous to map/reduce(:count). Returns an integer

Specifies the table or view you want to query and is an alias for the with/1 function using a string as a table name. This is useful for specifying a table within a schema

Deletes a record based on your filter. Example:

Deletes a record based on your filter, part of a transaction

Creates a DELETE command

Executes a command, returning a list of results

Executes a command, returning a list of results as part of a transaction

Executes a pass-through query and returns a single result as part of a transaction

Builds a parameterized WHERE statement with ANDs for each passed list item

Builds a parameterized WHERE statement based on the passed in string. This is useful for queries that pass in string information that you want to protect from SQL Injection

Executes a given pipeline and returns the first matching result. You should specify a sort to be sure first works as intended

Executes a function with the given name, passed as an atom

Executes a function with the given name, passed as an atom, returning a single result

Executes a function with the given name, passed as an atom, returning a single result

Specifies a GROUP BY for a map/reduce (aggregate) query that is a string

A simple insert that that returns the inserted record. Create your list of data and send it on in

A simple insert that is part of a transaction that returns the inserted record. Create your list of data and send it on in

Creates an insert command based on the assembled pipeline

Build a table join for your query. There are a number of options to handle various joins. Joins can also be piped for multiple joins

Executes a given pipeline and returns the last matching result. You should specify a sort to be sure first works as intended

Sets the limit of the return

An alias for filter, specifies a range to rollup on for an aggregate query using a WHERE statement

Offsets the limit and is an alias for skip/1

A rollup operation that aggregates the mapped result set by the specified operation

Executes a raw SQL query with parameters

Executes a raw SQL query with parameters returning a single result

Full text search using Postgres’ built in indexing, ranked using tsrank. This query will result in a full table scan and is not optimized for large result sets. For better results, create a tsvector field and populate it with a trigger on insert/update. This will cause some side effects, one of them being that Postgrex, the Elixir driver we use, doesn’t know how to resolve the tsvector type, and will throw

Creates a SELECT command based on the assembled pipeline. Uses the QueryCommand as its core structure

Offsets the limit and is an alias for offset/1

Sets the order by. Ascending using :asc is the default, you can send in :desc if you like

Executes the SQL in a given SQL file without parameters. Specify the scripts directory by setting the scripts directive in the config. Pass the file name as an atom, without extension

Executes the SQL in a given SQL file with the specified parameters. Specify the scripts directory by setting the scripts directive in the config. Pass the file name as an atom, without extension

Executes the SQL in a given SQL file with the specified parameters, returning a single result. Specify the scripts directory by setting the scripts directive in the config. Pass the file name as an atom, without extension

Creates a SQL File command

Executes a given pipeline and returns all results. An alias for all/2

Opens a transaction, returning a pid (Process ID) that you can pass to each of your queries that take part in the transaction. If an error occurs, it is passed back to you with {:error, message}. The transaction will automatically COMMIT on completion

A bulk update based on the criteria you specify. All changed records are returned

A simple update based on the criteria you specify. This is a partial update. Returns a single record as a result when you pass :single

A simple update that is part of a transaction based on the criteria you specify. This is a partial update. Returns a single record as a result when you pass :single

Creates an update command based on the assembled pipeline

Specifies the table or view you want to query and is an alias for the db/1 function using a string as a table name. This is useful for specifying a table within a schema

Functions

all(cmd, cols \\ "*")

Executes a given pipeline and returns all results. An alias for to_list/2

cols - Any columns (specified as a string) that you want to have aliased or restricted in your return.

For example `now() as current_time, name, description`. Defaults to "*"

Example:

all_users = db(:users)
  |> all("first, last, email")
count(cmd)

Executes a COUNT query based on the assembled pipeline. Analagous to map/reduce(:count). Returns an integer.

Example:

count = db(:users)

|> limit(20)
|> count

#count == 20

db(table)

Specifies the table or view you want to query and is an alias for the with/1 function using a string as a table name. This is useful for specifying a table within a schema.

“table” - the name of the table you want to query, such as membership.users

Example

result = db("membership.users")
  |> to_list
delete(cmd)

Deletes a record based on your filter. Example:

db(:users)
  |> filter("id > $1", 1)
  |> delete
delete(cmd, pid)

Deletes a record based on your filter, part of a transaction.

pid: - The process id from the current transaction callback.

Example:

transaction fn(pid) ->
  db(:users)
    |> filter("id > $1", 1)
    |> delete(pid)
end
delete_command(cmd)

Creates a DELETE command

execute(cmd)

Executes a command, returning a list of results

execute(cmd, pid)

Executes a command, returning a list of results as part of a transaction

execute(cmd, atom, pid)

Executes a pass-through query and returns a single result as part of a transaction

filter(cmd, criteria)

Builds a parameterized WHERE statement with ANDs for each passed list item.

criteria - email: 'test@test.com', company: 'Test Company'

Example:

result = db(:products)
    |> filter(email: 'test@test.com', company: 'Test Company')
    |> to_list
filter(cmd, criteria, params)

Builds a parameterized WHERE statement based on the passed in string. This is useful for queries that pass in string information that you want to protect from SQL Injection.

criteria - “name LIKE $1” params - “%steve%” Example:

result = db(:products)
    |> filter("name LIKE %$1%", "steve")
    |> to_list
first(cmd, cols \\ "*")

Executes a given pipeline and returns the first matching result. You should specify a sort to be sure first works as intended.

cols - Any columns (specified as a string) that you want to have aliased or restricted in your return.

For example `now() as current_time, name, description`. Defaults to "*"

Example:

top_spender = db(:users)
  |> sort(:money_spent, :desc)
  |> first("first, last, email")
function(cmd, function_name)

Executes a function with the given name, passed as an atom.

Example:

result = db(:users)
  |> function(:all_users)
function(cmd, function_name, params)

Executes a function with the given name, passed as an atom, returning a single result.

params: - An array of values to be passed to the function.

Example:

result = db(:users)
  |> function(:friends, ["mike","jane"])
function(cmd, function_name, atom, params)

Executes a function with the given name, passed as an atom, returning a single result.

Example:

result = db(:users)
  |> function(:all_users)
function_command(cmd, function_name, params \\ [])

Creates a function command

group(cmd, cols)

Specifies a GROUP BY for a map/reduce (aggregate) query that is a string.

cols - A string specifying the column to GROUP BY. Will also be part of the SELECT list.

Example:

result = db(:users)
  |> map("money_spent > 100")
  |> group("company, state")
  |> reduce(:sum, :money_spent)
insert(cmd, criteria)

A simple insert that that returns the inserted record. Create your list of data and send it on in.

criteria: - A list or map of data to be saved

Example:

new_user = db(:users)
    |> insert(email: "test@test.com", first: "Test", last: "User")
insert(cmd, pid, criteria)

A simple insert that is part of a transaction that returns the inserted record. Create your list of data and send it on in.

pid: - The process id of the transaction (retrieved from the transaction callback) criteria: - A list or map of data to be saved

Example:

tranaction fn(pid) ->
  new_user = db(:users)
      |> insert(pid, email: "test@test.com", first: "Test", last: "User")
end
insert_command(cmd, criteria)

Creates an insert command based on the assembled pipeline

join(cmd, table, opts \\ [])

Build a table join for your query. There are a number of options to handle various joins. Joins can also be piped for multiple joins.

:join - set the type of join. LEFT, RIGHT, FULL, etc. defaults to INNER :on - specify the table to join on :foreign_key - specify the tables foreign key column :primary_key - specify the joining tables primary key column :using - used to specify a USING queries list of columns to join on

Example of simple join:

cmd = db(:customers)
      |> join(:orders)
      |> select

Example of multiple table joins:

cmd = db(:customers)
      |> join(:orders, on: :customers)
      |> join(:items, on: :orders)
      |> select
last(cmd, sort_by)

Executes a given pipeline and returns the last matching result. You should specify a sort to be sure first works as intended.

cols - Any columns (specified as a string) that you want to have aliased or restricted in your return.

For example `now() as current_time, name, description`. Defaults to "*"

Example:

cheap_skate = db(:users)
  |> sort(:money_spent, :desc)
  |> last("first, last, email")
limit(cmd, bound)

Sets the limit of the return.

bound - And integer limiter

Example:

result = db(:users)
    |> limit(20)
    |> to_list
map(cmd, criteria)

An alias for filter, specifies a range to rollup on for an aggregate query using a WHERE statement.

criteria - A string, atom or list (see filter)

Example:

result = db(:users)
  |> map("money_spent > 100")
  |> reduce(:sum, :money_spent)
offset(cmd, n)

Offsets the limit and is an alias for skip/1

Example:

result = db(:users)
    |> limit(20)
    |> offset(2)
    |> to_list
reduce(cmd, op, column)

A rollup operation that aggregates the mapped result set by the specified operation.

op - An atom indicating what you want to have happen, such as :sum, :avg, :min, :max.

Corresponds directly to a PostgreSQL rollup function.

Example:

result = db(:users)
  |> map("money_spent > 100")
  |> reduce(:sum, :money_spent)
run(sql)
run(sql, params)

Executes a raw SQL query with parameters

run(sql, params, atom)

Executes a raw SQL query with parameters returning a single result

search(cmd, list)

Full text search using Postgres’ built in indexing, ranked using tsrank. This query will result in a full table scan and is not optimized for large result sets. For better results, create a tsvector field and populate it with a trigger on insert/update. This will cause some side effects, one of them being that Postgrex, the Elixir driver we use, doesn’t know how to resolve the tsvector type, and will throw.

You will need to be sure that you exclude that search column from your query.

for: - The string term you want to query against. in: - An atomized list of columns to search againts.

Example:

result = db(:users)
      |> search(for: "Mike", in: [:first, :last, :email])
      |> run
select_command(cmd, cols \\ "*")

Creates a SELECT command based on the assembled pipeline. Uses the QueryCommand as its core structure.

cols - Any columns (specified as a string) that you want to have aliased or restricted in your return.

For example `now() as current_time, name, description`

Example:

command = db(:users)
    |> limit(20)
    |> offset(2)
    |> select_command("now() as current_time, name, description")

#command is a QueryCommand object with all of the pipelined settings applied
skip(cmd, n)

Offsets the limit and is an alias for offset/1

Example:

result = db(:users)
    |> limit(20)
    |> skip(2)
    |> to_list
sort(cmd, cols, direction \\ :asc)

Sets the order by. Ascending using :asc is the default, you can send in :desc if you like.

cols - The atomized name of the columns, such as :company direction - :asc (default) or :desc

Example:

result = db(:users)
    |> sort(:name, :desc)
    |> to_list
sql_file(file)

Executes the SQL in a given SQL file without parameters. Specify the scripts directory by setting the scripts directive in the config. Pass the file name as an atom, without extension.

result = sql_file(:simple)
sql_file(file, params)

Executes the SQL in a given SQL file with the specified parameters. Specify the scripts directory by setting the scripts directive in the config. Pass the file name as an atom, without extension.

result = sql_file(:save_user, [1])
sql_file(file, atom, params \\ [])

Executes the SQL in a given SQL file with the specified parameters, returning a single result. Specify the scripts directory by setting the scripts directive in the config. Pass the file name as an atom, without extension.

result = sql_file(:save_user, [1])
sql_file_command(file, params)

Creates a SQL File command

to_list(cmd, cols \\ "*")

Executes a given pipeline and returns all results. An alias for all/2

cols - Any columns (specified as a string) that you want to have aliased or restricted in your return.

For example `now() as current_time, name, description`. Defaults to "*"

Example:

all_users = db(:users)
  |> to_list("first, last, email")
transaction(fun)

Opens a transaction, returning a pid (Process ID) that you can pass to each of your queries that take part in the transaction. If an error occurs, it is passed back to you with {:error, message}. The transaction will automatically COMMIT on completion.

Example:

result = transaction fn(pid) ->
  new_user = with(:users)
    |> insert(pid, email: "frodo@test.com")

  with(:logs)
    |> insert(pid, user_id: new_user.id, log: "Hi Frodo")

  new_user
end
update(cmd, criteria)

A bulk update based on the criteria you specify. All changed records are returned.

Example:

db(:users)
  |> filter(company: "Test Company")
  |> update(status: "preferred")
update(cmd, atom, criteria)

A simple update based on the criteria you specify. This is a partial update. Returns a single record as a result when you pass :single

pid: - The process id of the transaction (retrieved from the transaction callback) criteria: - A list or map of data to be saved

Example:

updated_user = db(:users)
    |> update(:single, email: "test@test.com", first: "Test", last: "User")
update(cmd, pid, atom, criteria)

A simple update that is part of a transaction based on the criteria you specify. This is a partial update. Returns a single record as a result when you pass :single

pid: - The process id of the transaction (retrieved from the transaction callback) criteria: - A list or map of data to be saved

Example:

tranaction fn(pid) ->
  updated_user = db(:users)
      |> update(pid, :single, email: "test@test.com", first: "Test", last: "User")
end
update_command(cmd, criteria)

Creates an update command based on the assembled pipeline.

with(table)

Specifies the table or view you want to query and is an alias for the db/1 function using a string as a table name. This is useful for specifying a table within a schema.

“table” - the name of the table you want to query, such as membership.users

Example

result = with("membership.users")
  |> to_list