Ejemplo n.º 1
0
        public static IEnumerable<PosName> ConvertFromNewConvention(this IEnumerable<PosName> posNames, PocoData pocoData)
        {
            var allMembers = pocoData.GetAllMembers();
            var scopedPocoMembers = pocoData.Members;
            string prefix = null;

            foreach (var posName in posNames)
            {
                if (posName.Name.StartsWith(SplitPrefix, StringComparison.OrdinalIgnoreCase))
                {
                    prefix = posName.Name.Substring(SplitPrefix.Length);
                    var relevantMembers = allMembers.SingleOrDefault(x => string.Equals(PocoColumn.GenerateKey(x.MemberInfoChain), prefix, StringComparison.OrdinalIgnoreCase));
                    if (relevantMembers != null)
                    {
                        scopedPocoMembers = relevantMembers.PocoMemberChildren;
                    }

                    continue;
                }

                var member = FindMember(scopedPocoMembers, posName.Name);
                if (member != null && member.PocoColumn != null)
                {
                    posName.Name = member.PocoColumn.MemberInfoKey;
                }
                else
                {
                    posName.Name = PocoDataBuilder.JoinStrings(prefix, posName.Name);
                }

                yield return posName;
            }
        }
Ejemplo n.º 2
0
        public override void Init(DbDataReader dataReader, PocoData pocoData)
        {
            var fields = GetColumnNames(dataReader, pocoData);

            _groupedNames = fields
                .GroupByMany(x => x.Name, PocoData.Separator)
                .ToList();

            _mapPlan = BuildMapPlan(dataReader, pocoData);
        }
Ejemplo n.º 3
0
 private static List<PocoMember> CreateDynamicDictionaryPocoMembers(IEnumerable<GroupResult<PosName>> subItems, PocoData pocoData)
 {
     return subItems.Select(x => new DynamicPocoMember(pocoData.Mapper)
     {
         MemberInfoData = new MemberInfoData(x.Item, typeof(object), typeof(IDictionary<string, object>)),
         PocoColumn = new ExpandoColumn
         {
             ColumnName = x.Item
         }
     }).Cast<PocoMember>().ToList();
 }
Ejemplo n.º 4
0
 private MapPlan BuildMapPlan(DbDataReader dataReader, PocoData pocoData)
 {
     var plans = _groupedNames.SelectMany(x => BuildMapPlans(x, dataReader, pocoData, pocoData.Members)).ToArray();
     return (reader, instance) =>
     {
         foreach (MapPlan plan in plans)
         {
             plan(reader, instance);
         }
         return true;
     };
 }
Ejemplo n.º 5
0
        protected PosName[] GetColumnNames(DbDataReader dataReader, PocoData pocoData)
        {
            if (_columnNames != null)
                return _columnNames;

            var cols = Enumerable.Range(0, dataReader.FieldCount)
                .Select(x => new PosName { Pos = x, Name = dataReader.GetName(x) })
                .Where(x => !string.Equals("poco_rn", x.Name))
                .ToList();

            if (cols.Any(x => x.Name.StartsWith(PropertyMapperNameConvention.SplitPrefix, StringComparison.OrdinalIgnoreCase)))
            {
                return (_columnNames = cols.ConvertFromNewConvention(pocoData).ToArray());
            }

            return (_columnNames = cols.ConvertFromOldConvention(pocoData.Members).ToArray());
        }
Ejemplo n.º 6
0
 protected BaseExecuteTests(DBTestProvider provider)
     : base(provider)
 {
     _pd = PocoData.ForType(typeof(Note), DB.DefaultMapper);
 }
Ejemplo n.º 7
0
 public override void Init(DbDataReader dataReader, PocoData pocoData)
 {
     _converter = GetConverter(pocoData, null, dataReader.GetFieldType(0), pocoData.Type) ?? (x => x);
     base.Init(dataReader, pocoData);
 }
Ejemplo n.º 8
0
 public override void Init(DbDataReader dataReader, PocoData pocoData)
 {
     _posNames = GetColumnNames(dataReader, pocoData);
 }
