Optionalname: stringSpecify the table for this policy
Specify the role this policy applies to
Set the USING clause (read filter)
Determines which existing rows can be seen/modified by the current user.
Set the WITH CHECK clause (write validation)
Validates that new/modified rows meet the specified condition.
// Prevent users from creating documents for other users
policy('create_docs')
.on('documents')
.write()
.withCheck(column('user_id').isOwner());
// For UPDATE, use both when() and withCheck()
policy('update_docs')
.on('documents')
.update()
.when(column('user_id').isOwner()) // Can only update own docs
.withCheck(column('user_id').isOwner()); // Can't change ownership
Type-safe method to set the appropriate clause(s) based on the operation.
// For SELECT - sets USING only
policy('read_docs')
.on('documents')
.read()
.allow(column('user_id').isOwner());
// For INSERT - sets WITH CHECK only
policy('create_docs')
.on('documents')
.write()
.allow(column('user_id').isOwner());
// For UPDATE - sets both USING and WITH CHECK
policy('update_docs')
.on('documents')
.update()
.allow(column('user_id').isOwner());
Set policy as RESTRICTIVE
Set policy as PERMISSIVE (default)
User-focused alias for .restrictive() - all policies must pass
Makes this policy RESTRICTIVE, meaning it must pass in addition to other policies. Useful for adding constraints that apply to all operations (e.g., tenant isolation).
// Tenant isolation that restricts all other policies
policy('tenant_isolation')
.on('documents')
.all()
.requireAll() // This policy AND other policies must pass
.when(column('tenant_id').belongsToTenant());
// Now add a permissive policy for user access
policy('user_access')
.on('documents')
.read()
.when(column('user_id').isOwner());
// Users can only see their own docs within their tenant
User-focused alias for .permissive() - any policy can grant access
Makes this policy PERMISSIVE (default), meaning if this policy passes, access is granted (unless blocked by a RESTRICTIVE policy).
// Multiple ways to access documents
policy('owner_access')
.on('documents')
.read()
.allowAny() // Explicit, but this is the default
.when(column('user_id').isOwner());
policy('public_access')
.on('documents')
.read()
.when(column('is_public').eq(true));
// User can see a document if EITHER policy passes
Add description/documentation
Get the policy definition
Generate SQL for this policy Matches PostgreSQL CREATE POLICY syntax: CREATE POLICY name ON table [AS PERMISSIVE|RESTRICTIVE] [FOR operation] [TO role] [USING ...] [WITH CHECK ...]
Optionaloptions: SQLGenerationOptionsOptions for SQL generation (e.g., includeIndexes)
Policy builder class implementing fluent API