using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Erp.SqlQueryManager.Application.Contracts;
using Erp.SqlQueryManager.Domain.Entities;
using Erp.SqlQueryManager.Domain.Services;
using Erp.SqlQueryManager.Domain.Shared;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.MultiTenancy;
namespace Erp.SqlQueryManager.Application;
///
/// Unified service for SQL Object Explorer
/// Combines all SQL objects into a single endpoint
///
[Authorize("App.SqlQueryManager")]
public class SqlObjectManagerAppService : ApplicationService, ISqlObjectManagerAppService
{
private readonly IRepository _queryRepository;
private readonly IRepository _procedureRepository;
private readonly IRepository _viewRepository;
private readonly IRepository _functionRepository;
private readonly ISqlExecutorService _sqlExecutorService;
private readonly ISqlTemplateProvider _templateProvider;
private readonly ICurrentTenant _currentTenant;
private readonly IHttpContextAccessor _httpContextAccessor;
public SqlObjectManagerAppService(
IRepository queryRepository,
IRepository procedureRepository,
IRepository viewRepository,
IRepository functionRepository,
ISqlExecutorService sqlExecutorService,
ISqlTemplateProvider templateProvider,
ICurrentTenant currentTenant,
IHttpContextAccessor httpContextAccessor
)
{
_queryRepository = queryRepository;
_procedureRepository = procedureRepository;
_viewRepository = viewRepository;
_functionRepository = functionRepository;
_sqlExecutorService = sqlExecutorService;
_templateProvider = templateProvider;
_currentTenant = currentTenant;
_httpContextAccessor = httpContextAccessor;
}
private string GetTenantFromHeader()
{
return _httpContextAccessor.HttpContext?
.Request?
.Headers["__tenant"]
.FirstOrDefault();
}
private void ValidateTenantAccess()
{
var headerTenant = GetTenantFromHeader();
var currentTenantName = _currentTenant.Name;
if (_currentTenant.IsAvailable)
{
if (headerTenant != currentTenantName)
{
throw new Volo.Abp.UserFriendlyException($"Tenant mismatch. Header tenant '{headerTenant}' does not match current tenant '{currentTenantName}'.");
}
}
}
public async Task GetAllObjectsAsync(string dataSourceCode)
{
ValidateTenantAccess();
var result = new SqlObjectExplorerDto();
// Get all queries for this data source
var queries = await _queryRepository.GetListAsync();
result.Queries = queries
.Where(q => q.DataSourceCode == dataSourceCode)
.Select(q => new SqlQueryDto
{
Id = q.Id,
Code = q.Code,
Name = q.Name,
Description = q.Description,
QueryText = q.QueryText,
DataSourceCode = q.DataSourceCode,
Status = q.Status,
Category = q.Category,
Tags = q.Tags,
IsModifyingData = q.IsModifyingData,
Parameters = q.Parameters,
ExecutionCount = q.ExecutionCount,
LastExecutedAt = q.LastExecutedAt
})
.ToList();
// Get all stored procedures for this data source (custom + native merged)
result.StoredProcedures = await GetMergedStoredProceduresAsync(dataSourceCode);
// Get all views for this data source (custom + native merged)
result.Views = await GetMergedViewsAsync(dataSourceCode);
// Get all functions for this data source (custom + native merged)
result.Functions = await GetMergedFunctionsAsync(dataSourceCode);
// Get all database tables
result.Tables = await GetTablesAsync(dataSourceCode);
// Get all templates
result.Templates = _templateProvider.GetAvailableQueryTemplates()
.Select(t => new SqlTemplateDto
{
Type = t.Type,
Name = t.Name,
Description = t.Description,
Template = _templateProvider.GetQueryTemplate(t.Type)
})
.ToList();
return result;
}
private async Task> GetTablesAsync(string dataSourceCode)
{
var query = @"
SELECT
SCHEMA_NAME(t.schema_id) AS SchemaName,
t.name AS TableName
FROM
sys.tables t
WHERE
t.is_ms_shipped = 0
ORDER BY
SCHEMA_NAME(t.schema_id), t.name";
var result = await _sqlExecutorService.ExecuteQueryAsync(query, dataSourceCode);
var tables = new List();
if (result.Success && result.Data != null)
{
foreach (var row in result.Data)
{
var dict = row as System.Collections.Generic.IDictionary;
if (dict != null)
{
tables.Add(new DatabaseTableDto
{
SchemaName = dict["SchemaName"]?.ToString() ?? "dbo",
TableName = dict["TableName"]?.ToString() ?? ""
});
}
}
}
return tables;
}
private async Task> GetMergedStoredProceduresAsync(string dataSourceCode)
{
// Get custom stored procedures from database
var customProcedures = await _procedureRepository.GetListAsync();
var customList = customProcedures
.Where(p => p.DataSourceCode == dataSourceCode)
.Select(p => new SqlStoredProcedureDto
{
Id = p.Id,
ProcedureName = p.ProcedureName,
SchemaName = p.SchemaName,
DisplayName = $"{p.SchemaName}.{p.ProcedureName}",
Description = p.Description,
ProcedureBody = p.ProcedureBody,
DataSourceCode = p.DataSourceCode,
Category = p.Category,
Parameters = p.Parameters,
IsDeployed = p.IsDeployed,
LastDeployedAt = p.LastDeployedAt,
IsCustom = true
})
.ToList();
// Get native stored procedures from SQL Server
var nativeQuery = @"
SELECT
SCHEMA_NAME(p.schema_id) AS SchemaName,
p.name AS ProcedureName,
p.create_date AS CreatedDate,
p.modify_date AS ModifiedDate
FROM
sys.procedures p
WHERE
p.is_ms_shipped = 0
ORDER BY
SCHEMA_NAME(p.schema_id), p.name";
var result = await _sqlExecutorService.ExecuteQueryAsync(nativeQuery, dataSourceCode);
var nativeList = new List();
if (result.Success && result.Data != null)
{
foreach (var row in result.Data)
{
var dict = row as System.Collections.Generic.IDictionary;
if (dict != null)
{
var schemaName = dict["SchemaName"]?.ToString() ?? "dbo";
var procName = dict["ProcedureName"]?.ToString() ?? "";
// Skip if already exists in custom list
if (!customList.Any(c => c.SchemaName == schemaName && c.ProcedureName == procName))
{
// Generate deterministic GUID from schema and name to ensure uniqueness
var uniqueId = GenerateDeterministicGuid($"SP_{dataSourceCode}_{schemaName}_{procName}");
nativeList.Add(new SqlStoredProcedureDto
{
Id = uniqueId,
SchemaName = schemaName,
ProcedureName = procName,
DisplayName = $"{schemaName}.{procName}",
DataSourceCode = dataSourceCode,
IsCustom = false,
IsDeployed = true // Native objects are already deployed
});
}
}
}
}
// Merge and return
return customList.Concat(nativeList).ToList();
}
private async Task> GetMergedViewsAsync(string dataSourceCode)
{
// Get custom views from database
var customViews = await _viewRepository.GetListAsync();
var customList = customViews
.Where(v => v.DataSourceCode == dataSourceCode)
.Select(v => new SqlViewDto
{
Id = v.Id,
ViewName = v.ViewName,
SchemaName = v.SchemaName,
DisplayName = $"{v.SchemaName}.{v.ViewName}",
Description = v.Description,
ViewDefinition = v.ViewDefinition,
DataSourceCode = v.DataSourceCode,
Category = v.Category,
WithSchemaBinding = v.WithSchemaBinding,
IsDeployed = v.IsDeployed,
LastDeployedAt = v.LastDeployedAt,
IsCustom = true
})
.ToList();
// Get native views from SQL Server
var nativeQuery = @"
SELECT
SCHEMA_NAME(v.schema_id) AS SchemaName,
v.name AS ViewName,
v.create_date AS CreatedDate,
v.modify_date AS ModifiedDate
FROM
sys.views v
WHERE
v.is_ms_shipped = 0
ORDER BY
SCHEMA_NAME(v.schema_id), v.name";
var result = await _sqlExecutorService.ExecuteQueryAsync(nativeQuery, dataSourceCode);
var nativeList = new List();
if (result.Success && result.Data != null)
{
foreach (var row in result.Data)
{
var dict = row as System.Collections.Generic.IDictionary;
if (dict != null)
{
var schemaName = dict["SchemaName"]?.ToString() ?? "dbo";
var viewName = dict["ViewName"]?.ToString() ?? "";
// Skip if already exists in custom list
if (!customList.Any(c => c.SchemaName == schemaName && c.ViewName == viewName))
{
// Generate deterministic GUID from schema and name to ensure uniqueness
var uniqueId = GenerateDeterministicGuid($"VIEW_{dataSourceCode}_{schemaName}_{viewName}");
nativeList.Add(new SqlViewDto
{
Id = uniqueId,
SchemaName = schemaName,
ViewName = viewName,
DisplayName = $"{schemaName}.{viewName}",
DataSourceCode = dataSourceCode,
IsCustom = false,
IsDeployed = true
});
}
}
}
}
return customList.Concat(nativeList).ToList();
}
private async Task> GetMergedFunctionsAsync(string dataSourceCode)
{
// Get custom functions from database
var customFunctions = await _functionRepository.GetListAsync();
var customList = customFunctions
.Where(f => f.DataSourceCode == dataSourceCode)
.Select(f => new SqlFunctionDto
{
Id = f.Id,
FunctionName = f.FunctionName,
SchemaName = f.SchemaName,
DisplayName = $"[{f.SchemaName}].[{f.FunctionName}]",
Description = f.Description,
FunctionType = f.FunctionType,
FunctionBody = f.FunctionBody,
ReturnType = f.ReturnType,
DataSourceCode = f.DataSourceCode,
Category = f.Category,
Parameters = f.Parameters,
IsDeployed = f.IsDeployed,
LastDeployedAt = f.LastDeployedAt,
IsCustom = true
})
.ToList();
// Get native functions from SQL Server
var nativeQuery = @"
SELECT
SCHEMA_NAME(o.schema_id) AS SchemaName,
o.name AS FunctionName,
o.create_date AS CreatedDate,
o.modify_date AS ModifiedDate,
CASE o.type
WHEN 'FN' THEN 'Scalar'
WHEN 'IF' THEN 'InlineTableValued'
WHEN 'TF' THEN 'TableValued'
ELSE 'Unknown'
END AS FunctionType
FROM
sys.objects o
WHERE
o.type IN ('FN', 'IF', 'TF')
AND o.is_ms_shipped = 0
ORDER BY
SCHEMA_NAME(o.schema_id), o.name";
var result = await _sqlExecutorService.ExecuteQueryAsync(nativeQuery, dataSourceCode);
var nativeList = new List();
if (result.Success && result.Data != null)
{
foreach (var row in result.Data)
{
var dict = row as System.Collections.Generic.IDictionary;
if (dict != null)
{
var schemaName = dict["SchemaName"]?.ToString() ?? "dbo";
var funcName = dict["FunctionName"]?.ToString() ?? "";
// Skip if already exists in custom list
if (!customList.Any(c => c.SchemaName == schemaName && c.FunctionName == funcName))
{
var funcTypeStr = dict["FunctionType"]?.ToString() ?? "Scalar";
var funcType = funcTypeStr == "Scalar" ? SqlFunctionType.ScalarFunction :
funcTypeStr == "InlineTableValued" ? SqlFunctionType.InlineTableValuedFunction :
SqlFunctionType.TableValuedFunction;
// Generate deterministic GUID from schema and name to ensure uniqueness
var uniqueId = GenerateDeterministicGuid($"FUNC_{dataSourceCode}_{schemaName}_{funcName}");
nativeList.Add(new SqlFunctionDto
{
Id = uniqueId,
SchemaName = schemaName,
FunctionName = funcName,
DisplayName = $"{schemaName}.{funcName}",
DataSourceCode = dataSourceCode,
FunctionType = funcType,
IsCustom = false,
IsDeployed = true
});
}
}
}
}
return customList.Concat(nativeList).ToList();
}
#region Query Operations
public async Task CreateQueryAsync(CreateSqlQueryDto input)
{
ValidateTenantAccess();
var query = ObjectMapper.Map(input);
query.Status = SqlQueryStatus.Draft;
var created = await _queryRepository.InsertAsync(query, autoSave: true);
return ObjectMapper.Map(created);
}
public async Task UpdateQueryAsync(Guid id, UpdateSqlQueryDto input)
{
ValidateTenantAccess();
var query = await _queryRepository.GetAsync(id);
query.Name = input.Name;
query.Description = input.Description;
query.QueryText = input.QueryText;
query.Category = input.Category;
query.Tags = input.Tags;
var updated = await _queryRepository.UpdateAsync(query, autoSave: true);
return ObjectMapper.Map(updated);
}
public async Task DeleteQueryAsync(Guid id)
{
ValidateTenantAccess();
await _queryRepository.DeleteAsync(id);
}
public async Task ExecuteQueryAsync(ExecuteSqlQueryDto input)
{
ValidateTenantAccess();
var sqlText = input.QueryText.Trim();
var sqlUpper = sqlText.ToUpperInvariant();
// Check if this is a DDL command (CREATE/ALTER/DROP for VIEW/PROCEDURE/FUNCTION)
bool isDDLCommand =
sqlUpper.Contains("CREATE VIEW") || sqlUpper.Contains("ALTER VIEW") ||
sqlUpper.Contains("CREATE PROCEDURE") || sqlUpper.Contains("CREATE PROC") ||
sqlUpper.Contains("ALTER PROCEDURE") || sqlUpper.Contains("ALTER PROC") ||
sqlUpper.Contains("CREATE FUNCTION") || sqlUpper.Contains("ALTER FUNCTION") ||
sqlUpper.Contains("DROP VIEW") || sqlUpper.Contains("DROP PROCEDURE") ||
sqlUpper.Contains("DROP PROC") || sqlUpper.Contains("DROP FUNCTION");
if (isDDLCommand)
{
// For DDL commands, only validate syntax without executing
try
{
// Try to parse/validate the SQL using SET PARSEONLY
var validationSql = $"SET PARSEONLY ON;\n{sqlText}\nSET PARSEONLY OFF;";
await _sqlExecutorService.ExecuteNonQueryAsync(validationSql, input.DataSourceCode);
return new SqlQueryExecutionResultDto
{
Success = true,
Message = "SQL syntax is valid. Use Save button to save and Deploy button to create in SQL Server.",
Data = new List