frappe-syntax-query-builder

Syntax manual for using frappe.qb (PyPika-based) query builder in Frappe v14–v16. Covers SELECT, INSERT, UPDATE, DELETE, joins, aggregation, subqueries, cross-database considerations (MariaDB/PostgreSQL), and guidance for migrating from raw SQL. Emphasizes preventing SQL injection and common database-specific errors, with examples of parameterized queries, joins and aggregations.

Last repository push
GitHub Stars
211
Forks
61
Issues / PRs
4

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "frappe-syntax-query-builder" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-4ae368abe00d62fac02ce4d1bc4e21dde501b40caa8914235f9ddbd583ffe794. Verify the upstream source and version against https://github.com/Impertio-Studio/Frappe_Claude_Skill_Package before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

github.com

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

Syntax manual for using frappe.qb (PyPika-based) query builder in Frappe v14–v16. Covers SELECT, INSERT, UPDATE, DELETE, joins, aggregation, subqueries, cross-database considerations (MariaDB/PostgreSQL), and guidance for migrating from raw SQL. Emphasizes preventing SQL injection and common database-specific errors, with examples of parameterized queries, joins and aggregations.

0 Downloads

Introduction source: third_party · Impertio-Studio · 3.0 Reference

SkillPi interpretation

Tasks
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() ```
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: frappe-syntax-query-builder
description: >
  Use when building database queries with frappe.qb in Frappe v14-v16.
  Covers the PyPika-based query builder: SELECT, INSERT, UPDATE, DELETE,
  joins, aggregation, subqueries, cross-DB compatibility (MariaDB/PostgreSQL),
  and migration from raw SQL. Prevents SQL injection and DB-specific bugs.
  Keywords: frappe.qb, query builder, DocType, Field, pypika, join,, frappe.qb example, how to write query, join tables, SQL replacement, parameterized query.
  aggregate, ImportMapper, cross-database, parameterized query.
license: MIT
compatibility: "Claude Code, Claude.ai Projects, Claude API. Frappe v14-v16."
metadata:
  author: OpenAEC-Foundation
  version: "3.0"

Frappe Query Builder (frappe.qb)

Quick Reference

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
Action Pattern
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() (tuples) / .run(as_dict=True) (dicts)

Decision Tree

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()

Core Patterns

SELECT with DocType

# 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)
)

Aggregation

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()

Filtering

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")

Cross-DB Compatibility

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 Use ImportMapper
GROUP_CONCAT STRING_AGG Yes
MATCH...AGAINST TO_TSVECTOR Yes
Locate Strpos Yes
Timestamp Extract-based Auto-handled

Anti-patterns

  1. NEVER pass qb query to frappe.db.sql() — bypasses parameterization
  2. NEVER use Table() for DocTypes — use DocType() (adds tab prefix)
  3. NEVER forget .run() — without it you get a query object, not results
  4. NEVER use raw SQL strings in frappe.get_all(fields=[...]) — use dict syntax
  5. ALWAYS use ImportMapper for DB-specific functions
  6. ALWAYS chain .run(as_dict=True) when you need dicts — default is tuples

Version Differences

Feature v14 v15 v16
Core qb API Introduced Yes Yes
ImportMapper Yes Yes Yes
SQLite backend -- -- Added
Masked fields -- -- Added
Union queries (.walk) -- Added Yes
Child query execution -- -- Added

Reference Files

Version history

  1. v3.1.1 GitHub ↗
    Original release notes

    ## What's new Expanded Keywords in all skill descriptions with user-friendly, non-technical discovery terms. Skills are now easier to find when users describe problems in plain language instead of technical terminology. Examples of added terms: - Symptom-based: "app is slow", "nothing shows", "container won't start" - Beginner-friendly: "how do I start", "what is", "getting started" - Error messages: literal error text users would paste - Alternative names: common synonyms and abbreviations No skill content was changed. Only the Keywords line in SKILL.md frontmatter was expanded.

  2. v3.1.0 GitHub ↗
    Original release notes

    ## What's new - package.json with agents.skills[] manifest for external discovery (60 skills) - agents/openai.yaml for OpenAI Codex - GitHub topic agentskills added - SKILLS_LOG.md added to .gitignore - Em-dashes replaced with colons in 31 SKILL.md section headings Enables discovery via npx skills add, skills.sh, LobeHub, and other platforms.

  3. v3.0.0 GitHub ↗
    Original release notes

    ## Summary - **60 deterministic skills** for Frappe Framework v14-v16 (up from 53 in v2.0) - **~95% surface area coverage** (up from ~85%) - 7 new skills + 12 existing skills extended with new reference files ## New Skills (7) | Skill | Category | Coverage | |-------|----------|----------| | `frappe-core-translation` | core | i18n, _(), __(), CSV/PO files, string extraction | | `frappe-core-utils` | core | 140+ date, number, string, validation functions | | `frappe-syntax-print` | syntax | Print formats, PDF generation, Letter Head | | `frappe-syntax-query-builder` | syntax | frappe.qb, joins, aggregation, cross-DB | | `frappe-impl-workspace` | impl | Workspace builder, number cards, charts | | `frappe-core-logging` | core | frappe.logger(), Error Log, Sentry integration | | `frappe-core-search` | core | Link search, global search, SQLiteSearch FTS5 | ## Extended Skills (12) 13 new reference files added to existing skills covering: Controls API, Tree View, Portal Generators, Print Format decision tree, Email system, Module/Workspace shipping, complete Document API, custom bench commands, request lifecycle, advanced debugging (VS Code DAP), Frappe Packages, data masking (v16+), and Python type stubs. ## Stats | Category | Count | |----------|:-----:| | syntax/ | 13 | | core/ | 11 | | impl/ | 14 | | errors/ | 7 | | ops/ | 8 | | agents/ | 5 | | testing/ | 2 | | **Total** | **60** | ## Install ```bash git clone https://github.com/OpenAEC-Foundation/Frappe_Claude_Skill_Package.git cp -r Frappe_Claude_Skill_Package/skills/source/* ~/.claude/skills/ ```

  4. v2.0.0 GitHub ↗
    Original release notes

    ## Frappe Claude Skill Package v2.0.0 Massive upgrade from 28 ERPNext-specific skills to **53 Frappe Framework skills** covering ~85% of the Frappe surface area. ### What's New - **25 new skills** across 3 new categories (ops, testing, agents) - **28 existing skills** fully rewritten with fresh research - **Renamed** from `erpnext-*` to `frappe-*` (all skills are Frappe Framework, not ERPNext-specific) - **7 categories**: syntax (11), core (7), impl (13), errors (7), ops (8), agents (5), testing (2) ### New Categories - **ops/** — Bench CLI, deployment, backup, performance, upgrades, frontend build, cloud - **testing/** — Unit/integration tests, CI/CD with GitHub Actions - **3 new agents** — debugger, migrator, architect ### Key Improvements - All skills verified against official Frappe docs (March 2026) - v16 features documented: `extend_doctype_class`, data masking, type annotations - MIT license (was LGPL-3.0) - Deterministic language throughout (ALWAYS/NEVER) 🤖 Generated with [Claude Code](https://claude.com/claude-code)

  5. v1.1.0 GitHub ↗
    Original release notes

    V16 compatibility update and documentation improvements. ## Added - USAGE.md with platform-specific guides (Claude.ai, Claude Code, API) - Complete README overhaul with quick start guide ## Changed - All 28 skills updated for ERPNext/Frappe V16 compatibility - Agent Skills now follow standard skill structure - Improved validation: 28/28 skills pass all checks ## Fixed - V16-specific syntax changes in 9 skills - Agent SKILL.md files now under 500 lines

