public void FeatureIntegration_PersistAndRetrieve_WithComplexStructure_RetrievedShouldBeSameAsPersisted()
        {
            try
            {
                int transId   = 35;
                int productId = 135;
                int serviceId = 235;

                IDbConnection connection = SetupTables();

                Product     product     = CreateDefaultProduct(connection, productId);
                Service     service     = CreateDefaultService(connection, serviceId);
                Transaction transaction = CreateDefaultTransaction(connection, transId, product, service);

                ITransaction tx = CreateTransaction(connection);
                var          loadedTransaction = new Transaction();
                LoadWithId(tx, loadedTransaction, transId);
                tx.Commit();
                DbMgtUtility.Close(connection);

                VerifyEquals(transaction, loadedTransaction);
            }
            catch (System.Exception e)
            {
                LogManager.GetLogger(typeof(DbGateFeatureIntegrationTest)).Fatal(e.Message, e);
                Assert.Fail(e.Message);
            }
        }
Exemple #2
0
        private Object ExtractCurrentVersionValue(IReadOnlyEntity entity, IColumn versionColumn, Type type
                                                  , ITransaction tx)
        {
            Object versionValue = null;

            ITypeFieldValueList keyFieldValueList = OperationUtils.ExtractEntityTypeKeyValues(entity, type);
            IDbCommand          cmd    = null;
            IDataReader         reader = null;

            try
            {
                cmd    = CreateRetrievalPreparedStatement(keyFieldValueList, tx);
                reader = cmd.ExecuteReader();
                if (reader.Read())
                {
                    versionValue = DbLayer.DataManipulate().ReadFromResultSet(reader, versionColumn);
                }
            }
            catch (Exception ex)
            {
                String message = String.Format("SQL Exception while trying retrieve version information from {0}"
                                               , entity.GetType().FullName);
                throw new StatementExecutionException(message, ex);
            }
            finally
            {
                DbMgtUtility.Close(reader);
                DbMgtUtility.Close(cmd);
            }
            return(versionValue);
        }
Exemple #3
0
        private ITypeFieldValueList ExtractCurrentRowValues(IReadOnlyEntity entity, Type type, ITransaction tx)
        {
            ITypeFieldValueList fieldValueList = null;

            ITypeFieldValueList keyFieldValueList = OperationUtils.ExtractEntityTypeKeyValues(entity, type);
            IDbCommand          cmd    = null;
            IDataReader         reader = null;

            try
            {
                cmd    = CreateRetrievalPreparedStatement(keyFieldValueList, tx);
                reader = cmd.ExecuteReader();
                if (reader.Read())
                {
                    fieldValueList = ReadValues(type, reader);
                }
            }
            catch (Exception ex)
            {
                string message = String.Format("SQL Exception while trying retrieve current data row from {0}"
                                               , entity.GetType().FullName);
                throw new StatementExecutionException(message, ex);
            }
            finally
            {
                DbMgtUtility.Close(reader);
                DbMgtUtility.Close(cmd);
            }
            return(fieldValueList);
        }
        public ICollection <Object> Select(ISelectionQuery query, ITransaction tx)
        {
            IDataReader rs = null;

            try
            {
                var logSb     = new StringBuilder();
                var showQuery = Config.ShowQueries;
                var buildInfo = DbLayer.DataManipulate().ProcessQuery(null, query.Structure);
                var execInfo  = buildInfo.ExecInfo;

                if (showQuery)
                {
                    logSb.Append(execInfo.Sql);
                    foreach (var param in execInfo.Params)
                    {
                        logSb.Append(" ,").Append("Param").Append(param.Index).Append("=").Append(param.Value);
                    }
                    Logger.GetLogger(Config.LoggerName).Debug(logSb.ToString());
                }

                rs = DbLayer.DataManipulate().CreateResultSet(tx, execInfo);

                IList <Object> retList = new List <Object> ();
                ICollection <IQuerySelection> selections = query.Structure.SelectList;
                var selectionCount = selections.Count;

                while (rs.Read())
                {
                    int count = 0;

                    object rowObject = selectionCount > 1 ? new object[selectionCount] : null;
                    foreach (IQuerySelection selection in selections)
                    {
                        Object loaded = ((IAbstractSelection)selection).Retrieve(rs, tx, buildInfo);
                        if (selectionCount > 1)
                        {
                            ((object[])rowObject)[count++] = loaded;
                        }
                        else
                        {
                            rowObject = loaded;
                        }
                    }
                    retList.Add(rowObject);
                }

                return(retList);
            }
            catch (Exception e)
            {
                Logger.GetLogger(Config.LoggerName).Error(e.Message, e);
                throw new RetrievalException(e.Message, e);
            }
            finally
            {
                DbMgtUtility.Close(rs);
            }
        }
