load_sql_proc/
lib.rs

1//! This crate provides a procedural macro to minify SQL queries at compile time.
2#![deny(missing_docs)]
3extern crate proc_macro;
4
5use proc_macro::TokenStream;
6use quote::quote;
7
8/// This macro will load and minify the provided SQL document at compile time
9///
10/// # Arguments
11/// * `path` - A string slice that holds the path to the SQL file
12///
13/// # Examples
14///
15/// ```rust
16/// use load_sql_proc::load_sql;
17///
18/// const SQL_CONTENT: &str = load_sql!("tests/test_file_1.sql");
19///
20/// assert_eq!(
21///     SQL_CONTENT,
22///     "CREATE TABLE IF NOT EXISTS taxa(id UUID PRIMARY KEY,name TEXT NOT NULL,ncbi_taxon_id INT)"
23/// );
24/// ```
25#[proc_macro]
26pub fn load_sql(input: TokenStream) -> TokenStream {
27    // Parse the input token stream
28    let path = syn::parse_macro_input!(input as syn::LitStr).value();
29
30    // We prepend CARGO_HOME to the path, as the path is relative to the project root
31    let path = format!("{}/{}", std::env::var("CARGO_MANIFEST_DIR").unwrap(), path);
32
33    // Read the content of the file
34    let document = std::fs::read_to_string(path).expect("Could not read SQL file to minify");
35
36    // Minify the SQL content
37    let minified_document: String = minify_sql::minify_sql(&document);
38
39    // Return the minified SQL content
40    TokenStream::from(quote! {
41        #minified_document
42    })
43}