Skip to content

Rules Base API

This section is for contributors writing new built-in rules or plugin rules.

SQLFluff rules are Python classes that subclass BaseRule. The linter crawls the parse tree and calls each rule's _eval() method, which returns zero or more LintResult objects. Each LintResult may carry LintFix objects describing how to auto-correct the violation.

The crawler passed to BaseRule.crawl_behaviour controls which segments _eval() is called on — see SegmentSeekerCrawler and RootOnlyCrawler.

Source: sqlfluff/core/rules/

BaseRule

The base class for a rule.

Parameters:

ParameterTypeDefaultDescription
codestrThe identifier for this rule, used in inclusion or exclusion.
descriptionstrA human readable description of what this rule does. It will be displayed when any violations are found.
kwargsAny

Methods

crawl

python
crawl(
    tree,
    dialect,
    fix,
    templated_file,
    ignore_mask,
    fname,
    config
)

Run the rule on a given tree.

Parameters:

ParameterTypeDefaultDescription
treeBaseSegment
dialectDialect
fixbool
templated_fileForwardRef('TemplatedFile') | None
ignore_maskForwardRef('IgnoreMask') | None
fnamestr | None
configFluffConfig

Returns:

A tuple of (vs, raw_stack, fixes, memory)

discard_unsafe_fixes

python
discard_unsafe_fixes(
    lint_result,
    templated_file
) → None

Remove (discard) LintResult fixes if they are "unsafe".

By removing its fixes, a LintResult will still be reported, but it will be treated as unfixable.

Parameters:

ParameterTypeDefaultDescription
lint_resultLintResult
templated_fileTemplatedFile | None

Returns:

None — See return type.

filter_meta

python
filter_meta(
    segments,
    keep_meta=False
) → tuple[BaseSegment, ...]

Filter the segments to non-meta.

Or optionally the opposite if keep_meta is True.

Parameters:

ParameterTypeDefaultDescription
segmentscollections.abc.Sequence[BaseSegment]
keep_metaboolFalse

Returns:

tuple[BaseSegment, ...] — See return type.

get_config_ref

python
get_config_ref() → str

Return the config lookup ref for this rule.

If a name is defined, it's the name - otherwise the code.

The name is a much more understandable reference and so makes config files more readable. For backward compatibility however we also support the rule code for those without names.

Returns:

str — See return type.

get_parent_of

python
get_parent_of(
    segment,
    root_segment
) → BaseSegment | None

Return the segment immediately containing segment.

NB: This is recursive.

Parameters:

ParameterTypeDefaultDescription
segmentBaseSegmentThe segment to look for.
root_segmentBaseSegmentSome known parent of the segment we're looking for (although likely not the direct parent in question).

Returns:

BaseSegment | None — See return type.

split_comma_separated_string

python
split_comma_separated_string(
    raw
) → list[str]

Converts comma separated string to List, stripping whitespace.

Parameters:

ParameterTypeDefaultDescription
rawstr | list[str]

Returns:

list[str] — See return type.

LintResult

A class to hold the results of a rule evaluation.

Parameters:

ParameterTypeDefaultDescription
anchorBaseSegment | NoneNoneA segment which represents the position of the problem. NB: Each fix will also hold its own reference to position, so this position is mostly for alerting the user to where the problem is.
fixeslist[LintFix] | NoneNoneAn array of any fixes which would correct this issue. If not present then it's assumed that this issue will have to manually fixed.
memoryAny | NoneNoneAn object which stores any working memory for the rule. The memory returned in any LintResult will be passed as an input to the next segment to be crawled.
descriptionstr | NoneNoneA description of the problem identified as part of this result. This will override the description of the rule as what gets reported to the user with the problem if provided.
sourcestr | NoneNoneA string identifier for what generated the result. Within larger libraries like reflow this can be useful for tracking where a result came from.

Methods

to_linting_error

python
to_linting_error(
    rule
) → SQLLintError | None

Convert a linting result to a :exc:SQLLintError if appropriate.

Parameters:

ParameterTypeDefaultDescription
ruleBaseRule

Returns:

SQLLintError | None — See return type.

LintFix

A class to hold a potential fix to a linting violation.

Parameters:

ParameterTypeDefaultDescription
edit_typestrOne of create_before, create_after, replace, delete to indicate the kind of fix this represents.
anchorBaseSegmentA segment which represents the position that this fix should be applied at. For deletions it represents the segment to delete, for creations it implies the position to create at (with the existing element at this position to be moved after the edit), for a replace it implies the segment to be replaced.
editcollections.abc.Iterable[BaseSegment] | NoneNoneFor replace and create fixes, this holds the iterable of segments to create or replace at the given anchor point.
sourcecollections.abc.Iterable[BaseSegment] | NoneNoneFor replace and create fixes, this holds iterable of segments that provided code. IMPORTANT: The linter uses this to prevent copying material from templated areas.

Methods

create_after

python
create_after(
    anchor_segment,
    edit_segments,
    source=None
) → LintFix

Create edit segments after the supplied anchor segment.

Parameters:

ParameterTypeDefaultDescription
anchor_segmentBaseSegment
edit_segmentscollections.abc.Iterable[BaseSegment]
sourcecollections.abc.Iterable[BaseSegment] | NoneNone

Returns:

LintFix — See return type.

create_before

