Developing Rules

Rules in SQLFluff are implemented as classes inheriting from BaseRule. SQLFluff crawls through the parse tree of a SQL file, calling the rule’s _eval() function for each segment in the tree. For many rules, this allows the rule code to be really streamlined and only contain the logic for the rule itself, with all the other mechanics abstracted away.

Traversal Options

recurse_into

Some rules are a poor fit for the simple traversal pattern described above. Typical reasons include:

  • The rule only looks at a small portion of the file (e.g. the beginning or end).

  • The rule needs to traverse the parse tree in a non-standard way.

These rules can override BaseRule’s recurse_into field, setting it to False. For these rules False, _eval() is only called once, with the root segment of the tree. This can be much more efficient, especially on large files. For example, see rules L050 and L009 , which only look at the beginning or end of the file, respectively.

_works_on_unparsable

By default, SQLFluff calls _eval() for all segments, even “unparsable” segments, i.e. segments that didn’t match the parsing rules in the dialect. This causes issues for some rules. If so, setting _works_on_unparsable to False tells SQLFluff not to call _eval() for unparsable segments and their descendants.

Base Rules

base_rules Module

Implements the base rule class.

Rules crawl through the trees returned by the parser and evaluate particular rules.

The intent is that it should be possible for the rules to be expressed as simply as possible, with as much of the complexity abstracted away.

The evaluation function should take enough arguments that it can evaluate the position of the given segment in relation to its neighbors, and that the segment which finally “triggers” the error, should be the one that would be corrected OR if the rule relates to something that is missing, then it should flag on the segment FOLLOWING, the place that the desired element is missing.

class BaseRule(code, description, **kwargs)

The base class for a rule.

Parameters:
  • code (str) – The identifier for this rule, used in inclusion or exclusion.

  • description (str) – A human readable description of what this rule does. It will be displayed when any violations are found.

crawl(tree: BaseSegment, dialect: Dialect, fix: bool, templated_file: Optional[TemplatedFile], ignore_mask: List[NoQaDirective], fname: Optional[str]) Tuple[List[SQLLintError], Tuple[RawSegment, ...], List[LintFix], Any]

Run the rule on a given tree.

Returns:

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

static discard_unsafe_fixes(lint_result: LintResult, templated_file: Optional[TemplatedFile])

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_.

static filter_meta(segments, keep_meta=False)

Filter the segments to non-meta.

Or optionally the opposite if keep_meta is True.

classmethod get_parent_of(segment, root_segment)

Return the segment immediately containing segment.

NB: This is recursive.

Parameters:
  • segment – The segment to look for.

  • root_segment – Some known parent of the segment we’re looking for (although likely not the direct parent in question).

indent

String for a single indent, based on configuration.

static matches_target_tuples(seg: BaseSegment, target_tuples: List[Tuple[str, str]], parent: Optional[BaseSegment] = None)

Does the given segment match any of the given type tuples?

static split_comma_separated_string(raw_str: str) List[str]

Converts comma separated string to List, stripping whitespace.

class LintFix(edit_type: str, anchor: BaseSegment, edit: Optional[Iterable[BaseSegment]] = None, source: Optional[Iterable[BaseSegment]] = None)

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

Parameters:
  • edit_type (str) – One of create_before, create_after, replace, delete to indicate the kind of fix this represents.

  • anchor (BaseSegment) – A 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.

  • edit (iterable of BaseSegment, optional) – For replace and create fixes, this holds the iterable of segments to create or replace at the given anchor point.

  • source (iterable of BaseSegment, optional) – For replace and create fixes, this holds iterable of segments that provided code. IMPORTANT: The linter uses this to prevent copying material from templated areas.

classmethod create_after(anchor_segment: BaseSegment, edit_segments: Iterable[BaseSegment], source: Optional[Iterable[BaseSegment]] = None) LintFix

Create edit segments after the supplied anchor segment.

classmethod create_before(anchor_segment: BaseSegment, edit_segments: Iterable[BaseSegment], source: Optional[Iterable[BaseSegment]] = None) LintFix

Create edit segments before the supplied anchor segment.

classmethod delete(anchor_segment: BaseSegment) LintFix

Delete supplied anchor segment.

get_fix_slices(templated_file: TemplatedFile, within_only: bool) Set[RawFileSlice]

Returns slices touched by the fix.

has_template_conflicts(templated_file: TemplatedFile) bool

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

is_just_source_edit() bool

Return whether this a valid source only edit.

is_trivial()

Return true if the fix is trivial.

