better-drizzle
Plugins

Rules

Runtime guardrails for raw SQL, destructive writes, pagination, locks, and tenant context.

better-drizzle/rules is the first-party guardrails plugin for Better Drizzle. It inspects every repository, raw SQL, and transaction call before it runs, and turns unsafe patterns into warnings or errors. You don't have to wrap each call yourself.

Install

npm install better-drizzle
pnpm add better-drizzle
yarn add better-drizzle
bun add better-drizzle

Usage

Start from a preset and override what you need:

import { better } from 'better-drizzle';
import { rules, safe } from 'better-drizzle/rules';

const client = better(db, {
	schema,
	plugins: [
		rules(
			safe({
				maxLimit: { level: 'error', value: 200 },
			}),
		),
	],
});

You can also list rules by hand. Any rule you leave out is off:

rules({
	noRawUnsafe: true,
	noUpdateManyWithoutWhere: true,
	requireOrderByForCursor: true,
	maxLimit: { level: 'warn', value: 500 },
});

Rule settings

Every rule accepts the same setting shapes:

SettingMeaning
true'error' with default options
false or 'off'disabled
'warn'reported, the operation still runs
'error'reported, then the operation throws
{ level?, ...options }rule-specific options; level defaults to 'error' when omitted
rules({
	noRawUnsafe: true,
	noUnboundedFindMany: 'warn',
	requireRawTimeout: { level: 'error', maxTimeoutMs: 30_000 },
	maxLimit: { value: 500 }, // level defaults to 'error'
});

Plugin options

These options control how violations are handled. They sit next to the rules in the same object.

Prop

Type

Presets

The package exports three presets. Each builds on the previous one:

  • safe() blocks destructive writes, unsafe raw SQL, and broken lock or cursor usage.
  • recommended() is safe() plus limits on includes and raw timeouts, sensitive-field checks, and a required tenant context.
  • strict() is recommended() with higher levels, lower limits, and the tenant, reason, and ordering rules.

recommended() and strict() require a tenant context

Both presets enable requireTenantContext at 'error'. Every operation, including raw SQL and transactions, then throws unless meta.tenantId is set (for example through db.$withContext({ tenantId })) or meta.system is truthy. If your app is not multi-tenant, turn it off: recommended({ requireTenantContext: false }).

This table shows the level each preset sets. off means the preset does not enable the rule.

Rulesafe()recommended()strict()
noDeleteManyWithoutWhereerrorerrorerror
noUpdateManyWithoutWhereerrorerrorerror
noDeleteWithoutWhereerrorerrorerror
noUpdateWithoutWhereerrorerrorerror
noEmptyWhereerrorerrorerror
noUnboundedFindManywarnwarnerror
requireExplicitLimitoffoffwarn
maxLimitwarn, 1000warn, 1000error, 500
requireOrderByForLimitoffoffwarn
requireOrderByForPaginationoffoffwarn
requireOrderByForCursorerrorerrorerror
requireStableOrderByForCursoroffwarnerror
maxIncludeDepthoffwarn, 3error, 2
maxIncludeRelationsoffwarn, 5error, 3
requireTransactionForLockwarnwarnerror
noLockWithIncludeerrorerrorerror
noInvalidLockCombinationerrorerrorerror
requireOrderByForSkipLockedoffwarnerror
requireLimitForSkipLockederrorerrorerror
noRawUnsafeerrorerrorerror
requireRawCommentoffoffwarn, 8 chars
requireRawTimeoutoffwarnerror
noRawMutationoffwarnerror
noRawWithoutTransactionoffoffwarn, mutations only
requireTimeoutForLongRunningOperationoffwarn, max 60serror, max 30s
requireTenantContextofferrorerror
noTenantBypassWithoutSystemoffofferror
noTenantColumnOverrideoffofferror
requireTenantOnCreateoffofferror
requireTenantOnUpdateoffofferror
requireTenantOnDeleteoffofferror
noSensitiveSelectofferrorerror
requireExplicitSensitiveAccessReasonoffofferror
noHardDeleteOnSoftDeleteModelofferrorerror
requireHardDeleteReasonoffofferror
noQueryDeletedWithoutExplicitOptInoffoffwarn
noSystemModeWithoutReasonoffwarnerror