Ejemplo n.º 9
0
        private async Task <int> ExecuteUpdateAsync(string tableName, string primaryKeyName, object poco, object primaryKeyValue, IEnumerable <string> columns)
        {
            try {
                await OpenSharedConnectionAsync();

                try {
                    using (var cmd = CreateCommand(_sharedConnection, "", new object[0])) {
                        var type = poco.GetType();
                        var pd   = PocoData.ForObject(poco, primaryKeyName);
                        var sql  = update.Get(Tuple.Create(type, _sqlHelper._sqlType), () => {
                            var sb    = new StringBuilder();
                            var index = 0;
                            foreach (var i in pd.Columns)
                            {
                                if (String.Compare(i.Value.ColumnName, primaryKeyName, StringComparison.OrdinalIgnoreCase) == 0)
                                {
                                    continue;
                                }
                                if (i.Value.ResultColumn)
                                {
                                    continue;
                                }

                                // Build the sql
                                if (index > 0)
                                {
                                    sb.Append(", ");
                                }
                                sb.AppendFormat("{0} = {1}{2}", _provider.EscapeSqlIdentifier(i.Value.ColumnName), _paramPrefix, index++);
                            }

                            return(string.Format("UPDATE {0} SET {1} WHERE {2} = {3}{4}",
                                                 _provider.EscapeTableName(tableName), sb.ToString(), _provider.EscapeSqlIdentifier(primaryKeyName), _paramPrefix, index++));
                        });

                        cmd.CommandText = sql;

                        foreach (var i in pd.Columns)
                        {
                            if (i.Value.ResultColumn)
                            {
                                continue;
                            }
                            if (string.Compare(i.Value.ColumnName, primaryKeyName, true) == 0)
                            {
                                if (primaryKeyValue == null)
                                {
                                    primaryKeyValue = i.Value.GetValue(poco);
                                }
                                continue;
                            }
                            AddParam(cmd, i.Value.GetValue(poco), i.Value.PropertyInfo);
                        }

                        // Find the property info for the primary key
                        PropertyInfo pkpi = null;
                        if (primaryKeyName != null)
                        {
                            PocoColumn col = pd.Columns.FirstOrDefault(q => q.Value.ColumnName == primaryKeyName).Value;
                            if (col != null)
                            {
                                pkpi = col.PropertyInfo;
                            }
                            else
                            {
                                pkpi = new { Id = primaryKeyValue }
                            }.GetType().GetProperties()[0];
                        }
                        AddParam(cmd, primaryKeyValue, pkpi);

                        DoPreExecute(cmd);

                        // Do it
                        var retv = await((SqlCommand)cmd).ExecuteNonQueryAsync();
                        OnExecutedCommand(cmd);
                        return(retv);
                    }
Ejemplo n.º 10
0
        public void GetFactory_GivenTypeWithNotPublicConstructor_ShouldThrow()
        {
            var pd = PocoData.ForObject(TestEntity.Instance, "Id", new ConventionMapper());

            Should.Throw <InvalidOperationException>(() => pd.GetFactory("", "", 1, 1, null, null));
        }
Ejemplo n.º 11
0
 public static Func<object, object> GetConverter(PocoData pocoData, PocoColumn pocoColumn, Type sourceType, Type desType)
 {
     var converter = MappingHelper.GetConverter(pocoData.Mapper, pocoColumn, sourceType, desType);
     return converter;
 }
Ejemplo n.º 12
0
 /// <summary>
 /// Determines whether a column should be part of a bulk-insert.
 /// </summary>
 /// <param name="pocoData">The PocoData object corresponding to the record's type.</param>
 /// <param name="column">The column.</param>
 /// <returns>A value indicating whether the column should be part of the bulk-insert.</returns>
 /// <remarks>Columns that are primary keys and auto-incremental, or result columns, are excluded from bulk-inserts.</remarks>
 private static bool IncludeColumn(PocoData pocoData, KeyValuePair <string, PocoColumn> column)
 {
     return(column.Value.ResultColumn == false &&
            (pocoData.TableInfo.AutoIncrement == false || column.Key != pocoData.TableInfo.PrimaryKey));
 }
Ejemplo n.º 13
0
 public abstract bool ShouldMap(PocoData pocoData);
Ejemplo n.º 14
0
 public virtual void Init(DbDataReader dataReader, PocoData pocoData)
 {
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Prepends the CQL statement specified with "UPDATE tablename " for a POCO of Type T.
        /// </summary>
        public void PrependUpdate <T>(Cql cql)
        {
            PocoData pocoData = _pocoDataFactory.GetPocoData <T>();

            cql.SetStatement(string.Format("UPDATE {0} {1}", pocoData.TableName, cql.Statement));
        }
Ejemplo n.º 16
0
 internal CqlUpdate(Expression expression, ITable table, StatementFactory stmtFactory, PocoData pocoData)
     : base(expression, table, stmtFactory, pocoData)
 {
 }
Ejemplo n.º 17
0
 /// <summary>
 /// 清空缓存
 /// </summary>
 public void FlushFunctionCaches()
 {
     PocoData.FlushCaches();
 }
Ejemplo n.º 18
0
 internal CqlUpdate(Expression expression, ITable table, StatementFactory stmtFactory, PocoData pocoData, MapperFactory mapperFactory)
     : base(expression, table, stmtFactory, pocoData)
 {
     _mapperFactory = mapperFactory;
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Bulk-insert records using SqlServer BulkCopy method.
        /// </summary>
        /// <typeparam name="T">The type of the records.</typeparam>
        /// <param name="database">The database.</param>
        /// <param name="pocoData">The PocoData object corresponding to the record's type.</param>
        /// <param name="records">The records.</param>
        /// <returns>The number of records that were inserted.</returns>
        internal static int BulkInsertRecordsSqlServer <T>(IUmbracoDatabase database, PocoData pocoData, IEnumerable <T> records)
        {
            // create command against the original database.Connection
            using (var command = database.CreateCommand(database.Connection, CommandType.Text, string.Empty))
            {
                // use typed connection and transactionf or SqlBulkCopy
                var tConnection  = GetTypedConnection <SqlConnection>(database.Connection);
                var tTransaction = GetTypedTransaction <SqlTransaction>(command.Transaction);
                var tableName    = pocoData.TableInfo.TableName;

                var syntax = database.SqlContext.SqlSyntax as SqlServerSyntaxProvider;
                if (syntax == null)
                {
                    throw new NotSupportedException("SqlSyntax must be SqlServerSyntaxProvider.");
                }

                using (var copy = new SqlBulkCopy(tConnection, SqlBulkCopyOptions.Default, tTransaction)
                {
                    BulkCopyTimeout = 10000, DestinationTableName = tableName
                })
                    using (var bulkReader = new PocoDataDataReader <T, SqlServerSyntaxProvider>(records, pocoData, syntax))
                    {
                        copy.WriteToServer(bulkReader);
                        return(bulkReader.RecordsAffected);
                    }
            }
        }
Ejemplo n.º 20
0
 public override bool ShouldMap(PocoData pocoData)
 {
     return true;
 }
Ejemplo n.º 21
0
        public static Func <object, object> GetConverter(PocoData pocoData, PocoColumn pocoColumn, Type sourceType, Type desType)
        {
            var converter = MappingHelper.GetConverter(pocoData.Mapper, pocoColumn, sourceType, desType);

            return(converter);
        }
Ejemplo n.º 22
0
 public override SqlExpression <T> ExpressionVisitor <T>(IDatabase db, PocoData pocoData, bool prefixTableName)
 {
     return(new SQLiteExpression <T>(db, pocoData, prefixTableName));
 }
Ejemplo n.º 23
0
 internal CqlScalar(Expression expression, ITable table, StatementFactory stmtFactory, PocoData pocoData)
     : base(expression, table, null, stmtFactory, pocoData)
 {
 }
Ejemplo n.º 24
0
 public abstract bool ShouldMap(PocoData pocoData);
Ejemplo n.º 25
0
        /// <summary>
        /// Prepends the CQL statement specified with "DELETE FROM tablename " for a POCO of Type T.
        /// </summary>
        public void PrependDelete <T>(Cql cql)
        {
            PocoData pocoData = _pocoDataFactory.GetPocoData <T>();

            cql.SetStatement(string.Format("DELETE FROM {0} {1}", pocoData.TableName, cql.Statement));
        }
Ejemplo n.º 26
0
        private async Task <object> ExecuteInsertAsync(string tableName, string primaryKeyName, bool autoIncrement, object poco)
        {
            try {
                await OpenSharedConnectionAsync();

                try {
                    using (var cmd = CreateCommand(_sharedConnection, "", new object[0])) {
                        var pd   = PocoData.ForObject(poco, primaryKeyName);
                        var type = poco.GetType();
                        var sql  = insert.Get(Tuple.Create(type, _sqlHelper._sqlType, 1), () => {
                            return(CteateInsertSql(pd, 1, tableName, primaryKeyName, autoIncrement));
                        });

                        foreach (var i in pd.Columns)
                        {
                            if (i.Value.ResultColumn)
                            {
                                continue;
                            }
                            if (autoIncrement && primaryKeyName != null && string.Compare(i.Value.ColumnName, primaryKeyName, true) == 0)
                            {
                                continue;
                            }
                            AddParam(cmd, i.Value.GetValue(poco), i.Value.PropertyInfo);
                        }
                        cmd.CommandText = sql;

                        if (!autoIncrement)
                        {
                            DoPreExecute(cmd);
                            await((SqlCommand)cmd).ExecuteNonQueryAsync();
                            OnExecutedCommand(cmd);

                            PocoColumn pkColumn;
                            if (primaryKeyName != null && pd.Columns.TryGetValue(primaryKeyName, out pkColumn))
                            {
                                return(pkColumn.GetValue(poco));
                            }
                            else
                            {
                                return(null);
                            }
                        }

                        object id = await _provider.ExecuteInsertAsync(this, (SqlCommand)cmd, primaryKeyName);

                        // Assign the ID back to the primary key property
                        if (primaryKeyName != null && !poco.GetType().Name.Contains("AnonymousType"))
                        {
                            PocoColumn pc;
                            if (pd.Columns.TryGetValue(primaryKeyName, out pc))
                            {
                                pc.SetValue(poco, pc.ChangeType(id));
                            }
                        }

                        return(id);
                    }
                } finally {
                    CloseSharedConnection();
                }
            } catch (Exception x) {
                if (OnException(x))
                {
                    throw new SqlExecuteException(x, _sqlHelper._sql.LastCommand);
                }
                return(null);
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Gets the CQL queries involved in a table creation (CREATE TABLE, CREATE INDEX)
        /// </summary>
        public static List <string> GetCreate(Serializer serializer, PocoData pocoData, string tableName, string keyspaceName, bool ifNotExists)
        {
            if (pocoData == null)
            {
                throw new ArgumentNullException("pocoData");
            }
            if (pocoData.MissingPrimaryKeyColumns.Count > 0)
            {
                throw new InvalidOperationException(string.Format(MissingPkColumns, "CREATE", pocoData.PocoType.Name,
                                                                  pocoData.MissingPrimaryKeyColumns.ToCommaDelimitedString()));
            }
            var commands         = new List <string>();
            var secondaryIndexes = new List <string>();
            var createTable      = new StringBuilder("CREATE TABLE ");

            tableName = Escape(tableName, pocoData);
            if (keyspaceName != null)
            {
                //Use keyspace.tablename notation
                tableName = Escape(keyspaceName, pocoData) + "." + tableName;
            }
            createTable.Append(tableName);
            createTable.Append(" (");
            foreach (var column in pocoData.Columns)
            {
                var columnName = Escape(column.ColumnName, pocoData);
                createTable
                .Append(columnName)
                .Append(" ");
                var columnType = GetTypeString(serializer, column);
                createTable
                .Append(columnType);
                createTable
                .Append(", ");
                if (column.SecondaryIndex)
                {
                    secondaryIndexes.Add(columnName);
                }
            }
            createTable.Append("PRIMARY KEY (");
            if (pocoData.PartitionKeys.Count == 0)
            {
                throw new InvalidOperationException("No partition key defined");
            }
            if (pocoData.PartitionKeys.Count == 1)
            {
                createTable.Append(Escape(pocoData.PartitionKeys[0].ColumnName, pocoData));
            }
            else
            {
                //tupled partition keys
                createTable
                .Append("(")
                .Append(String.Join(", ", pocoData.PartitionKeys.Select(Escape(pocoData))))
                .Append(")");
            }
            if (pocoData.ClusteringKeys.Count > 0)
            {
                createTable.Append(", ");
                createTable.Append(String.Join(", ", pocoData.ClusteringKeys.Select(k => Escape(k.Item1.ColumnName, pocoData))));
            }
            //close primary keys
            createTable.Append(")");
            //close table column definition
            createTable.Append(")");
            var clusteringOrder = String.Join(", ", pocoData.ClusteringKeys
                                              .Where(k => k.Item2 != SortOrder.Unspecified)
                                              .Select(k => Escape(k.Item1.ColumnName, pocoData) + " " + (k.Item2 == SortOrder.Ascending ? "ASC" : "DESC")));

            if (!String.IsNullOrEmpty(clusteringOrder))
            {
                createTable
                .Append(" WITH CLUSTERING ORDER BY (")
                .Append(clusteringOrder)
                .Append(")");
            }
            if (pocoData.CompactStorage)
            {
                createTable.Append(" WITH COMPACT STORAGE");
            }
            commands.Add(createTable.ToString());
            //Secondary index definitions
            commands.AddRange(secondaryIndexes.Select(name => "CREATE INDEX ON " + tableName + " (" + name + ")"));
            return(commands);
        }
Ejemplo n.º 28
0
        private static Delegate CreateDefaultFunction <T>()
        {
            #region 初始时间
            var pd = PocoData.ForType(typeof(T));
            List <PropertyInfo> datetimes       = new List <PropertyInfo>();
            List <PropertyInfo> datetimeoffsets = new List <PropertyInfo>();
            List <PropertyInfo> strings         = new List <PropertyInfo>();
            List <PropertyInfo> ansiStrings     = new List <PropertyInfo>();
            List <PropertyInfo> guids           = new List <PropertyInfo>();
            foreach (var item in pd.Columns)
            {
                if (item.Value.ResultColumn)
                {
                    continue;
                }
                var pi = item.Value.PropertyInfo;
                if (pi.PropertyType == typeof(DateTime))
                {
                    datetimes.Add(pi);
                }
                else if (pi.PropertyType == typeof(DateTimeOffset))
                {
                    datetimeoffsets.Add(pi);
                }
                else if (pi.PropertyType == typeof(string))
                {
                    strings.Add(pi);
                }
                else if (pi.PropertyType == typeof(Guid))
                {
                    guids.Add(pi);
                }
                else if (pi.PropertyType == typeof(AnsiString))
                {
                    ansiStrings.Add(pi);
                }
            }
            #endregion

            #region dateTimeType dateTimeOffsetType AnsiString
            var dateTimeType = typeof(DateTime);
            //var getYear = dateTimeType.GetProperty("Year");
            var getNow         = dateTimeType.GetProperty("Now", BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic);
            var getMinValue    = dateTimeType.GetField("MinValue", BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic);
            var getop_Equality = dateTimeType.GetMethod("op_Equality", BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic);



            var dateTimeOffsetType = typeof(DateTimeOffset);
            var getNow2            = dateTimeOffsetType.GetProperty("Now", BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic);
            var getMinValue2       = dateTimeOffsetType.GetField("MinValue", BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic);
            var getop_Equality2    = dateTimeOffsetType.GetMethod("op_Equality", BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic);


            var guidType        = typeof(Guid);
            var getEmpty        = guidType.GetField("Empty", BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic);
            var getNewGuid      = guidType.GetMethod("NewGuid", BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic);
            var getop_Equality3 = guidType.GetMethod("op_Equality", BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic);


            var asctor = typeof(AnsiString).GetConstructor(new Type[] { typeof(string) });

            #endregion

            var m  = new DynamicMethod("toolgood_default_" + Guid.NewGuid().ToString().Replace("-", ""), typeof(void), new Type[] { typeof(T), typeof(bool), typeof(bool), typeof(bool) }, true);
            var il = m.GetILGenerator();

            #region string
            if (strings.Count > 0)
            {
                il.Emit(OpCodes.Ldarg_1);
                var lab1 = il.DefineLabel();
                if (strings.Count < 7)
                {
                    il.Emit(OpCodes.Brfalse_S, lab1);
                }
                else
                {
                    il.Emit(OpCodes.Brfalse, lab1);
                }
                for (int i = 0; i < strings.Count; i++)
                {
                    var item = strings[i];

                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Callvirt, item.GetGetMethod());
                    var lab = il.DefineLabel();
                    il.Emit(OpCodes.Brtrue_S, lab);


                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Ldstr, "");
                    il.Emit(OpCodes.Callvirt, item.GetSetMethod());
                    il.MarkLabel(lab);
                }
                il.MarkLabel(lab1);
            }
            #endregion

            #region AnsiString
            if (ansiStrings.Count > 0)
            {
                il.Emit(OpCodes.Ldarg_1);
                var lab1 = il.DefineLabel();
                if (ansiStrings.Count < 7)
                {
                    il.Emit(OpCodes.Brfalse_S, lab1);
                }
                else
                {
                    il.Emit(OpCodes.Brfalse, lab1);
                }

                for (int i = 0; i < ansiStrings.Count; i++)
                {
                    var item = ansiStrings[i];
                    var lab  = il.DefineLabel();

                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Callvirt, item.GetGetMethod());
                    il.Emit(OpCodes.Brtrue_S, lab);


                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Ldstr, "");
                    il.Emit(OpCodes.Newobj, asctor);
                    il.Emit(OpCodes.Callvirt, item.GetSetMethod());
                    il.MarkLabel(lab);
                }
                il.MarkLabel(lab1);
            }


            #endregion

            #region date
            if (datetimes.Count + datetimeoffsets.Count > 0)
            {
                il.Emit(OpCodes.Ldarg_2);
                var lab2 = il.DefineLabel();
                if (datetimes.Count + datetimeoffsets.Count < 5)
                {
                    il.Emit(OpCodes.Brfalse_S, lab2);
                }
                else
                {
                    il.Emit(OpCodes.Brfalse, lab2);
                }

                #region datetimes
                foreach (var item in datetimes)
                {
                    var lab = il.DefineLabel();
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Callvirt, item.GetGetMethod());
                    il.Emit(OpCodes.Ldsfld, getMinValue);
                    il.Emit(OpCodes.Call, getop_Equality);
                    il.Emit(OpCodes.Brfalse_S, lab);

                    il.Emit(OpCodes.Ldarg_0);
                    //il.Emit(OpCodes.Ldsfld, getMinValue);
                    il.Emit(OpCodes.Call, getNow.GetGetMethod());
                    il.Emit(OpCodes.Callvirt, item.GetSetMethod());
                    il.MarkLabel(lab);
                }
                #endregion

                #region datetimeoffsets
                foreach (var item in datetimeoffsets)
                {
                    var lab = il.DefineLabel();
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Callvirt, item.GetGetMethod());
                    il.Emit(OpCodes.Ldsfld, getMinValue2);
                    il.Emit(OpCodes.Call, getop_Equality2);
                    il.Emit(OpCodes.Brfalse_S, lab);

                    il.Emit(OpCodes.Ldarg_0);
                    //il.Emit(OpCodes.Ldsfld, getMinValue);
                    il.Emit(OpCodes.Call, getNow2.GetGetMethod());
                    il.Emit(OpCodes.Callvirt, item.GetSetMethod());
                    il.MarkLabel(lab);
                }
                #endregion
                il.MarkLabel(lab2);
            }

            #endregion

            #region guid
            if (guids.Count > 0)
            {
                il.Emit(OpCodes.Ldarg_3);
                var lab3 = il.DefineLabel();
                if (guids.Count < 5)
                {
                    il.Emit(OpCodes.Brfalse_S, lab3);
                }
                else
                {
                    il.Emit(OpCodes.Brfalse, lab3);
                }

                foreach (var item in guids)
                {
                    var lab = il.DefineLabel();

                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Callvirt, item.GetGetMethod());
                    il.Emit(OpCodes.Ldsfld, getEmpty);
                    il.Emit(OpCodes.Call, getop_Equality3);
                    il.Emit(OpCodes.Brfalse_S, lab);

                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Call, getNewGuid);
                    il.Emit(OpCodes.Callvirt, item.GetSetMethod());
                    il.MarkLabel(lab);
                }
                il.MarkLabel(lab3);
            }
            #endregion

            il.Emit(OpCodes.Ret);
            return(m.CreateDelegate(Expression.GetActionType(typeof(T), typeof(bool), typeof(bool), typeof(bool))));
        }
