Skip to content

Commit aab83b4

Browse files
authored
Warning on missing alias (#71)
* chore: install env_logger * warn * chore: update everything t ouse env logger * chore: fmt * chore: grammar * chore: better warn message * chore: info * chore: fix test * chore: adding logger * chore: add log level * docs: add log level in cli options * test: add clashing field name test * chore: adding warning * chore: adding panic test * fmt
1 parent 14197c9 commit aab83b4

File tree

13 files changed

+308
-30
lines changed

13 files changed

+308
-30
lines changed

Cargo.lock

Lines changed: 32 additions & 6 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ mysql = { version = "24.0.0" }
3030
convert_case = "0.6.0"
3131
lazy_static = { version = "1.4.0" }
3232
openssl = { version = "0.10.56", features = ["vendored"] }
33+
colored = "2"
3334

3435
[dev-dependencies]
3536
assert_cmd = "2.0.12"
Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
11
# sqlx-ts CLI Opitons
22

3-
| Flag | Description |
4-
| --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
5-
| --help | Help command to display all available |
6-
| --config <CONFIG> | Path to file based configuration. Use this flag if you are dealing with multiple database connections. Check here for more details |
7-
| --db-host <DB_HOST> | Primary DB host |
8-
| --db-pass <DB_PASS> | Primary DB password |
9-
| --db-port <DB_PORT> | Primary DB port number |
10-
| --db-type <DB_TYPE> | Type of primary database to connect [default: postgres] [possible values: postgres, mysql] |
11-
| --db-user <DB_USER> | Primary DB user name |
12-
| --db-name <DB_NAME> | Primary DB name |
13-
| --ext <Extension> | Javascript Extension to check SQLs against [default: ts] [possible values: ts, js] |
14-
| --generate-types <GENERATE_TYPES> | Flag to enable typescript type generation against SQLs |
15-
| --generate-path <GENERATE_PATH> | Relative path to the type generation (e.g. ./somedir/test.queries.ts) |
16-
| -V, --version | Print version information |
3+
| Flag | Description | TS generation | Future Roadmap |
4+
|-------------------|------------------------------------------------------------------------------------------------------------------------------------|---------------|---------------------------------------------------------------------------------------------|
5+
| --help | Help command to display all available | yes | N/A |
6+
| --config | Path to file based configuration. Use this flag if you are dealing with multiple database connections. Check here for more details | yes | N/A |
7+
| --db-host | Primary DB host | yes | N/A |
8+
| --db-pass | Primary DB password | yes | N/A |
9+
| --db-port | Primary DB port number | yes | N/A |
10+
| --db-type | Type of primary database to connect [default: postgres] [possible values: postgres, mysql] | not yet | Will be supported in the near future |
11+
| --db-user | Primary DB user name | N/A | Will be supported in the near future as this will be a unique feature that sqlx-ts provides |
12+
| --db-name | Primary DB name | | |
13+
| --ext | Javascript Extension to check SQLs against [default: ts] [possible values: ts, js] | | |
14+
| --generate-types | Flag to enable typescript type generation against SQLs | | |
15+
| --generate-path | Relative path to the type generation (e.g. ./somedir/test.queries.ts) | | |
16+
| --log-level | Log level to be used in sqlx-ts (the priority is in info > warn > error order) | | |
17+
| -V, --version | Print version information | | |

src/common/cli.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::common::types::{DatabaseType, JsExtension};
1+
use crate::common::types::{DatabaseType, JsExtension, LogLevel};
22
use clap::Parser;
33

44
impl ToString for JsExtension {
@@ -67,4 +67,8 @@ pub struct Cli {
6767

6868
#[clap(long, short)]
6969
pub message_format: Option<String>,
70+
71+
/// log level to be used for the CLI info > warn > error
72+
#[clap(arg_enum, long)]
73+
pub log_level: Option<LogLevel>,
7074
}

src/common/config.rs

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use crate::common::dotenv::Dotenv;
22
use crate::common::lazy::CLI_ARGS;
3-
use crate::common::types::DatabaseType;
3+
use crate::common::types::{DatabaseType, LogLevel};
44
use mysql::OptsBuilder;
55
use regex::Regex;
66
use serde;
@@ -13,6 +13,7 @@ use std::str::FromStr;
1313

1414
#[derive(Clone, Debug, Deserialize, Serialize)]
1515
pub struct SqlxConfig {
16+
pub log_level: Option<LogLevel>,
1617
pub generate_types: Option<GenerateTypesConfig>,
1718
pub connections: HashMap<String, DbConnectionConfig>,
1819
}
@@ -51,6 +52,7 @@ pub struct Config {
5152
pub generate_types_config: Option<GenerateTypesConfig>,
5253
pub connections: HashMap<String, DbConnectionConfig>,
5354
pub ignore_patterns: Vec<String>,
55+
pub log_level: LogLevel,
5456
}
5557

5658
impl Config {
@@ -65,12 +67,14 @@ impl Config {
6567
let generate_types_config =
6668
generate_types_config.and_then(|config| if config.enabled { Some(config) } else { None });
6769
let ignore_patterns = Self::get_ignore_patterns(&default_ignore_config_path);
70+
let log_level = Self::get_log_level(file_config_path);
6871

6972
Config {
7073
dotenv,
7174
connections,
7275
generate_types_config,
7376
ignore_patterns,
77+
log_level,
7478
}
7579
}
7680

@@ -290,4 +294,16 @@ impl Config {
290294
.pass(db_pass.clone())
291295
.db_name(db_name.clone())
292296
}
297+
298+
pub fn get_log_level(file_config_path: &PathBuf) -> LogLevel {
299+
let file_based_config = fs::read_to_string(file_config_path);
300+
let file_based_config = &file_based_config.map(|f| serde_json::from_str::<SqlxConfig>(f.as_str()).unwrap());
301+
let log_level_from_file = file_based_config
302+
.as_ref()
303+
.ok()
304+
.map(|config| config.log_level)
305+
.flatten();
306+
307+
CLI_ARGS.log_level.or(log_level_from_file).unwrap_or(LogLevel::Info)
308+
}
293309
}

src/common/logger.rs

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
// TODO: Add documentation including examples
2+
// TODO: Use SQLX_TS_LOG env var to set log level
3+
4+
macro_rules! info {
5+
($arg:tt) => ({
6+
use crate::common::lazy::CONFIG;
7+
use crate::common::types::LogLevel;
8+
9+
if CONFIG.log_level.gte(&LogLevel::Info) {
10+
use colored::*;
11+
let level = "[INFO]".cyan();
12+
println!("{level} {}", $arg)
13+
}
14+
});
15+
($arg:tt, $($arg2:tt)*) => ({
16+
use crate::common::lazy::CONFIG;
17+
use crate::common::types::LogLevel;
18+
19+
if CONFIG.log_level.gte(&LogLevel::Info) {
20+
use colored::*;
21+
let level = "[INFO]".cyan();
22+
println!("{level} {}", format!($arg, $($arg2)*))
23+
}
24+
});
25+
}
26+
27+
pub(crate) use info;
28+
29+
macro_rules! warning {
30+
($arg:tt) => ({
31+
use crate::common::lazy::CONFIG;
32+
use crate::common::types::LogLevel;
33+
34+
if CONFIG.log_level.gte(&LogLevel::Warning) {
35+
use colored::*;
36+
let level = "[WARN]".yellow();
37+
println!("{level} {}", $arg)
38+
}
39+
});
40+
($arg:tt, $($arg2:tt)*) => ({
41+
use crate::common::lazy::CONFIG;
42+
use crate::common::types::LogLevel;
43+
44+
if CONFIG.log_level.gte(&LogLevel::Warning) {
45+
use colored::*;
46+
let level = "[WARN]".yellow();
47+
println!("{level} {}", format!($arg, $($arg2)*))
48+
}
49+
});
50+
}
51+
52+
pub(crate) use warning;
53+
54+
macro_rules! error {
55+
($arg:tt) => ({
56+
use crate::common::lazy::CONFIG;
57+
use crate::common::types::LogLevel;
58+
59+
if CONFIG.log_level.gte(&LogLevel::Error) {
60+
use colored::*;
61+
let level = "[ERROR]".red();
62+
let message = $arg;
63+
eprintln!("{level} {message}")
64+
}
65+
});
66+
($arg:tt, $($arg2:tt)*) => ({
67+
use crate::common::lazy::CONFIG;
68+
use crate::common::types::LogLevel;
69+
if CONFIG.log_level.gte(&LogLevel::Error) {
70+
use colored::*;
71+
let level = "[ERROR]".red();
72+
let message = format!("{}", format!($arg, $($arg2)*));
73+
eprintln!("{level} {message}")
74+
}
75+
});
76+
}
77+
78+
pub(crate) use error;

src/common/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
pub mod logger;
12
extern crate core;
23

34
use swc_common::MultiSpan;

src/common/types.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,18 @@ pub enum DatabaseType {
1313
Postgres,
1414
Mysql,
1515
}
16+
17+
#[derive(ArgEnum, Debug, Clone, Serialize, Deserialize, Copy)]
18+
#[serde(rename_all = "lowercase")]
19+
pub enum LogLevel {
20+
Info = 3,
21+
Warning = 2,
22+
Error = 1,
23+
}
24+
25+
impl LogLevel {
26+
/// Check if the current log level is greater than or equal to the other log level
27+
pub fn gte(&self, other: &Self) -> bool {
28+
*self as u8 >= *other as u8
29+
}
30+
}

src/main.rs

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,23 +11,31 @@ use crate::core::execute::execute;
1111

1212
use dotenv::dotenv;
1313
use sqlx_ts::ts_generator::generator::clear_single_ts_file_if_exists;
14+
use std::env;
15+
use std::io::{stderr, stdout, Write};
1416

1517
use crate::common::lazy::CLI_ARGS;
18+
use crate::common::logger::*;
1619
use crate::{parser::parse_source, scan_folder::scan_folder};
1720
use color_eyre::{eyre::eyre, eyre::Result};
1821

22+
fn set_default_env_var() {
23+
if env::var("SQLX_TS_LOG").is_err() {
24+
env::set_var("SQLX_TS_LOG", "info");
25+
}
26+
}
27+
1928
fn main() -> Result<()> {
20-
color_eyre::install()?;
21-
dotenv().ok();
29+
set_default_env_var();
2230

2331
let source_folder = &CLI_ARGS.path;
2432
let ext = &CLI_ARGS.ext;
2533

26-
println!("Scanning {:?} for SQLs with extension {:?}", source_folder, ext);
34+
info!("Scanning {:?} for SQLs with extension {:?}", source_folder, ext);
2735

2836
let files = scan_folder(source_folder, ext);
2937
if files.is_empty() {
30-
println!(
38+
info!(
3139
"No targets detected, is it an empty folder? - source_folder: {:?}, ext: {:?}",
3240
source_folder, ext
3341
);
@@ -41,12 +49,12 @@ fn main() -> Result<()> {
4149
let (sqls, handler) = parse_source(&file_path)?;
4250
let failed = execute(&sqls, &handler)?;
4351
if failed {
44-
eprintln!("SQLs failed to compile!");
52+
eprint!("SQLs failed to compile!");
4553
std::process::exit(1)
4654
}
4755
}
4856

49-
println!("No SQL errors detected!");
57+
info!("No SQL errors detected!");
5058
// NOTE: There are different exit code depending on the platform https://doc.rust-lang.org/std/process/fn.exit.html#platform-specific-behavior
5159
// Make sure to consider exit code all major platforms
5260
std::process::exit(0);

src/ts_generator/sql_parser/expressions/translate_expr.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use crate::common::lazy::{CONFIG, DB_SCHEMA};
2+
use crate::common::logger::warning;
23
use crate::ts_generator::errors::TsGeneratorError;
34
use crate::ts_generator::sql_parser::expressions::translate_data_type::translate_value;
45
use crate::ts_generator::sql_parser::expressions::translate_table_with_joins::translate_table_from_expr;
@@ -183,7 +184,14 @@ pub fn translate_expr(
183184

184185
// if the select item is a compound identifier and does not has an alias, we should use `table_name.ident` as the key name
185186
let key_name = format!("{}_{}", table_name, ident);
186-
let key_name = alias.unwrap_or(key_name.as_str());
187+
let key_name = &alias.unwrap_or_else(|| {
188+
warning!(
189+
"Missing an alias for a compound identifier, using {} as the key name. Prefer adding an alias for example: `{} AS {}`",
190+
key_name, expr, ident
191+
);
192+
key_name.as_str()
193+
});
194+
187195
ts_query.insert_result(
188196
Some(key_name),
189197
&[field.field_type.to_owned()],

0 commit comments

Comments
 (0)