The presets also set some rules that are not enforced yet. Those settings have no effect today.

Preset options in detail

Some preset entries set options beyond the level:

  • noEmptyWhere checks only update, updateMany, delete, and deleteMany. It treats a missing where and an empty AND: [] / OR: [] as empty.
  • noUnboundedFindMany allows a findMany that has take or limit. safe() and recommended() also allow it when there is a where; strict() does not.
  • maxLimit applies to findMany, paginate, and cursor.
  • requireStableOrderByForCursor is set with requirePrimaryKeyInOrderBy: false, so it never fires in any preset. Set requirePrimaryKeyInOrderBy: true to use it.
  • requireRawTimeout uses defaultTimeoutMs: 5000 and maxTimeoutMs: 30000.
  • noRawMutation allows statements that start with create extension or refresh materialized view.
  • requireTenantContext uses allowSystem: true.
  • noSensitiveSelect allows the select when the call passes withSensitive: true.
  • noHardDeleteOnSoftDeleteModel allows a hard delete when a reason is given.
  • noQueryDeletedWithoutExplicitOptIn in strict() requires a reason when a call reads deleted rows.

Overriding a preset

Every preset takes an overrides object. The merge is shallow: an override replaces the preset's whole setting for that rule, it does not merge into it.

recommended({
	// Replaces the preset's { level: 'warn', value: 1000, applyTo: [...] }.
	// level is now 'error' and applyTo falls back to the rule defaults.
	maxLimit: { value: 200 },
	requireTenantContext: false,
});

To combine several configs yourself, use merge. It takes an options object:

  • extends: one config or an array of configs, applied in order.
  • rules: overrides applied last, on top of every extends entry.

The merge is shallow here too. undefined, null, and false entries are skipped, so you can add a config conditionally:

import { merge, rules, safe } from 'better-drizzle/rules';

rules(
	merge({
		extends: [safe(), process.env.NODE_ENV === 'production' && { throwOnError: false }],
		rules: { noRawMutation: 'warn' },
	}),
);

Scoping rules to models

Most model rules accept models and ignoreModels. Names are matched against the schema table key.

rules({
	noUnboundedFindMany: {
		level: 'error',
		ignoreModels: ['countries', 'currencies'],
	},
	requireTenantContext: {
		models: ['invoices', 'customers'],
	},
});

The scope type also has an operations field, but only noEmptyWhere, requireExplicitLimit, and requireTimeoutForLongRunningOperation read it. maxLimit uses applyTo instead. Raw SQL and transactions have no model, so models and ignoreModels never exclude them.

Rule reference

Every rule below is enforced today. Defaults are the values used when you configure a rule without that option.

Destructive writes

RuleFires whenOptions
noDeleteManyWithoutWheredeleteMany has no wherescope
noUpdateManyWithoutWhereupdateMany has no wherescope
noDeleteWithoutWheredelete has no wherescope
noUpdateWithoutWhereupdate has no wherescope
noEmptyWherewhere is {}, or missing, or an empty AND/OR (depending on options)operations (default: all), treatUndefinedAsEmpty (default true), treatEmptyAndOrAsEmpty (default false), scope

The *WithoutWhere rules only catch a missing where. Pair them with noEmptyWhere to also catch where: {}.

With no operations set, noEmptyWhere checks every operation, and a missing where counts as empty. A plain findMany() or count() then violates it. Set operations to limit it to writes, as the presets do.

Reads and pagination