Exemple #5
0
        private void Insert(IEntity entity, ITypeFieldValueList valueTypeList, Type entityType, ITransaction tx)
        {
            EntityInfo entityInfo = CacheManager.GetEntityInfo(entityType);

            StringBuilder logSb = new StringBuilder();
            string        query = entityInfo.GetInsertQuery(DbLayer);
            IDbCommand    cmd   = tx.CreateCommand();

            cmd.CommandText = query;

            bool showQuery = Config.ShowQueries;

            if (showQuery)
            {
                logSb.Append(query);
            }
            int i = 0;

            foreach (EntityFieldValue fieldValue in valueTypeList.FieldValues)
            {
                IColumn column = fieldValue.Column;
                Object  columnValue;

                if (column.ReadFromSequence &&
                    column.SequenceGenerator != null)
                {
                    columnValue = column.SequenceGenerator.GetNextSequenceValue(tx);
                    PropertyInfo setter = entityType.GetProperty(column.AttributeName);
                    ReflectionUtils.SetValue(setter, entity, columnValue);
                }
                else
                {
                    columnValue = fieldValue.Value;
                }
                if (showQuery)
                {
                    logSb.Append(" ,").Append(column.ColumnName).Append("=").Append(columnValue);
                }
                DbLayer.DataManipulate().SetToPreparedStatement(cmd, columnValue, i + 1, column);
                i++;
            }
            if (showQuery)
            {
                Logger.GetLogger(Config.LoggerName).Debug(logSb.ToString());
            }
            if (Config.EnableStatistics)
            {
                Statistics.RegisterInsert(entityType);
            }
            cmd.ExecuteNonQuery();
            DbMgtUtility.Close(cmd);
        }
