handle db insert
Some checks are pending
CI / Test (push) Waiting to run
CI / End-to-End (push) Waiting to run
CI / Lint (push) Waiting to run
CI / Publish Docker (push) Blocked by required conditions
continuous-integration/drone/push Build is passing

This commit is contained in:
2024-09-25 14:59:18 +10:00
parent 7cc16819f7
commit 3c5aa418df

View File

@@ -1,7 +1,10 @@
package handler package handler
import ( import (
"context"
"database/sql"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@@ -34,14 +37,41 @@ func (h *Handler) VmImport(w http.ResponseWriter, r *http.Request) {
prettyPrint(inData) prettyPrint(inData)
} }
ctx := context.Background()
// TODO - query Inventory table for this VM before adding it
h.Logger.Debug("Checking inventory table for VM record")
invParams := queries.GetInventoryVmIdParams{
VmId: sql.NullString{String: inData.VmId, Valid: inData.VmId != ""},
DatacenterName: sql.NullString{String: inData.Datacenter, Valid: inData.Datacenter != ""},
}
_, err = h.Database.Queries().GetInventoryVmId(ctx, invParams)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
// do the insert
// Create an instance of CreateInventoryParams // Create an instance of CreateInventoryParams
var params queries.CreateInventoryParams var params queries.CreateInventoryParams
// Convert vmModel to CreateInventoryParams using the utility function // Convert vmModel to CreateInventoryParams using the utility function
db.ConvertToSQLParams(&inData, &params) db.ConvertToSQLParams(&inData, &params)
prettyPrint(params) prettyPrint(params)
// Insert the new inventory record into the database
result, err := h.Database.Queries().CreateInventory(ctx, params)
if err != nil {
h.Logger.Error("unable to perform database insert", "error", err)
} else {
h.Logger.Debug("created database record", "insert_result", result)
}
} else {
h.Logger.Error("unable to check inventory for vm", "error", err, "vm_id", inData.VmId, "datacenter_name", inData.Datacenter)
}
} else {
h.Logger.Info("not adding vm to inventory table since record alraedy exists", "vm_id", inData.VmId, "datacenter_name", inData.Datacenter)
}
//h.Logger.Debug("received import request", "body", string(reqBody)) //h.Logger.Debug("received import request", "body", string(reqBody))
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Import Request (%d): %v\n", len(reqBody), string(reqBody)) fmt.Fprintf(w, "Import Request (%d): %v\n", len(reqBody), string(reqBody))