Update Mongodb

This commit is contained in:
sunkaixuan
2025-05-04 18:39:11 +08:00
parent 5bc23c8d0f
commit 411e186788
18 changed files with 83 additions and 77 deletions

View File

@@ -24,7 +24,7 @@ namespace MongoDb.Ado.data
DbDataReaderFactory.Items.TryGetValue(operation, out var handler);
if (handler==null)
{
ExecuteHandlerFactory.Handler(operation, json, collection);
ExecuteHandlerFactory.Handler(operation, json, collection,new HandlerContext());
return new DataTable().CreateDataReader();
}
return handler.Handler(collection, doc);

View File

@@ -9,6 +9,8 @@ namespace MongoDb.Ado.data
public class DeleteHandler : IMongoOperationHandler
{
public string operation { get; set; }
public HandlerContext context { get; set; }
public int Handle(IMongoCollection<BsonDocument> collection, string json)
{
var doc = BsonDocument.Parse(json);

View File

@@ -9,6 +9,7 @@ namespace MongoDb.Ado.data
{
public class DeleteManyHandler : IMongoOperationHandler
{
public HandlerContext context { get; set; }
public string operation { get; set; }
public int Handle(IMongoCollection<BsonDocument> collection, string json)
{

View File

@@ -21,7 +21,7 @@ namespace MongoDb.Ado.data
};
public static int Handler(string operation, string json, IMongoCollection<BsonDocument> collection)
public static int Handler(string operation, string json, IMongoCollection<BsonDocument> collection, HandlerContext handlerContext)
{
MongoDbMethodUtils.ValidateOperation(operation);
var handlers = ExecuteHandlerFactory.Items;
@@ -29,6 +29,7 @@ namespace MongoDb.Ado.data
if (!handlers.TryGetValue(operation, out var handler))
throw new NotSupportedException($"不支持的操作类型: {operation}");
handler.operation = operation;
handler.context = handlerContext;
return handler.Handle(collection, json);
}

View File

@@ -9,6 +9,8 @@ namespace MongoDb.Ado.data
public interface IMongoOperationHandler
{
string operation { get; set; }
HandlerContext context { get; set; }
int Handle(IMongoCollection<BsonDocument> collection, string json);
}
}

View File

@@ -8,11 +8,13 @@ namespace MongoDb.Ado.data
{
public class InsertHandler : IMongoOperationHandler
{
public HandlerContext context { get; set; }
public string operation { get; set; }
public int Handle(IMongoCollection<BsonDocument> collection, string json)
{
var doc = BsonDocument.Parse(json);
collection.InsertOne(doc);
var objectId = doc["_id"].AsObjectId.ToString();
return 1;
}
}

View File

@@ -4,16 +4,20 @@ using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace MongoDb.Ado.data
{
public class InsertManyHandler : IMongoOperationHandler
{
public HandlerContext context { get; set; }
public string operation { get; set; }
public int Handle(IMongoCollection<BsonDocument> collection, string json)
{
var documents = ParseJsonArray(json);
collection.InsertMany(documents);
var objectIds = documents.Select(it=>it["_id"].AsObjectId.ToString()).ToArray();
context.ids = objectIds;
return documents.Count;
}

View File

@@ -8,6 +8,7 @@ namespace MongoDb.Ado.data
{
public class NonFindHandler : IMongoOperationHandler
{
public HandlerContext context { get; set; }
public string operation { get; set; }
public int Handle(IMongoCollection<BsonDocument> collection, string json)
{

View File

@@ -8,6 +8,7 @@ namespace MongoDb.Ado.data
{
public class UpdateHandler : IMongoOperationHandler
{
public HandlerContext context { get; set; }
public string operation { get; set; }
public int Handle(IMongoCollection<BsonDocument> collection, string json)
{

View File

@@ -9,6 +9,7 @@ namespace MongoDb.Ado.data
{
public class UpdateManyHandler : IMongoOperationHandler
{
public HandlerContext context { get; set; }
public string operation { get; set; }
public int Handle(IMongoCollection<BsonDocument> collection, string json)
{

View File

@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace MongoDb.Ado.data
{
public class HandlerContext
{
public string[] ids { get; set; }
}
}

View File

@@ -60,7 +60,10 @@ namespace MongoDb.Ado.data
{
var (operation, collectionName, json) = ParseCommand(_commandText);
var collection = GetCollection(collectionName);
return ExecuteHandlerFactory.Handler(operation, json, collection);
var context = new HandlerContext();
var result= ExecuteHandlerFactory.Handler(operation, json, collection, context);
((MongoDbConnection)this.Connection).ObjectIds = context.ids;
return result;
}
public override object ExecuteScalar()
{

View File

@@ -24,6 +24,7 @@ namespace MongoDb.Ado.data
public override ConnectionState State => _state;
public override string ConnectionString { get => _originalConnectionString; set => _originalConnectionString = value; }
public string[] ObjectIds { get; internal set; }
private MongoClient _client;

View File

@@ -9,8 +9,8 @@ namespace MongoDbTest
public class OrderInfo
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true,ColumnName ="_Id")]
public int Id { get; set; }
[SugarColumn(IsPrimaryKey = true, IsOnlyIgnoreInsert =true)]
public string Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }

View File

@@ -15,9 +15,12 @@ namespace MongoDbTest
var db = DbHelper.GetNewDb();
db.Insertable(new OrderInfo() { CreateTime = DateTime.Now, Name = "a", Price = 1 })
.ExecuteCommand();
db.Insertable(new List<OrderInfo>(){
var ids= db.Insertable(new List<OrderInfo>(){
new OrderInfo() { CreateTime = DateTime.Now, Name = "a1", Price = 2 },
new OrderInfo() { CreateTime = DateTime.Now, Name = "a2", Price = 3 }})
.ExecuteReturnPkList<string>();
db.Deleteable(new OrderInfo() { Id="a" })
.ExecuteCommand();
}
}

View File

@@ -1,4 +1,5 @@
using System;
using MongoDb.Ado.data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
@@ -9,6 +10,10 @@ namespace SqlSugar.MongoDb
{
public class MongoDbInsertable<T> : InsertableProvider<T> where T : class, new()
{
public override List<Type> ExecuteReturnPkList<Type>()
{
return ((MongoDbConnection)this.Ado.Connection).ObjectIds.Select(it=>(Type)(object)it).ToList();
}
public override int ExecuteReturnIdentity()
{
InsertBuilder.IsReturnIdentity = true;

View File

@@ -1,7 +1,39 @@
namespace SqlSugar.MongoDb
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
namespace SqlSugar.MongoDb
{
public class MongoDbDeleteBuilder : DeleteBuilder
{
public override string ToSqlString()
{
var sb = new StringBuilder("deleteMany b ");
var jsonObjects = new List<string>();
foreach (var item in this.WhereInfos)
{
var key = this.EntityInfo.Columns.FirstOrDefault(it => it.IsPrimarykey);
var startWithValue = $"{Builder.GetTranslationColumnName(key.DbColumnName)} IN (";
if (item.StartsWith(startWithValue))
{
var sql = item;
sql = sql.TrimEnd(')');
sql = sql.Replace(startWithValue, "").Replace("'", "");
var dict = new Dictionary<string, object>();
var array = sql.Split(",");
dict["_id"] = new Dictionary<string, object> { { "$in", array } }; // Fixed syntax for dictionary initialization
string json = JsonSerializer.Serialize(dict, new JsonSerializerOptions
{
WriteIndented = false
});
jsonObjects.Add(json);
}
}
sb.Append("[{\"filter\":");
sb.Append(string.Join(", ", jsonObjects));
sb.Append("}]");
return sb.ToString();
}
}
}

View File

@@ -76,69 +76,5 @@ namespace SqlSugar.MongoDb
return sb.ToString();
}
public object FormatValue(object value, string name, int i, DbColumnInfo columnInfo)
{
if (value == null)
{
return "NULL";
}
else
{
var type = value.GetType();
if (type == UtilConstants.DateType || columnInfo.IsArray || columnInfo.IsJson)
{
var parameterName = this.Builder.SqlParameterKeyWord + name + i;
var paramter = new SugarParameter(parameterName, value);
if (columnInfo.IsJson)
{
paramter.IsJson = true;
}
if (columnInfo.IsArray)
{
paramter.IsArray = true;
}
this.Parameters.Add(paramter);
return parameterName;
}
else if (type == UtilConstants.ByteArrayType)
{
string bytesString = "0x" + BitConverter.ToString((byte[])value);
return bytesString;
}
else if (type.IsEnum())
{
if (this.Context.CurrentConnectionConfig.MoreSettings?.TableEnumIsString == true)
{
return value.ToSqlValue();
}
else
{
return Convert.ToInt64(value);
}
}
else if (type == UtilConstants.DateTimeOffsetType)
{
return FormatDateTimeOffset(value);
}
else if (type == UtilConstants.BoolType)
{
return value.ObjToBool() ? "1" : "0";
}
else if (type == UtilConstants.StringType || type == UtilConstants.ObjType)
{
return "'" + value.ToString().ToSqlFilter() + "'";
}
else
{
return "'" + value.ToString() + "'";
}
}
}
public override string FormatDateTimeOffset(object value)
{
return "'" + ((DateTimeOffset)value).ToString("o") + "'";
}
}
}