frappe-syntax-query-builder について
Frappeでデータベースクエリを構築する開発者向けの、Frappe Query Builder(frappe.qb)の利用リファレンスです。複雑なクエリに向けて、クエリ構築、データ操作、データベース間の互換パターンを扱います。
主な機能
- 01SELECTクエリの構築
- 02JOINと集計クエリ
- 03データの挿入、更新、削除
- 04結果の絞り込みと並べ替え
- 05データベース間の関数マッピング
活用シーン
- 01JOINを含むクエリの作成
- 02データベースレコードのグループ化と集計
- 03パラメーター化したデータ変更
- 04MariaDBとPostgreSQLに合わせたクエリ調整
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ impertio-studio/ frappe_claude_skill_package --skill frappe-syntax-query-builderインストール後、Claude Code で/frappe-syntax-query-builderを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
references/cross-db-patterns.mdfunctions-reference.mdmigration-from-sql.md詳細
Frappe Query Builder (frappe.qb)
クイックリファレンス
from frappe.query_builder import DocType, Field
from frappe.query_builder.functions import Count, Sum, IfNull
from frappe.query_builder.custom import ConstantColumn, GROUP_CONCAT
from frappe.query_builder.terms import SubQuery
from frappe.query_builder.utils import ImportMapper, db_type_is
from pypika.terms import Case, ValueWrapper
from pypika import CustomFunction, Order
| 操作 | パターン |
|---|---|
| SELECT | frappe.qb.from_("DocType").select("field1", "field2") |
| WHERE | .where(Field("status") == "Open") |
| ORDER | .orderby("creation", order=Order.desc) |
| LIMIT | .limit(10).offset(0) |
| JOIN | .left_join(dt2).on(dt2.name == dt1.parent) |
| COUNT | .select(Count("*")) |
| INSERT | frappe.qb.into("DocType").columns("f1", "f2").insert("v1", "v2") |
| UPDATE | frappe.qb.update("DocType").set("field", "value").where(...) |
| DELETE | frappe.qb.from_("DocType").delete().where(...) |
| 実行 | .run()(タプル)/.run(as_dict=True)(辞書) |
選択フロー
Need to query the database?
│
├─ Simple get/list → frappe.db.get_value(), frappe.get_all()
│ (See frappe-core-database skill)
│
├─ Complex query with joins/aggregates/subqueries → frappe.qb ✓
│
├─ Very complex SQL not expressible in qb → frappe.db.sql()
│ (ALWAYS use parameterized values: frappe.db.sql(query, values))
│
└─ Need cross-DB compatibility → frappe.qb + ImportMapper ✓
Using frappe.qb?
│
├─ Table reference → DocType("Sales Order") — NEVER use Table()
├─ Field reference → dt.field_name or Field("field_name")
├─ Execute → .run() for tuples, .run(as_dict=True) for dicts
├─ DB-specific function → ImportMapper({db_type_is.MARIADB: X, db_type_is.POSTGRES: Y})
└─ Get SQL string → query.get_sql() — NEVER pass to frappe.db.sql()
基本パターン
DocType を使った SELECT
# ALWAYS use DocType() for table references — adds "tab" prefix
so = frappe.qb.DocType("Sales Order")
soi = frappe.qb.DocType("Sales Order Item")
orders = (
frappe.qb.from_(so)
.select(so.name, so.customer, so.grand_total)
.where(so.status == "To Deliver and Bill")
.where(so.docstatus == 1)
.orderby(so.creation, order=Order.desc)
.limit(20)
.run(as_dict=True)
)
JOIN
result = (
frappe.qb.from_(so)
.left_join(soi).on(soi.parent == so.name)
.select(so.name, so.customer, soi.item_code, soi.qty)
.where(so.docstatus == 1)
.where(soi.item_code.like("ITEM-%"))
.run(as_dict=True)
)
集計
from frappe.query_builder.functions import Count, Sum
gl = frappe.qb.DocType("GL Entry")
result = (
frappe.qb.from_(gl)
.select(gl.account, Sum(gl.debit).as_("total_debit"), Count("*").as_("entries"))
.where(gl.docstatus == 1)
.groupby(gl.account)
.run(as_dict=True)
)
# Shortcut aggregation methods
total = frappe.qb.sum("GL Entry", "debit", filters={"account": "Sales"})
max_qty = frappe.qb.max("Stock Ledger Entry", "actual_qty", filters={"item_code": "ITEM-001"})
INSERT / UPDATE / DELETE
# INSERT
frappe.qb.into("Activity Log").columns("user", "action").insert("admin", "login").run()
# UPDATE
customer = frappe.qb.DocType("Customer")
(frappe.qb.update(customer)
.set(customer.status, "Active")
.where(customer.name == "CUST-001")
.run())
# DELETE
frappe.qb.from_("Error Log").delete().where(Field("creation") < "2024-01-01").run()
フィルタリング
dt = frappe.qb.DocType("Sales Order")
# Equality
.where(dt.status == "Open")
# OR (pipe operator)
.where((dt.status == "Open") | (dt.status == "Draft"))
# AND (chain .where() calls)
.where(dt.status == "Open")
.where(dt.docstatus == 1)
# LIKE
.where(dt.customer.like("CUST-%"))
# IN
.where(dt.status.isin(["Open", "Draft"]))
# BETWEEN (bracket syntax)
.where(dt.creation[start_date:end_date])
# NULL checks
.where(dt.email.isnotnull())
.where(dt.phone.isnull())
# Comparison
.where(dt.grand_total > 1000)
.where(dt.grand_total >= 500)
.where(dt.status != "Cancelled")
データベース間の互換性
from frappe.query_builder.utils import ImportMapper, db_type_is
from frappe.query_builder.custom import GROUP_CONCAT, STRING_AGG
# ImportMapper selects correct function per database
GroupConcat = ImportMapper({
db_type_is.MARIADB: GROUP_CONCAT,
db_type_is.POSTGRES: STRING_AGG,
})
dt = frappe.qb.DocType("Has Role")
result = (
frappe.qb.from_(dt)
.select(dt.parent, GroupConcat(dt.role))
.groupby(dt.parent)
.run(as_dict=True)
)
| MariaDB | PostgreSQL | ImportMapper を使用 |
|---|---|---|
GROUP_CONCAT | STRING_AGG | はい |
MATCH...AGAINST | TO_TSVECTOR | はい |
Locate | Strpos | はい |
Timestamp | Extract ベース | 自動処理 |
アンチパターン
- qb クエリを
frappe.db.sql()に渡さないでください — パラメーター化が回避されます - DocType に
Table()を使用しないでください —DocType()を使用してください(tabプレフィックスが追加されます) .run()を忘れないでください — 省略すると、結果ではなくクエリオブジェクトが返されますfrappe.get_all(fields=[...])で生の SQL 文字列を使用しないでください — 辞書形式を使用してください- データベース固有の関数には必ず
ImportMapperを使用してください - 辞書が必要な場合は、必ず
.run(as_dict=True)をチェーンしてください — デフォルトはタプルです
バージョンごとの差異
| 機能 | v14 | v15 | v16 |
|---|---|---|---|
| コア qb API | 導入 | はい | はい |
| ImportMapper | はい | はい | はい |
| SQLite バックエンド | -- | -- | 追加 |
| マスクされたフィールド | -- | -- | 追加 |
| Union クエリ(.walk) | -- | 追加 | はい |
| 子クエリの実行 | -- | -- | 追加 |
参照ファイル
- 関数と集計 — 使用可能な qb 関数の一覧
- 移行ガイド — 生の SQL と get_all パターンの変換
- データベース間のパターン — ImportMapper とデータベース固有の関数
コメント
Markdown 対応