use no_mistakes_postgres_sql::statement_facts::SqlIsolation;
use no_mistakes_ts_facts::syntax_helpers::unwrap_ts_wrappers;
use oxc_ast::ast::{Argument, Expression, ObjectPropertyKind, PropertyKey, PropertyKind};
pub(super) struct Initializer {
pub(super) factory: String,
pub(super) call_start: u32,
pub(super) isolation: SqlIsolation,
}
pub(super) fn from_initializer(init: &Expression<'_>) -> Option<Initializer> {
let mut init = unwrap_ts_wrappers(init);
if let Expression::AwaitExpression(awaited) = init {
init = unwrap_ts_wrappers(&awaited.argument);
}
let Expression::CallExpression(call) = init else {
return None;
};
let Expression::Identifier(factory) = unwrap_ts_wrappers(&call.callee) else {
return None;
};
Some(Initializer {
factory: factory.name.to_string(),
call_start: call.span.start,
isolation: from_argument(call.arguments.first()),
})
}
pub(super) fn from_argument(argument: Option<&Argument<'_>>) -> SqlIsolation {
let Some(Expression::ObjectExpression(options)) = argument
.and_then(Argument::as_expression)
.map(unwrap_ts_wrappers)
else {
return SqlIsolation::Unknown;
};
let mut level = SqlIsolation::Unknown;
for property in &options.properties {
let ObjectPropertyKind::ObjectProperty(property) = property else {
level = SqlIsolation::Unknown;
continue;
};
let Some(key) = property.key.static_name().filter(|_| {
!property.key.is_computed() || matches!(property.key, PropertyKey::StringLiteral(_))
}) else {
level = SqlIsolation::Unknown;
continue;
};
if key != "isolationLevel" {
continue;
}
if property.kind != PropertyKind::Init {
level = SqlIsolation::Unknown;
continue;
}
let Expression::StringLiteral(value) = unwrap_ts_wrappers(&property.value) else {
level = SqlIsolation::Unknown;
continue;
};
level = match no_mistakes_ts_facts::ast::js_literal(value)
.to_ascii_lowercase()
.as_str()
{
"serializable" => SqlIsolation::Serializable,
"read committed" | "read uncommitted" | "repeatable read" => SqlIsolation::Other,
_ => SqlIsolation::Unknown,
};
}
level
}