use handlebars::Handlebars;
use lazy_static::lazy_static;
use regex::Regex;
use serde_json::json;
use crate::prelude2::*;
use crate::sitepages::developer::isql::Field;
use super::{to_rust_type, Table, IQL_TEMPLATE};
#[rustfmt::skip]
lazy_static! {
static ref REGEX_LINE: Regex = Regex::new(r"`(\w+)` (\w+(?:\(\d+(?:,\d+)?\))?) (\w+)?(?: COMMENT '([^']+)')?").unwrap();
}
pub async fn index(request: HttpRequest) -> impl Responder {
let ctx = tera::Context::new();
request.render(200, "developer/isql/isql_index.html", ctx)
}
pub async fn gen_code(
query: web::Query<HashMap<String, String>>,
body: web::Bytes,
request: HttpRequest,
) -> impl Responder {
let prefix = query
.get("prefix")
.ok_or_else(|| Error::invalid_request("Missing query string parameter: prefix"))?;
let table_name = query
.get("table_name")
.ok_or_else(|| Error::invalid_request("Missing query string parameter: table_name"))?;
let pk_rs_name = query
.get("pk_rs_name")
.ok_or_else(|| Error::invalid_request("Missing query string parameter: pk_rs_name"))?;
let pk_rs_type = query
.get("pk_rs_type")
.ok_or_else(|| Error::invalid_request("Missing query string parameter: pk_rs_type"))?;
let pk_db_name = query
.get("pk_db_name")
.ok_or_else(|| Error::invalid_request("Missing query string parameter: pk_db_name"))?;
let create_table_stmt = match crate::commons::bytes_to_string(body.to_vec()) {
Ok(val) => val,
Err(e) => return request.json(200, R::failed(500, e.to_string())),
};
let mut fields = Vec::<Field>::new();
for capture in REGEX_LINE.captures_iter(&create_table_stmt) {
let field_name = &capture[1];
let data_type = &capture[2];
let is_not_null = &capture[3];
let _comment = capture.get(4).map_or("", |m| m.as_str());
fields.push(Field {
name: field_name.replace(prefix, "").to_owned(),
rust_type: to_rust_type(data_type).to_owned(),
nullable: is_not_null != "NOT",
db_field_name: field_name.to_owned(),
})
}
#[rustfmt::skip]
let table = Table {
name: table_name.to_owned(),
pk_rs_name: pk_rs_name.to_owned(),
pk_rs_type: pk_rs_type.to_owned(),
fields,
pk_db_name: pk_db_name.to_owned(),
};
let mut handlebars = Handlebars::new();
#[rustfmt::skip]
handlebars.register_template_string("t1", *IQL_TEMPLATE).unwrap();
let data = json!({
"struct_name": table.get_struct_name(),
"table_name": table.name,
"pk_rs_name": table.pk_rs_name,
"pk_rs_type": table.pk_rs_type,
"pk_db_name": table.pk_db_name,
"fields": table.fields.clone(),
"field_count": table.fields.len(),
});
let r = handlebars.render("t1", &data).unwrap();
request.text(200, r.trim())
}