Exemple #6
0
        private void DeleteOrphanChildren(ITransaction tx, IEnumerable <ITypeFieldValueList> childrenToDelete)
        {
            foreach (ITypeFieldValueList relationKeyValueList in childrenToDelete)
            {
                EntityInfo entityInfo = CacheManager.GetEntityInfo(relationKeyValueList.Type);
                if (entityInfo == null)
                {
                    continue;
                }

                if (relationKeyValueList is EntityRelationFieldValueList)
                {
                    EntityRelationFieldValueList entityRelationFieldValueList = (EntityRelationFieldValueList)relationKeyValueList;
                    if (entityRelationFieldValueList.Relation.ReverseRelationship ||
                        entityRelationFieldValueList.Relation.NonIdentifyingRelation)
                    {
                        continue;
                    }
                }

                bool        recordExists = false;
                IDbCommand  cmd          = null;
                IDataReader reader       = null;
                try
                {
                    cmd    = CreateRetrievalPreparedStatement(relationKeyValueList, tx);
                    reader = cmd.ExecuteReader();
                    if (reader.Read())
                    {
                        recordExists = true;
                    }
                }
                catch (Exception ex)
                {
                    string message =
                        String.Format(
                            "SQL Exception while trying determine if orphan child entities are available for type {0}",
                            relationKeyValueList.Type.FullName);
                    throw new StatementExecutionException(message, ex);
                }
                finally
                {
                    DbMgtUtility.Close(reader);
                    DbMgtUtility.Close(cmd);
                }

                if (recordExists)
                {
                    Delete(relationKeyValueList, relationKeyValueList.Type, tx);
                }
            }
        }
        private ICollection <IReadOnlyEntity> ExecuteAndReadFromPreparedStatement(IReadOnlyEntity entity, ITransaction tx, IDbCommand cmd
                                                                                  , Type childType)
        {
            EntityInfo                    entityInfo = CacheManager.GetEntityInfo(childType);
            ICollection <IColumn>         childKeys  = null;
            ICollection <IReadOnlyEntity> data       = new List <IReadOnlyEntity>();

            IDataReader reader = null;

            try
            {
                reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    if (childKeys == null)
                    {
                        childKeys = entityInfo.GetKeys();
                    }
                    ITypeFieldValueList childTypeKeyList = new EntityTypeFieldValueList(childType);
                    foreach (IColumn childKey in childKeys)
                    {
                        Object value = DbLayer.DataManipulate().ReadFromResultSet(reader, childKey);
                        childTypeKeyList.FieldValues.Add(new EntityFieldValue(value, childKey));
                    }
                    if (entity.Context.AlreadyInCurrentObjectGraph(childTypeKeyList))
                    {
                        data.Add(entity.Context.GetFromCurrentObjectGraph(childTypeKeyList));
                        continue;
                    }

                    IReadOnlyEntity rodbClass = (IReadOnlyEntity)Activator.CreateInstance(childType);
                    rodbClass.Context.CopyReferenceStoreFrom(entity);
                    rodbClass.Retrieve(reader, tx);
                    data.Add(rodbClass);

                    entity.Context.AddToCurrentObjectGraphIndex(rodbClass);
                }
            }
            catch (Exception ex)
            {
                string message = String.Format("SQL Exception while trying to read type {0} from result set", childType.FullName);
                throw new ReadFromResultSetException(message, ex);
            }
            finally
            {
                DbMgtUtility.Close(reader);
                DbMgtUtility.Close(cmd);
            }

            return(data);
        }
        private void LoadFromDb(IReadOnlyEntity roEntity, IDataReader reader, ITransaction tx)
        {
            EntityInfo entityInfo = CacheManager.GetEntityInfo(roEntity);

            while (entityInfo != null)
            {
                string tableName = entityInfo.TableInfo.TableName;
                if (entityInfo.EntityType == roEntity.GetType() || tableName == null) //if i==0 that means it's base class and can use existing result set
                {
                    LoadForType(roEntity, entityInfo.EntityType, reader, tx);
                }
                else
                {
                    IDbCommand  superCmd    = null;
                    IDataReader superReader = null;
                    try
                    {
                        ITypeFieldValueList keyValueList = OperationUtils.ExtractEntityTypeKeyValues(roEntity, entityInfo.EntityType);
                        superCmd    = CreateRetrievalPreparedStatement(keyValueList, tx);
                        superReader = superCmd.ExecuteReader();
                        if (superReader.Read())
                        {
                            LoadForType(roEntity, entityInfo.EntityType, superReader, tx);
                        }
                        else
                        {
                            string message =
                                String.Format(
                                    "Super class {0} does not contains a matching record for the base class {1}",
                                    entityInfo.EntityType.FullName, roEntity.GetType().FullName);
                            throw new NoMatchingRecordFoundForSuperClassException(message);
                        }
                    }
                    catch (Exception ex)
                    {
                        String message = String.Format("SQL Exception while trying to read from table {0}", tableName);
                        throw new ReadFromResultSetException(message, ex);
                    }
                    finally
                    {
                        DbMgtUtility.Close(superReader);
                        DbMgtUtility.Close(superCmd);
                    }
                }
                entityInfo = entityInfo.SuperEntityInfo;
            }
        }
Exemple #9
0
        private void Delete(ITypeFieldValueList valueTypeList, Type type, ITransaction tx)
        {
            EntityInfo               entityInfo = CacheManager.GetEntityInfo(type);
            StringBuilder            logSb      = new StringBuilder();
            string                   query      = entityInfo.GetDeleteQuery(DbLayer);
            IList <EntityFieldValue> keys       = new List <EntityFieldValue>();

            foreach (EntityFieldValue fieldValue in valueTypeList.FieldValues)
            {
                if (fieldValue.Column.Key)
                {
                    keys.Add(fieldValue);
                }
            }

            bool showQuery = Config.ShowQueries;

            if (showQuery)
            {
                logSb.Append(query);
            }
            IDbCommand ps = tx.CreateCommand();

            ps.CommandText = query;
            for (int i = 0; i < keys.Count; i++)
            {
                EntityFieldValue fieldValue = keys[i];

                if (showQuery)
                {
                    logSb.Append(" ,").Append(fieldValue.Column.ColumnName).Append("=").Append(fieldValue.Value);
                }
                DbLayer.DataManipulate().SetToPreparedStatement(ps, fieldValue.Value, i + 1, fieldValue.Column);
            }
            if (showQuery)
            {
                Logger.GetLogger(Config.LoggerName).Debug(logSb.ToString());
            }
            if (Config.EnableStatistics)
            {
                Statistics.RegisterDelete(type);
            }
            ps.ExecuteNonQuery();
            DbMgtUtility.Close(ps);
        }
