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, forSyntax, Markdown code fences and the console’s code highlighting. - SqlPlugin
- Registers
SqlHighlighteras the code highlighter"sql". - Token
- A token: its kind and its byte range in the source.
Enums§
- Token
Kind - 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
codeas SQL withtheme(one ofTHEMES; anything else ismonokai), as a styledText. Needs noSyntax, 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
kindintheme;Nonefor text left in the default style. - tokenize
- Split
codeinto tokens covering every byte, in order.