From b13eee593d07a6d1daed38b718f727c086693446 Mon Sep 17 00:00:00 2001 From: Mattias Rasmusson Date: Tue, 17 Aug 2021 18:01:15 -0700 Subject: [PATCH] PostgreSQL dialect - handle getIdentitySql properly using RETURNING --- Dapper.SimpleCRUD/SimpleCRUD.cs | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/Dapper.SimpleCRUD/SimpleCRUD.cs b/Dapper.SimpleCRUD/SimpleCRUD.cs index 691075c..bbe0e94 100644 --- a/Dapper.SimpleCRUD/SimpleCRUD.cs +++ b/Dapper.SimpleCRUD/SimpleCRUD.cs @@ -55,7 +55,7 @@ private static void StringBuilderCache(StringBuilder sb, string cacheKey, Action StringBuilderCacheDict.AddOrUpdate(cacheKey, value, (t, v) => value); sb.Append(value); } - + /// /// Returns the current dialect name /// @@ -76,7 +76,7 @@ public static void SetDialect(Dialect dialect) case Dialect.PostgreSQL: _dialect = Dialect.PostgreSQL; _encapsulation = "\"{0}\""; - _getIdentitySql = string.Format("SELECT LASTVAL() AS id"); + _getIdentitySql = "RETURNING {0} AS id"; _getPagedListSql = "Select {SelectColumns} from {TableName} {WhereClause} Order By {OrderBy} LIMIT {RowsPerPage} OFFSET (({PageNumber}-1) * {RowsPerPage})"; break; case Dialect.SQLite: @@ -359,9 +359,9 @@ public static TKey Insert(this IDbConnection connection, TEntity if (typeof(TEntity).IsInterface) //FallBack to BaseType Generic Method : https://stackoverflow.com/questions/4101784/calling-a-generic-method-with-a-dynamic-type { return (TKey)typeof(SimpleCRUD) - .GetMethods().Where(methodInfo=>methodInfo.Name == nameof(Insert) && methodInfo.GetGenericArguments().Count()==2).Single() + .GetMethods().Where(methodInfo => methodInfo.Name == nameof(Insert) && methodInfo.GetGenericArguments().Count() == 2).Single() .MakeGenericMethod(new Type[] { typeof(TKey), entityToInsert.GetType() }) - .Invoke(null, new object[] { connection,entityToInsert,transaction,commandTimeout }); + .Invoke(null, new object[] { connection, entityToInsert, transaction, commandTimeout }); } var idProps = GetIdProperties(entityToInsert).ToList(); @@ -405,7 +405,15 @@ public static TKey Insert(this IDbConnection connection, TEntity if ((keytype == typeof(int) || keytype == typeof(long)) && Convert.ToInt64(idProps.First().GetValue(entityToInsert, null)) == 0) { - sb.Append(";" + _getIdentitySql); + switch (_dialect) + { + case (Dialect.PostgreSQL): + sb.Append(" " + string.Format(_getIdentitySql, GetColumnName(idProps.First()))); + break; + default: + sb.Append(";" + _getIdentitySql); + break; + } } else { @@ -1264,6 +1272,6 @@ public static bool IsSimpleType(this Type type) public static string CacheKey(this IEnumerable props) { - return string.Join(",",props.Select(p=> p.DeclaringType.FullName + "." + p.Name).ToArray()); + return string.Join(",", props.Select(p => p.DeclaringType.FullName + "." + p.Name).ToArray()); } }