Ejemplo n.º 29
0
        private static Func <PocoColumn, string> Escape(PocoData pocoData)
        {
            Func <PocoColumn, string> f = c => Escape(c.ColumnName, pocoData);

            return(f);
        }
Ejemplo n.º 30
0
        public void PD_IncludedResultColumn_InAutoSelect()
        {
            var pd = PocoData.ForType(typeof(PocoWithIncludedResultColumn), new ConventionMapper());

            pd.QueryColumns.ShouldBe(new[] { "RegularProperty", "ResultProperty" });
        }
Ejemplo n.º 31
0
        private static Func <PocoColumn, string> Escape(PocoData pocoData, string format)
        {
            Func <PocoColumn, string> f = c => String.Format(format, Escape(c.ColumnName, pocoData));

            return(f);
        }
Ejemplo n.º 32
0
 public override bool ShouldMap(PocoData pocoData)
 {
     return pocoData.Type.GetTypeInfo().IsValueType || pocoData.Type == typeof (string) || pocoData.Type == typeof (byte[]);
 }
Ejemplo n.º 33
0
 /// <summary>
 /// 获取表名称
 /// </summary>
 /// <param name="db">数据库实例</param>
 /// <param name="type">实体类型</param>
 /// <returns>转码后的表名</returns>
 public static string GetTableName(this IDatabase db, Type type)
 {
     return(GetTableName(db, PocoData.ForType(type, db.DefaultMapper).TableInfo.TableName));
 }
