public JsonNetResult GetProgressExecution(PrimaryKey id)
        {
            decimal progress = Database.Query<ProcessEntity>().Where(pe =>
                    pe.Id == id && pe.State == ProcessState.Executing).Select(pe => pe.Progress).SingleOrDefaultEx() ?? 1;

            return this.JsonNet(progress);
        }
Example #2
0
 public override Entity Retrieve(Type type, PrimaryKey id)
 {
     return Return(MethodInfo.GetCurrentMethod(), type.Name,
         () =>
         {
             using (ViewLogLogic.LogView(Lite.Create(type, id), "WCFRetrieve"))
                 return Database.Retrieve(type, id);
         });
 }
 public void ShouldGenerateMappingForOracleTable()
 {
     const string generatedXML = "<?xml version=\"1.0\"?><hibernate-mapping assembly=\"myAssemblyName\" namespace=\"myNameSpace\" xmlns=\"urn:nhibernate-mapping-2.2\"><class name=\"Customer\" table=\"Customer\" lazy=\"true\" xmlns=\"\"><id name=\"Id\" column=\"Id\" /></class></hibernate-mapping>";
     var preferences = new ApplicationPreferences
                           {
                               FolderPath = "\\",
                               TableName = "Customer",
                               AssemblyName = "myAssemblyName",
                               NameSpace = "myNameSpace",
                               Sequence = "mySequenceNumber",
                           };
     var pkColumn = new Column {Name = "Id", IsPrimaryKey = true, DataType = "Int"};
     var primaryKey = new PrimaryKey {Columns = new List<Column> {pkColumn}};
     var generator = new OracleMappingGenerator(preferences, new Table {PrimaryKey = primaryKey, Columns = new List<Column> {pkColumn}});
     var document = generator.CreateMappingDocument();
     Assert.AreEqual(generatedXML, document.InnerXml);
 }
        public PrimaryKey DeterminePrimaryKeys(Table table)
        {
            IList<Column> primaryKeys = table.Columns.Where(x => x.IsPrimaryKey.Equals(true)).ToList();

            if (primaryKeys.Count() == 1)
            {
                var c = primaryKeys.First();
                var key = new PrimaryKey
                    {
                        Type = PrimaryKeyType.PrimaryKey,
                        Columns =
                            {
                                new Column
                                    {
                                        DataType = c.DataType,
                                        Name = c.Name
                                    }
                            }
                    };
                return key;
            }
            else
            {
                var key = new PrimaryKey
                    {
                        Type = PrimaryKeyType.CompositeKey
                    };
                foreach (var primaryKey in primaryKeys)
                {
                    key.Columns.Add(new Column
                        {
                            DataType = primaryKey.DataType,
                            Name = primaryKey.Name
                        });
                }
                return key;
            }
        }
 public async Task <int> Delete(PrimaryKey pk)
 {
     CMDText = DELETE_STMT;
     return(await base.Delete(pk));
 }
        public static void ConditionPutRow()
        {
            Console.WriteLine("Start put row...");

            PrepareTable();
            OTSClient otsClient = Config.GetClient();

            // 定义行的主键,必须与创建表时的TableMeta中定义的一致
            PrimaryKey primaryKey = new PrimaryKey();

            primaryKey.Add("pk0", new ColumnValue(0));
            primaryKey.Add("pk1", new ColumnValue("abc"));

            // 定义要写入改行的属性列
            AttributeColumns attribute = new AttributeColumns();

            attribute.Add("col0", new ColumnValue(0));
            attribute.Add("col1", new ColumnValue("a"));
            attribute.Add("col2", new ColumnValue(true));

            PutRowRequest request = new PutRowRequest(tableName, new Condition(RowExistenceExpectation.IGNORE), primaryKey, attribute);

            // 不带condition时put row,预期成功
            try
            {
                otsClient.PutRow(request);

                Console.WriteLine("Put row succeeded.");
            } catch (Exception ex)
            {
                Console.WriteLine("Put row failed. error:{0}", ex.Message);
            }

            // 当col0列的值不等于5的时候,允许再次put row,覆盖掉原值,预期成功
            try
            {
                request.Condition.ColumnCondition = new RelationalCondition("col0",
                                                                            CompareOperator.NOT_EQUAL,
                                                                            new ColumnValue(5));
                otsClient.PutRow(request);

                Console.WriteLine("Put row succeeded.");
            } catch (Exception ex)
            {
                Console.WriteLine("Put row failed. error:{0}", ex.Message);
            }

            // 当col0列的值等于5的时候,允许再次put row,覆盖掉原值,预期失败
            try
            {
                // 新增条件:col0列的值等于5
                request.Condition.ColumnCondition = new RelationalCondition("col0",
                                                                            CompareOperator.EQUAL,
                                                                            new ColumnValue(5));
                otsClient.PutRow(request);

                Console.WriteLine("Put row succeeded.");
            }
            catch (OTSServerException)
            {
                // 由于条件不满足,抛出OTSServerException
                Console.WriteLine("Put row failed  because condition check failed. but expected");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Put row failed. error:{0}", ex.Message);
            }
        }
Example #7
0
        public static Expression InPrimaryKey(Expression element, PrimaryKey[] values)
        {
            var cleanValues = values.Select(a => a.Object).ToArray();

            var cleanElement = SmartEqualizer.UnwrapPrimaryKey(element);

            if (cleanElement == NewId)
                return False;

            return InExpression.FromValues(DbExpressionNominator.FullNominate(cleanElement), cleanValues);
        }