Trivial edits are: - Anything of zero length. - Any edits which result in themselves.

Removing these makes the routines which process fixes much faster.

classmethod replace(anchor_segment: BaseSegment, edit_segments: Iterable[BaseSegment], source: Optional[Iterable[BaseSegment]] = None) LintFix

Replace supplied anchor segment with the edit segments.

class LintResult(anchor: Optional[BaseSegment] = None, fixes: Optional[List[LintFix]] = None, memory=None, description=None)

A class to hold the results of a rule evaluation.

Parameters:
  • anchor (BaseSegment, optional) – A segment which represents the position of the a 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.

  • fixes (list of LintFix, optional) – An array of any fixes which would correct this issue. If not present then it’s assumed that this issue will have to manually fixed.

  • memory (dict, optional) – An 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.

  • description (str, optional) – A 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.

to_linting_error(rule) Optional[SQLLintError]

Convert a linting result to a SQLLintError if appropriate.

class RuleGhost(code, description)
property code

Alias for field number 0

property description

Alias for field number 1

class RuleLoggingAdapter(logger, extra)

A LoggingAdapter for rules which adds the code of the rule to it.

process(msg, kwargs)

Add the code element to the logging message before emit.

class RuleSet(name, config_info)

Class to define a ruleset.

A rule set is instantiated on module load, but the references to each of its classes are instantiated at runtime. This means that configuration values can be passed to those rules live and be responsive to any changes in configuration from the path that the file is in.

Rules should be fetched using the get_rulelist() command which also handles any filtering (i.e. allowlisting and denylisting).

New rules should be added to the instance of this class using the register() decorator. That decorator registers the class, but also performs basic type and name-convention checks.

The code for the rule will be parsed from the name, the description from the docstring. The eval function is assumed that it will be overriden by the subclass, and the parent class raises an error on this function if not overriden.

copy()

Return a copy of self with a separate register.

get_rulelist(config) List[BaseRule]

Use the config to return the appropriate rules.

We use the config both for allowlisting and denylisting, but also for configuring the rules given the given config.

Returns:

list of instantiated BaseRule.

register(cls, plugin=None)

Decorate a class with this to add it to the ruleset.

@myruleset.register
class Rule_L001(BaseRule):
    "Description of rule."

    def eval(self, **kwargs):
        return LintResult()

We expect that rules are defined as classes with the name Rule_XXXX where XXXX is of the form LNNN, where L is a letter (literally L for linting by default) and N is a three digit number.

If this receives classes by any other name, then it will raise a ValueError.

property valid_rule_name_regex

Defines the accepted pattern for rule names.

The first group captures the plugin name (optional), which must be capitalized. The second group captures the rule code.

Examples of valid rule names:

  • Rule_PluginName_L001

  • Rule_L001

Functional API

These newer modules provide a higher-level API for rules working with segments and slices. Rules that need to navigate or search the parse tree may benefit from using these. Eventually, the plan is for all rules to use these modules. As of December 30, 2021, 17+ rules use these modules.

The modules listed below are submodules of sqlfluff.utils.functional.

segments Module

Surrogate class for working with Segment collections.

class Segments(*segments, templated_file=None)

Encapsulates a sequence of one or more BaseSegments.

The segments may or may not be contiguous in a parse tree. Provides useful operations on a sequence of segments to simplify rule creation.

all(predicate: Optional[Callable[[BaseSegment], bool]] = None) bool

Do all the segments match?

any(predicate: Optional[Callable[[BaseSegment], bool]] = None) bool

Do any of the segments match?

apply(fn: Callable[[BaseSegment], Any]) List[Any]

Apply function to every item.

children(predicate: Optional[Callable[[BaseSegment], bool]] = None) Segments

Returns an object with children of the segments in this object.

find(segment: Optional[BaseSegment]) int

Returns index if found, -1 if not found.

first(predicate: Optional[Callable[[BaseSegment], bool]] = None) Segments

Returns the first segment (if any) that satisfies the predicates.

get(index: int = 0, *, default: Optional[Any] = None) Optional[BaseSegment]

Return specified item. Returns default if index out of range.

iterate_segments(predicate: Optional[Callable[[BaseSegment], bool]] = None) Iterable[Segments]

Loop over each element as a fresh Segments.

last(predicate: Optional[Callable[[BaseSegment], bool]] = None) Segments

Returns the last segment (if any) that satisfies the predicates.

property raw_segments: Segments

Get raw segments underlying the segments.

property raw_slices: RawFileSlices

Raw slices of the segments, sorted in source file order.

