Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

ecto-query-patterns

БесплатноБез исполняемых скриптовНе проверен

Use when querying data with Ecto.Query DSL including where clauses, joins, aggregates, preloading, and query composition. Use for building flexible database…

TheBushidoCollectiveот TheBushidoCollective★ 202 звезды на GitHub

Об этом скилле

Ecto Query Patterns

Master Ecto's powerful Query DSL to build efficient, composable database queries. This skill covers the query syntax, filtering, joining, aggregation, preloading associations, and advanced query composition patterns.

Basic Query with from Macro

import Ecto.Query, only: [from: 2]

# Basic query using keyword syntax
query = from u in "users",
          where: u.age > 18,
          select: u.name

# Execute the query
MyApp.Repo.all(query)

Queries are built using the from/2 macro and only sent to the database when passed to a Repo function like all/1, one/1, or get/2. The keyword syntax provides a readable way to construct queries.

Query with Schema Module

query = from u in MyApp.User,
          where: u.age > 18,
          select: u.name

MyApp.Repo.all(query)

Using a schema module instead of a table name string provides better type safety and allows Ecto to use the schema's field definitions for validation and casting.

Bindingless Query Construction

from MyApp.Post,
  where: [category: "fresh and new"],
  order_by: [desc: :published_at],
  select: [:id, :title, :body]

Bindingless syntax allows building queries without explicit variable bindings. This works well for simple queries and when using keyword list syntax for conditions.

Query with Explicit Bindings

query = from p in MyApp.Post,
          where: p.category == "fresh and new",
          order_by: [desc: p.published_at],
          select: struct(p, [:id, :title, :body])

MyApp.Repo.all(query)

Explicit bindings (like p for posts) allow for more complex conditions and selections. The struct/2 function selects only specific fields from the schema.

Dynamic Query Variables

category = "fresh and new"
order_by = [desc: :published_at]
select_fields = [:id, :title, :body]

query = from MyApp.Post,
          where: [category: ^category],
          order_by: ^order_by,
          select: ^select_fields

MyApp.Repo.all(query)

The pin operator ^ allows interpolating Elixir values into queries. This is essential for parameterized queries and prevents SQL injection.

Where Clause with Expressions

query = from u in MyApp.User,
          where: u.age > 0,
          select: u.name

# Multiple where clauses are combined with AND
query = from u in MyApp.User,
          where: u.age > 18,
          where: u.confirmed == true,
          select: u

MyApp.Repo.all(query)

Query expressions support field access, comparison operators, and literals. Multiple where clauses are automatically combined with AND logic.

Composable Queries

# Create a base query
query = from u in MyApp.User, where: u.age > 18

# Extend the query
query = from u in query, select: u.name

MyApp.Repo.all(query)

Queries are composable - you can build on existing queries by using them in the in clause. This enables powerful query abstraction and reusability.

Query Composition Function Pattern

def most_recent_from(query, minimum_date) do
  from p in query,
    where: p.published_at > ^minimum_date,
    order_by: [desc: p.published_at]
end

# Usage
MyApp.Post
|> most_recent_from(~N[2024-01-01 00:00:00])
|> MyApp.Repo.all()

Extracting query logic into functions creates reusable, testable query components. This pattern is fundamental to building maintainable query code.

Or Where Conditions

from p in MyApp.Post,
  where: p.category == "elixir" or p.category == "phoenix",
  select: p

Use the or keyword for alternative conditions. For more complex OR logic, consider using Ecto.Query.dynamic/2.

IN Query with List

categories = ["elixir", "phoenix", "ecto"]

query = from p in MyApp.Post,
          where: p.category in ^categories,
          select: p

MyApp.Repo.all(query)

The in operator checks if a field value exists in a list of values. Use the pin operator to interpolate the list variable.

Like and ILike for Pattern Matching

search_term = "%elixir%"

query = from p in MyApp.Post,
          where: like(p.title, ^search_term),
          select: p

# Case-insensitive version
query = from p in MyApp.Post,
          where: ilike(p.title, ^search_term),
          select: p

Use like/2 for case-sensitive pattern matching and ilike/2 for case-insensitive matching. Wildcards % match any characters.

Selecting Specific Fields

# Select multiple fields
query = from p in MyApp.Post,
          select: {p.id, p.title}

MyApp.Repo.all(query)  # Returns [{1, "Title 1"}, {2, "Title 2"}]

# Select as map
query = from p in MyApp.Post,
          select: %{id: p.id, title: p.title}

MyApp.Repo.all(query)  # Returns [%{id: 1, title: "Title 1"}, ...]

# Select struct with specific fields
query = from p in MyApp.Post,
          select: struct(p, [:id, :title, :body])

MyApp.Repo.all(query)  # Returns Post structs with only selected fields loaded

Selecting

Полный SKILL.md на GitHub

Установить ecto-query-patterns в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Bash
Read

FAQ

Что делает скилл ecto-query-patterns?

Use when querying data with Ecto.Query DSL including where clauses, joins, aggregates, preloading, and query composition. Use for building flexible database queries in Elixir applications.

Как установить скилл ecto-query-patterns?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл ecto-query-patterns запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить ecto-query-patterns с