Example #8
0
 internal override bool Contains(PrimaryKey primaryKey)
 {
     throw new InvalidOperationException("CacheMListTable does not implements contains");
 }
        public static void ConditionUpdateRow()
        {
            Console.WriteLine("Start update row...");

            PrepareTable();
            var otsClient = Config.GetClient();

            // 定义行的主键,必须与创建表时的TableMeta中定义的一致
            var primaryKey = new PrimaryKey();

            primaryKey.Add("pk0", new ColumnValue(1));
            primaryKey.Add("pk1", new ColumnValue("abc"));

            // 定义要写入改行的属性列
            var attribute = new AttributeColumns();

            attribute.Add("col0", new ColumnValue(1));
            attribute.Add("col1", new ColumnValue("a"));
            attribute.Add("col2", new ColumnValue(true));

            var request = new PutRowRequest(tableName, new Condition(RowExistenceExpectation.IGNORE), primaryKey, attribute);

            // 新创建一行数据
            try
            {
                otsClient.PutRow(request);

                Console.WriteLine("Put row succeeded.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Put row failed. error:{0}", ex.Message);
            }


            // 当col0不等于5,且col1等于'a'时,允许修改,否则不允许修改
            try
            {
                // 构造condition
                var cond1 = new RelationalCondition("col0",
                                                    CompareOperator.NOT_EQUAL,
                                                    new ColumnValue(5));
                var cond2 = new RelationalCondition("col1", CompareOperator.EQUAL,
                                                    new ColumnValue("a"));
                var columenCondition = new CompositeCondition(LogicOperator.AND);
                columenCondition.AddCondition(cond1);
                columenCondition.AddCondition(cond2);

                var condition = new Condition(RowExistenceExpectation.IGNORE);
                condition.ColumnCondition = columenCondition;

                // 构造更新请求
                var updateOfAttribute = new UpdateOfAttribute();
                updateOfAttribute.AddAttributeColumnToPut("col2", new ColumnValue(false));
                var updateRowRequest = new UpdateRowRequest(tableName, condition, primaryKey, updateOfAttribute);

                // 更新数据
                otsClient.UpdateRow(updateRowRequest);

                // 更新成功
                Console.WriteLine("Update row succeeded.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Update row failed. error:{0}", ex.Message);
            }
        }
Example #10
0
 internal abstract bool Contains(PrimaryKey primaryKey);
Example #11
0
 internal override bool Contains(PrimaryKey primaryKey)
 {
     return(this.GetRows().ContainsKey(primaryKey));
 }
Example #12
0
            private Column CreateColumn(MemberInfo mi, INamingStrategy namingStrategy)
            {
                if (ReflectHelper.HasAttribute<IgnoreAttribute>(mi))
                    return null;

                ColumnAttribute colAttr = ReflectHelper.GetAttribute<ColumnAttribute>(mi);
                Column column = new Column();

                column.ColumnName = (colAttr == null || String.IsNullOrEmpty(colAttr.Name)) ? namingStrategy.GetColumnName(mi.Name) : colAttr.Name;
                if (colAttr != null)
                {
                    if (colAttr.DbType != DbType.Empty)
                        column.DbType = colAttr.DbType;
                    column.Updatable = colAttr.Updatable;
                }

                if (ReflectHelper.HasAttribute<PrimaryKeyAttribute>(mi))
                {
                    if (PrimaryKey == null)
                        PrimaryKey = new PrimaryKey();
                    PrimaryKey.AddColumn(column);
                }

                return column;
            }
Example #13
0
        public void ContainsListId()
        {
            PrimaryKey[] ids = new PrimaryKey[] { 1, 2, 3 };

            var artist = Database.Query<ArtistEntity>().Where(a => ids.Contains(a.Id)).ToList();
        }
Example #14
0
 /// <summary>Initializes a new <see cref="RevocationCertForm"/> with the key for which the revocation certificate
 /// will be generated, and a list of keys for which the user has the secret key, which could possibly serve as
 /// designated revokers.
 /// </summary>
 public RevocationCertForm(PrimaryKey keyToRevoke, PrimaryKey[] ownedKeys) : this()
 {
   Initialize(keyToRevoke, ownedKeys);
 }
 public override Entity Retrieve(Type type, PrimaryKey id)
 {
     using (ViewLogLogic.LogView(Lite.Create(type, id), "WCFRetrieve"))
         return base.Retrieve(type, id);
 }
Example #16
0
 public static bool Throw(PrimaryKey a)
 {
     throw new ArgumentException("a");
 }
 public PrimaryKeyDisplay(PrimaryKey value)
 {
     Value        = value;
     DisplayValue = string.Format("{0} ({1})", value.TableName, value.ColumnName);
 }
Example #18
0
    public FileStreamResult DownloadFilePath(string filePathId)
    {
        var filePath = Database.Retrieve <FilePathEntity>(PrimaryKey.Parse(filePathId, typeof(FilePathEntity)));

        return(GetFileStreamResult(filePath.OpenRead(), filePath.FileName));
    }
		internal override string DropPrimaryKey(PrimaryKey key)
		{
			string ret = "";
            Connection conn = pool.GetConnection();
			conn.ExecuteQuery(DropPrimaryKeyString, new IDbDataParameter[]{conn.CreateParameter(CreateParameterName("TableName"),key.Name)});
			if (conn.Read())
				ret = conn[0].ToString();
            conn.CloseConnection();
			return ret;
		}
		internal override string DropPrimaryKey(PrimaryKey key)
		{
			string ret="";
            Connection conn = pool.GetConnection();
			foreach (string str in key.Fields)
			{
				conn.ExecuteQuery(String.Format(DropPrimaryKeyString, key.Name, str));
				if (conn.Read())
					ret += conn[0].ToString()+";\n";
				conn.Close();
			}
            conn.CloseConnection();
			return ret;
		}
