Skip to main content

Module sql

Module sql 

Source
Expand description

A small SQL highlighter in pure Rust: no syntect, no C, no dependencies.

SqlHighlighter is a CodeHighlighter built on a hand-written lexer (tokenize). It knows standard SQL and the common words of PostgreSQL, MySQL, SQLite, BigQuery, Snowflake and DuckDB, and treats Jinja blocks ({{ … }}, {% … %}, {# … #}), as dbt models use them, as a token class of their own. It answers to the language sql and the aliases in LANGUAGES; any other language is plain text, or goes to a fallback highlighter (SqlHighlighter::with_fallback).

Turn on the sql feature. It needs neither syntax nor markdown: highlight gives a styled Text in a lean build, and with syntax the highlighter serves Syntax and Markdown’s ```sql fences through the console’s code highlighting.

use rich::protocol::{CodeHighlighting, ConsoleCodeHighlighting};
use rich::{ColorSystem, Console};
use rich_ext::sql::{self, SqlHighlighter};

// A styled `Text`, no `Syntax` needed.
let text = sql::highlight("SELECT 1 -- one", "ansi_dark");
assert_eq!(text.plain(), "SELECT 1 -- one");

// Or every SQL code block a console renders.
let mut console = Console::builder()
    .force_terminal(true)
    .color_system(Some(ColorSystem::Standard))
    .build();
console.set_code_highlighting(Some(CodeHighlighting {
    highlighter: SqlHighlighter::shared(),
    theme: Some("ansi_dark".into()),
}));
let out = console.render_to_string(&rich::Syntax::new("SELECT 1", "sql"));
assert!(out.contains("\x1b[94mSELECT"), "{out:?}");

§Themes

monokai (the default, upstream’s default code theme), and ansi_dark and ansi_light, upstream’s themes in the terminal’s own 16 colours. A theme this highlighter does not know highlights SQL with monokai, so a console set up for another engine’s theme still colours SQL.

Structs§

SqlHighlighter
SQL highlighting as a CodeHighlighter, for Syntax, Markdown code fences and the console’s code highlighting.
SqlPlugin
Registers SqlHighlighter as the code highlighter "sql".
Token
A token: its kind and its byte range in the source.

Enums§

TokenKind
What a token is.

Constants§

DEFAULT_THEME
The theme used when none is chosen.
LANGUAGES
The language names this highlighter answers to.
THEMES
The themes this highlighter has.

Functions§

highlight
Highlight code as SQL with theme (one of THEMES; anything else is monokai), as a styled Text. Needs no Syntax, so it works in a build without syntect.
is_sql
Whether language (a name or a file extension) is SQL to this highlighter.
token_style
The style of kind in theme; None for text left in the default style.
tokenize
Split code into tokens covering every byte, in order.