Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
945 changes: 386 additions & 559 deletions Cargo.lock

Large diffs are not rendered by default.

23 changes: 11 additions & 12 deletions src/common/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,7 @@ impl Config {
let connections = Self::build_configs(&dotenv, file_config_path);
let generate_types_config = Self::generate_types_config(file_config_path);

let generate_types_config =
generate_types_config.and_then(|config| if config.enabled { Some(config) } else { None });
let generate_types_config = generate_types_config.filter(|config| config.enabled);
let ignore_patterns = Self::get_ignore_patterns(&default_ignore_config_path);
let log_level = Self::get_log_level(file_config_path);
Config {
Expand Down Expand Up @@ -374,11 +373,11 @@ impl Config {

format!(
"mysql://{user}:{pass}@{host}:{port}/{db_name}",
user = &conn.db_user,
pass = &conn.db_pass.as_ref().unwrap_or(&"".to_string()),
host = &conn.db_host,
port = &conn.db_port,
db_name = &conn.db_name.clone().unwrap_or(conn.db_user.to_owned()),
user = conn.db_user,
pass = conn.db_pass.as_ref().unwrap_or(&"".to_string()),
host = conn.db_host,
port = conn.db_port,
db_name = conn.db_name.clone().unwrap_or(conn.db_user.to_owned()),
)
.to_string()
}
Expand All @@ -404,14 +403,14 @@ impl Config {

format!(
"postgresql://{user}:{pass}@{host}:{port}/{db_name}",
user = &conn.db_user,
pass = &conn.db_pass.as_ref().unwrap_or(&"".to_string()),
host = &conn.db_host,
port = &conn.db_port,
user = conn.db_user,
pass = conn.db_pass.as_ref().unwrap_or(&"".to_string()),
host = conn.db_host,
port = conn.db_port,
// This is to follow the spec of Rust Postgres
// `db_user` name gets used if `db_name` is not provided
// https://docs.rs/postgres/latest/postgres/config/struct.Config.html#keys
db_name = &conn.db_name.clone().unwrap_or(conn.db_user.to_owned()),
db_name = conn.db_name.clone().unwrap_or(conn.db_user.to_owned()),
)
}

Expand Down
2 changes: 1 addition & 1 deletion src/common/lazy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ pub static DB_CONN_CACHE: LazyLock<HashMap<String, Arc<Mutex<DBConn>>>> = LazyLo
if connection_config.pg_search_path.is_some() {
let search_path_query = format!(
"SET search_path TO {}",
&connection_config.pg_search_path.clone().unwrap().as_str()
connection_config.pg_search_path.clone().unwrap().as_str()
);
{
let conn = conn.lock().await;
Expand Down
1 change: 1 addition & 0 deletions src/ts_generator/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ pub enum TsGeneratorError {
UpdateStatementProcessingFailed { reason: String, query: String },
#[error("[E019] Table '{table}' not found in database schema. Check that the table exists and is accessible.")]
TableNotFoundInSchema { table: String },
#[allow(dead_code)]
#[error("[E020] Failed to infer table name while processing WHERE clause. Query: `{query}`")]
TableNameInferenceFailedInWhere { query: String },
#[error("Unknown error: `{0}`")]
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 @@ -89,7 +89,7 @@ pub fn write_single_ts_file(sqls_to_write: String) -> Result<()> {
.unwrap_or_else(|_| {
panic!(
"Failed to write to file {:?} - check if the --generate-path provided is an existing folder",
&output
output
)
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ pub async fn handle_polymorphic_functions(
if let Some(field) = table_details.get(&column_name) {
return ctx.ts_query.insert_result(
Some(ctx.alias),
&[field.field_type.to_owned()],
std::slice::from_ref(&field.field_type),
ctx.is_selection,
false, // IFNULL/COALESCE removes nullability
expr_log,
Expand All @@ -68,7 +68,7 @@ pub async fn handle_polymorphic_functions(
if let Some(field) = table_details.get(&column_name) {
return ctx.ts_query.insert_result(
Some(ctx.alias),
&[field.field_type.to_owned()],
std::slice::from_ref(&field.field_type),
ctx.is_selection,
false, // IFNULL/COALESCE removes nullability
expr_log,
Expand Down
20 changes: 10 additions & 10 deletions src/ts_generator/sql_parser/expressions/translate_expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,15 +155,13 @@ async fn get_sql_query_param_directed(
db_conn: &DBConn,
cte_columns: &std::collections::HashMap<String, std::collections::HashMap<String, TsFieldType>>,
) -> Result<Option<(TsFieldType, bool, Option<String>)>, TsGeneratorError> {
let table_name: Option<String>;

if table_with_joins.is_some() {
table_name = translate_table_from_expr(table_with_joins, &column_expr.clone()).ok();
let table_name: Option<String> = if table_with_joins.is_some() {
translate_table_from_expr(table_with_joins, &column_expr.clone()).ok()
} else if single_table_name.is_some() {
table_name = single_table_name.map(|x| x.to_string());
single_table_name.map(|x| x.to_string())
} else {
return Ok(None);
}
};

let column_name = translate_column_name_expr(column_expr);

Expand Down Expand Up @@ -236,9 +234,10 @@ pub async fn translate_expr(
if let Some(tvf_columns) = ts_query.table_valued_function_columns.get(table_name) {
if let Some(ts_type) = tvf_columns.get(&column_name) {
let field_name = alias.unwrap_or(column_name.as_str());
let ts_type = ts_type.to_owned();
ts_query.insert_result(
Some(field_name),
&[ts_type.to_owned()],
std::slice::from_ref(&ts_type),
is_selection,
false, // Table-valued function columns are not nullable by default
expr_for_logging,
Expand All @@ -255,7 +254,7 @@ pub async fn translate_expr(
let field_name = alias.unwrap_or(column_name.as_str());
ts_query.insert_result(
Some(field_name),
&[field.field_type.to_owned()],
std::slice::from_ref(&field.field_type),
is_selection,
field.is_nullable,
expr_for_logging,
Expand Down Expand Up @@ -293,9 +292,10 @@ pub async fn translate_expr(
key_name.as_str()
});

let ts_type = ts_type.to_owned();
ts_query.insert_result(
Some(key_name),
&[ts_type.to_owned()],
std::slice::from_ref(&ts_type),
is_selection,
false, // Table-valued function columns are not nullable by default
expr_for_logging,
Expand Down Expand Up @@ -325,7 +325,7 @@ pub async fn translate_expr(

ts_query.insert_result(
Some(key_name),
&[field.field_type.to_owned()],
std::slice::from_ref(&field.field_type),
is_selection,
field.is_nullable,
expr_for_logging,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ pub fn translate_table_from_assignments(
match first_part {
Some(part) => {
if let Some(ident) = part.as_ident() {
find_table_name_from_identifier(table_with_joins, &[ident.value.to_string()])
find_table_name_from_identifier(table_with_joins, std::slice::from_ref(&ident.value))
} else {
// If it's a function-based name, use default table
Ok(get_default_table(table_with_joins))
Expand Down
2 changes: 1 addition & 1 deletion src/ts_generator/sql_parser/translate_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ async fn translate_assignments(
db_conn: &DBConn,
) -> Result<(), TsGeneratorError> {
for assignment in assignments {
let table = translate_table_from_assignments(&[table_with_joins.to_owned()], assignment)?;
let table = translate_table_from_assignments(std::slice::from_ref(table_with_joins), assignment)?;

translate_assignment(assignment, table.as_str(), ts_query, db_conn)
.await
Expand Down
2 changes: 1 addition & 1 deletion test-utils/src/sandbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ impl TestConfig {

/// Checks if the MySQL server at the given host:port is above the specified major.minor version.
/// Uses `docker exec` to query the version. Returns true if version cannot be determined.
pub fn is_mysql_version_above(db_host: &str, db_port: i32, major: u32, minor: u32) -> bool {
pub fn is_mysql_version_above(_db_host: &str, _db_port: i32, major: u32, minor: u32) -> bool {
let output = std::process::Command::new("docker")
.args(["exec", "sqlx-ts-mysql-1", "mysql", "-u", "root", "-N", "-e", "SELECT VERSION();"])
.output();
Expand Down
86 changes: 40 additions & 46 deletions tests/demo_happy_path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,30 +58,27 @@ mod demo_happy_path_tests {
}

// Verify all generated types match snapshots
for entry in WalkDir::new(demo_path) {
if entry.is_ok() {
let entry = entry.unwrap();
let path = entry.path();
let parent = entry.path().parent().unwrap();
let file_name = path.file_name().unwrap().to_str().unwrap().to_string();

if path.is_file() && file_name.ends_with(".queries.ts") {
let base_file_name = file_name.split('.').collect::<Vec<&str>>();
let base_file_name = base_file_name.first().unwrap();
let snapshot_path = parent.join(format!("{base_file_name}.snapshot.ts"));

let generated_types = fs::read_to_string(path)?;

if !snapshot_path.exists() {
let mut snapshot_file = fs::File::create(&snapshot_path)?;
writeln!(snapshot_file, "{generated_types}")?;
}

assert_eq!(
generated_types.trim().to_string().trim(),
fs::read_to_string(&snapshot_path)?.to_string().trim(),
)
for entry in WalkDir::new(demo_path).into_iter().flatten() {
let path = entry.path();
let parent = entry.path().parent().unwrap();
let file_name = path.file_name().unwrap().to_str().unwrap().to_string();

if path.is_file() && file_name.ends_with(".queries.ts") {
let base_file_name = file_name.split('.').collect::<Vec<&str>>();
let base_file_name = base_file_name.first().unwrap();
let snapshot_path = parent.join(format!("{base_file_name}.snapshot.ts"));

let generated_types = fs::read_to_string(path)?;

if !snapshot_path.exists() {
let mut snapshot_file = fs::File::create(&snapshot_path)?;
writeln!(snapshot_file, "{generated_types}")?;
}

assert_eq!(
generated_types.trim().to_string().trim(),
fs::read_to_string(&snapshot_path)?.to_string().trim(),
)
}
}

Expand Down Expand Up @@ -334,30 +331,27 @@ mod demo_happy_path_tests {
.stdout(predicates::str::contains("No SQL errors detected!"));

// Verify all generated types match snapshots
for entry in WalkDir::new(&demo_path) {
if entry.is_ok() {
let entry = entry.unwrap();
let path = entry.path();
let parent = entry.path().parent().unwrap();
let file_name = path.file_name().unwrap().to_str().unwrap().to_string();

if path.is_file() && file_name.ends_with(".queries.ts") {
let base_file_name = file_name.split('.').collect::<Vec<&str>>();
let base_file_name = base_file_name.first().unwrap();
let snapshot_path = parent.join(format!("{base_file_name}.snapshot.ts"));

let generated_types = fs::read_to_string(path)?;

if !snapshot_path.exists() {
let mut snapshot_file = fs::File::create(&snapshot_path)?;
writeln!(snapshot_file, "{generated_types}")?;
}

assert_eq!(
generated_types.trim().to_string().trim(),
fs::read_to_string(&snapshot_path)?.to_string().trim(),
)
for entry in WalkDir::new(&demo_path).into_iter().flatten() {
let path = entry.path();
let parent = entry.path().parent().unwrap();
let file_name = path.file_name().unwrap().to_str().unwrap().to_string();

if path.is_file() && file_name.ends_with(".queries.ts") {
let base_file_name = file_name.split('.').collect::<Vec<&str>>();
let base_file_name = base_file_name.first().unwrap();
let snapshot_path = parent.join(format!("{base_file_name}.snapshot.ts"));

let generated_types = fs::read_to_string(path)?;

if !snapshot_path.exists() {
let mut snapshot_file = fs::File::create(&snapshot_path)?;
writeln!(snapshot_file, "{generated_types}")?;
}

assert_eq!(
generated_types.trim().to_string().trim(),
fs::read_to_string(&snapshot_path)?.to_string().trim(),
)
}
}

Expand Down
Loading