/nette:nette-databasefrom nette
Provides guidance on Nette Database conventions, entity mapping, and query patterns including Selection API vs raw SQL. Use when writing queries, designing ActiveRow classes, or configuring database connections in .neon files.
Ships in nette. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Uses Nette Database, typically with MySQL, PostgreSQL or SQLite as the backend.
composer require nette/database
See the Explorer documentation for the full ActiveRow/Selection API. See the SQL way documentation for direct SQL queries.
user not users)id for primary keysutf8mb4 with appropriate collation (e.g. utf8mb4_0900_ai_ci, or utf8mb4_cs_0900_ai_ci for Czech)created_at DATETIME DEFAULT CURRENT_TIMESTAMPNette Database has a built-in EntityMapping interface (since 3.2) that the Explorer uses to resolve an ActiveRow subclass for each table and (optionally) translate between column names and PHP property names. The default implementation (DefaultEntityMapping) supports:
special_table), wildcard patterns (forum_*) or a bare * catch-all. Class names may contain *, which is replaced with the PascalCase of the captured portion: forum_post + App\Forum\*Row → App\Forum\PostRow. A class without * is a fixed class (log_*: App\Logging\LogRow maps every log_* table to the same LogRow). Schema prefixes like public. are stripped before PascalCase conversion. Exact keys take precedence; wildcard entries are tried in declaration order, so put more specific patterns first and the bare * last.author_id is exposed as property authorId everywhere: property access, iteration, toArray(), insert(), update(), and column references in where() / order().Activate via the mapping config option (see Database Configuration below).
All entities in App\Entity with consistent Row suffix (matches the App\Entity\*Row convention):
product table → ProductRoworder_item table → OrderItemRowvariant_expiration table → VariantExpirationRowWhy flat: Entities are data structures that cross domain boundaries. A ProductRow might be used in catalog, orders, inventory, and reporting contexts. Subdividing entities by domain forces you to either pick one arbitrary "home" domain or duplicate references.
All entities in single App\Entity namespace - avoid domain subdivision:
app/Entity/
├── ProductRow.php ← Core business entities
├── OrderItemRow.php ← Relationship entities
└── StockTransferRow.php ← Operational entities
use Nette\Database\Table;
/**
* @property-read int $id
* @property-read string $title
* @property-read bool $active
* @property-read ?CategoryRow $category ← nullable relationship
* @property-read UserRow $author ← required relationship
*/
final class ProductRow extends Table\ActiveRow
{
}
Documentation rules:
Foreign key patterns:
@property-read ?CategoryRow $category for optional relationships@property-read UserRow $author for required relationships@property-read Selection<OrderItemRow> $order_items for back-referencesNaming convention: Follow Nette Database relationship naming (foreign key without _id suffix).
With camelCase: true mapping: scalar columns map to camelCase properties ($firstName, $createdAt). Relationship property names ($author, $category) are resolved by Conventions against database columns, so they aren't affected by the camelCase setting.
Use for:
return $this->db->table('product')
->where('active', true)
->where('category_id', $categoryId)
->order('name');
Use for:
return $this->db->query('
WITH RECURSIVE category_tree AS (...)
SELECT ...
', $params)->fetchAll();
Build queries by progressive refinement – start with a base method, then add conditions. Always use generic types for Selection returns:
/** @return Selection<ProductRow> */
public function getProducts(): Selection
{
return $this->db->table('product');
}
/** @return Selection<ProductRow> */
public function getActiveProducts(): Selection
{
return $this->getProducts()->where('active', true);
}
/** @return Selection<ProductRow> */
public function getProductsInCategory(int $categoryId): Selection
{
return $this->getActiveProducts()
->where(':product_category.category_id', $categoryId);
}
Use colon notation for efficient joins:
// Forward relationship (via foreign key)
->where('category.slug', $categorySlug)
// Back-reference (reverse relationship)
->where(':order_item.quantity >', 1)
// Deep relationships
->where('category.parent.name', 'Root Category')
The array KEY is SQL, the value is a bound parameter. where() splits the key on the first
space into a column and an operator and emits both into the query, so a key built from user
input is an injection hole – and mass-assigning a request array into where() or insert()
lets the client choose columns and operators:
$db->table('user')->where(['id >' => 5]); // fine: key is yours, value is bound
$db->table('user')->where($_GET['filter']); // NEVER: keys come from the client
Write SQL keywords in UPPERCASE inside fragments. Explorer quotes lowercase words as
identifiers, so where('name like ?', $x) compiles to `name` `like` ? and fails; uppercase
words are left alone:
->where('name LIKE ?', "%$q%") // correct
->where('name like ?', "%$q%") // `like` gets quoted as a column name
An empty array flips the meaning of a condition. where('id', []) becomes
IS NULL AND FALSE (matches nothing), while where('id NOT', []) becomes IS NULL OR TRUE
(matches everything). Guard empty filter lists explicitly. Mixing operators without
parentheses raises Possible SQL query corruption. Add parentheses around operators.
Single optional result: ->fetch()
All results as array: ->fetchAll()
Key-value pairs: ->fetchPairs('key_column', 'value_column')
Single scalar value: ->fetchField() (first column of first row)
Count only: ->count('*')
Structured data with fetchAssoc:
// Key by column value
$byId = $db->table('product')->fetchAssoc('id');
// [1 => ProductRow, 2 => ProductRow, ...]
// Group by column
$byCategory = $db->table('product')->fetchAssoc('category_id[]');
// [5 => [ProductRow, ProductRow], 8 => [ProductRow, ...]]
// Nested grouping
$nested = $db->table('product')->fetchAssoc('category_id|active');
// [5 => [true => ProductRow, false => ProductRow], ...]
The path string uses [] for array grouping, | for nested keys, and = to extract a single value.
Use direct SQL migrations rather than ORM-style migrations – store schema in sql/db.sql with manual migration scripts. Rely on database constraints (foreign keys, unique, check) for data integrity and handle constraint violations in services with meaningful business exceptions.
Wrap multi-step writes in transactions to ensure consistency:
$this->db->transaction(function () use ($data, $items) {
$order = $this->db->table('order')->insert($data);
foreach ($items as $item) {
$order->related('order_item')->insert($item);
}
});
The callback approach automatically commits on success and rolls back on exception, and it returns whatever the callback returns, so you can produce a value out of it.
Nested transaction() calls are counted, and only the outermost one actually commits. Calling
beginTransaction(), commit() or rollBack() manually inside the callback throws
LogicException – pick one style per code path and stay with it.
Don't create separate Repository classes – in Nette, services combine data access with business logic. A separate repository layer adds indirection without benefit because Nette Database Explorer already provides a clean query API. The service IS the repository.
Transform database errors to business exceptions:
try {
$customer->update(['email' => $newEmail]);
} catch (Nette\Database\UniqueConstraintViolationException) {
throw new EmailAlreadyExistsException();
}
Handle at service boundary – presenters should receive business exceptions, not database exceptions. This keeps the UI layer independent of the storage layer and produces meaningful error messages.
database:
dsn: 'mysql:host=127.0.0.1;dbname=myapp'
user: root
password: secret
# Entity mapping (table → ActiveRow subclass, optional column ↔ property)
mapping:
tables: App\Entity\*Row # string shortcut: equivalent to { '*': 'App\Entity\*Row' }
options:
lazy: true # Connect on first query
charset: utf8mb4 # Default
convertBoolean: true # TINYINT(1) to bool
newDateTime: true # Return DateTimeImmutable
Full mapping form when you need explicit overrides or camelCase properties:
database:
dsn: 'mysql:host=127.0.0.1;dbname=myapp'
mapping:
tables:
special_table: App\Entity\SpecialRow # exact match wins over wildcards
forum_*: App\Forum\*Row # wildcard in key (* captured as PascalCase)
"*": App\Entity\*Row # catch-all fallback (must be last)
camelCase: true # column author_id ↔ property authorId
Multiple connections:
database:
main:
dsn: 'mysql:host=127.0.0.1;dbname=app'
user: root
password: secret
logs:
dsn: 'mysql:host=127.0.0.1;dbname=logs'
user: logs
password: secret
autowired: false # Must reference explicitly
Reference non-autowired connection:
services:
- LogService(@database.logs.connection)
The full Nette documentation for this topic is bundled with the plugin. Read a page when you need details beyond this skill:
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
PHP, MySQL, PostgreSQL, SQLite
npx claudepluginhub nette/agent-plugins --plugin nette20 skills in this plugin
/frontend-developmentProvides frontend development guidelines for Nette. Use when working with Vite, SCSS, JavaScript/TypeScript, Nette Assets ({asset} tag, asset mapping), ESLint with @nette/eslint-plugin, Naja AJAX library, frontend entry points, npm packages in Nette context, Tailwind CSS with Latte templates, nette-forms npm package, HMR, build commands (npm run dev/build), or passing data from PHP to JavaScript./latte-templatesInvoke before creating or modifying .latte files, even for single-line changes. Provides Latte syntax, tags, filters, n:attributes, layouts, template inheritance, AJAX snippets, extensions, and Nette integration. Also trigger when user mentions Latte by name./neon-formatInvoke before creating or modifying .neon files. Provides NEON syntax and Nette configuration conventions. Use when writing or editing .neon config files, asking about NEON syntax (entities, multiline strings, inline notation, special values, escaping), converting YAML to NEON, parsing or encoding NEON in PHP (Neon::decode, Neon::encode), running neon-lint, or debugging NEON syntax errors. For phpstan.neon, use the phpstan-analysis skill (from nette-dev plugin) instead. Do not trigger for Nette DI concepts like autowiring and service registration without .neon file context./nette-architectureInvoke before designing presenters, modules, or application structure in web application. Use when asking about directory structure (app/ folder organization), presenter organization (modules, Admin/Front/Api, BasePresenter), domain-driven placement (Core/ vs Model/), component and factory placement, presenter lifecycle (action/render/template), CLI tasks, Accessory placement, project skeleton, or refactoring architecture. Also trigger when starting a new Nette project./nette-cachingInvoke before writing or reviewing code that uses nette/caching. Covers the Cache object and namespaces, load() with a generator callback, save(), remove(), clean(), the dependency array (Cache::Expire, Cache::Tags, Cache::Files, Cache::Items, Cache::Priority, Cache::Sliding, Cache::Callbacks), the Journal requirement for tags and priorities, bulkLoad(), output capture, storages (FileStorage, MemcachedStorage, SQLiteStorage, MemoryStorage, DevNullStorage) and the {cache} Latte tag. Also trigger for cache.storage or cache.journal in NEON, invalidation by tag, cache stampede, or disabling the cache in tests. Not for the Latte template cache or the DI container cache, which are separate mechanisms./nette-command-lineInvoke before writing or reviewing a PHP command-line script or tool that uses nette/command-line 2.0. Covers Command with addFlag(), addOption(), addArgument() and addCommand(), the Parser and its ParseResult, standalone --help and --version, negatable flags, optional values, defaults, enum, repeatable parameters, Normalizers, commands and subcommands dispatched with match, HelpRenderer, ParseException and ParseFailure, and the Console (colors and ColorDepth, NO_COLOR and FORCE_COLOR, links, setStatus() progress lines) with Ansi for measuring text. Also trigger for bin/ scripts, CLI argument parsing, "print the help", colored terminal output or progress bars in PHP. Also trigger when upgrading from 1.x, for code using new Parser($help), addFromHelp(), addSwitch(), parseOnly() or Parser::normalizeRealPath(), and for errors such as "Call to undefined method Parser::addFromHelp()" or "Too few arguments to function Parser::parse()".Other plugins' skills for the same job