python
create_before(
    anchor_segment,
    edit_segments,
    source=None
) → LintFix

Create edit segments before the supplied anchor segment.

Parameters:

ParameterTypeDefaultDescription
anchor_segmentBaseSegment
edit_segmentscollections.abc.Iterable[BaseSegment]
sourcecollections.abc.Iterable[BaseSegment] | NoneNone

Returns:

LintFix — See return type.

delete

python
delete(
    anchor_segment
) → LintFix

Delete supplied anchor segment.

Parameters:

ParameterTypeDefaultDescription
anchor_segmentBaseSegment

Returns:

LintFix — See return type.

get_fix_slices

python
get_fix_slices(
    templated_file,
    within_only
) → set[RawFileSlice]

Returns slices touched by the fix.

Parameters:

ParameterTypeDefaultDescription
templated_fileTemplatedFile
within_onlybool

Returns:

set[RawFileSlice] — See return type.

has_template_conflicts

python
has_template_conflicts(
    templated_file
) → bool

Based on the fix slices, should we discard the fix?

Parameters:

ParameterTypeDefaultDescription
templated_fileTemplatedFile

Returns:

bool — See return type.

is_just_source_edit

python
is_just_source_edit(
    single_source_fix=False
) → bool

Return whether this a valid source only edit.

Parameters:

ParameterTypeDefaultDescription
single_source_fixboolFalseCheck for a single source_fixes.

Returns:

bool — See return type.

replace

python
replace(
    anchor_segment,
    edit_segments,
    source=None
) → LintFix

Replace supplied anchor segment with the edit segments.

Parameters:

ParameterTypeDefaultDescription
anchor_segmentBaseSegment
edit_segmentscollections.abc.Iterable[BaseSegment]
sourcecollections.abc.Iterable[BaseSegment] | NoneNone

Returns:

LintFix — See return type.

to_dict

python
to_dict() → dict[str, Any]

Serialise this LintFix as a dict.

Returns:

dict[str, Any] — See return type.

RuleContext

Class for holding the context passed to rule eval functions.

Parameters:

ParameterTypeDefaultDescription
dialectDialect
fixbool
templated_fileTemplatedFile | None
pathpathlib.Path | None
configFluffConfig
segmentBaseSegment
parent_stacktuple[BaseSegment, ...]()
raw_stacktuple[RawSegment, ...]()
memoryAny<factory>
segment_idxint0

BaseCrawler

The base interface for crawler classes.

Parameters:

ParameterTypeDefaultDescription
works_on_unparsableboolFalse
kwargsAny

Methods

crawl

python
crawl(
    context
) → collections.abc.Iterator[RuleContext]

Yields a RuleContext for each segment the rule should process.

Parameters:

ParameterTypeDefaultDescription
contextRuleContext

Returns:

collections.abc.Iterator[RuleContext] — See return type.

passes_filter

python
passes_filter(
    segment
) → bool

Returns true if this segment considered at all.

This method is called during crawling but also in evaluating the anchors for linting violations and their fixes to make sure we don't get issues with linting sections of queries that we can't parse.

See BaseRule._process_lint_result().

Parameters:

ParameterTypeDefaultDescription
segmentBaseSegment

Returns:

bool — See return type.

SegmentSeekerCrawler

A crawler that efficiently searches for specific segment types.

The segment type(s) are specified on creation.

Parameters:

ParameterTypeDefaultDescription
typesset[str]
provide_raw_stackboolFalse
allow_recurseboolTrue
kwargsAny

Methods

crawl

python
crawl(
    context
) → collections.abc.Iterator[RuleContext]

Yields a RuleContext for each segment the rule should process.

We assume that segments are yielded by their parent.

Parameters:

ParameterTypeDefaultDescription
contextRuleContext

Returns:

collections.abc.Iterator[RuleContext] — See return type.

is_self_match

python
is_self_match(
    segment
) → bool

Does this segment match the relevant criteria.

Parameters:

ParameterTypeDefaultDescription
segmentBaseSegment

Returns:

bool — See return type.

passes_filter

python
passes_filter(
    segment
) → bool

Returns true if this segment considered at all.

This method is called during crawling but also in evaluating the anchors for linting violations and their fixes to make sure we don't get issues with linting sections of queries that we can't parse.

See BaseRule._process_lint_result().

Parameters:

ParameterTypeDefaultDescription
segmentBaseSegment

Returns:

bool — See return type.

RootOnlyCrawler

A crawler that doesn't crawl.

This just yields one context on the root-level (topmost) segment of the file.

Parameters:

ParameterTypeDefaultDescription
works_on_unparsableboolFalse
kwargsAny

Methods

crawl

python
crawl(
    context
) → collections.abc.Iterator[RuleContext]

Yields a RuleContext for each segment the rule should process.

Parameters:

ParameterTypeDefaultDescription
contextRuleContext

Returns:

collections.abc.Iterator[RuleContext] — See return type.

passes_filter

python
passes_filter(
    segment
) → bool

Returns true if this segment considered at all.

This method is called during crawling but also in evaluating the anchors for linting violations and their fixes to make sure we don't get issues with linting sections of queries that we can't parse.

See BaseRule._process_lint_result().

Parameters:

ParameterTypeDefaultDescription
segmentBaseSegment

Returns:

bool — See return type.

Released under the MIT License.