recursive_crawl(*seg_type: str, recurse_into: bool = True) Segments

Recursively crawl for segments of a given type.

recursive_crawl_all() Segments

Recursively crawl all descendant segments.

reversed() Segments

Return the same segments in reverse order.

select(select_if: Optional[Callable[[BaseSegment], bool]] = None, loop_while: Optional[Callable[[BaseSegment], bool]] = None, start_seg: Optional[BaseSegment] = None, stop_seg: Optional[BaseSegment] = None) Segments

Retrieve range/subset.

NOTE: Iterates the segments BETWEEN start_seg and stop_seg, i.e. those segments are not included in the loop.

segment_predicates Module

Defines commonly used segment predicates for rule writers.

For consistency, all the predicates in this module are implemented as functions returning functions. This avoids rule writers having to remember the distinction between normal functions and functions returning functions.

This is not necessarily a complete set of predicates covering all possible requirements. Rule authors can define their own predicates as needed, either as regular functions, lambda, etc.

and_(*functions: Callable[[BaseSegment], bool]) Callable[[BaseSegment], bool]

Returns a function that computes the functions and-ed together.

get_type() Callable[[BaseSegment], str]

Returns a function that gets segment type.

is_code() Callable[[BaseSegment], bool]

Returns a function that checks if segment is code.

is_comment() Callable[[BaseSegment], bool]

Returns a function that checks if segment is comment.

is_expandable() Callable[[BaseSegment], bool]

Returns a function that checks if segment is expandable.

is_keyword(*keyword_name) Callable[[BaseSegment], bool]

Returns a function that determines if it’s a matching keyword.

is_meta() Callable[[BaseSegment], bool]

Returns a function that checks if segment is meta.

is_raw() Callable[[BaseSegment], bool]

Returns a function that checks if segment is raw.

is_templated() Callable[[BaseSegment], bool]

Returns a function that checks if segment is templated.

is_type(*seg_type: str) Callable[[BaseSegment], bool]

Returns a function that determines if segment is one of the types.

is_whitespace() Callable[[BaseSegment], bool]

Returns a function that checks if segment is whitespace.

not_(fn: Callable[[BaseSegment], bool]) Callable[[BaseSegment], bool]

Returns a function that computes: not fn().

or_(*functions: Callable[[BaseSegment], bool]) Callable[[BaseSegment], bool]

Returns a function that computes the functions or-ed together.

raw_is(*raws: str) Callable[[BaseSegment], bool]

Returns a function that determines if segment matches one of the raw inputs.

raw_slice(segment: BaseSegment, raw_slice_: RawFileSlice) str

Return the portion of a segment’s source provided by raw_slice.

raw_slices(segment: BaseSegment, templated_file: Optional[TemplatedFile]) RawFileSlices

Returns raw slices for a segment.

raw_upper_is(*raws: str) Callable[[BaseSegment], bool]

Returns a function that determines if segment matches one of the raw inputs.

templated_slices(segment: BaseSegment, templated_file: Optional[TemplatedFile]) TemplatedFileSlices

Returns raw slices for a segment.

raw_file_slices Module

Surrogate class for working with RawFileSlice collections.

class RawFileSlices(*raw_slices, templated_file=None)

Encapsulates a sequence of one or more RawFileSlice.

The slices may or may not be contiguous in a file. Provides useful operations on a sequence of slices to simplify rule creation.

all(predicate: Optional[Callable[[RawFileSlice], bool]] = None) bool

Do all the raw slices match?

any(predicate: Optional[Callable[[RawFileSlice], bool]] = None) bool

Do any of the raw slices match?

select(select_if: Optional[Callable[[RawFileSlice], bool]] = None, loop_while: Optional[Callable[[RawFileSlice], bool]] = None, start_slice: Optional[RawFileSlice] = None, stop_slice: Optional[RawFileSlice] = None) RawFileSlices

Retrieve range/subset.

NOTE: Iterates the slices BETWEEN start_slice and stop_slice, i.e. those slices are not included in the loop.

raw_file_slice_predicates Module

Defines commonly used raw file slice predicates for rule writers.

For consistency, all the predicates in this module are implemented as functions returning functions. This avoids rule writers having to remember the distinction between normal functions and functions returning functions.

This is not necessarily a complete set of predicates covering all possible requirements. Rule authors can define their own predicates as needed, either as regular functions, lambda, etc.

is_slice_type(*slice_types: str) Callable[[RawFileSlice], bool]

Returns a function that determines if segment is one of the types.