Skip to content

Commit

Permalink
docs update (#110)
Browse files Browse the repository at this point in the history
* docs: convertToCamelCase is false by default

* rename

* tests: adding enabled config test

* test: adding enabled tests

* clippy: fix

* chore: fix tests

* fix test
  • Loading branch information
JasonShin authored May 18, 2024
1 parent 6b4984c commit d047321
Show file tree
Hide file tree
Showing 27 changed files with 236 additions and 50 deletions.
2 changes: 1 addition & 1 deletion book/src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
# API

- [Connecting to databases](./api/1.connecting-to-db.md)
- [.sqlxrc file](./api/1.3.configs-file-based.md)
- [.sqlxrc.json file](./api/1.3.configs-file-based.md)
- [CLI options](./api/1.1.cli-options.md)
- [environment variables](./api/1.2.environment-variables.md)
- [.sqlxignore file](./api/2.ignore-patterns.md)
Expand Down
4 changes: 2 additions & 2 deletions book/src/api/1.3.configs-file-based.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ this name, unless you give it a custom path to override it using `--config` CLI
$ sqlx-ts --config <path to a custom .sqlxrc.json>
```

Example `sqlxrc.json`
Example `.sqlxrc.json`

```json
{
Expand Down Expand Up @@ -90,4 +90,4 @@ Supported fields of each connection include

Support for configuration of generate types operations.
- `enabled` (default: false): enables type generation via config
- `convertToCamelCaseColumnName` (default: true): when generating field name based on table's column name, it will automatically cast to camelCase in TypeScript
- `convertToCamelCaseColumnName` (default: false): when generating field name based on table's column name, it will automatically cast to camelCase in TypeScript
3 changes: 1 addition & 2 deletions src/common/cli.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@

use crate::common::types::{DatabaseType, JsExtension, LogLevel};
use std::fmt;
use clap::Parser;
use std::fmt;

impl fmt::Display for JsExtension {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Expand Down
10 changes: 7 additions & 3 deletions src/common/config.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::common::dotenv::Dotenv;
use crate::common::lazy::CLI_ARGS;
use crate::common::types::{DatabaseType, LogLevel};
use crate::core::connection;
use regex::Regex;
use serde;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -64,6 +63,12 @@ pub struct Config {
pub log_level: LogLevel,
}

impl Default for Config {
fn default() -> Self {
Self::new()
}
}

impl Config {
pub fn new() -> Config {
let dotenv = Dotenv::new();
Expand Down Expand Up @@ -325,8 +330,7 @@ impl Config {
let log_level_from_file = file_based_config
.as_ref()
.ok()
.map(|config| config.log_level)
.flatten();
.and_then(|config| config.log_level);

CLI_ARGS.log_level.or(log_level_from_file).unwrap_or(LogLevel::Info)
}
Expand Down
6 changes: 6 additions & 0 deletions src/common/dotenv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ pub struct Dotenv {
pub pg_search_path: Option<String>,
}

impl Default for Dotenv {
fn default() -> Self {
Self::new()
}
}

impl Dotenv {
pub fn new() -> Dotenv {
Dotenv {
Expand Down
1 change: 0 additions & 1 deletion src/common/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,4 +75,3 @@ macro_rules! error {
});
}

pub(crate) use error;
2 changes: 0 additions & 2 deletions src/core/postgres/prepare.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
use crate::common::lazy::CONFIG;
use crate::common::SQL;
use crate::core::connection::DBConn;
use crate::ts_generator::generator::generate_ts_interface;
use crate::ts_generator::types::ts_query::TsQuery;
use color_eyre::eyre::Result;
use std::borrow::BorrowMut;

use swc_common::errors::Handler;

Expand Down
2 changes: 1 addition & 1 deletion src/parser/decl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ pub fn process_class_decl(sqls: &mut Vec<SQL>, class: &ClassDecl, import_alias:
Ok(())
}

pub fn process_decl(mut sqls: &mut Vec<SQL>, decl: &Decl, import_alias: &String) -> Result<()> {
pub fn process_decl(sqls: &mut Vec<SQL>, decl: &Decl, import_alias: &String) -> Result<()> {
match decl {
Decl::Class(class) => {
process_class_decl(sqls, class, import_alias)?;
Expand Down
4 changes: 2 additions & 2 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use swc_common::{
sync::Lrc,
FileName, MultiSpan, SourceMap,
};
use swc_ecma_ast::{ImportSpecifier, Key, ModuleDecl, ModuleItem, Stmt};
use swc_ecma_ast::{Key, ModuleDecl, ModuleItem, Stmt};
use swc_ecma_parser::TsConfig;
use swc_ecma_parser::{lexer::Lexer, Parser, Syntax};
use tag::get_sql_from_expr;
Expand Down Expand Up @@ -43,7 +43,7 @@ fn get_var_decl_name_from_key(key: &Key) -> Option<String> {
}
}

fn recurse_and_find_sql(mut sqls: &mut Vec<SQL>, stmt: &Stmt, import_alias: &String) -> Result<()> {
fn recurse_and_find_sql(sqls: &mut Vec<SQL>, stmt: &Stmt, import_alias: &String) -> Result<()> {
match stmt {
Stmt::Block(block) => {
for stmt in &block.stmts {
Expand Down
2 changes: 1 addition & 1 deletion src/parser/tag.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::common::SQL;
use swc_common::MultiSpan;
use swc_ecma_ast::{
AssignTarget, BlockStmt, ClassMember, Expr, OptChainBase, Pat, Prop, PropOrSpread, SuperProp, VarDeclarator,
BlockStmt, ClassMember, Expr, OptChainBase, Pat, Prop, PropOrSpread, SuperProp, VarDeclarator,
};

use super::{get_var_decl_name_from_key, recurse_and_find_sql};
Expand Down
2 changes: 1 addition & 1 deletion src/ts_generator/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ pub fn write_single_ts_file(sqls_to_write: String) -> Result<()> {
let mut file_to_write = OpenOptions::new()
.create(true)
.read(true)
.write(true)

.append(true)
.open(&output)?;

Expand Down
6 changes: 6 additions & 0 deletions src/ts_generator/information_schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@ pub struct DBSchema {
tables_cache: HashMap<String, Fields>,
}

impl Default for DBSchema {
fn default() -> Self {
Self::new()
}
}

impl DBSchema {
pub fn new() -> DBSchema {
DBSchema {
Expand Down
2 changes: 1 addition & 1 deletion src/ts_generator/types/ts_query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ impl TsQuery {
) -> Result<(), TsGeneratorError> {
if is_selection {
if let Some(alias) = alias {
let temp_alias = alias.clone();
let temp_alias = alias;
let alias = &self.format_column_name(alias);
let value = &self
.annotated_results
Expand Down
20 changes: 14 additions & 6 deletions test-utils/src/sandbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,12 @@ pub struct TestConfig {
pub db_user: String,
pub db_pass: Option<String>,
pub db_name: String,
pub generate_types: bool,
pub config_file_name: Option<String>,
}

impl TestConfig {
pub fn new(db_type: &str, config_file_name: Option<String>) -> Self {
pub fn new(db_type: &str, generate_types: bool, config_file_name: Option<String>) -> Self {
if db_type == "mysql" {
return TestConfig {
db_type: "mysql".into(),
Expand All @@ -35,6 +36,7 @@ impl TestConfig {
db_user: "root".to_string(),
db_pass: None,
db_name: "sqlx-ts".to_string(),
generate_types,
config_file_name,
}
}
Expand All @@ -46,6 +48,7 @@ impl TestConfig {
db_user: "postgres".to_string(),
db_pass: Some("postgres".to_string()),
db_name: "postgres".to_string(),
generate_types,
config_file_name,
}
}
Expand Down Expand Up @@ -123,8 +126,12 @@ $(
.arg(format!("--db-host={db_host}"))
.arg(format!("--db-port={db_port}"))
.arg(format!("--db-user={db_user}"))
.arg(format!("--db-name={db_name}"))
.arg("-g");
.arg(format!("--db-name={db_name}"));

println!("checking generate types {:?}", test_config.generate_types);
if (test_config.generate_types) {
cmd.arg("-g");
}

if (config_file_name.is_some()) {
let cwd = env::current_dir()?;
Expand All @@ -143,10 +150,11 @@ $(
.success()
.stdout(predicates::str::contains("No SQL errors detected!"));

let generated_types: &str = $generated_types;
let generated_types: &str = $generated_types.clone();

if generated_types != "" {
let type_file = fs::read_to_string(parent_path.join("index.queries.ts"))?;
let type_file = fs::read_to_string(parent_path.join("index.queries.ts"));
if type_file.is_ok() {
let type_file = type_file.unwrap().clone();
let type_file = type_file.trim();
assert_eq!(
generated_types.trim().to_string().flatten(),
Expand Down
23 changes: 23 additions & 0 deletions tests/configs/.sqlxrc.enabled.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"generateTypes": {
"enabled": false
},
"connections": {
"default": {
"DB_TYPE": "postgres",
"DB_HOST": "127.0.0.1",
"DB_PORT": 54321,
"DB_USER": "postgres",
"DB_PASS": "postgres",
"DB_NAME": "postgres",
"PG_SEARCH_PATH": "public,myschema"
},
"db_mysql": {
"DB_TYPE": "mysql",
"DB_HOST": "127.0.0.1",
"DB_PORT": 33306,
"DB_USER": "root",
"DB_NAME": "sqlx-ts"
}
}
}
23 changes: 23 additions & 0 deletions tests/configs/.sqlxrc.not_enabled.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"generateTypes": {
"enabled": false
},
"connections": {
"default": {
"DB_TYPE": "postgres",
"DB_HOST": "127.0.0.1",
"DB_PORT": 54321,
"DB_USER": "postgres",
"DB_PASS": "postgres",
"DB_NAME": "postgres",
"PG_SEARCH_PATH": "public,myschema"
},
"db_mysql": {
"DB_TYPE": "mysql",
"DB_HOST": "127.0.0.1",
"DB_PORT": 33306,
"DB_USER": "root",
"DB_NAME": "sqlx-ts"
}
}
}
11 changes: 4 additions & 7 deletions tests/covert_to_camelcase.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/// Test suites for converting any case to camelCase if generateTypes.convertToCamelCase is true
///
///
#[cfg(test)]
mod string_functions_tests {
use assert_cmd::prelude::*;
Expand All @@ -9,15 +9,13 @@ mod string_functions_tests {
use std::io::Write;
use std::process::Command;
use tempfile::tempdir;


use pretty_assertions::assert_eq;
use test_utils::test_utils::TSString;
use test_utils::{run_test, sandbox::TestConfig};


#[rustfmt::skip]
run_test!(retain_original, TestConfig::new("postgres", Some(".sqlxrc.camelcase1.json".to_string())),
run_test!(retain_original, TestConfig::new("postgres", true, Some(".sqlxrc.camelcase1.json".to_string())),
//// TS query ////
r#"
const someQuery = sql`
Expand Down Expand Up @@ -47,7 +45,7 @@ export interface ISomeQueryQuery {
);

#[rustfmt::skip]
run_test!(convert_camelcase, TestConfig::new("postgres", Some(".sqlxrc.camelcase2.json".to_string())),
run_test!(convert_camelcase, TestConfig::new("postgres", true, Some(".sqlxrc.camelcase2.json".to_string())),

//// TS query ////
r#"
Expand Down Expand Up @@ -77,9 +75,8 @@ export interface ISomeQueryQuery {
"#
);


#[rustfmt::skip]
run_test!(retain_original_on_missing_config, TestConfig::new("postgres", Some(".sqlxrc.camelcase3.json".to_string())),
run_test!(retain_original_on_missing_config, TestConfig::new("postgres", true, Some(".sqlxrc.camelcase3.json".to_string())),

//// TS query ////
r#"
Expand Down
4 changes: 2 additions & 2 deletions tests/mysql_delete_query_parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ mod mysql_delete_query_parameters {
use test_utils::{run_test, sandbox::TestConfig};

#[rustfmt::skip]
run_test!(should_pick_query_params_from_binary_ops, TestConfig::new("mysql", None),
run_test!(should_pick_query_params_from_binary_ops, TestConfig::new("mysql", true, None),

//// TS query ////
r#"
Expand All @@ -40,7 +40,7 @@ export interface ISomeDeleteQueryQuery {
"#);

#[rustfmt::skip]
run_test!(should_pick_query_params_from_subquery, TestConfig::new("mysql", None),
run_test!(should_pick_query_params_from_subquery, TestConfig::new("mysql", true, None),

//// TS query ////
r#"
Expand Down
4 changes: 2 additions & 2 deletions tests/mysql_insert_query_parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ mod mysql_insert_query_parameters {
use test_utils::{run_test, sandbox::TestConfig};

#[rustfmt::skip]
run_test!(should_pick_query_params_from_single_row_of_values, TestConfig::new("mysql", None),
run_test!(should_pick_query_params_from_single_row_of_values, TestConfig::new("mysql", true, None),

//// TS query ////
r#"
Expand All @@ -39,7 +39,7 @@ export interface ISomeInputQueryQuery {
"#);

#[rustfmt::skip]
run_test!(should_pick_query_params_from_multiple_rows_of_values, TestConfig::new("mysql", None),
run_test!(should_pick_query_params_from_multiple_rows_of_values, TestConfig::new("mysql", true, None),

//// TS query ////
r#"
Expand Down
8 changes: 4 additions & 4 deletions tests/mysql_query_parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ mod mysql_query_parameters_tests {
use test_utils::{run_test, sandbox::TestConfig};

#[rustfmt::skip]
run_test!(should_pick_query_params_from_flat_list_of_binary_ops, TestConfig::new("mysql", None),
run_test!(should_pick_query_params_from_flat_list_of_binary_ops, TestConfig::new("mysql", true, None),

//// TS query ////
r#"
Expand Down Expand Up @@ -45,7 +45,7 @@ export interface ISomeQueryQuery {
"#);

#[rustfmt::skip]
run_test!(should_pick_query_params_from_in_list, TestConfig::new("mysql", None),
run_test!(should_pick_query_params_from_in_list, TestConfig::new("mysql", true, None),

//// TS query ////
r#"
Expand Down Expand Up @@ -75,7 +75,7 @@ export interface ISomeQueryQuery {
"#);

#[rustfmt::skip]
run_test!(should_pick_query_params_from_in_subqueries, TestConfig::new("mysql", None),
run_test!(should_pick_query_params_from_in_subqueries, TestConfig::new("mysql", true, None),

//// TS query ////
r#"
Expand Down Expand Up @@ -114,7 +114,7 @@ export interface ISomeQueryQuery {
"#);

#[rustfmt::skip]
run_test!(should_pick_query_params_from_subqueries, TestConfig::new("mysql", None),
run_test!(should_pick_query_params_from_subqueries, TestConfig::new("mysql", true, None),

//// TS query ////
r#"
Expand Down
Loading

0 comments on commit d047321

Please sign in to comment.