Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Correct bracket type used around nvarchar/varchar when formatting the command #643

Open
wants to merge 15 commits into
base: v5
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
NPoco
=====
![Nuget](https://img.shields.io/nuget/v/npoco)

Welcome to the NPoco! NPoco is a fork of PetaPoco based on Schotime's branch with a handful of extra features.

Expand All @@ -19,4 +20,5 @@ List<User> users = db.Fetch<User>("select userId, email from users");
This works by mapping the column names to the property names on the ``User`` object. This is a case-insensitive match.
There is no mapping setup needed for this (query only) scenario.

Checkout the [Wiki](https://github.com/schotime/NPoco/wiki/Home) for more documentation.
Checkout the [Wiki](https://github.com/schotime/NPoco/wiki/Home) for more documentation.

4 changes: 2 additions & 2 deletions src/NPoco.JsonNet/NPoco.JsonNet.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<Description>Provides an implementation to use Json.NET as the serializer for serialized columns</Description>
<VersionPrefix>5.0.0</VersionPrefix>
<VersionPrefix>5.3.0</VersionPrefix>
<TargetFrameworks>net461;netstandard2.0;netstandard2.1</TargetFrameworks>
<AssemblyName>NPoco.JsonNet</AssemblyName>
<PackageId>NPoco.JsonNet</PackageId>
Expand All @@ -14,7 +14,7 @@
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
<GenerateAssemblyCopyrightAttribute>false</GenerateAssemblyCopyrightAttribute>
<LangVersion>8.0</LangVersion>
<LangVersion>latest</LangVersion>
</PropertyGroup>

<ItemGroup>
Expand Down
39 changes: 35 additions & 4 deletions src/NPoco.SqlServer/DatabaseTypes/SqlServer2012DatabaseType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,43 @@ public static Database Create(string connectionString)

public override string BuildPageQuery(long skip, long take, PagingHelper.SQLParts parts, ref object[] args)
{
if (!parts.sql.ToLower().Contains("order by"))
throw new Exception("SQL Server 2012 Paging via OFFSET requires an ORDER BY statement.");

var sqlPage = string.Format("{0}\nOFFSET @{1} ROWS FETCH NEXT @{2} ROWS ONLY", parts.sql, args.Length, args.Length + 1);
var sqlPage = string.Format("{0}{1}\nOFFSET @{2} ROWS FETCH NEXT @{3} ROWS ONLY",
parts.sql,
!HasTopLevelOrderBy(parts.sql) ? "\nORDER BY (SELECT NULL)" : string.Empty,
args.Length,
args.Length + 1);
args = args.Concat(new object[] {skip, take}).ToArray();
return sqlPage;
}

public static bool HasTopLevelOrderBy(string sql)
{
var indent = 0;
for (int i = sql.Length - 1; i >= 0; i--)
{
if (i >= 7)
{
if (indent == 0
&& (sql[i - 7] == 'o' || sql[i - 7] == 'O')
&& (sql[i - 6] == 'r' || sql[i - 6] == 'R')
&& (sql[i - 5] == 'd' || sql[i - 5] == 'D')
&& (sql[i - 4] == 'e' || sql[i - 4] == 'E')
&& (sql[i - 3] == 'r' || sql[i - 3] == 'R')
&& (sql[i - 2] == ' ')
&& (sql[i - 1] == 'b' || sql[i - 1] == 'B')
&& (sql[i] == 'y' || sql[i] == 'Y'))
{
return true;
}
}

if (sql[i] == ')')
indent++;
else if (sql[i] == '(')
indent--;
}

return false;
}

public override string? GetAutoIncrementExpression(TableInfo ti)
Expand Down
4 changes: 4 additions & 0 deletions src/NPoco.SqlServer/DatabaseTypes/SqlServerDatabaseType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,10 @@ public override string FormatCommand(string sql, object[] args)
sb.AppendFormat("DECLARE {0}{1} {2} = '{3}'\n", GetParameterPrefix(string.Empty), i, p.SqlDbType, value);
}
}
else if (p.SqlDbType == SqlDbType.NVarChar || p.SqlDbType == SqlDbType.VarChar)
{
sb.AppendFormat("DECLARE {0}{1} {2}({3}) = '{4}'\n", GetParameterPrefix(string.Empty), i, p.SqlDbType, p.Size, value);
}
else
{
sb.AppendFormat("DECLARE {0}{1} {2}[{3}] = '{4}'\n", GetParameterPrefix(string.Empty), i, p.SqlDbType, p.Size, value);
Expand Down
4 changes: 2 additions & 2 deletions src/NPoco.SqlServer/NPoco.SqlServer.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@

<PropertyGroup>
<Description>An extremely easy to use Micro-ORM supporting Sql Server.</Description>
<VersionPrefix>5.0.0</VersionPrefix>
<VersionPrefix>5.3.0</VersionPrefix>
<TargetFrameworks>net461;netstandard2.0;netstandard2.1</TargetFrameworks>
<AssemblyName>NPoco.SqlServer</AssemblyName>
<PackageId>NPoco.SqlServer</PackageId>
<Authors>Adam Schröder</Authors>
<PackageTags>orm;sql;micro-orm;database;mvc</PackageTags>
<PackageProjectUrl>https://github.com/schotime/NPoco</PackageProjectUrl>
<LangVersion>8.0</LangVersion>
<LangVersion>latest</LangVersion>
<nullable>enable</nullable>
</PropertyGroup>

Expand Down
9 changes: 1 addition & 8 deletions src/NPoco.SqlServer/SqlBulkCopyHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,14 +79,7 @@ private static DataTable BuildBulkInsertDataTable<T>(IDatabase db, IEnumerable<T
var values = new object[cols.Count];
for (var i = 0; i < values.Length; i++)
{
var value = cols[i].Value.GetValue(item!);
if (db.Mappers != null)
{
value = db.Mappers.FindAndExecute(x => x.GetToDbConverter(cols[i].Value.ColumnType, cols[i].Value.MemberInfoData.MemberInfo), value);
}

value = db.DatabaseType.MapParameterValue(value);

var value = db.DatabaseType.MapParameterValue(db.ProcessMapper(cols[i].Value, cols[i].Value.GetValue(item!)));
if (value.GetTheType() == typeof (SqlParameter))
{
value = ((SqlParameter) value).Value;
Expand Down
4 changes: 2 additions & 2 deletions src/NPoco/AsyncDatabase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -465,7 +465,7 @@ public Task<T> SingleOrDefaultByIdAsync<T>(object primaryKey)

public Task<T> FirstAsync<T>(string sql, params object[] args)
{
return QueryAsync<T>(sql).FirstAsync().AsTask();
return QueryAsync<T>(sql, args).FirstAsync().AsTask();
}

public Task<T> FirstAsync<T>(Sql sql)
Expand All @@ -475,7 +475,7 @@ public Task<T> FirstAsync<T>(Sql sql)

public Task<T> FirstOrDefaultAsync<T>(string sql, params object[] args)
{
return QueryAsync<T>(sql).FirstOrDefaultAsync().AsTask();
return QueryAsync<T>(sql, args).FirstOrDefaultAsync().AsTask();
}

public Task<T> FirstOrDefaultAsync<T>(Sql sql)
Expand Down
9 changes: 8 additions & 1 deletion src/NPoco/ColumnInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,18 @@ public static ColumnInfo FromMemberInfo(MemberInfo mi)
ci.IgnoreColumn = true;
}

var complexMappingAttribute = mi.GetMemberInfoType().GetCustomAttribute<ComplexMappingAttribute>();

if (complexMapping.Any())
{
ci.ComplexMapping = true;
ci.ComplexMapping = complexMapping.First().ComplexMapping;
ci.ComplexPrefix = complexMapping.First().CustomPrefix;
}
else if (complexMappingAttribute != null)
{
ci.ComplexMapping = complexMappingAttribute.ComplexMapping;
ci.ComplexPrefix = complexMappingAttribute.CustomPrefix;
}
else if (mi.GetMemberInfoType().GetInterfaces().Any(x => x == typeof(IValueObject)))
{
ci.ValueObjectColumn = true;
Expand Down
1 change: 1 addition & 0 deletions src/NPoco/ComplexMappingAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ namespace NPoco
{
public class ComplexMappingAttribute : Attribute
{
public bool ComplexMapping { get; set; } = true;
public string CustomPrefix { get; set; }

public ComplexMappingAttribute()
Expand Down
4 changes: 2 additions & 2 deletions src/NPoco/Database.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1493,7 +1493,7 @@ private async Task<int> DeleteImpAsync(string tableName, string primaryKeyName,
var sql = $"DELETE FROM {_dbType.EscapeTableName(tableName)} WHERE {BuildPrimaryKeySql(this, primaryKeyValuePairs, ref index)}";
var rawValues = primaryKeyValuePairs.Select(x => x.Value).ToList();

var versionColumn = pd?.AllColumns.SingleOrDefault(x => x.VersionColumn);
var versionColumn = pd?.Columns.Where(x => x.Value.VersionColumn).Select(x => x.Value).SingleOrDefault();
string? versionName = null;
object? versionValue = null;
if (versionColumn != null)
Expand Down Expand Up @@ -1760,7 +1760,7 @@ internal static object ProcessDefaultMappings(IDatabase database, PocoColumn poc
{
if (pocoColumn.SerializedColumn)
{
return DatabaseFactory.ColumnSerializer.Serialize(value);
return database.Mappers.ColumnSerializer.Serialize(value);
}
if (pocoColumn.ColumnType == typeof(string) && Database.IsEnum(pocoColumn.MemberInfoData) && value != null)
{
Expand Down
10 changes: 9 additions & 1 deletion src/NPoco/DatabaseFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,14 @@ private void ConfigurePocoDataFactoryAndMappers(IDatabase database, MapperCollec
database.Mappers = mappers;
if (_options.PocoDataFactory != null)
{
database.PocoDataFactory = _cachedPocoDataFactory = (_cachedPocoDataFactory == null ? _options.PocoDataFactory.Config(mappers) : _cachedPocoDataFactory);
database.PocoDataFactory = _cachedPocoDataFactory ??= _options.PocoDataFactory.Config(mappers);
}
}

private MapperCollection BuildMapperCollection(IDatabase database)
{
var mc = new MapperCollection();
mc.ColumnSerializer = _options.ColumnSerializer ?? ColumnSerializer;
mc.AddRange(database.Mappers);
mc.AddRange(_options.Mapper);

Expand Down Expand Up @@ -105,6 +106,7 @@ public DatabaseFactoryConfigOptions()
public MapperCollection Mapper { get; private set; }
public FluentConfig PocoDataFactory { get; set; }
public List<IInterceptor> Interceptors { get; private set; }
public IColumnSerializer ColumnSerializer { get; set; }
}

public class DatabaseFactoryConfig
Expand Down Expand Up @@ -145,5 +147,11 @@ public DatabaseFactoryConfig WithInterceptor(IInterceptor interceptor)
_options.Interceptors.Add(interceptor);
return this;
}

public DatabaseFactoryConfig WithColumnSerializer(IColumnSerializer columnSerializer)
{
_options.ColumnSerializer = columnSerializer;
return this;
}
}
}
2 changes: 1 addition & 1 deletion src/NPoco/DatabaseType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ namespace NPoco
public abstract partial class DatabaseType
{
// Helper Properties
public static DatabaseType SqlServer2012 { get { return DynamicDatabaseType.MakeSqlServerType("SqlServerDatabaseType"); } }
public static DatabaseType SqlServer2012 { get { return DynamicDatabaseType.MakeSqlServerType("SqlServer2012DatabaseType"); } }
public static DatabaseType SqlServer2008 { get { return DynamicDatabaseType.MakeSqlServerType("SqlServer2008DatabaseType"); } }
public static DatabaseType SqlServer2005 { get { return DynamicDatabaseType.MakeSqlServerType("SqlServerDatabaseType"); } }
public static DatabaseType PostgreSQL { get { return Singleton<PostgreSQLDatabaseType>.Instance; } }
Expand Down
12 changes: 10 additions & 2 deletions src/NPoco/Expressions/SqlExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ public interface ISqlExpression
List<SelectMember> SelectMembers { get; }
List<GeneralMember> GeneralMembers { get; }
string ApplyPaging(string sql, IEnumerable<PocoColumn[]> columns, Dictionary<string, JoinData> joinSqlExpressions);
string TableHint { get; }
}

public abstract class SqlExpression<T> : ISqlExpression
Expand All @@ -82,6 +83,7 @@ public abstract class SqlExpression<T> : ISqlExpression
private string groupBy = string.Empty;
private string havingExpression;
private string orderBy = string.Empty;
private string tableHint = string.Empty;

List<OrderByMember> ISqlExpression.OrderByMembers { get { return orderByMembers; } }
List<SelectMember> ISqlExpression.SelectMembers { get { return selectMembers; } }
Expand All @@ -91,6 +93,7 @@ public abstract class SqlExpression<T> : ISqlExpression
int? ISqlExpression.Skip { get { return Skip; } }
Type ISqlExpression.Type { get { return _type; } }
object[] ISqlExpression.Params { get { return Context.Params; } }
string ISqlExpression.TableHint { get{ return tableHint; }}

string ISqlExpression.ApplyPaging(string sql, IEnumerable<PocoColumn[]> columns, Dictionary<string, JoinData> joinSqlExpressions)
{
Expand Down Expand Up @@ -371,6 +374,10 @@ private void BuildOrderByClauseInternal()
}
}

public virtual void TableHint(string hint)
{
tableHint += " " + hint;
}

/// <summary>
/// Set the specified offset and rows for SQL Limit clause.
Expand Down Expand Up @@ -1417,7 +1424,7 @@ protected object GetQuotedFalseValue()
private string BuildSelectExpression(List<SelectMember> fields, bool distinct)
{
var cols = fields ?? _pocoData.QueryColumns.Select(x => new SelectMember{ PocoColumn = x.Value, EntityType = _pocoData.Type, PocoColumns = new[] { x.Value }});
return string.Format("SELECT {0}{1} \nFROM {2}",
return string.Format("SELECT {0}{1} \nFROM {2}{3}",
(distinct ? "DISTINCT " : ""),
string.Join(", ", cols.Select(x =>
{
Expand All @@ -1435,7 +1442,8 @@ private string BuildSelectExpression(List<SelectMember> fields, bool distinct)

return x.SelectSql;
}).ToArray()),
_databaseType.EscapeTableName(_pocoData.TableInfo.TableName) + (PrefixFieldWithTableName ? " " + _databaseType.EscapeTableName(_pocoData.TableInfo.AutoAlias) : string.Empty));
_databaseType.EscapeTableName(_pocoData.TableInfo.TableName) + (PrefixFieldWithTableName ? " " + _databaseType.EscapeTableName(_pocoData.TableInfo.AutoAlias) : string.Empty),
tableHint);
}

internal List<PocoColumn> GetAllMembers()
Expand Down
7 changes: 6 additions & 1 deletion src/NPoco/FastCreate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,12 @@

namespace NPoco
{
public class FastCreate
public interface IFastCreate
{
object Create(DbDataReader dataReader);
}

public class FastCreate : IFastCreate
{
private readonly Type _type;
private readonly MapperCollection _mapperCollection;
Expand Down
9 changes: 3 additions & 6 deletions src/NPoco/FluentMappings/FluentMappingConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -290,20 +290,17 @@ private static FluentConfig SetFactory(Mappings mappings, Action<IConventionScan
{
if (maps != null)
{
if (maps.Config.ContainsKey(t))
{
return new FluentMappingsPocoDataBuilder(t, mappings, mapper).Init();
}

if (scana != null)
{
var settings = ProcessSettings(scana);
var typeMapping = CreateMappings(settings, new[] { t });
return new FluentMappingsPocoDataBuilder(t, typeMapping, mapper).Init();
}

return new FluentMappingsPocoDataBuilder(t, mappings, mapper).Init();
}
return new PocoDataBuilder(t, mapper).Init();
}));
}, mapper));
}

// Helper method if code is in seperate assembly
Expand Down
13 changes: 7 additions & 6 deletions src/NPoco/Linq/ComplexSqlBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public Sql BuildJoin(IDatabase database, SqlExpression<T> sqlExpression, List<Jo
// Override select columns with projected ones
if (newMembers != null)
{
var selectMembers = ((ISqlExpression) _sqlExpression).OrderByMembers
var selectMembers = exp.OrderByMembers
.Select(x => new SelectMember() {PocoColumn = x.PocoColumn, EntityType = x.EntityType, PocoColumns = x.PocoColumns})
.Where(x => !newMembers.Any(y => y.EntityType == x.EntityType && y.PocoColumns.SequenceEqual(x.PocoColumns)));

Expand All @@ -103,12 +103,12 @@ public Sql BuildJoin(IDatabase database, SqlExpression<T> sqlExpression, List<Jo
// replace templates
var resultantSql = string.Format(sqlTemplate,
(distinct ? "DISTINCT " : "") + string.Join(", ", cols.Select(x=>x.StringCol).ToArray()),
database.DatabaseType.EscapeTableName(modelDef.TableInfo.TableName) + " " + database.DatabaseType.EscapeTableName(modelDef.TableInfo.AutoAlias),
database.DatabaseType.EscapeTableName(modelDef.TableInfo.TableName) + " " + database.DatabaseType.EscapeTableName(modelDef.TableInfo.AutoAlias) + exp.TableHint,
joins,
where,
orderbys);

var newsql = count ? resultantSql : ((ISqlExpression)_sqlExpression).ApplyPaging(resultantSql, cols.Select(x=>x.PocoColumn), _joinSqlExpressions);
var newsql = count ? resultantSql : exp.ApplyPaging(resultantSql, cols.Select(x=>x.PocoColumn), _joinSqlExpressions);

return new Sql(newsql, _sqlExpression.Context.Params);
}
Expand All @@ -130,13 +130,13 @@ private static string BuildJoinSql(IDatabase database, List<JoinData> joinSqlExp
PocoColumn = new[] { x.PocoColumn }
})).ToList();

joins.Add(string.Format(" {0} JOIN " + database.DatabaseType.EscapeTableName(member.PocoColumn.TableInfo.TableName) + " " + database.DatabaseType.EscapeTableName(member.PocoColumn.TableInfo.AutoAlias) + " ON " + joinSqlExpression.OnSql, joinSqlExpression.JoinType == JoinType.Inner ? "INNER" : "LEFT"));
joins.Add(string.Format(" {0} JOIN " + database.DatabaseType.EscapeTableName(member.PocoColumn.TableInfo.TableName) + " " + database.DatabaseType.EscapeTableName(member.PocoColumn.TableInfo.AutoAlias) + joinSqlExpression.Hint + " ON " + joinSqlExpression.OnSql, joinSqlExpression.JoinType == JoinType.Inner ? "INNER" : "LEFT"));
}

return joins.Any() ? " \n" + string.Join(" \n", joins.ToArray()) : string.Empty;
}

public Dictionary<string, JoinData> GetJoinExpressions(Expression expression, string tableAlias, JoinType joinType)
public Dictionary<string, JoinData> GetJoinExpressions(Expression expression, string tableAlias, JoinType joinType, string hint)
{
var memberInfos = MemberChainHelper.GetMembers(expression);
var members = _pocoData.Members;
Expand Down Expand Up @@ -167,7 +167,8 @@ public Dictionary<string, JoinData> GetJoinExpressions(Expression expression, st
PocoMember = pocoMember,
PocoMemberJoin = pocoMember2,
PocoMembers = pocoMember.PocoMemberChildren,
JoinType = joinType
JoinType = joinType,
Hint = hint == string.Empty ? hint : " " + hint
});
}

Expand Down
1 change: 1 addition & 0 deletions src/NPoco/Linq/JoinData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ public class JoinData
public PocoMember PocoMemberJoin { get; set; }
public List<PocoMember> PocoMembers { get; set; }
public JoinType JoinType { get; set; }
public string Hint { get; set; }
}
}
Loading