日常更新

This commit is contained in:
2025-09-27 11:02:31 +08:00
parent 0cb6dd50e0
commit c9f4ce4ef3
659 changed files with 8695 additions and 697 deletions

203
Ramitta/Database/Neo4j.cs Normal file
View File

@@ -0,0 +1,203 @@
using Neo4j.Driver;
using NPOI;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;
namespace Ramitta
{
public class Neo4jtool
{
private IDriver _driver;
public Neo4jtool(string uri, string user, string password)
{
_driver = GraphDatabase.Driver(uri, AuthTokens.Basic(user, password));
}
public void Close()
{
_driver?.Dispose();
}
private string dictToLimit(Dictionary<string, string> nodeProperties)
{
return string.Join(", ", nodeProperties.Select(prop => $"{prop.Key}: '{prop.Value.Replace("'", "\\'")}'"));
}
#region
public async Task CreateNodeAsync(string nodeType, Dictionary<string, string> properties, bool alway_create = false)
{
using (var session = _driver.AsyncSession())
{
// 通过 dictToLimit 将字典转换成条件字符串
var propertyString = dictToLimit(properties);
// 构建查询语句
var query = (alway_create ? "CREATE" : "MERGE") +
$" (n:{nodeType} {{{propertyString}}})";
await session.RunAsync(query);
}
}
// 创建任意关系,支持动态定义关系类型
public enum ArrowDirection
{
Left, // 反向关系
Right, // 正向关系(默认)
Both // 双向关系
}
public async Task CreateRelationshipAsync(
string relationshipType,
string nodeType1, Dictionary<string, string> nodeProperties1, // 使用字典替代单独的参数
string nodeType2, Dictionary<string, string> nodeProperties2, // 使用字典替代单独的参数
ArrowDirection arrow = ArrowDirection.Right,
Dictionary<string, string> relationshipProperties = null // 可选字典参数
){
using (var session = _driver.AsyncSession())
{
// 构建查询的 MATCH 部分,动态地使用字典中的键值对来构造节点的属性
var node1Properties = string.Join(", ", nodeProperties1.Select(kv => $"{kv.Key}: \"{kv.Value}\""));
var node2Properties = string.Join(", ", nodeProperties2.Select(kv => $"{kv.Key}: \"{kv.Value}\""));
var query = $"MATCH (a:{nodeType1} {{{node1Properties}}}), (b:{nodeType2} {{{node2Properties}}}) ";
// 动态构造关系属性部分
string relationshipPropertiesPart = "";
if (relationshipProperties != null && relationshipProperties.Count > 0)
{
var properties = string.Join(", ", relationshipProperties.Select(kv => $"{kv.Key}: \"{kv.Value}\""));
relationshipPropertiesPart = $"{{{properties}}}";
}
// 根据箭头方向来决定关系的方向,并可能附加关系的属性
if (arrow == ArrowDirection.Right)
query += $"MERGE (a)-[:{relationshipType} {relationshipPropertiesPart}]->(b)";
else if (arrow == ArrowDirection.Left)
query += $"MERGE (b)-[:{relationshipType} {relationshipPropertiesPart}]->(a)";
else if (arrow == ArrowDirection.Both)
{
query += $"MERGE (a)-[:{relationshipType} {relationshipPropertiesPart}]->(b)";
query += $"MERGE (b)-[:{relationshipType} {relationshipPropertiesPart}]->(a)";
}
// 执行查询
await session.RunAsync(query);
}
}
#endregion
#region
// 寻找指定节点
// await neo4jService.GetRelatedNodesAsync("文件", properties);
public async Task<List<Dictionary<string, string>>> GetRelatedNodesAsync(
string nodeLabel,
Dictionary<string, string>? nodeProperties=null)
{
string query;
if (nodeProperties == null)
{
query = $@"
MATCH (h:{nodeLabel})-[r]-(related)
RETURN DISTINCT h,related";
}
else
{
query = $@"
MATCH (h:{nodeLabel} {{{dictToLimit(nodeProperties)}}})-[r]-(related)
RETURN DISTINCT h,related";
}
var resultList = new List<Dictionary<string, string>>();
using (var session = _driver.AsyncSession())
{
var result = await session.RunAsync(query);
await result.ForEachAsync(record =>
{
var hNode = record["h"].As<INode>();
var dict = new Dictionary<string, string>();
// 添加所有属性
foreach (var property in hNode.Properties)
{
dict[property.Key] = property.Value?.ToString() ?? string.Empty;
}
resultList.Add(dict);
});
}
return resultList;
}
public async Task<List<(INode h, IRelationship r, INode related)>> slavenode(
string nodeLabel,
Dictionary<string, string>? nodeProperties = null)
{
string query;
if (nodeProperties == null)
{
query = $@"
MATCH (h:{nodeLabel})-[r]-(related)
RETURN DISTINCT h,r,related";
}
else
{
query = $@"
MATCH (h:{nodeLabel} {{{dictToLimit(nodeProperties)}}})-[r]-(related)
RETURN DISTINCT h,r,related";
}
var resultList = new List<(INode h, IRelationship r, INode related)>();
using (var session = _driver.AsyncSession())
{
var result = await session.RunAsync(query);
await result.ForEachAsync(record =>
{
var hNode = record["h"].As<INode>();
var rRelation = record["r"].As<IRelationship>();
var relatedNode = record["related"].As<INode>();
// 将h, r, related 作为元组加入结果列表
resultList.Add((hNode, rRelation, relatedNode));
});
}
return resultList;
}
#endregion
#region
public async Task DeleteNodeAsync(string nodeType, Dictionary<string, string> nodeProperties)
{
using (var session = _driver.AsyncSession())
{
// 构建查询条件
var queryConditions = string.Join(" AND ", nodeProperties.Keys.Select(k => $"n.{k} = ${k}"));
// 运行查询并传递字典参数
await session.RunAsync(
$"MATCH (n:{nodeType}) WHERE {queryConditions} DETACH DELETE n",
nodeProperties
);
}
}
// 删除所有节点和关系
public async Task DeleteAllNodesAndRelationshipsAsync()
{
using (var session = _driver.AsyncSession())
{
await session.RunAsync("MATCH (n) DETACH DELETE n");
}
}
#endregion
}
}

