Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -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<String, String> previewQuery(@RequestBody Map<String, String> 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());
}
}
Original file line number Diff line number Diff line change
@@ -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<String, String> TABLE_MAP = Map.of(
"patients", "patients",
"users", "users"
);

private static final Set<String> 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;
}
}