Ejemplo n.º 34
0
 public override bool ShouldMap(PocoData pocoData)
 {
     return pocoData.Type.IsArray;
 }
Ejemplo n.º 35
0
 public override bool ShouldMap(PocoData pocoData)
 {
     return(true);
 }
Ejemplo n.º 36
0
        /// <summary>
        /// 添加带自增 ID 的实体
        /// </summary>
        /// <typeparam name="T">返回的自增 ID 类型</typeparam>
        /// <param name="db">数据库实例</param>
        /// <param name="entity">要添加的实体</param>
        /// <returns>自增 ID 的值</returns>
        public static T Add <T>(this Database db, object entity)
        {
            var pd = PocoData.ForType(entity.GetType());

            return((T)Convert.ChangeType(db.Insert(pd.TableInfo.TableName, pd.TableInfo.PrimaryKey, true, entity), typeof(T)));
        }
Ejemplo n.º 37
0
 internal void InternalInitialize(Expression expression, ITable table, MapperFactory mapperFactory, StatementFactory stmtFactory, PocoData pocoData)
 {
     Expression       = expression;
     Table            = table;
     MapperFactory    = mapperFactory;
     StatementFactory = stmtFactory;
     PocoData         = pocoData;
 }
Ejemplo n.º 38
0
        /// <summary>
        /// 添加
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="db">数据库实例</param>
        /// <param name="entity">要添加的实体</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        public static bool Add <T>(this Database db, T entity) where T : new()
        {
            var pd = PocoData.ForType(entity.GetType());

            return(db.Insert(pd.TableInfo.TableName, pd.TableInfo.PrimaryKey, false, entity).ToBool_());
        }
