diff --git a/medplat-web/src/main/java/com/argusoft/medplat/query/controller/NlpQueryController.java b/medplat-web/src/main/java/com/argusoft/medplat/query/controller/NlpQueryController.java new file mode 100644 index 000000000..b0b90131a --- /dev/null +++ b/medplat-web/src/main/java/com/argusoft/medplat/query/controller/NlpQueryController.java @@ -0,0 +1,26 @@ +package com.argusoft.medplat.query.controller; + +import com.argusoft.medplat.query.service.NlpQueryService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +@RestController +@RequestMapping("/api/nlp") +public class NlpQueryController { + + @Autowired + private NlpQueryService nlpQueryService; + + @PostMapping("/preview") +public Map previewQuery(@RequestBody Map request) { + + try { + String input = request.get("query"); + String sql = nlpQueryService.buildQuery(input); + return Map.of("previewSql", sql); + } catch (Exception e) { + return Map.of("error", e.getMessage()); + } +} \ No newline at end of file diff --git a/medplat-web/src/main/java/com/argusoft/medplat/query/service/NlpQueryService.java b/medplat-web/src/main/java/com/argusoft/medplat/query/service/NlpQueryService.java new file mode 100644 index 000000000..5c11e8a65 --- /dev/null +++ b/medplat-web/src/main/java/com/argusoft/medplat/query/service/NlpQueryService.java @@ -0,0 +1,60 @@ +package com.argusoft.medplat.query.service; + +import org.springframework.stereotype.Service; + +import java.util.*; + +@Service +public class NlpQueryService { + + private static final Map TABLE_MAP = Map.of( + "patients", "patients", + "users", "users" + ); + + private static final Set ALLOWED_COLUMNS = Set.of( + "id", "name", "age", "gender" + ); + + public String buildQuery(String input) { + + input = input.toLowerCase(); + + if (!input.startsWith("show")) { + throw new IllegalArgumentException("Only SELECT queries supported."); + } + + String table = null; + for (String key : TABLE_MAP.keySet()) { + if (input.contains(key)) { + table = TABLE_MAP.get(key); + break; + } + } + + if (table == null) { + throw new IllegalArgumentException("No valid table found."); + } + + String query = "SELECT * FROM " + table; + + if (input.contains("where")) { + String conditionPart = input.split("where")[1].trim(); + + String[] tokens = conditionPart.split(" "); + if (tokens.length >= 3) { + String column = tokens[0]; + String operator = tokens[1]; + String value = tokens[2]; + + if (!ALLOWED_COLUMNS.contains(column)) { + throw new IllegalArgumentException("Invalid column."); + } + + query += " WHERE " + column + " " + operator + " ?"; + } + } + + return query; + } +} \ No newline at end of file