diff --git a/Src/Asp.Net/SqlSugar/Lib/System.Data.SQLite.dll b/Src/Asp.Net/SqlSugar/Lib/System.Data.SQLite.dll new file mode 100644 index 000000000..ecc1c11b9 Binary files /dev/null and b/Src/Asp.Net/SqlSugar/Lib/System.Data.SQLite.dll differ diff --git a/Src/Asp.Net/SqlSugar/Realization/Sqlite/CodeFirst/SqliteCodeFirst.cs b/Src/Asp.Net/SqlSugar/Realization/Sqlite/CodeFirst/SqliteCodeFirst.cs new file mode 100644 index 000000000..74c5aa1f8 --- /dev/null +++ b/Src/Asp.Net/SqlSugar/Realization/Sqlite/CodeFirst/SqliteCodeFirst.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SqlSugar +{ + public class SqliteCodeFirst : CodeFirstProvider + { + public override void NoExistLogic(EntityInfo entityInfo) + { + var tableName = GetTableName(entityInfo); + Check.Exception(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1, "Use Code First ,The primary key must not exceed 1"); + List columns = new List(); + if (entityInfo.Columns.IsValuable()) + { + foreach (var item in entityInfo.Columns) + { + DbColumnInfo dbColumnInfo = this.EntityColumnToDbColumn(entityInfo, tableName, item); + columns.Add(dbColumnInfo); + } + } + this.Context.DbMaintenance.CreateTable(tableName, columns); + } + protected override DbColumnInfo EntityColumnToDbColumn(EntityInfo entityInfo, string tableName, EntityColumnInfo item) + { + var result = new DbColumnInfo() + { + DataType = this.Context.Ado.DbBind.GetDbTypeName(PubMethod.GetUnderType(item.PropertyInfo).Name), + TableId = entityInfo.Columns.IndexOf(item), + DbColumnName = item.DbColumnName.IsValuable() ? item.DbColumnName : item.PropertyName, + IsPrimarykey = item.IsPrimarykey, + IsIdentity = item.IsIdentity, + TableName = tableName, + IsNullable = item.IsNullable, + DefaultValue = item.DefaultValue, + ColumnDescription = item.ColumnDescription, + Length = item.Length + }; + if (result.DataType.Equals("varchar", StringComparison.CurrentCultureIgnoreCase) && result.Length == 0) + { + result.Length = 1; + } + return result; + } + + protected override void ConvertColumns(List dbColumns) + { + foreach (var item in dbColumns) + { + if (item.DataType == "DateTime") + { + item.Length = 0; + } + } + } + + protected override void ChangeKey(EntityInfo entityInfo, string tableName, EntityColumnInfo item) + { + this.Context.DbMaintenance.UpdateColumn(tableName, EntityColumnToDbColumn(entityInfo, tableName, item)); + if (!item.IsPrimarykey) + this.Context.DbMaintenance.DropConstraint(tableName,null); + if (item.IsPrimarykey) + this.Context.DbMaintenance.AddPrimaryKey(tableName, item.DbColumnName); + } + } +} diff --git a/Src/Asp.Net/SqlSugar/Realization/Sqlite/DbBind/SqliteDbBind.cs b/Src/Asp.Net/SqlSugar/Realization/Sqlite/DbBind/SqliteDbBind.cs new file mode 100644 index 000000000..ff535c8f0 --- /dev/null +++ b/Src/Asp.Net/SqlSugar/Realization/Sqlite/DbBind/SqliteDbBind.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace SqlSugar +{ + public class SqliteDbBind : DbBindProvider + { + public override string GetDbTypeName(string csharpTypeName) + { + if (csharpTypeName == PubConst.ByteArrayType.Name) + { + return "blob"; + } + if (csharpTypeName == "Int32") + csharpTypeName = "int"; + if (csharpTypeName == "Int16") + csharpTypeName = "short"; + if (csharpTypeName == "Int64") + csharpTypeName = "long"; + if (csharpTypeName == "Boolean") + csharpTypeName = "bool"; + var mappings = this.MappingTypes.Where(it => it.Value.ToString().Equals(csharpTypeName, StringComparison.CurrentCultureIgnoreCase)); + return mappings.IsValuable() ? mappings.First().Key : "varchar"; + } + public override List> MappingTypes + { + get + { + return new List>() + { + + new KeyValuePair("int",CSharpDataType.@int), + new KeyValuePair("mediumint",CSharpDataType.@int), + new KeyValuePair("integer",CSharpDataType.@int), + + new KeyValuePair("varchar",CSharpDataType.@string), + new KeyValuePair("text",CSharpDataType.@string), + new KeyValuePair("char",CSharpDataType.@string), + new KeyValuePair("enum",CSharpDataType.@string), + + new KeyValuePair("tinyint",CSharpDataType.@byte), + new KeyValuePair("smallint",CSharpDataType.@short), + new KeyValuePair("bigint",CSharpDataType.@long), + new KeyValuePair("bit",CSharpDataType.@bool), + new KeyValuePair("real",CSharpDataType.@double), + new KeyValuePair("double",CSharpDataType.@double), + new KeyValuePair("float",CSharpDataType.@float), + new KeyValuePair("decimal",CSharpDataType.@decimal), + new KeyValuePair("numeric",CSharpDataType.@decimal), + new KeyValuePair("year",CSharpDataType.@int), + + new KeyValuePair("datetime",CSharpDataType.DateTime), + new KeyValuePair("timestamp",CSharpDataType.DateTime), + new KeyValuePair("date",CSharpDataType.DateTime), + new KeyValuePair("time",CSharpDataType.DateTime), + + new KeyValuePair("blob",CSharpDataType.byteArray), + new KeyValuePair("tinyblob",CSharpDataType.byteArray), + new KeyValuePair("varbinary",CSharpDataType.byteArray), + new KeyValuePair("binary",CSharpDataType.byteArray), + new KeyValuePair("multipoint",CSharpDataType.byteArray), + new KeyValuePair("geometry",CSharpDataType.byteArray), + new KeyValuePair("multilinestring",CSharpDataType.byteArray), + new KeyValuePair("polygon",CSharpDataType.byteArray), + + new KeyValuePair("varchar",CSharpDataType.Guid), + }; + } + } + public override List StringThrow + { + get + { + return new List() { "int32", "datetime", "decimal", "double", "byte"}; + } + } + } +} diff --git a/Src/Asp.Net/SqlSugar/Realization/Sqlite/DbFirst/SqliteDbFirst.cs b/Src/Asp.Net/SqlSugar/Realization/Sqlite/DbFirst/SqliteDbFirst.cs new file mode 100644 index 000000000..cb378dc23 --- /dev/null +++ b/Src/Asp.Net/SqlSugar/Realization/Sqlite/DbFirst/SqliteDbFirst.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SqlSugar +{ + public class SqliteDbFirst : DbFirstProvider + { + } +} diff --git a/Src/Asp.Net/SqlSugar/Realization/Sqlite/DbMaintenance/SqliteDbMaintenance.cs b/Src/Asp.Net/SqlSugar/Realization/Sqlite/DbMaintenance/SqliteDbMaintenance.cs new file mode 100644 index 000000000..ecb6ba18f --- /dev/null +++ b/Src/Asp.Net/SqlSugar/Realization/Sqlite/DbMaintenance/SqliteDbMaintenance.cs @@ -0,0 +1,236 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SqlSugar +{ + public class SqliteDbMaintenance : DbMaintenanceProvider + { + #region DML + protected override string GetColumnInfosByTableNameSql + { + get + { + string sql = @"SELECT + 0 as TableId, + TABLE_NAME as TableName, + column_name AS DbColumnName, + CASE WHEN left(COLUMN_TYPE,LOCATE('(',COLUMN_TYPE)-1)='' THEN COLUMN_TYPE ELSE left(COLUMN_TYPE,LOCATE('(',COLUMN_TYPE)-1) END AS DataType, + CAST(SUBSTRING(COLUMN_TYPE,LOCATE('(',COLUMN_TYPE)+1,LOCATE(')',COLUMN_TYPE)-LOCATE('(',COLUMN_TYPE)-1) AS signed) AS Length, + column_default AS `DefaultValue`, + column_comment AS `ColumnDescription`, + CASE WHEN COLUMN_KEY = 'PRI' + THEN true ELSE false END AS `IsPrimaryKey`, + CASE WHEN EXTRA='auto_increment' THEN true ELSE false END as IsIdentity, + CASE WHEN is_nullable = 'YES' + THEN true ELSE false END AS `IsNullable` + FROM + Information_schema.columns where TABLE_NAME='{0}' and TABLE_SCHEMA=(select database()) ORDER BY TABLE_NAME"; + return sql; + } + } + protected override string GetTableInfoListSql + { + get + { + return @"select TABLE_NAME as Name,TABLE_COMMENT as Description from information_schema.tables + where TABLE_SCHEMA=(select database()) AND TABLE_TYPE='BASE TABLE'"; + } + } + protected override string GetViewInfoListSql + { + get + { + return @"select TABLE_NAME as Name,TABLE_COMMENT as Description from information_schema.tables + where TABLE_SCHEMA=(select database()) AND TABLE_TYPE='VIEW' + "; + } + } + #endregion + + #region DDL + protected override string AddPrimaryKeySql + { + get + { + return "ALTER TABLE {0} ADD PRIMARY KEY({2}) /*{1}*/"; + } + } + protected override string AddColumnToTableSql + { + get + { + return "ALTER TABLE {0} ADD {1} {2}{3} {4} {5} {6}"; + } + } + protected override string AlterColumnToTableSql + { + get + { + // return "ALTER TABLE {0} ALTER COLUMN {1} {2}{3} {4} {5} {6}"; + return "alter table {0} change column {1} {1} {2}{3} {4} {5} {6}"; + } + } + protected override string BackupDataBaseSql + { + get + { + return "mysqldump.exe {0} -uroot -p > {1} "; + } + } + protected override string CreateTableSql + { + get + { + return "CREATE TABLE {0}(\r\n{1} $PrimaryKey)"; + } + } + protected override string CreateTableColumn + { + get + { + return "{0} {1}{2} {3} {4} {5}"; + } + } + protected override string TruncateTableSql + { + get + { + return "TRUNCATE TABLE {0}"; + } + } + protected override string BackupTableSql + { + get + { + return "SELECT * INTO {1} FROM {2} limit 0,{0}"; + } + } + protected override string DropTableSql + { + get + { + return "DROP TABLE {0}"; + } + } + protected override string DropColumnToTableSql + { + get + { + return "ALTER TABLE {0} DROP COLUMN {1}"; + } + } + protected override string DropConstraintSql + { + get + { + return "ALTER TABLE {0} drop primary key;"; + } + } + protected override string RenameColumnSql + { + get + { + return "exec sp_rename '{0}.{1}','{2}','column';"; + } + } + #endregion + + #region Check + protected override string CheckSystemTablePermissionsSql + { + get + { + return "select 1 from Information_schema.columns limit 0,1"; + } + } + #endregion + + #region Scattered + protected override string CreateTableNull + { + get + { + return "DEFAULT NULL"; + } + } + protected override string CreateTableNotNull + { + get + { + return "NOT NULL"; + } + } + protected override string CreateTablePirmaryKey + { + get + { + return "PRIMARY KEY"; + } + } + protected override string CreateTableIdentity + { + get + { + return "AUTO_INCREMENT"; + } + } + #endregion + + #region Methods + public override bool CreateTable(string tableName, List columns) + { + if (columns.IsValuable()) + { + foreach (var item in columns) + { + if (item.DbColumnName.Equals("GUID",StringComparison.CurrentCultureIgnoreCase)) + { + item.Length = 10; + } + } + } + string sql = GetCreateTableSql(tableName, columns); + string primaryKeyInfo = null; + if (columns.Any(it => it.IsIdentity)) { + primaryKeyInfo =string.Format( ", Primary key({0})",string.Join(",",columns.Where(it=>it.IsIdentity).Select(it=>this.SqlBuilder.GetTranslationColumnName(it.DbColumnName)))); + + } + sql = sql.Replace("$PrimaryKey", primaryKeyInfo); + this.Context.Ado.ExecuteCommand(sql); + return true; + } + protected override string GetCreateTableSql(string tableName, List columns) + { + List columnArray = new List(); + Check.Exception(columns.IsNullOrEmpty(), "No columns found "); + foreach (var item in columns) + { + string columnName = item.DbColumnName; + string dataType = item.DataType; + if (dataType == "varchar"&& item.Length==0) { + item.Length = 1; + } + string dataSize = item.Length > 0 ? string.Format("({0})", item.Length) : null; + string nullType = item.IsNullable ? this.CreateTableNull : CreateTableNotNull; + string primaryKey = null; + string identity = item.IsIdentity ? this.CreateTableIdentity : null; + string addItem = string.Format(this.CreateTableColumn, this.SqlBuilder.GetTranslationColumnName(columnName), dataType, dataSize, nullType, primaryKey, identity); + columnArray.Add(addItem); + } + string tableString = string.Format(this.CreateTableSql, this.SqlBuilder.GetTranslationTableName(tableName), string.Join(",\r\n", columnArray)); + return tableString; + } + public override bool IsAnyConstraint(string constraintName) + { + throw new NotSupportedException("MySql IsAnyConstraint NotSupportedException"); + } + public override bool BackupDataBase(string databaseName, string fullFileName) + { + Check.ThrowNotSupportedException("MySql BackupDataBase NotSupported"); + return false; + } + #endregion + } +} diff --git a/Src/Asp.Net/SqlSugar/Realization/Sqlite/DbType.cs b/Src/Asp.Net/SqlSugar/Realization/Sqlite/DbType.cs new file mode 100644 index 000000000..cecb3c341 --- /dev/null +++ b/Src/Asp.Net/SqlSugar/Realization/Sqlite/DbType.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SqlSugar +{ + public partial class DbType + { + public const string Sqlite = "Sqlite"; + } +} diff --git a/Src/Asp.Net/SqlSugar/Realization/Sqlite/Queryable/SqliteQueryable.cs b/Src/Asp.Net/SqlSugar/Realization/Sqlite/Queryable/SqliteQueryable.cs new file mode 100644 index 000000000..d81ef67eb --- /dev/null +++ b/Src/Asp.Net/SqlSugar/Realization/Sqlite/Queryable/SqliteQueryable.cs @@ -0,0 +1,38 @@ +namespace SqlSugar +{ + public class SqliteQueryable:QueryableProvider + { + public override ISugarQueryable With(string withString) + { + return this; + } + } + public class SqliteQueryable : QueryableProvider + { + + } + public class SqliteQueryable : QueryableProvider + { + + } + public class SqliteQueryable : QueryableProvider + { + + } + public class SqliteQueryable : QueryableProvider + { + + } + public class SqliteQueryable : QueryableProvider + { + + } + public class SqliteQueryable : QueryableProvider + { + + } + public class SqliteQueryable : QueryableProvider + { + + } +} diff --git a/Src/Asp.Net/SqlSugar/Realization/Sqlite/SqlBuilder/SqliteBuilder.cs b/Src/Asp.Net/SqlSugar/Realization/Sqlite/SqlBuilder/SqliteBuilder.cs new file mode 100644 index 000000000..948f16e70 --- /dev/null +++ b/Src/Asp.Net/SqlSugar/Realization/Sqlite/SqlBuilder/SqliteBuilder.cs @@ -0,0 +1,46 @@ +using System; +using System.Linq; +using System.Text.RegularExpressions; + +namespace SqlSugar +{ + public class SqliteBuilder : SqlBuilderProvider + { + + public override string GetTranslationTableName(string name) + { + if (name.Contains("`")) return name; + Check.ArgumentNullException(name, string.Format(ErrorMessage.ObjNotExist, "Table Name")); + var context = this.Context; + var mappingInfo = context + .MappingTables + .FirstOrDefault(it => it.EntityName.Equals(name, StringComparison.CurrentCultureIgnoreCase)); + return "`" + (mappingInfo == null ? name : mappingInfo.DbTableName) + "`"; + } + public override string GetTranslationColumnName(string entityName, string propertyName) + { + Check.ArgumentNullException(entityName, string.Format(ErrorMessage.ObjNotExist, "Table Name")); + Check.ArgumentNullException(propertyName, string.Format(ErrorMessage.ObjNotExist, "Column Name")); + var context = this.Context; + var mappingInfo = context + .MappingColumns + .FirstOrDefault(it => + it.EntityName.Equals(entityName, StringComparison.CurrentCultureIgnoreCase) && + it.PropertyName.Equals(propertyName, StringComparison.CurrentCultureIgnoreCase)); + return (mappingInfo == null ? "`" + propertyName + "`" : "`" + mappingInfo.DbColumnName + "`"); + } + + public override string GetTranslationColumnName(string propertyName) + { + if (propertyName.Contains("`")) return propertyName; + else + return "`" + propertyName + "`"; + } + + public override string GetNoTranslationColumnName(string name) + { + if (!name.Contains("`")) return name; + return name == null ? string.Empty : Regex.Match(name, @"\`(.*?)\`").Groups[1].Value; + } + } +} diff --git a/Src/Asp.Net/SqlSugar/Realization/Sqlite/SqlBuilder/SqliteDeleteBuilder.cs b/Src/Asp.Net/SqlSugar/Realization/Sqlite/SqlBuilder/SqliteDeleteBuilder.cs new file mode 100644 index 000000000..97189bcab --- /dev/null +++ b/Src/Asp.Net/SqlSugar/Realization/Sqlite/SqlBuilder/SqliteDeleteBuilder.cs @@ -0,0 +1,7 @@ +namespace SqlSugar +{ + public class MySqlDeleteBuilder : DeleteBuilder + { + + } +} diff --git a/Src/Asp.Net/SqlSugar/Realization/Sqlite/SqlBuilder/SqliteExpressionContext.cs b/Src/Asp.Net/SqlSugar/Realization/Sqlite/SqlBuilder/SqliteExpressionContext.cs new file mode 100644 index 000000000..18a37a342 --- /dev/null +++ b/Src/Asp.Net/SqlSugar/Realization/Sqlite/SqlBuilder/SqliteExpressionContext.cs @@ -0,0 +1,59 @@ +using System; +using System.Linq; +namespace SqlSugar +{ + public class SqliteExpressionContext : ExpressionContext, ILambdaExpressions + { + public SqlSugarClient Context { get; set; } + public SqliteExpressionContext() + { + base.DbMehtods = new SqliteMethod(); + } + public override string GetTranslationTableName(string entityName, bool isMapping = true) + { + Check.ArgumentNullException(entityName, string.Format(ErrorMessage.ObjNotExist, "Table Name")); + if (IsTranslationText(entityName)) return entityName; + if (isMapping && this.MappingTables.IsValuable()) + { + if (entityName.Contains(".")) + { + var columnInfo = entityName.Split('.'); + var mappingInfo = this.MappingTables.FirstOrDefault(it => it.EntityName.Equals(columnInfo.Last(), StringComparison.CurrentCultureIgnoreCase)); + if (mappingInfo != null) + { + columnInfo[columnInfo.Length - 1] = mappingInfo.EntityName; + } + return string.Join(".", columnInfo.Select(it => GetTranslationText(it))); + } + else + { + var mappingInfo = this.MappingTables.FirstOrDefault(it => it.EntityName.Equals(entityName, StringComparison.CurrentCultureIgnoreCase)); + return "`" + (mappingInfo == null ? entityName : mappingInfo.EntityName) + "`"; + } + } + else + { + if (entityName.Contains(".")) + { + return string.Join(".", entityName.Split('.').Select(it => GetTranslationText(it))); + } + else + { + return GetTranslationText(entityName); + } + } + } + public override bool IsTranslationText(string name) + { + return name.Contains("`") && name.Contains("`"); + } + public override string GetTranslationText(string name) + { + return "`" + name + "`"; + } + } + public class SqliteMethod : DefaultDbMethod, IDbMethods + { + + } +} diff --git a/Src/Asp.Net/SqlSugar/Realization/Sqlite/SqlBuilder/SqliteInsertBuilder.cs b/Src/Asp.Net/SqlSugar/Realization/Sqlite/SqlBuilder/SqliteInsertBuilder.cs new file mode 100644 index 000000000..6cffeb242 --- /dev/null +++ b/Src/Asp.Net/SqlSugar/Realization/Sqlite/SqlBuilder/SqliteInsertBuilder.cs @@ -0,0 +1,27 @@ +namespace SqlSugar +{ + public class SqliteInsertBuilder : InsertBuilder + { + public override string SqlTemplate + { + get + { + if (IsReturnIdentity) + { + return @"INSERT INTO {0} + ({1}) + VALUES + ({2}) ;SELECT LAST_INSERT_ID();"; + } + else + { + return @"INSERT INTO {0} + ({1}) + VALUES + ({2}) ;"; + + } + } + } + } +} diff --git a/Src/Asp.Net/SqlSugar/Realization/Sqlite/SqlBuilder/SqliteQueryBuilder.cs b/Src/Asp.Net/SqlSugar/Realization/Sqlite/SqlBuilder/SqliteQueryBuilder.cs new file mode 100644 index 000000000..bdddfa2e7 --- /dev/null +++ b/Src/Asp.Net/SqlSugar/Realization/Sqlite/SqlBuilder/SqliteQueryBuilder.cs @@ -0,0 +1,86 @@ +using System.Linq; +using System.Text; + +namespace SqlSugar +{ + public partial class SqliteQueryBuilder : QueryBuilder + { + #region Sql Template + public override string PageTempalte + { + get + { + /* + SELECT * FROM TABLE WHERE CONDITION ORDER BY ID DESC LIMIT 0,10 + */ + var template = "SELECT {0} FROM {1} {2} {3} {4} LIMIT {5},{6}"; + return template; + } + } + public override string DefaultOrderByTemplate + { + get + { + return "ORDER BY NOW() "; + } + } + + #endregion + + #region Common Methods + + public override string ToSqlString() + { + sql = new StringBuilder(); + sql.AppendFormat(SqlTemplate, GetSelectValue, GetTableNameString, GetWhereValueString, GetGroupByString + HavingInfos, (Skip != null || Take != null) ? null : GetOrderByString); + if (IsCount) { return sql.ToString(); } + if (Skip != null && Take == null) + { + if (this.OrderByValue == "ORDER BY ") this.OrderByValue += GetSelectValue.Split(',')[0]; + return string.Format(PageTempalte, GetSelectValue, GetTableNameString, GetWhereValueString, GetGroupByString + HavingInfos, (Skip != null || Take != null) ? null : GetOrderByString, Skip.ObjToInt(), long.MaxValue); + } + else if (Skip == null && Take != null) + { + if (this.OrderByValue == "ORDER BY ") this.OrderByValue += GetSelectValue.Split(',')[0]; + return string.Format(PageTempalte, GetSelectValue, GetTableNameString, GetWhereValueString, GetGroupByString + HavingInfos, GetOrderByString, 1, Take.ObjToInt()); + } + else if (Skip != null && Take != null) + { + if (this.OrderByValue == "ORDER BY ") this.OrderByValue += GetSelectValue.Split(',')[0]; + return string.Format(PageTempalte, GetSelectValue, GetTableNameString, GetWhereValueString, GetGroupByString + HavingInfos, GetOrderByString, Skip.ObjToInt() > 0 ? Skip.ObjToInt(): 0, Take); + } + else + { + return sql.ToString(); + } + + } + + #endregion + + #region Get SQL Partial + public override string GetSelectValue + { + get + { + if (this.IsCount) return "COUNT(1) AS `Count` "; + string reval = string.Empty; + if (this.SelectValue == null || this.SelectValue is string) + { + reval = GetSelectValueByString(); + } + else + { + reval = GetSelectValueByExpression(); + } + if (this.SelectType == ResolveExpressType.SelectMultiple) + { + this.SelectCacheKey = this.SelectCacheKey + string.Join("-", this.JoinQueryInfos.Select(it => it.TableName)); + } + return reval; + } + } + + #endregion + } +} diff --git a/Src/Asp.Net/SqlSugar/Realization/Sqlite/SqlBuilder/SqliteUpdateBuilder.cs b/Src/Asp.Net/SqlSugar/Realization/Sqlite/SqlBuilder/SqliteUpdateBuilder.cs new file mode 100644 index 000000000..359aa5351 --- /dev/null +++ b/Src/Asp.Net/SqlSugar/Realization/Sqlite/SqlBuilder/SqliteUpdateBuilder.cs @@ -0,0 +1,91 @@ +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SqlSugar +{ + public class SqliteUpdateBuilder : UpdateBuilder + { + public override string SqlTemplateBatch + { + get + { + return @"UPDATE {1} S {2} INNER JOIN ${{0}} SET {0} "; + } + } + public override string SqlTemplateJoin + { + get + { + return @" ( + {0} + + ) T ON {1} + "; + } + } + protected override string TomultipleSqlString(List> groupList) + { + Check.Exception(PrimaryKeys == null || PrimaryKeys.Count == 0, " Update List need Primary key"); + int pageSize = 200; + int pageIndex = 1; + int totalRecord = groupList.Count; + int pageCount = (totalRecord + pageSize - 1) / pageSize; + StringBuilder batchUpdateSql = new StringBuilder(); + while (pageCount >= pageIndex) + { + StringBuilder updateTable = new StringBuilder(); + string setValues = string.Join(",", groupList.First().Where(it => it.IsPrimarykey == false && (it.IsIdentity == false || (IsOffIdentity && it.IsIdentity))).Select(it => + { + if (SetValues.IsValuable()) + { + var setValue = SetValues.Where(sv => sv.Key == Builder.GetTranslationColumnName(it.DbColumnName)); + if (setValue != null && setValue.Any()) + { + return setValue.First().Value; + } + } + var result = string.Format("S.{0}=T.{0}", Builder.GetTranslationColumnName(it.DbColumnName)); + return result; + })); + batchUpdateSql.AppendFormat(SqlTemplateBatch.ToString(), setValues, GetTableNameStringNoWith, TableWithString); + int i = 0; + foreach (var columns in groupList.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList()) + { + var isFirst = i == 0; + if (!isFirst) + { + updateTable.Append(SqlTemplateBatchUnion); + } + updateTable.Append("\r\n SELECT " + string.Join(",", columns.Select(it => string.Format(SqlTemplateBatchSelect, FormatValue(it.Value), it.DbColumnName)))); + ++i; + } + pageIndex++; + updateTable.Append("\r\n"); + string whereString = null; + if (this.WhereValues.IsValuable()) + { + foreach (var item in WhereValues) + { + var isFirst = whereString == null; + whereString += (isFirst ? null : " AND "); + whereString += item; + } + } + else if (PrimaryKeys.IsValuable()) + { + foreach (var item in PrimaryKeys) + { + var isFirst = whereString == null; + whereString += (isFirst ? null : " AND "); + whereString += string.Format("S.{0}=T.{0}", Builder.GetTranslationColumnName(item)); + } + } + var format= string.Format(SqlTemplateJoin, updateTable, whereString); + batchUpdateSql.Replace("${0}",format); + batchUpdateSql.Append(";"); + } + return batchUpdateSql.ToString(); + } + } +} diff --git a/Src/Asp.Net/SqlSugar/Realization/Sqlite/SqliteProvider.cs b/Src/Asp.Net/SqlSugar/Realization/Sqlite/SqliteProvider.cs new file mode 100644 index 000000000..22c3de683 --- /dev/null +++ b/Src/Asp.Net/SqlSugar/Realization/Sqlite/SqliteProvider.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Data.SQLite; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +namespace SqlSugar +{ + public class SqliteProvider : AdoProvider + { + public SqliteProvider() { } + public override IDbConnection Connection + { + get + { + if (base._DbConnection == null) + { + var SQLiteConnectionString = base.Context.CurrentConnectionConfig.ConnectionString; + if (!SQLiteConnectionString.ToLower().Contains("charset")) + { + SQLiteConnectionString=SQLiteConnectionString.Trim().TrimEnd(';') + ";charset=utf8;"; + } + base._DbConnection = new SQLiteConnection(SQLiteConnectionString); + } + return base._DbConnection; + } + set + { + base._DbConnection = value; + } + } + + public override void BeginTran(string transactionName) + { + ((SQLiteConnection)this.Connection).BeginTransaction(); + } + /// + /// Only SqlServer + /// + /// + /// + public override void BeginTran(IsolationLevel iso, string transactionName) + { + ((SQLiteConnection)this.Connection).BeginTransaction(iso); + } + public override IDataAdapter GetAdapter() + { + return new SQLiteDataAdapter(); + } + public override IDbCommand GetCommand(string sql, SugarParameter[] parameters) + { + SQLiteCommand sqlCommand = new SQLiteCommand(sql, (SQLiteConnection)this.Connection); + sqlCommand.CommandType = this.CommandType; + sqlCommand.CommandTimeout = this.CommandTimeOut; + if (this.Transaction != null) + { + sqlCommand.Transaction = (SQLiteTransaction)this.Transaction; + } + if (parameters.IsValuable()) + { + IDataParameter[] ipars = ToIDbDataParameter(parameters); + sqlCommand.Parameters.AddRange((SQLiteParameter[])ipars); + } + CheckConnection(); + return sqlCommand; + } + public override void SetCommandToAdapter(IDataAdapter dataAdapter, IDbCommand command) + { + ((SQLiteDataAdapter)dataAdapter).SelectCommand = (SQLiteCommand)command; + } + /// + /// if SQLite return SQLiteParameter[] pars + /// if sqlerver return SqlParameter[] pars ... + /// + /// + /// + public override IDataParameter[] ToIDbDataParameter(params SugarParameter[] parameters) + { + if (parameters == null || parameters.Length == 0) return null; + SQLiteParameter[] result = new SQLiteParameter[parameters.Length]; + int index = 0; + foreach (var parameter in parameters) + { + if (parameter.Value == null) parameter.Value = DBNull.Value; + var sqlParameter = new SQLiteParameter(); + sqlParameter.ParameterName = parameter.ParameterName; + sqlParameter.Size = parameter.Size; + sqlParameter.Value = parameter.Value; + sqlParameter.DbType = parameter.DbType; + sqlParameter.Direction = parameter.Direction; + result[index] = sqlParameter; + if (sqlParameter.Direction == ParameterDirection.Output) { + if (this.OutputParameters == null) this.OutputParameters = new List(); + this.OutputParameters.RemoveAll(it => it.ParameterName == sqlParameter.ParameterName); + this.OutputParameters.Add(sqlParameter); + } + ++index; + } + return result; + } + } +} diff --git a/Src/Asp.Net/SqlSugar/SqlSugar.csproj b/Src/Asp.Net/SqlSugar/SqlSugar.csproj index 84b6d58fa..6033bfd41 100644 --- a/Src/Asp.Net/SqlSugar/SqlSugar.csproj +++ b/Src/Asp.Net/SqlSugar/SqlSugar.csproj @@ -41,6 +41,10 @@ + + False + Lib\System.Data.SQLite.dll + @@ -67,6 +71,19 @@ + + + + + + + + + + + + + @@ -192,10 +209,10 @@ + -