Ejemplo n.º 39
0
        private IEnumerable <MapPlan> BuildMapPlans(GroupResult <PosName> groupedName, DbDataReader dataReader, PocoData pocoData, List <PocoMember> pocoMembers)
        {
            // find pocomember by property name
            var pocoMember = pocoMembers.FirstOrDefault(x => IsEqual(groupedName.Item, x.Name, x.PocoColumn?.ExactColumnNameMatch ?? false) ||
                                                        string.Equals(groupedName.Item, x.PocoColumn?.ColumnAlias, StringComparison.OrdinalIgnoreCase));

            if (pocoMember == null)
            {
                yield break;
            }

            if (groupedName.SubItems.Any())
            {
                var memberInfoType = pocoMember.MemberInfoData.MemberType;
                if (memberInfoType.IsAClass() || pocoMember.IsDynamic)
                {
                    var children = PocoDataBuilder.IsDictionaryType(memberInfoType)
                        ? CreateDynamicDictionaryPocoMembers(groupedName.SubItems, pocoData, memberInfoType)
                        : pocoMember.PocoMemberChildren;

                    var subPlans = groupedName.SubItems.SelectMany(x => BuildMapPlans(x, dataReader, pocoData, children)).ToArray();

                    yield return((reader, values, instance) =>
                    {
                        var newObject = pocoMember.IsList ? pocoMember.Create(dataReader) : (pocoMember.GetValue(instance) ?? pocoMember.Create(dataReader));

                        var shouldSetNestedObject = false;
                        foreach (var subPlan in subPlans)
                        {
                            shouldSetNestedObject |= subPlan(reader, values, newObject);
                        }

                        if (shouldSetNestedObject)
                        {
                            if (pocoMember.IsList)
                            {
                                var list = pocoMember.CreateList();
                                list.Add(newObject);
                                newObject = list;
                            }

                            pocoMember.SetValue(instance, newObject);
                            return true;
                        }
                        return false;
                    });
                }
            }
            else
            {
                var destType     = pocoMember.MemberInfoData.MemberType;
                var defaultValue = MappingHelper.GetDefault(destType);
                var converter    = GetConverter(pocoData, pocoMember.PocoColumn, dataReader.GetFieldType(groupedName.Key.Pos), destType);
                yield return((reader, values, instance) => MapValue(groupedName, values, converter, instance, pocoMember.PocoColumn, defaultValue));
            }
        }
