using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace XP.Common.Database.Helpers
{
///
/// 通用CRUD SQL构建器(适配SQLite)
///
public static class SqlBuilderHelper
{
///
/// 构建插入SQL
///
/// 表名
/// 列名集合
/// 插入SQL(参数名:@列名)
public static string BuildInsertSql(string tableName, IEnumerable columns)
{
if (string.IsNullOrEmpty(tableName)) throw new ArgumentNullException(nameof(tableName));
var columnList = columns?.ToList() ?? throw new ArgumentNullException(nameof(columns));
if (columnList.Count == 0) throw new ArgumentException("列名集合不能为空");
var columnsStr = string.Join(", ", columnList);
var paramsStr = string.Join(", ", columnList.Select(c => $"@{c}"));
return $"INSERT INTO {tableName} ({columnsStr}) VALUES ({paramsStr})";
}
///
/// 构建更新SQL
///
/// 表名
/// 更新列名
/// 条件列名(如Id)
/// 更新SQL
public static string BuildUpdateSql(string tableName, IEnumerable updateColumns, IEnumerable whereColumns)
{
if (string.IsNullOrEmpty(tableName)) throw new ArgumentNullException(nameof(tableName));
var updateList = updateColumns?.ToList() ?? throw new ArgumentNullException(nameof(updateColumns));
var whereList = whereColumns?.ToList() ?? throw new ArgumentNullException(nameof(whereColumns));
if (updateList.Count == 0) throw new ArgumentException("更新列名集合不能为空");
if (whereList.Count == 0) throw new ArgumentException("条件列名集合不能为空");
var updateStr = string.Join(", ", updateList.Select(c => $"{c}=@{c}"));
var whereStr = string.Join(" AND ", whereList.Select(c => $"{c}=@{c}"));
return $"UPDATE {tableName} SET {updateStr} WHERE {whereStr}";
}
///
/// 构建删除SQL
///
public static string BuildDeleteSql(string tableName, IEnumerable whereColumns)
{
if (string.IsNullOrEmpty(tableName)) throw new ArgumentNullException(nameof(tableName));
var whereList = whereColumns?.ToList() ?? throw new ArgumentNullException(nameof(whereColumns));
if (whereList.Count == 0) throw new ArgumentException("条件列名集合不能为空");
var whereStr = string.Join(" AND ", whereList.Select(c => $"{c}=@{c}"));
return $"DELETE FROM {tableName} WHERE {whereStr}";
}
///
/// 构建查询SQL
///
public static string BuildSelectSql(string tableName, IEnumerable columns, IEnumerable? whereColumns = null, string orderBy = "")
{
if (string.IsNullOrEmpty(tableName)) throw new ArgumentNullException(nameof(tableName));
var columnList = columns?.ToList() ?? throw new ArgumentNullException(nameof(columns));
if (columnList.Count == 0) columnList.Add("*");
var columnsStr = string.Join(", ", columnList);
var sql = new StringBuilder($"SELECT {columnsStr} FROM {tableName}");
// 添加WHERE条件
if (whereColumns != null && whereColumns.Any())
{
var whereStr = string.Join(" AND ", whereColumns.Select(c => $"{c}=@{c}"));
sql.Append($" WHERE {whereStr}");
}
// 添加排序
if (!string.IsNullOrEmpty(orderBy))
{
sql.Append($" ORDER BY {orderBy}");
}
return sql.ToString();
}
}
}