View File

@@ -0,0 +1,176 @@
using Npgsql;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ramitta
{
public partial class PostgreSql
{
private readonly string _connectionString;
public PostgreSql(string connectionString)
{
_connectionString = connectionString;
}
// 执行查询操作,返回查询结果
public async Task<List<Dictionary<string, object>>> ExecuteQueryAsync(string query, Dictionary<string, object> parameters = null)
{
var result = new List<Dictionary<string, object>>();
using (var conn = new NpgsqlConnection(_connectionString))
{
try
{
await conn.OpenAsync();
Debug.WriteLine("Database connection established.");
using (var cmd = new NpgsqlCommand(query, conn))
{
if (parameters != null)
{
foreach (var param in parameters)
{
cmd.Parameters.AddWithValue(param.Key, param.Value ?? DBNull.Value);
}
}
using (var reader = await cmd.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
var row = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++)
{
row[reader.GetName(i)] = await reader.IsDBNullAsync(i) ? null : reader.GetValue(i);
}
result.Add(row);
}
}
}
Debug.WriteLine($"Query executed: {query}");
}
catch (Exception ex)
{
Debug.WriteLine($"Error executing query: {ex.Message}");
}
}
return result;
}
// 执行插入、更新、删除操作
public async Task<int> ExecuteNonQueryAsync(string query, Dictionary<string, object> parameters = null)
{
using (var conn = new NpgsqlConnection(_connectionString))
{
try
{
await conn.OpenAsync();
Debug.WriteLine("Database connection established.");
using (var cmd = new NpgsqlCommand(query, conn))
{
if (parameters != null)
{
foreach (var param in parameters)
{
cmd.Parameters.AddWithValue(param.Key, param.Value ?? DBNull.Value);
}
}
var rowsAffected = await cmd.ExecuteNonQueryAsync();
Debug.WriteLine($"Executed query: {query}, Rows affected: {rowsAffected}");
return rowsAffected;
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error executing non-query: {ex.Message}");
return -1;
}
}
}
// 执行插入操作,返回生成的主键
public async Task<int> ExecuteInsertAsync(string query, Dictionary<string, object> parameters = null, string returnColumn = "id")
{
using (var conn = new NpgsqlConnection(_connectionString))
{
try
{
await conn.OpenAsync();
Debug.WriteLine("Database connection established.");
using (var cmd = new NpgsqlCommand(query, conn))
{
if (parameters != null)
{
foreach (var param in parameters)
{
cmd.Parameters.AddWithValue(param.Key, param.Value ?? DBNull.Value);
}
}
cmd.CommandText += $" RETURNING {returnColumn};";
var result = await cmd.ExecuteScalarAsync();
Debug.WriteLine($"Executed insert, inserted ID: {result}");
return result != null ? Convert.ToInt32(result) : -1;
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error executing insert: {ex.Message}");
return -1;
}
}
}
// 执行事务操作
public async Task<bool> ExecuteTransactionAsync(List<string> queries, List<Dictionary<string, object>> parametersList)
{
using (var conn = new NpgsqlConnection(_connectionString))
{
try
{
await conn.OpenAsync();
Debug.WriteLine("Database connection established.");
using (var transaction = await conn.BeginTransactionAsync())
{
for (int i = 0; i < queries.Count; i++)
{
using (var cmd = new NpgsqlCommand(queries[i], conn, (NpgsqlTransaction)transaction))
{
var parameters = parametersList[i];
if (parameters != null)
{
foreach (var param in parameters)
{
cmd.Parameters.AddWithValue(param.Key, param.Value ?? DBNull.Value);
}
}
await cmd.ExecuteNonQueryAsync();
}
}
await transaction.CommitAsync();
Debug.WriteLine("Transaction committed.");
return true;
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error executing transaction: {ex.Message}");
return false;
}
}
}
}
}

270
Ramitta/Database/SQLite.cs Normal file
View File

@@ -0,0 +1,270 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
namespace Ramitta
{
public class SQLite : IDisposable
{
private SQLiteConnection db;
private bool disposed = false;
// 构造函数,初始化数据库连接
// 参数: connectionString - 数据库连接字符串
// 例如: "Data Source=mydatabase.db;Version=3;"
public SQLite(string connectionString)
{
db = new SQLiteConnection(connectionString);
db.Open();
}
// 创建表:根据表名和字段定义创建表
// 参数: tableName - 表名
// 参数: columns - 字段定义字典,键为字段名,值为字段类型
// 例如: CreateTable("Users", new Dictionary<string, string> { {"Id", "INTEGER"}, {"Name", "TEXT"} });
public void CreateTable(string tableName, Dictionary<string, string> columns)
{
// 构建列定义的字符串
var columnsDefinition = string.Join(", ", columns.Select(c => $"{c.Key} {c.Value}"));
string createTableQuery = $"CREATE TABLE IF NOT EXISTS {tableName} ({columnsDefinition});";
using (var cmd = new SQLiteCommand(createTableQuery, db))
{
cmd.ExecuteNonQuery();
}
}
// 向已存在的表中添加新列
// 参数: tableName - 表名
// 参数: columnName - 要添加的列名
// 参数: columnType - 列的数据类型
// 例如: AddColumn("Users", "Email", "TEXT");
public void AddColumn(string tableName, string columnName, string columnType)
{
// 检查表是否存在
if (!TableExists(tableName))
{
throw new ArgumentException($"表 '{tableName}' 不存在");
}
// 检查列是否已存在
if (ColumnExists(tableName, columnName))
{
Console.WriteLine($"列 '{columnName}' 在表 '{tableName}' 中已存在");
return;
}
// 构建添加列的SQL语句
string addColumnQuery = $"ALTER TABLE {tableName} ADD COLUMN {columnName} {columnType};";
using (var cmd = new SQLiteCommand(addColumnQuery, db))
{
cmd.ExecuteNonQuery();
}
Console.WriteLine($"已向表 '{tableName}' 添加列 '{columnName}'");
}
// 检查表是否存在
private bool TableExists(string tableName)
{
string query = "SELECT count(*) FROM sqlite_master WHERE type='table' AND name=@tableName;";
using (var cmd = new SQLiteCommand(query, db))
{
cmd.Parameters.AddWithValue("@tableName", tableName);
var result = cmd.ExecuteScalar();
return Convert.ToInt32(result) > 0;
}
}
// 检查列是否已存在
private bool ColumnExists(string tableName, string columnName)
{
string query = $"PRAGMA table_info({tableName});";
using (var cmd = new SQLiteCommand(query, db))
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
if (reader["name"].ToString().Equals(columnName, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
}
return false;
}
// 批量添加多个列
// 参数: tableName - 表名
// 参数: columns - 字段定义字典,键为字段名,值为字段类型
// 例如: AddColumns("Users", new Dictionary<string, string> { {"Email", "TEXT"}, {"Age", "INTEGER"} });
public void AddColumns(string tableName, Dictionary<string, string> columns)
{
foreach (var column in columns)
{
AddColumn(tableName, column.Key, column.Value);
}
}
// 插入数据:向指定表插入一条记录
// 参数: tableName - 表名
// 参数: columnValues - 字段和对应值的字典
// 例如: InsertData("Users", new Dictionary<string, object> { {"Name", "John"}, {"Age", 30} });
public void InsertData(string tableName, Dictionary<string, object> columnValues)
{
// 构建列和参数的字符串
var columns = string.Join(", ", columnValues.Keys);
var parameters = string.Join(", ", columnValues.Keys.Select(k => "@" + k));
string insertQuery = $"INSERT INTO {tableName} ({columns}) VALUES ({parameters})";
using (var cmd = new SQLiteCommand(insertQuery, db))
{
foreach (var kvp in columnValues)
{
cmd.Parameters.AddWithValue("@" + kvp.Key, kvp.Value);
}
cmd.ExecuteNonQuery();
}
}
// 查询数据:执行任意查询语句并返回结果
// 参数: query - SQL查询语句
// 参数: parameters - 可选的查询参数字典
// 例如: SelectData("SELECT * FROM Users WHERE Age > @age", new Dictionary<string, object> { {"age", 25} });
public List<Dictionary<string, object>> SelectData(string query, Dictionary<string, object> parameters = null)
{
var result = new List<Dictionary<string, object>>();
using (var cmd = new SQLiteCommand(query, db))
{
// 添加查询参数(如果有的话)
if (parameters != null)
{
foreach (var kvp in parameters)
{
cmd.Parameters.AddWithValue("@" + kvp.Key, kvp.Value);
}
}
using (SQLiteDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var row = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++)
{
row[reader.GetName(i)] = reader.GetValue(i);
}
result.Add(row);
}
}
}
return result;
}
// 更新数据:根据条件更新指定表中的记录
// 参数: tableName - 表名
// 参数: columnValues - 需要更新的字段和对应值的字典
// 参数: condition - 更新条件
// 例如: UpdateData("Users", new Dictionary<string, object> { {"Age", 31} }, "Name = 'John'");
public void UpdateData(string tableName, Dictionary<string, object> columnValues, string condition)
{
// 构建SET子句
var setClause = string.Join(", ", columnValues.Keys.Select(k => $"{k} = @{k}"));
string updateQuery = $"UPDATE {tableName} SET {setClause} WHERE {condition}";
using (var cmd = new SQLiteCommand(updateQuery, db))
{
foreach (var kvp in columnValues)
{
cmd.Parameters.AddWithValue("@" + kvp.Key, kvp.Value);
}
cmd.ExecuteNonQuery();
}
}
// 删除数据:根据条件删除指定表中的记录
// 参数: tableName - 表名
// 参数: condition - 删除条件
// 例如: DeleteData("Users", "Age < 18");
public void DeleteData(string tableName, string condition)
{
string deleteQuery = $"DELETE FROM {tableName} WHERE {condition}";
using (var cmd = new SQLiteCommand(deleteQuery, db))
{
cmd.ExecuteNonQuery();
}
}
// 支持事务操作:允许在同一个事务中执行多个操作
// 参数: transactionActions - 一个包含多个数据库操作的委托
// 例如: ExecuteTransaction(() =>
// {
// InsertData("Users", new Dictionary<string, object> { {"Name", "Alice"}, {"Age", 28} });
// UpdateData("Users", new Dictionary<string, object> { {"Age", 29} }, "Name = 'Bob'");
// });
public void ExecuteTransaction(Action transactionActions)
{
using (var transaction = db.BeginTransaction())
{
try
{
transactionActions.Invoke(); // 执行多个操作
transaction.Commit(); // 提交事务
}
catch (Exception)
{
transaction.Rollback(); // 回滚事务
throw;
}
}
}
// 删除所有表
public void DropAllTables()
{
// 获取所有表名
string getTablesQuery = "SELECT name FROM sqlite_master WHERE type='table';";
var tables = SelectData(getTablesQuery);
foreach (var table in tables)
{
string tableName = table["name"].ToString();
string dropTableQuery = $"DROP TABLE IF EXISTS {tableName};";
using (var cmd = new SQLiteCommand(dropTableQuery, db))
{
cmd.ExecuteNonQuery();
}
}
}
// 释放资源,关闭数据库连接
// 确保数据库连接在对象销毁时被正确关闭
public void Dispose()
{
if (!disposed)
{
if (db != null && db.State == ConnectionState.Open)
{
db.Close();
db.Dispose();
}
disposed = true;
}
GC.SuppressFinalize(this);
}
// 析构函数调用Dispose释放资源
~SQLite()
{
Dispose();
}
}
}