Ejemplo n.º 40
0
        private IEnumerable<MapPlan> BuildMapPlans(GroupResult<PosName> groupedName, DbDataReader dataReader, PocoData pocoData, List<PocoMember> pocoMembers)
        {
            // find pocomember by property name
            var pocoMember = pocoMembers.FirstOrDefault(x => IsEqual(groupedName.Item, x.Name));

            if (pocoMember == null)
            {
                yield break;
            }

            if (groupedName.SubItems.Any())
            {
                var memberInfoType = pocoMember.MemberInfoData.MemberType;
                if (memberInfoType.IsAClass() || pocoMember.IsDynamic)
                {
                    var children = PocoDataBuilder.IsDictionaryType(memberInfoType)
                        ? CreateDynamicDictionaryPocoMembers(groupedName.SubItems, pocoData)
                        : pocoMember.PocoMemberChildren;

                    var subPlans = groupedName.SubItems.SelectMany(x => BuildMapPlans(x, dataReader, pocoData, children)).ToArray();

                    yield return (reader, instance) =>
                    {
                        var newObject = pocoMember.IsList ? pocoMember.Create(dataReader) : (pocoMember.GetValue(instance) ?? pocoMember.Create(dataReader));

                        var shouldSetNestedObject = false;
                        foreach (var subPlan in subPlans)
                        {
                            shouldSetNestedObject |= subPlan(reader, newObject);
                        }

                        if (shouldSetNestedObject)
                        {
                            if (pocoMember.IsList)
                            {
                                var list = pocoMember.CreateList();
                                list.Add(newObject);
                                newObject = list;
                            }

                            pocoMember.SetValue(instance, newObject);
                            return true;
                        }
                        return false;
                    };
                }
            }
            else
            {
                var destType = pocoMember.MemberInfoData.MemberType;
                var defaultValue = MappingHelper.GetDefault(destType);
                var converter = GetConverter(pocoData, pocoMember.PocoColumn, dataReader.GetFieldType(groupedName.Key.Pos), destType);
                yield return (reader, instance) => MapValue(groupedName, reader, converter, instance, pocoMember.PocoColumn, defaultValue);
            }
        }