RuleFires whenOptions
noUnboundedFindManyfindMany has neither an allowed bound nor a whereallowWithWhere, allowWithLimit, allowWithTake, allowSmallStaticModels, scope (all flags default to false)
requireExplicitLimitthe operation has no take/limitoperations (default ['findMany']), scope
maxLimitthe resolved limit is above valuevalue (required), applyTo (default ['findMany', 'paginate', 'cursor']), scope
requireOrderByForLimitany read with take/limit has no orderByscope
requireOrderByForPaginationpaginate has no orderByscope
requireOrderByForCursorcursor has no orderByscope
requireStableOrderByForCursorcursor orders by columns that don't include idrequirePrimaryKeyInOrderBy (must be true for the rule to fire), allowAppendPrimaryKey, scope
maxIncludeDepthinclude nests deeper than valuevalue (required), scope
maxIncludeRelationsinclude loads more than value relations in total, nested ones includedvalue (required), scope

The resolved limit is take or limit. With noUnboundedFindMany, allowWithLimit accepts either take or limit, and allowSmallStaticModels currently behaves like allowWithWhere.

Row locks

RuleFires whenOptions
requireTransactionForLocka read uses lock outside a transactionscope
noLockWithIncludea read uses lock together with a non-empty includescope
noInvalidLockCombinationlock sets both skipLocked and noWaitscope
requireOrderByForSkipLockedlock.skipLocked is used without orderByscope
requireLimitForSkipLockedlock.skipLocked is used without a limitscope

Raw SQL

RuleFires whenOptions
noRawUnsafe$rawUnsafe is callednone
requireRawCommentthe raw call has no comment, or it is shorter than minLengthminLength (default 1)
requireRawTimeoutthe raw call has no timeoutMs, or it is above defaultTimeoutMs or maxTimeoutMsdefaultTimeoutMs, maxTimeoutMs
noRawMutationthe SQL starts with insert, update, delete, replace, create, alter, drop, or truncateallow: statement prefixes to allow
noRawWithoutTransactionthe raw call runs outside a transactiononlyMutations (default false)
requireTimeoutForLongRunningOperationa $raw, $rawUnsafe, or $executeRaw call has no timeoutMs, or it is above maxTimeoutMsoperations (default ['raw', 'executeRaw', 'explain']), defaultTimeoutMs, maxTimeoutMs
await db.$raw(sql`select * from reports where id = ${id}`, {
	comment: 'monthly report lookup',
	timeoutMs: 2000,
});

The raw rules check $raw, $rawUnsafe, and $executeRaw, except noRawUnsafe, which only fires on $rawUnsafe. Because $executeRaw exists for writes, noRawMutation flags every mutation sent through it; use allow for the statements you expect.

requireRawTimeout reports a timeout above defaultTimeoutMs at the rule's own level. When the rule is 'error', defaultTimeoutMs works as the real ceiling.

Multi-tenant safety

Tenant rules read the tenant from the merged operation meta first, then from the transaction context.

const tenantDb = db.$withContext({ tenantId: session.tenantId });
await tenantDb.invoices.findMany({ where: { status: 'open' } });

// Background jobs that must cross tenants:
const systemDb = db.$withContext({ system: true, reason: 'nightly billing' });
RuleFires whenOptions
requireTenantContextthe tenant key is missing, on any operationcontextKey (default 'tenantId'), allowSystem: skip when meta.system is truthy, scope
noTenantBypassWithoutSystemthe call passes bypassTenant: true without a system flag in metasystemContextKey (default 'system')
noTenantColumnOverridedata sets the tenant column to a value different from the current tenanttenantColumn (default 'tenantId'), contextKey (defaults to tenantColumn), scope
requireTenantOnCreatea tenant is set but a create, createMany, upsert, or upsertMany row has no tenantIdscope
requireTenantOnUpdatea tenant is set but an update, updateMany, updateEach, or upsert has no wherescope
requireTenantOnDeletea tenant is set but a delete or deleteMany has no wherescope

The three requireTenantOn* rules always look for the tenantId key and column; they don't read contextKey. They don't add the tenant filter for you either. They only check that the payload has the column, or that the write has a where.

Sensitive fields

RuleFires whenOptions
noSensitiveSelectselect picks a sensitive fieldallowWithSensitive, withSensitiveArg (default 'withSensitive'), scope
requireExplicitSensitiveAccessReasona sensitive field is selected with withSensitive: true but no reasonwithSensitiveArg (default 'withSensitive'), reasonArg (default 'reason'), scope

