feat: multi-query/upload .sql en query runner + selector BD por rol
This commit is contained in:
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/sujit-baniya/fiber-boilerplate/app"
|
||||
"github.com/sujit-baniya/fiber-boilerplate/pkg/auth"
|
||||
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
|
||||
"github.com/sujit-baniya/fiber-boilerplate/pkg/services"
|
||||
)
|
||||
@@ -42,10 +43,29 @@ func QueryRunnerPage(c *fiber.Ctx) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetConxDbList devuelve todas las conexiones DB disponibles (para el selector).
|
||||
// GetConxDbList devuelve las conexiones DB disponibles (según el rol del usuario).
|
||||
// Para API calls (Hermes) sin sesión retorna todas.
|
||||
func GetConxDbList(c *fiber.Ctx) error {
|
||||
user, err := auth.User(c)
|
||||
if err != nil || user == nil {
|
||||
var all []models.ConxDb
|
||||
app.Http.Database.DB.Preload("TipoDb").Preload("Servidor").Find(&all)
|
||||
return c.JSON(fiber.Map{"data": all})
|
||||
}
|
||||
|
||||
var items []models.ConxDb
|
||||
app.Http.Database.DB.Preload("TipoDb").Preload("Servidor").Find(&items)
|
||||
if user.IsAdmin {
|
||||
app.Http.Database.DB.Preload("TipoDb").Preload("Servidor").Find(&items)
|
||||
} else {
|
||||
ids := make([]uint, 0)
|
||||
for _, db := range user.Role.ConxDBs {
|
||||
ids = append(ids, db.ID)
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return c.JSON(fiber.Map{"data": []models.ConxDb{}})
|
||||
}
|
||||
app.Http.Database.DB.Preload("TipoDb").Preload("Servidor").Where("id IN ?", ids).Find(&items)
|
||||
}
|
||||
return c.JSON(fiber.Map{"data": items})
|
||||
}
|
||||
|
||||
@@ -103,6 +123,102 @@ func RunQuery(c *fiber.Ctx) error {
|
||||
return c.JSON(result)
|
||||
}
|
||||
|
||||
// RunBatchQuery ejecuta múltiples consultas en lote.
|
||||
// POST /app/query-runner/run-batch
|
||||
// Body: { conx_db_id, database, sqls: ["...", "..."] }
|
||||
// También soporta multipart/form-data con file .sql
|
||||
func RunBatchQuery(c *fiber.Ctx) error {
|
||||
conxDbIDStr := c.FormValue("conx_db_id", c.Query("conx_db_id"))
|
||||
database := c.FormValue("database", c.Query("database"))
|
||||
|
||||
// Obtener statements del body o del archivo subido
|
||||
var statements []string
|
||||
|
||||
// 1. Intentar leer archivo .sql subido
|
||||
if file, err := c.FormFile("file"); err == nil {
|
||||
f, err := file.Open()
|
||||
if err == nil {
|
||||
defer f.Close()
|
||||
buf := new(bytes.Buffer)
|
||||
buf.ReadFrom(f)
|
||||
content := buf.String()
|
||||
// Dividir por ;
|
||||
for _, stmt := range strings.Split(content, ";") {
|
||||
stmt = strings.TrimSpace(stmt)
|
||||
if stmt != "" {
|
||||
statements = append(statements, stmt)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Si no hay archivo, leer del body JSON
|
||||
if len(statements) == 0 {
|
||||
var body struct {
|
||||
ConxDbID uint `json:"conx_db_id"`
|
||||
Database string `json:"database"`
|
||||
SQLs []string `json:"sqls"`
|
||||
}
|
||||
if err := c.BodyParser(&body); err == nil {
|
||||
conxDbIDStr = strconv.Itoa(int(body.ConxDbID))
|
||||
if body.Database != "" {
|
||||
database = body.Database
|
||||
}
|
||||
for _, s := range body.SQLs {
|
||||
s = strings.TrimSpace(s)
|
||||
if s != "" {
|
||||
statements = append(statements, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(statements) == 0 {
|
||||
return c.Status(400).JSON(fiber.Map{"error": "No hay consultas para ejecutar. Envía sqls[] o un archivo .sql"})
|
||||
}
|
||||
|
||||
conx, err := loadConxDb(conxDbIDStr)
|
||||
if err != nil {
|
||||
return c.Status(400).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
|
||||
type batchResult struct {
|
||||
Index int `json:"index"`
|
||||
SQL string `json:"sql"`
|
||||
Status string `json:"status"`
|
||||
Duration string `json:"duration"`
|
||||
Rows int `json:"rows"`
|
||||
Columns []string `json:"columns,omitempty"`
|
||||
Data []fiber.Map `json:"data,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
results := make([]batchResult, 0, len(statements))
|
||||
|
||||
for i, stmt := range statements {
|
||||
r := services.ExecuteSQL(conx, database, stmt)
|
||||
br := batchResult{
|
||||
Index: i,
|
||||
SQL: stmt,
|
||||
Status: "ok",
|
||||
Duration: fmt.Sprintf("%dms", r.DurationMs),
|
||||
Rows: r.RowCount,
|
||||
}
|
||||
if r.Error != "" {
|
||||
br.Status = "error"
|
||||
br.Error = r.Error
|
||||
} else {
|
||||
br.Columns = r.Columns
|
||||
br.Data = make([]fiber.Map, len(r.Rows))
|
||||
for j, row := range r.Rows {
|
||||
br.Data[j] = fiber.Map(row)
|
||||
}
|
||||
}
|
||||
results = append(results, br)
|
||||
}
|
||||
|
||||
return c.JSON(fiber.Map{"results": results, "total": len(results)})
|
||||
}
|
||||
|
||||
// TestConnection verifica que la conexión funciona.
|
||||
// GET /app/query-runner/test?conx_db_id=1
|
||||
func TestConnection(c *fiber.Ctx) error {
|
||||
|
||||
@@ -69,6 +69,12 @@ func GetRoles(c *fiber.Ctx) error {
|
||||
// })
|
||||
// }
|
||||
|
||||
// Obtener todas las conexiones disponibles para asignar a roles
|
||||
conexiones, err := models.GetConxDbSelect("")
|
||||
if err != nil {
|
||||
conexiones = []models.ConxDb{}
|
||||
}
|
||||
|
||||
// Calcular el total de páginas
|
||||
totalPages := int(math.Ceil(float64(total) / float64(limit)))
|
||||
|
||||
@@ -76,6 +82,7 @@ func GetRoles(c *fiber.Ctx) error {
|
||||
return c.JSON(fiber.Map{
|
||||
"roles": roles,
|
||||
"modules": modules,
|
||||
"conexiones": conexiones,
|
||||
"total": total, // Total de disponibles
|
||||
"totalPages": totalPages, // Total de páginas
|
||||
"page": page, // Página actual
|
||||
@@ -128,10 +135,18 @@ func UpdateRole(c *fiber.Ctx) error {
|
||||
newSubmodules = append(newSubmodules, newSubmodule)
|
||||
}
|
||||
}
|
||||
|
||||
// Asignar los nuevos submódulos al rol
|
||||
m.Submodules = newSubmodules
|
||||
|
||||
// Agregar las nuevas conexiones a BD
|
||||
var newConxDBs []models.ConxDb
|
||||
for _, db := range m.ConxDBs {
|
||||
var found models.ConxDb
|
||||
if err := app.Http.Database.DB.First(&found, db.ID).Error; err == nil {
|
||||
newConxDBs = append(newConxDBs, found)
|
||||
}
|
||||
}
|
||||
m.ConxDBs = newConxDBs
|
||||
|
||||
// Actualizar el rol en la base de datos
|
||||
if err := app.Http.Database.DB.Session(&gorm.Session{FullSaveAssociations: true}).Save(&m).Error; err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
@@ -158,6 +173,16 @@ func CreateRole(c *fiber.Ctx) error {
|
||||
})
|
||||
}
|
||||
|
||||
// Look up ConxDBs by ID
|
||||
var conxDbs []models.ConxDb
|
||||
for _, db := range m.ConxDBs {
|
||||
var found models.ConxDb
|
||||
if err := app.Http.Database.DB.First(&found, db.ID).Error; err == nil {
|
||||
conxDbs = append(conxDbs, found)
|
||||
}
|
||||
}
|
||||
m.ConxDBs = conxDbs
|
||||
|
||||
// Create the role in the database
|
||||
if err := models.CreateRole(m); err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
|
||||
Reference in New Issue
Block a user