Ejemplo n.º 41
0
 public OracleExpression(IDatabase database, PocoData pocoData, bool prefixTableName) : base(database, pocoData, prefixTableName)
 {
 }
Ejemplo n.º 42
0
 public virtual void Init(DbDataReader dataReader, PocoData pocoData)
 {
 }
Ejemplo n.º 43
0
 internal CqlQuery(Expression expression, ITable table, MapperFactory mapperFactory, StatementFactory stmtFactory, PocoData pocoData)
     : base(expression, table, mapperFactory, stmtFactory, pocoData)
 {
 }
Ejemplo n.º 44
0
        private static List <PocoMember> CreateDynamicDictionaryPocoMembers(IEnumerable <GroupResult <PosName> > subItems, PocoData pocoData, Type type)
        {
            var isDict   = type != typeof(object);
            var dataType = isDict ? type.GetGenericArguments().Last() : type;

            return(subItems.Select(x =>
            {
                var member = new DynamicPocoMember
                {
                    MemberInfoData = new MemberInfoData(x.Item, dataType, type),
                    PocoColumn = new ExpandoColumn
                    {
                        ColumnName = x.Item
                    }
                };

                if (isDict)
                {
                    var pocoDataBuilder = new PocoDataBuilder(dataType, pocoData.Mapper);
                    member.PocoMemberChildren = pocoDataBuilder.GetPocoMembers(pocoDataBuilder.GetColumnInfos(dataType), new List <MemberInfo>()).Select(plan => plan(pocoData.TableInfo)).ToList();
                    member.SetDynamicMemberAccessor(new FastCreate(dataType, pocoData.Mapper));
                }

                return (PocoMember)member;
            }).ToList());
        }
Ejemplo n.º 45
0
 /// <summary>
 /// 获取表名称
 /// </summary>
 /// <param name="db">数据库实例</param>
 /// <param name="type">实体类型</param>
 /// <returns>转码后的表名</returns>
 public static string GetTableName(this Database db, Type type)
 {
     return(GetTableName(db, PocoData.ForType(type).TableInfo.TableName));
 }