The sensitive field names are fixed: password, passwordHash, secret, secrets, token, tokens, apiKey, apiKeys, and ssn. Only top-level select keys set to true are checked.

Soft delete and system mode

These rules pair with better-drizzle/soft-delete, which adds the mode and deleted call arguments.

RuleFires whenOptions
noHardDeleteOnSoftDeleteModeldelete is called with mode: 'hard'allowWithReason, allowWithContextKey: skip when this meta key is truthy, scope
requireHardDeleteReasondelete is called with mode: 'hard' and no reasonreasonArg (default 'reason'), scope
noQueryDeletedWithoutExplicitOptIna call reads deleted rows (deleted: 'with' or 'only') without a reasonrequireReason (must be true for the rule to fire), reasonArg (default 'reason'), scope
noSystemModeWithoutReasonthe call passes system: true without a reasonreasonArg (default 'reason')

Only delete is checked for hard deletes; deleteMany is not.

Where opt-in flags are read

Rules look for their flags in these places:

  • Reasons (reason or your reasonArg): the call arguments first, then meta, then the transaction context. Pass them through meta to stay type-safe: { meta: { reason: 'GDPR export' } }.
  • withSensitive, bypassTenant, and system: only the call arguments. The core delegate types don't declare these fields, so you need another plugin that declares them through operationArgs, or a cast.
  • Tenant and system keys: meta first, then the transaction context.

Violations and errors

Each violation reaches your handlers as a RulesViolation:

type RulesViolation = {
	rule: string; // e.g. 'noDeleteManyWithoutWhere'
	level: 'warn' | 'error';
	message: string;
	operation?: RulesOperation; // 'findMany', 'raw', 'transaction', ...
	model?: string;
	path?: readonly string[]; // e.g. ['where'] or ['select', 'password']
	query?: { where?; data?; select?; include?; orderBy?; limit?; lock? };
	context?: Record<string, unknown>;
	meta?: Record<string, unknown>;
};
rules({
	...recommended(),
	reporter: {
		warn: (v) => logger.warn({ rule: v.rule, model: v.model }, v.message),
		error: (v) => logger.error({ rule: v.rule, model: v.model }, v.message),
	},
	onViolation: (v) => metrics.increment('db.rule_violation', { rule: v.rule }),
});

Handlers run in this order:

  1. onViolation receives every violation.
  2. reporter.warn receives warnings, unless warnOnViolation: false.
  3. reporter.error receives errors, and then the plugin throws, unless throwOnError: false.

The thrown error is a BetterDrizzleError with code OperationError. Its message is the violation message, and details holds rule, level, operation, model, path, query, and meta. The operation stops at the first error-level violation.

import { BetterDrizzleError } from 'better-drizzle';

try {
	await db.users.deleteMany();
} catch (error) {
	if (error instanceof BetterDrizzleError && error.details?.rule === 'noDeleteManyWithoutWhere') {
		// handle the blocked write
	}
}

Not enforced yet

The types, and some presets, accept the rules below, but the plugin does not evaluate them yet. Setting them has no effect. They are reserved so configs keep working once support lands.

  • noSensitiveFieldsInLogs
  • requireRestoreReason
  • noWithoutPlugins, noPluginBypassWithoutReason
  • requireAuditContext, noAuditLogForIgnoredModelWrite
  • maxNestedWriteDepth, requireTransactionForNestedWrite
  • requireUniqueWhereForConnect, requireUniqueWhereForConnectOrCreate, noAmbiguousNestedRelation
  • requireWhereForAggregate, requireLimitForGroupBy, maxGroupByLimit, requireOrderByForGroupByLimit
  • noDynamicPreparedShape, noPreparedNameConflict
  • noUnsupportedDialectFeature, noSilentDialectFallback

Current boundary

The plugin runs only at runtime, through before* hooks, and reads only what the hook payload contains. If a rule can't be evaluated from that payload, it is skipped instead of guessed. Rules run on the root query only; where, orderBy, or take inside a nested include are not checked.

For editor and CI feedback on the parts that can be checked statically, see the ESLint plugin.

On this page