Exemple #10
0
        public One2OneParentEntity Retrieve(ITransaction tx, int id)
        {
            IDbCommand cmd = tx.CreateCommand();

            cmd.CommandText = "select * from parent_entity where id = ?";

            IDbDataParameter parameter = cmd.CreateParameter();

            cmd.Parameters.Add(parameter);
            parameter.DbType = DbType.Int32;
            parameter.Value  = id;

            One2OneParentEntity entity = null;
            IDataReader         reader = cmd.ExecuteReader();

            if (reader.Read())
            {
                entity = new One2OneParentEntity();
                entity.Retrieve(reader, tx);
            }
            DbMgtUtility.Close(reader);
            DbMgtUtility.Close(cmd);
            return(entity);
        }
Exemple #11
0
        public Transaction Retrieve(ITransaction tx)
        {
            IDbCommand cmd = tx.CreateCommand();

            cmd.CommandText = "select * from order_transaction where transaction_id = ?";

            IDbDataParameter parameter = cmd.CreateParameter();

            cmd.Parameters.Add(parameter);
            parameter.DbType = DbType.Int32;
            parameter.Value  = TransactionId;

            Transaction entity = null;
            IDataReader reader = cmd.ExecuteReader();

            if (reader.Read())
            {
                entity = new Transaction();
                entity.Retrieve(reader, tx);
            }
            DbMgtUtility.Close(reader);
            DbMgtUtility.Close(cmd);
            return(entity);
        }
Exemple #12
0
        public void Intercept(IInvocation invocation)
        {
            if (!_intercepted)
            {
                _intercepted = true;
                bool newTransaction = false;
                try
                {
                    if (_transaction.Closed)
                    {
                        _transaction   = _transactionFactory.CreateTransaction();
                        newTransaction = true;
                    }
                    _dataRetrievalOperationLayer.LoadChildrenFromRelation(_parentRoEntity, _applicableParentType,
                                                                          _transaction, _relation, true);
                }
                finally
                {
                    if (newTransaction)
                    {
                        DbMgtUtility.Close(_transaction);
                        _transaction = null;
                    }
                }

                EntityInfo   entityInfo     = CacheManager.GetEntityInfo(_parentRoEntity);
                PropertyInfo property       = entityInfo.GetProperty(_relation.AttributeName);
                Object       objectToInvoke = property.GetValue(_parentRoEntity, new object[] {});

                invocation.ReturnValue = invocation.Method.Invoke(objectToInvoke, new object[] {});
            }
            else
            {
                invocation.Proceed();
            }
        }
Exemple #13
0
        private void Update(IEntity entity, ITypeFieldValueList valueTypeList, Type type, ITransaction tx)
        {
            EntityInfo entityInfo = CacheManager.GetEntityInfo(type);
            ICollection <EntityFieldValue> keys   = new List <EntityFieldValue>();
            ICollection <EntityFieldValue> values = new List <EntityFieldValue>();
            StringBuilder logSb = new StringBuilder();
            string        query;


            if (entityInfo.TableInfo.UpdateStrategy == UpdateStrategy.ChangedColumns)
            {
                values = GetModifiedFieldValues(entity, type);
                if (values.Count == 0)
                {
                    return;
                }

                keys = OperationUtils.ExtractEntityKeyValues(entity).FieldValues;
                ICollection <IColumn> keysAndModified = new List <IColumn>();
                foreach (EntityFieldValue fieldValue in values)
                {
                    keysAndModified.Add(fieldValue.Column);
                }
                foreach (EntityFieldValue fieldValue in keys)
                {
                    keysAndModified.Add(fieldValue.Column);
                }
                query = DbLayer.DataManipulate().CreateUpdateQuery(entityInfo.TableInfo.TableName, keysAndModified);
            }
            else
            {
                query = entityInfo.GetUpdateQuery(DbLayer);
                foreach (EntityFieldValue fieldValue in valueTypeList.FieldValues)
                {
                    if (fieldValue.Column.Key)
                    {
                        keys.Add(fieldValue);
                    }
                    else
                    {
                        values.Add(fieldValue);
                    }
                }
            }

            bool showQuery = Config.ShowQueries;

            if (showQuery)
            {
                logSb.Append(query);
            }

            IDbCommand cmd = tx.CreateCommand();

            cmd.CommandText = query;
            int count = 0;

            foreach (EntityFieldValue fieldValue in values)
            {
                if (showQuery)
                {
                    logSb.Append(" ,").Append(fieldValue.Column.ColumnName).Append("=").Append(fieldValue.Value);
                }
                DbLayer.DataManipulate().SetToPreparedStatement(cmd, fieldValue.Value, ++count, fieldValue.Column);
            }

            foreach (EntityFieldValue fieldValue in keys)
            {
                if (showQuery)
                {
                    logSb.Append(" ,").Append(fieldValue.Column.ColumnName).Append("=").Append(fieldValue.Value);
                }
                DbLayer.DataManipulate().SetToPreparedStatement(cmd, fieldValue.Value, ++count, fieldValue.Column);
            }
            if (showQuery)
            {
                Logger.GetLogger(Config.LoggerName).Debug(logSb.ToString());
            }
            if (Config.EnableStatistics)
            {
                Statistics.RegisterUpdate(type);
            }
            cmd.ExecuteNonQuery();
            DbMgtUtility.Close(cmd);
        }