Example #21
0
        async Task DoRandomAtomicCalls()
        {
            for (int callNum = 0; callNum < MigrationModel.NUM_CALLS_PER_MACHINE; callNum++)
            {
                SortedDictionary<PrimaryKey, DynamicTableEntity> dump = await peekProxy.DumpReferenceTableAsync();

                if (PSharpRuntime.Nondeterministic())
                {
                    // Query
                    var query = new TableQuery<DynamicTableEntity>();
                    query.FilterString = ChainTableUtils.CombineFilters(
                        TableQuery.GenerateFilterCondition(
                            TableConstants.PartitionKey, QueryComparisons.Equal, MigrationModel.SINGLE_PARTITION_KEY),
                        TableOperators.And,
                        NondeterministicUserPropertyFilterString());
                    await RunQueryAtomicAsync(query);
                }
                else
                {
                    // Batch write
                    int batchSize = PSharpRuntime.Nondeterministic() ? 2 : 1;
                    var batch = new TableBatchOperation();
                    var rowKeyChoices = new List<string> { "0", "1", "2", "3", "4", "5" };

                    for (int opNum = 0; opNum < batchSize; opNum++)
                    {
                        int opTypeNum = PSharpNondeterminism.Choice(7);
                        int rowKeyI = PSharpNondeterminism.Choice(rowKeyChoices.Count);
                        string rowKey = rowKeyChoices[rowKeyI];
                        rowKeyChoices.RemoveAt(rowKeyI);  // Avoid duplicate in same batch
                        var primaryKey = new PrimaryKey(MigrationModel.SINGLE_PARTITION_KEY, rowKey);
                        string eTag = null;
                        if (opTypeNum >= 1 && opTypeNum <= 3)
                        {
                            DynamicTableEntity existingEntity;
                            int etagTypeNum = PSharpNondeterminism.Choice(
                                dump.TryGetValue(primaryKey, out existingEntity) ? 3 : 2);
                            switch (etagTypeNum)
                            {
                                case 0: eTag = ChainTable2Constants.ETAG_ANY; break;
                                case 1: eTag = "wrong"; break;
                                case 2: eTag = existingEntity.ETag; break;
                            }
                        }
                        DynamicTableEntity entity = new DynamicTableEntity
                        {
                            PartitionKey = MigrationModel.SINGLE_PARTITION_KEY,
                            RowKey = rowKey,
                            ETag = eTag,
                            Properties = new Dictionary<string, EntityProperty> {
                                // Give us something to see on merge.  Might help with tracing too!
                                { string.Format("{0}_c{1}_o{2}", machineId.ToString(), callNum, opNum),
                                    new EntityProperty(true) },
                                // Property with 50%/50% distribution for use in filters.
                                { "isHappy", new EntityProperty(PSharpRuntime.Nondeterministic()) }
                            }
                        };
                        switch (opTypeNum)
                        {
                            case 0: batch.Insert(entity); break;
                            case 1: batch.Replace(entity); break;
                            case 2: batch.Merge(entity); break;
                            case 3: batch.Delete(entity); break;
                            case 4: batch.InsertOrReplace(entity); break;
                            case 5: batch.InsertOrMerge(entity); break;
                            case 6:
                                entity.ETag = ChainTable2Constants.ETAG_DELETE_IF_EXISTS;
                                batch.Delete(entity); break;
                        }
                    }

                    await RunBatchAsync(batch);
                }
            }
        }