Only the five most recent versions are shown. View full version history at the source ↗

Current listing version

3.0

Verify the source revision ↗

Safety and assessment details

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value85/100

Highlights

  • 提供全面的 frappe.qb 查询构建器使用指南,涵盖 CRUD、JOIN、聚合、子查询等核心功能
  • 包含详细的最佳实践、反模式和版本差异说明,实用价值高
  • 面向 Frappe 开发者,属于明确场景的通用工具
Trigger Precision95/100

Highlights

  • 关键词覆盖完整且精准(frappe.qb、查询构建器、DocType、Field、pypika、连接等)
  • 边界清晰,用户能准确判断是否需要使用该 Skill
Structure and Standards75/100

Areas to improve

  • 缺少 When to Use 章节 Reported severity: Minor

    文档结构良好但未设置明确的 'When to Use' 章节标题

    Recommendation: 建议添加显式的 'When to Use' 章节以增强规范性

  • 文档过长 Reported severity: Minor

    主文档超过500行

    Recommendation: 建议将部分内容拆分到子文档或进行适度精简

Highlights

  • 文档结构清晰,包含快速参考、决策树、核心模式等多个实用章节
  • frontmatter 完整,包含名称、描述、许可证、兼容性等信息
  • 提供丰富的代码示例和表格说明
Execution Reliability95/100

Highlights

  • 所有代码示例均使用正确的 frappe.qb API
  • 强调了防止 SQL 注入和数据库特定错误的重要实践
  • 详细说明了反模式以避免常见错误
  • 提供了跨数据库兼容性的解决方案
Evidence Verifiability (mean of the first four)88/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

These common operations were not identified in the main document. This does not mean no permissions or risks exist.

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.