Exemple #14
0
        public void PatchDataBase(ITransaction tx, ICollection <Type> entityTypes, bool dropAll)
        {
            try
            {
                foreach (Type entityType in entityTypes)
                {
                    CacheManager.Register(entityType);
                }

                IMetaManipulate         metaManipulate = _dbLayer.MetaManipulate(tx);
                ICollection <IMetaItem> existingItems  = metaManipulate.GetMetaData(tx);
                ICollection <IMetaItem> requiredItems  = CreateMetaItemsFromEntityTypes(entityTypes);

                List <MetaQueryHolder> queryHolders = new List <MetaQueryHolder>();

                if (dropAll)
                {
                    ICollection <IMetaComparisonGroup> groupExisting = CompareUtility.Compare(metaManipulate, existingItems, new List <IMetaItem>());
                    ICollection <IMetaComparisonGroup> groupRequired = CompareUtility.Compare(metaManipulate, new List <IMetaItem>(), requiredItems);

                    List <MetaQueryHolder> queryHoldersExisting = new List <MetaQueryHolder>();
                    foreach (IMetaComparisonGroup comparisonGroup in groupExisting)
                    {
                        queryHoldersExisting.AddRange(_dbLayer.MetaManipulate(tx).CreateDbPathSql(comparisonGroup));
                    }
                    queryHoldersExisting.Sort();

                    List <MetaQueryHolder> queryHoldersRequired = new List <MetaQueryHolder>();
                    foreach (IMetaComparisonGroup comparisonGroup in groupRequired)
                    {
                        queryHoldersRequired.AddRange(_dbLayer.MetaManipulate(tx).CreateDbPathSql(comparisonGroup));
                    }
                    queryHoldersRequired.Sort();

                    queryHolders.AddRange(queryHoldersExisting);
                    queryHolders.AddRange(queryHoldersRequired);
                }
                else
                {
                    ICollection <IMetaComparisonGroup> groups = CompareUtility.Compare(metaManipulate, existingItems, requiredItems);
                    foreach (IMetaComparisonGroup comparisonGroup in groups)
                    {
                        queryHolders.AddRange(_dbLayer.MetaManipulate(tx).CreateDbPathSql(comparisonGroup));
                    }
                    queryHolders.Sort();
                }

                foreach (MetaQueryHolder holder in queryHolders)
                {
                    if (holder.QueryString == null)
                    {
                        continue;
                    }

                    Logger.GetLogger(_config.LoggerName).Debug(holder.QueryString);

                    IDbCommand cmd = tx.CreateCommand();
                    cmd.CommandText = holder.QueryString;
                    cmd.ExecuteNonQuery();
                    DbMgtUtility.Close(cmd);

                    if (_config.EnableStatistics)
                    {
                        _statistics.RegisterPatch();
                    }
                }
            }
            catch (Exception e)
            {
                Logger.GetLogger(_config.LoggerName).Fatal(e.Message, e);
                throw new MetaDataException(e.Message, e);
            }
        }