Example #22
0
        public void TableStoreAddLocation(DataRowCollection drs)
        {
            if (drs.Count == 0)
            {
                return;
            }
            int           batchCount = 0;
            int           i          = 0;
            List <string> list       = new List <string>();//存储批量上传的主键字符串,用于判断批量上传数据中是否有重复

            try
            {
                RowChanges rowChanges = new RowChanges();
                foreach (DataRow dr in drs)
                {
                    var primaryKey = new PrimaryKey();
                    primaryKey.Add("d", new ColumnValue(Convert.ToInt64(dr["device_code"])));
                    primaryKey.Add("t", new ColumnValue(TimeHelper.ConvertDateTimeToInt(Convert.ToDateTime(dr["gps_time"]))));

                    string primarykey = dr["device_code"].ToString() + ";" + dr["gps_time"].ToString();
                    if (list.Contains(primarykey))
                    {
                        log.Info("发现重复记录" + primarykey + "数据库记录:");
                        continue;
                    }
                    list.Add(primarykey);

                    var attribute = new AttributeColumns();
                    //定位数据
                    attribute.Add("l", new ColumnValue(ByteIntHelper.GetLocationByte(dr["latitude"], dr["longitude"], Convert.ToInt32(dr["speed"]), Convert.ToInt32(dr["direct"]), 0)));

                    rowChanges.AddPut(new Condition(RowExistenceExpectation.IGNORE), primaryKey, attribute);
                    batchCount++;
                    i++;
                    if (batchCount == 200)//200行数据进行批量提交一次
                    {
                        batchRequest.Add(TableName, rowChanges);
                        BatchWriteRowResponse bwResponse = oTSClient.BatchWriteRow(batchRequest);


                        if (bwResponse.IsAllSucceed)
                        {
                            //所有数据插入成功
                            log.Info(i + "批量提交成功");
                        }
                        else
                        {
                            log.Error(i + "批量提交有出错记录");
                            //把批量提交的数据,赋值给新的list,进行异常插入处理方法
                            //分析具体是哪个index行数据出错

                            var tableRows = bwResponse.TableRespones;
                            var rows      = tableRows[TableName];
                            for (int j = 0; j < rows.PutResponses.Count; j++)
                            {
                                if (rows.PutResponses[j].IsOK)
                                {
                                }
                                else
                                {
                                    log.Error("批量提交 问题数据在第【" + j + "】行");
                                    Task task = new Task(() => {
                                        var errorRow = rowChanges.PutOperations[j];
                                        //异步处理错误数据行
                                        PutErrorHandle putError = new PutErrorLocation();
                                        putError.HandlePutError(errorRow, TableName, log);
                                    });
                                    task.Start();
                                }
                            }
                        }
                        rowChanges   = new RowChanges();
                        batchRequest = new BatchWriteRowRequest();
                        batchCount   = 0;
                        list         = new List <string>();
                    }
                }
                if (rowChanges.PutOperations.Count > 0)
                {
                    batchRequest.Add("L_100000000", rowChanges);
                    oTSClient.BatchWriteRow(batchRequest);
                    log.Info(i + "批量提交成功");
                }
                batchRequest = new BatchWriteRowRequest();
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }
Example #23
0
 public override Lite<Entity> RetrieveLite(Type type, PrimaryKey id)
 {
     if (!Database.Exists(type, id))
         return null;
     return Database.FillToString(Lite.Create(type, id));
 }
Example #24
0
 public abstract string TryGetToString(PrimaryKey id);
Example #25
0
 /// <summary>
 /// Constructor for creating a constraint from a Hibnerate PrimaryKey object.
 /// </summary>
 /// <param name="table"></param>
 /// <param name="constraint"></param>
 internal ConstraintInfo(Table table, PrimaryKey constraint)
     : this("PK_", table.Name, constraint.ColumnIterator, null)
 {
 }
Example #26
0
        /// <summary>
        /// Sets the supplied collection records to a given selected status.
        /// </summary>
        /// <param name="ArrayOf_PrimaryKeys">Primary keys of the records to set the check state for.</param>
        /// <param name="value">True if the records must be checked. Otherwise False.</param>
        public void SetRecordsChecked(object[] ArrayOf_PrimaryKeys, bool value)
        {
            this.ClearSelection();

            if (ArrayOf_PrimaryKeys != null)
            {
                foreach (object PrimaryKey in ArrayOf_PrimaryKeys)
                {
                    System.Web.UI.WebControls.ListItem listItem = this.Items.FindByValue(PrimaryKey.ToString());
                    if (listItem != null)
                    {
                        listItem.Selected = value;
                    }
                }
            }
        }
Example #27
0
 public string GetToString(PrimaryKey id)
 {
     return(toStrGetter(id));
 }
Example #28
0
        private void ReadIndexColumnData(DbDataReader reader, ExtractionContext context,
                                         ref int tableId, int spatialIndexType, ref PrimaryKey primaryKey,
                                         ref UniqueConstraint uniqueConstraint, ref Index index, ref ColumnResolver table)
        {
            var columnId  = reader.GetInt32(10);
            int indexType = reader.GetByte(5);

            // First column in index => new index or index is spatial (always has exactly one column)
            if (reader.GetByte(12) == 1 || indexType == spatialIndexType)
            {
                primaryKey       = null;
                uniqueConstraint = null;
                index            = null;
                // Table could be changed only on new index creation
                GetDataTable(reader.GetInt32(1), context, ref tableId, ref table);
                var indexId   = reader.GetInt32(3);
                var indexName = reader.GetString(4);

                // Index is a part of primary key constraint
                if (reader.GetBoolean(6))
                {
                    primaryKey = ((Table)table.Table).CreatePrimaryKey(indexName);
                    if (Driver.ServerInfo.PrimaryKey.Features.Supports(PrimaryKeyConstraintFeatures.Clustered))
                    {
                        primaryKey.IsClustered = reader.GetByte(5) == 1;
                    }
                }
                else
                {
                    // Spatial index
                    if (indexType == spatialIndexType)
                    {
                        index            = table.Table.CreateSpatialIndex(indexName);
                        index.FillFactor = reader.GetByte(9);
                    }
                    else
                    {
                        index          = table.Table.CreateIndex(indexName);
                        index.IsUnique = reader.GetBoolean(7);
                        if (Driver.ServerInfo.Index.Features.Supports(IndexFeatures.Clustered))
                        {
                            index.IsClustered = reader.GetByte(5) == 1;
                        }

                        index.FillFactor = reader.GetByte(9);
                        if (!reader.IsDBNull(15) && reader.GetBoolean(15))
                        {
                            index.Where = SqlDml.Native(reader.GetString(16));
                        }

                        // Index is a part of unique constraint
                        if (reader.GetBoolean(8))
                        {
                            uniqueConstraint = ((Table)table.Table).CreateUniqueConstraint(indexName);
                            if (index.IsClustered &&
                                Driver.ServerInfo.UniqueConstraint.Features.Supports(UniqueConstraintFeatures.Clustered))
                            {
                                uniqueConstraint.IsClustered = true;
                            }
                        }
                    }
                }
            }

            // Column is a part of a primary index
            if (reader.GetBoolean(6))
            {
                primaryKey.Columns.Add((TableColumn)table.GetColumn(columnId));
            }
            else
            {
                // Column is a part of unique constraint
                if (reader.GetBoolean(8))
                {
                    uniqueConstraint.Columns.Add((TableColumn)table.GetColumn(columnId));
                }

                if (index != null)
                {
                    // Column is non key column
                    if (reader.GetBoolean(14))
                    {
                        index.NonkeyColumns.Add(table.GetColumn(columnId));
                    }
                    else
                    {
                        _ = index.CreateIndexColumn(table.GetColumn(columnId), !reader.GetBoolean(13));
                    }
                }
            }
        }
Example #29
0
        public CachedTableMList(ICacheLogicController controller, TableMList table, AliasGenerator?aliasGenerator, string lastPartialJoin, string?remainingJoins)
            : base(controller)
        {
            this.table = table;

            CachedTableConstructor ctr = this.Constructor = new CachedTableConstructor(this, aliasGenerator);

            //Query
            using (ObjectName.OverrideOptions(new ObjectNameOptions {
                AvoidDatabaseName = true
            }))
            {
                string select = "SELECT\r\n{0}\r\nFROM {1} {2}\r\n".FormatWith(
                    ctr.table.Columns.Values.ToString(c => ctr.currentAlias + "." + c.Name.SqlEscape(), ",\r\n"),
                    table.Name.ToString(),
                    ctr.currentAlias !.ToString());

                ctr.remainingJoins = lastPartialJoin + ctr.currentAlias + "." + table.BackReference.Name.SqlEscape() + "\r\n" + remainingJoins;

                query = new SqlPreCommandSimple(select);
            }

            //Reader
            {
                rowReader = ctr.GetRowReader();
            }

            //Completer
            {
                List <Expression> instructions = new List <Expression>
                {
                    Expression.Assign(ctr.origin, Expression.Convert(CachedTableConstructor.originObject, ctr.tupleType)),
                    Expression.Assign(result, ctr.MaterializeField(table.Field))
                };
                var ci = typeof(MList <T> .RowIdElement).GetConstructor(new [] { typeof(T), typeof(PrimaryKey), typeof(int?) });

                var order = table.Order == null?Expression.Constant(null, typeof(int?)) :
                                ctr.GetTupleProperty(table.Order).Nullify();

                instructions.Add(Expression.New(ci, result, CachedTableConstructor.NewPrimaryKey(ctr.GetTupleProperty(table.PrimaryKey)), order));

                var block = Expression.Block(typeof(MList <T> .RowIdElement), new[] { ctr.origin, result }, instructions);

                activatorExpression = Expression.Lambda <Func <object, IRetriever, MList <T> .RowIdElement> >(block, CachedTableConstructor.originObject, CachedTableConstructor.retriever);

                activator = activatorExpression.Compile();

                parentIdGetter = ctr.GetPrimaryKeyGetter(table.BackReference);
                rowIdGetter    = ctr.GetPrimaryKeyGetter(table.PrimaryKey);
            }

            relationalRows = new ResetLazy <Dictionary <PrimaryKey, Dictionary <PrimaryKey, object> > >(() =>
            {
                CacheLogic.AssertSqlDependencyStarted();

                var connector = (SqlConnector)Connector.Current;

                var subConnector = connector.ForDatabase(table.Name.Schema?.Database);

                Dictionary <PrimaryKey, Dictionary <PrimaryKey, object> > result = new Dictionary <PrimaryKey, Dictionary <PrimaryKey, object> >();

                using (MeasureLoad())
                    using (Connector.Override(subConnector))
                        using (Transaction tr = Transaction.ForceNew(IsolationLevel.ReadCommitted))
                        {
                            if (CacheLogic.LogWriter != null)
                            {
                                CacheLogic.LogWriter.WriteLine("Load {0}".FormatWith(GetType().TypeName()));
                            }

                            ((SqlConnector)Connector.Current).ExecuteDataReaderOptionalDependency(query, OnChange, fr =>
                            {
                                object obj          = rowReader(fr);
                                PrimaryKey parentId = parentIdGetter(obj);
                                var dic             = result.TryGetC(parentId);
                                if (dic == null)
                                {
                                    result[parentId] = dic = new Dictionary <PrimaryKey, object>();
                                }

                                dic[rowIdGetter(obj)] = obj;
                            });
                            tr.Commit();
                        }

                return(result);
            }, mode: LazyThreadSafetyMode.ExecutionAndPublication);
        }
Example #30
0
        static MList <T> ReadJsonInternal <T>(JsonReader reader, IMListPrivate <T> existingValue, JsonSerializer serializer)
        {
            var dic = existingValue == null ? new Dictionary <PrimaryKey, MList <T> .RowIdElement>() :
                      existingValue.InnerList.Where(a => a.RowId.HasValue).ToDictionary(a => a.RowId.Value, a => a);

            var newList = new List <MList <T> .RowIdElement>();

            var pr = JsonSerializerExtensions.CurrentPropertyRoute;

            var elementPr = pr.Add("Item");

            var rowIdType = GetRowIdTypeFromAttribute(pr);


            reader.Assert(JsonToken.StartArray);

            reader.Read();

            using (JsonSerializerExtensions.SetCurrentPropertyRoute(elementPr))
            {
                while (reader.TokenType == JsonToken.StartObject)
                {
                    reader.Read();
                    reader.Assert(JsonToken.PropertyName);
                    if (((string)reader.Value) != "rowId")
                    {
                        throw new JsonSerializationException($"member 'rowId' expected in {reader.Path}");
                    }

                    reader.Read();
                    var rowIdValue = reader.Value;

                    reader.Read();
                    reader.Assert(JsonToken.PropertyName);
                    if (((string)reader.Value) != "element")
                    {
                        throw new JsonSerializationException($"member 'element' expected in {reader.Path}");
                    }

                    reader.Read();
                    if (rowIdValue != null && !rowIdValue.Equals(GraphExplorer.DummyRowId.Object))
                    {
                        var rowId = new PrimaryKey((IComparable)ReflectionTools.ChangeType(rowIdValue, rowIdType));

                        var oldValue = dic.TryGetS(rowId);

                        if (oldValue == null)
                        {
                            T newValue = (T)serializer.DeserializeValue(reader, typeof(T), null);

                            newList.Add(new MList <T> .RowIdElement(newValue, rowId, null));
                        }
                        else
                        {
                            T newValue = (T)serializer.DeserializeValue(reader, typeof(T), oldValue.Value.Element);

                            if (oldValue.Value.Element.Equals(newValue))
                            {
                                newList.Add(new MList <T> .RowIdElement(newValue, rowId, oldValue.Value.OldIndex));
                            }
                            else
                            {
                                newList.Add(new MList <T> .RowIdElement(newValue));
                            }
                        }
                    }
                    else
                    {
                        var newValue = (T)serializer.DeserializeValue(reader, typeof(T), null);
                        newList.Add(new MList <T> .RowIdElement(newValue));
                    }

                    reader.Read();

                    reader.Assert(JsonToken.EndObject);
                    reader.Read();
                }
            }

            reader.Assert(JsonToken.EndArray);

            if (existingValue == null) //Strange case...
            {
                if (newList.IsEmpty())
                {
                    return(null);
                }
                else
                {
                    existingValue = new MList <T>();
                }
            }

            bool orderMatters = GetPreserveOrderFromAttribute(pr);

            if (!existingValue.IsEqualTo(newList, orderMatters))
            {
                EntityJsonConverter.AssertCanWrite(pr);

                existingValue.AssignMList(newList);
            }

            return((MList <T>)existingValue);
        }
Example #31
0
 internal override bool Contains(PrimaryKey primaryKey)
 {
     return(this.toStrings.Value.ContainsKey(primaryKey));
 }
Example #32
0
        ImplementedByAllExpression ToIBA(Expression node, Type type)
        {
            if (node.IsNull())
            {
                return(new ImplementedByAllExpression(type,
                                                      Expression.Constant(null, typeof(string)),
                                                      new TypeImplementedByAllExpression(new PrimaryKeyExpression(Expression.Constant(null, PrimaryKey.Type(typeof(TypeEntity))))), null));
            }

            if (node is EntityExpression e)
            {
                return(new ImplementedByAllExpression(type,
                                                      new SqlCastExpression(typeof(string), e.ExternalId.Value),
                                                      new TypeImplementedByAllExpression(new PrimaryKeyExpression(QueryBinder.TypeConstant(e.Type))), null));
            }

            if (node is ImplementedByExpression ib)
            {
                return(new ImplementedByAllExpression(type,
                                                      new PrimaryKeyExpression(QueryBinder.Coalesce(ib.Implementations.Values.Select(a => a.ExternalId.ValueType.Nullify()).Distinct().SingleEx(), ib.Implementations.Select(e => e.Value.ExternalId))),
                                                      new TypeImplementedByAllExpression(new PrimaryKeyExpression(
                                                                                             ib.Implementations.Select(imp => new When(imp.Value.ExternalId.NotEqualsNulll(), QueryBinder.TypeConstant(imp.Key))).ToList()
                                                                                             .ToCondition(PrimaryKey.Type(typeof(TypeEntity)).Nullify()))), null));
            }

            if (node is ImplementedByAllExpression iba)
            {
                return(iba);
            }

            throw new UnexpectedValueException(node);
        }
        public static void ConditionBatchWriteRow()
        {
            Console.WriteLine("Start batch write row...");

            PrepareTable();
            OTSClient otsClient = Config.GetClient();

            // 定义行的主键,必须与创建表时的TableMeta中定义的一致
            PrimaryKey primaryKey = new PrimaryKey();

            primaryKey.Add("pk0", new ColumnValue(3));
            primaryKey.Add("pk1", new ColumnValue("abc"));

            // 定义要写入改行的属性列
            AttributeColumns attribute = new AttributeColumns();

            attribute.Add("col0", new ColumnValue(0));
            attribute.Add("col1", new ColumnValue("a"));
            attribute.Add("col2", new ColumnValue(true));

            PutRowRequest request = new PutRowRequest(tableName, new Condition(RowExistenceExpectation.IGNORE), primaryKey, attribute);

            // 新创建一行数据
            try
            {
                otsClient.PutRow(request);

                Console.WriteLine("Put row succeeded.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Put row failed. error:{0}", ex.Message);
            }

            // 当col0列的值不等于5的时候,允许再次put row,覆盖掉原值,预期成功
            try
            {
                // 构造条件语句:col0列的值不等于5
                var condition = new Condition(RowExistenceExpectation.IGNORE);
                condition.ColumnCondition = new RelationalCondition("col0",
                                                                    CompareOperator.NOT_EQUAL,
                                                                    new ColumnValue(5));

                // 构造col2列的值
                var attr1 = new AttributeColumns();
                attr1.Add("col2", new ColumnValue(false));

                // 构造批量写请求
                var rowChange = new RowChanges(tableName);
                rowChange.AddPut(condition, primaryKey, attr1);

                var batchWriteRequest = new BatchWriteRowRequest();
                batchWriteRequest.Add(tableName, rowChange);

                // 批量写数据
                otsClient.BatchWriteRow(batchWriteRequest);

                Console.WriteLine("Batch write row succeeded.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Batch write row failed. error:{0}", ex.Message);
            }
        }
Example #34
0
 private static EntityExpression NullEntity(Type type)
 {
     return(new EntityExpression(type, new PrimaryKeyExpression(Expression.Constant(null, PrimaryKey.Type(type).Nullify())), null, null, null, null, null, false));
 }
Example #35
0
 public Type GetType(PrimaryKey id)
 {
     return(typeCachesLazy.Value.IdToType[id]);
 }
Example #36
0
 protected override void CreatePrimaryKey(PrimaryKey primaryKey)
 {
     // Not supported by sqlite
     // https://www.sqlite.org/omitted.html
 }
Example #37
0
 public static bool Throw(PrimaryKey a)
 {
     throw new ArgumentException("a");
 }
Example #38
0
 protected override bool IsPrimaryKeyExist(PrimaryKey primaryKey)
 {
     return(IsPrimaryKeyExist(primaryKey.Entity.GetNameInStore()));
 }
Example #39
0
 public DbParameter CreateReferenceParameter(string parameterName, PrimaryKey? id, IColumn column)
 {
     return CreateParameter(parameterName, column.SqlDbType, null, column.Nullable, id == null ? (object)null : id.Value.Object);
 }
Example #40
0
        /// <summary>
        /// 生成保存实体的sql及参数,返回Dict的结构:包含两个键text和params,text值为sql字符串,params值为sql参数Dict
        /// </summary>
        /// <param name="p_row">待保存的行</param>
        /// <returns>返回提交参数</returns>
        internal Dict GetSaveSql(Row p_row)
        {
            // 不再重复判断
            //if (p_row == null)
            //    throw new Exception(_saveError);

            //// 无需保存
            //if (!p_row.IsAdded && !p_row.IsChanged)
            //    return null;

            // 检查是否包含主键
            foreach (var col in PrimaryKey)
            {
                if (!p_row.Contains(col.Name))
                {
                    throw new Exception(string.Format(_primaryError, p_row.GetType().Name, col.Name));
                }
            }

            Dict          dtParams = new Dict();
            StringBuilder sql      = new StringBuilder();

            if (p_row.IsAdded)
            {
                // 插入
                StringBuilder insertCol = new StringBuilder();
                StringBuilder insertVal = new StringBuilder();
                foreach (var col in PrimaryKey.Concat(Columns))
                {
                    if (!p_row.Contains(col.Name))
                    {
                        continue;
                    }

                    if (insertCol.Length > 0)
                    {
                        insertCol.Append(",");
                    }
                    insertCol.Append(col.Name);

                    if (insertVal.Length > 0)
                    {
                        insertVal.Append(",");
                    }
                    insertVal.Append("@");
                    insertVal.Append(col.Name);

                    dtParams[col.Name] = p_row[col.Name];
                }
                sql.Append("insert into ");
                sql.Append(Name);
                sql.Append("(");
                sql.Append(insertCol.ToString());
                sql.Append(") values (");
                sql.Append(insertVal.ToString());
                sql.Append(")");
            }
            else
            {
                // 更新
                StringBuilder updateVal   = new StringBuilder();
                StringBuilder whereVal    = new StringBuilder();
                int           updateIndex = 1;

                foreach (var col in PrimaryKey.Concat(Columns))
                {
                    if (!p_row.Contains(col.Name) || !p_row.Cells[col.Name].IsChanged)
                    {
                        continue;
                    }

                    // 只更新变化的列
                    if (updateVal.Length > 0)
                    {
                        updateVal.Append(", ");
                    }
                    updateVal.Append(col.Name);
                    updateVal.Append("=@");
                    updateVal.Append(updateIndex);

                    // 更新主键时避免重复
                    dtParams[updateIndex.ToString()] = p_row[col.Name];
                    updateIndex++;
                }

                // 主键
                foreach (var col in PrimaryKey)
                {
                    if (whereVal.Length > 0)
                    {
                        whereVal.Append(" and ");
                    }
                    whereVal.Append(col.Name);
                    whereVal.Append("=@");
                    whereVal.Append(col.Name);

                    // 主键可能被更新
                    dtParams[col.Name] = p_row.Cells[col.Name].OriginalVal;
                }

                sql.Append("update ");
                sql.Append(Name);
                sql.Append(" set ");
                sql.Append(updateVal.ToString());
                sql.Append(" where ");
                sql.Append(whereVal.ToString());
            }

            Dict dt = new Dict();

            dt["text"]   = sql.ToString();
            dt["params"] = dtParams;
            return(dt);
        }
        public override PrimaryKey DeterminePrimaryKeys(Table table)
        {
            var primaryKeys = table.Columns.Where(x => x.IsPrimaryKey.Equals(true)).ToList();

            if (primaryKeys.Count() == 1)
            {
                var c = primaryKeys.First();
                var key = new PrimaryKey
                              {
                                  Type = PrimaryKeyType.PrimaryKey,
                                  Columns = { c }
                              };
                return key;
            }

            if (primaryKeys.Count() > 1)
            {
                // Composite key
                var key = new PrimaryKey
                              {
                                  Type = PrimaryKeyType.CompositeKey,
                                  Columns = primaryKeys
                              };

                return key;
            }

            return null;
        }
 public bool Equals(JsonObjectDto other)
 {
     return(PrimaryKey.Equals(other.PrimaryKey) &&
            Values.Equals(other.Values));
 }
Example #43
0
            /// <summary>
            /// Initializes a mapping table.
            /// </summary>
            /// <param name="type">the type to map</param>
            /// <param name="namingStrategy">the naming strategy to apply</param>
            public Table(Type type, INamingStrategy namingStrategy)
            {
                String typeName = type.FullName;
                TableAttribute tableAttr = ReflectHelper.GetAttribute<TableAttribute>(type);

                Name = (tableAttr == null) ? namingStrategy.GetTableName(typeName) : tableAttr.Name;
                EntityType = type;
                _fields = ReflectHelper.GetSettableFields(type);
                _properties = DefaultTypeMap.GetSettableProps(type);

                foreach (PropertyInfo pi in _properties)
                {
                    Column column = CreateColumn(pi, namingStrategy);
                    if (column != null)
                    {
                        if (column.DbType == DbType.Empty)
                            column.DbType = LookupDbType(pi.PropertyType, pi.Name);
                        column.MemberInfo = new SimpleMemberMap(column.ColumnName, pi);
                        AddColumn(column);
                    }
                }

                foreach (FieldInfo fi in _fields)
                {
                    Column column = CreateColumn(fi, namingStrategy);
                    if (column != null)
                    {
                        if (column.DbType == DbType.Empty)
                            column.DbType = LookupDbType(fi.FieldType, fi.Name);
                        column.MemberInfo = new SimpleMemberMap(column.ColumnName, fi);
                        AddColumn(column);
                    }
                }

                if (PrimaryKey == null)
                {
                    Column idCol = FindColumnByFieldName("id");
                    if (idCol != null)
                    {
                        PrimaryKey = new PrimaryKey();
                        PrimaryKey.AddColumn(idCol);
                    }
                }
            }
 public override int GetHashCode()
 {
     return(PrimaryKey.GetHashCode() ^ Values.GetHashCode());
 }
        private static PrimaryKey GetPrimaryKeys(SqlTable sqltable)
        {
            IEnumerable<Column> primaryKeys = sqltable.Columns.Where(x => x.IsPrimaryKey.Equals(true));

            switch (primaryKeys.Count())
            {
                case 1:
                    {
                        Column col = primaryKeys.First();
                        var pkey = new PrimaryKey
                                       {
                                           Type = PrimaryKeyType.PrimaryKey,
                                           Columns =
                                               {
                                                   new Column
                                                       {
                                                           DataType = col.DataType,
                                                           Name = col.Name
                                                       }
                                               }
                                       };
                        return pkey;
                    }
                default:
                    {
                        var pkey = new PrimaryKey {Type = PrimaryKeyType.CompositeKey};
                        foreach (Column primaryKey in primaryKeys)
                        {
                            pkey.Columns.Add(new Column
                                                 {
                                                     DataType = primaryKey.DataType,
                                                     Name = primaryKey.Name
                                                 });
                        }
                        return pkey;
                    }
            }
        }
Example #46
0
 public void ShouldBe(UnconventionalPoco other)
 {
     PrimaryKey.ShouldBe(other.PrimaryKey);
     Text.ShouldBe(other.Text);
 }
Example #47
0
        public void ContainsIEnumerableId()
        {
            IEnumerable<PrimaryKey> ids = new PrimaryKey[] { 1, 2, 3 }.Select(a => a);

            var artist = Database.Query<ArtistEntity>().Where(a => ids.Contains(a.Id)).ToList();
        }
Example #48
0
        public override MList <S> GetValue(MappingContext <MList <S> > ctx)
        {
            using (HeavyProfiler.LogNoStackTrace("GetValue", () => "MListMapping<{0}>".FormatWith(typeof(S).TypeName())))
            {
                if (ctx.Empty())
                {
                    return(ctx.None());
                }

                IMListPrivate <S> mlistPriv = ctx.Value;

                var dic = mlistPriv == null ? new Dictionary <PrimaryKey, MList <S> .RowIdElement>() :
                          mlistPriv.InnerList.Where(a => a.RowId.HasValue).ToDictionary(a => a.RowId.Value, a => a);

                var newList = new List <MList <S> .RowIdElement>();
                foreach (MappingContext <S> itemCtx in GenerateItemContexts(ctx))
                {
                    Debug.Assert(!itemCtx.Empty());

                    string rowIdString = (itemCtx.Inputs.ContainsKey(EntityListBaseKeys.RowId)? itemCtx.Inputs[EntityListBaseKeys.RowId]:null);

                    if (rowIdString.HasText())
                    {
                        var rowId = new PrimaryKey((IComparable)ReflectionTools.Parse(rowIdString, GetRowIdType(ctx)));

                        var oldValue = dic.GetOrThrow(rowId, "No RowID {0} found");

                        itemCtx.Value = oldValue.Element;
                        itemCtx.Value = ElementMapping(itemCtx);

                        ctx.AddChild(itemCtx);

                        if (itemCtx.Value != null)
                        {
                            var val = itemCtx.SupressChange ? oldValue.Element : itemCtx.Value;

                            if (oldValue.Element.Equals(val))
                            {
                                newList.Add(new MList <S> .RowIdElement(val, rowId, oldValue.OldIndex));
                            }
                            else
                            {
                                newList.Add(new MList <S> .RowIdElement(val));
                            }
                        }
                    }
                    else
                    {
                        itemCtx.Value = ElementMapping(itemCtx);
                        ctx.AddChild(itemCtx);
                        if (itemCtx.Value != null && !itemCtx.SupressChange)
                        {
                            newList.Add(new MList <S> .RowIdElement(itemCtx.Value));
                        }
                    }
                }

                if (!AreEqual(newList, mlistPriv == null ? null : mlistPriv.InnerList))
                {
                    Signum.Web.Mapping.AssertCanChange(ctx.PropertyRoute);

                    if (ctx.Value == null)
                    {
                        mlistPriv = ctx.Value = new MList <S>();
                    }

                    var added   = newList.Select(a => a.Element).Except(mlistPriv.InnerList.Select(a => a.Element)).ToList();
                    var removed = mlistPriv.InnerList.Select(a => a.Element).Except(newList.Select(a => a.Element)).ToList();

                    mlistPriv.InnerList.Clear();
                    mlistPriv.InnerList.AddRange(newList);
                    mlistPriv.InnerListModified(added, removed);
                }

                return(ctx.Value);
            }
        }
Example #49
0
 ViewResult ResetPasswordSetNewError(PrimaryKey idResetPasswordRequest, string error)
 {
     ModelState.AddModelError("_FORM", error);
     ViewData["rpr"] = idResetPasswordRequest;
     return View(AuthClient.ResetPasswordSetNewView);
 }
Example #50
0
 public static ForeignKey ForeignKey(ResourceProperty primaryKeyProperty)
 {
     PrimaryKey pk = new PrimaryKey(null, primaryKeyProperty);
     return new ForeignKey(null, pk);
 }