Пример #1
0
        /// <summary>
        /// Constrói o resultado com as informações que serão processadas.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public override QueryReturnInfo BuildResultInfo <T>(GDA.Interfaces.IProviderConfiguration configuration)
        {
            if (string.IsNullOrEmpty(_commandText))
            {
                throw new QueryException("Command text not informed.");
            }
            var query = _commandText;

            if (!string.IsNullOrEmpty(Order))
            {
                var orderByIndex = query.LastIndexOf("ORDER BY");
                if (orderByIndex >= 0)
                {
                    query = query.Substring(0, orderByIndex);
                }
                query += " ORDER BY " + Order;
            }
            var mapping     = MappingManager.GetMappers <T>(null, null);
            var selectProps = new List <Mapper>(mapping);

            if (!string.IsNullOrEmpty(_selectProperties) && _selectProperties != "*")
            {
                List <string> functions = new List <string>();
                Parser        p         = new Parser(new Lexer(_selectProperties));
                SelectPart    sp        = p.ExecuteSelectPart();
                selectProps = new List <Mapper>(sp.SelectionExpressions.Count);
                foreach (SelectExpression se in sp.SelectionExpressions)
                {
                    if (se.ColumnName.Type == GDA.Sql.InterpreterExpression.Enums.SqlExpressionType.Column)
                    {
                        Column col = se.Column;
                        foreach (Mapper mp in mapping)
                        {
                            if (string.Compare(se.ColumnName.Value.Text, mp.PropertyMapperName, true) == 0 && (mp.Direction == DirectionParameter.Input || mp.Direction == DirectionParameter.InputOutput || mp.Direction == DirectionParameter.OutputOnlyInsert))
                            {
                                if (!selectProps.Exists(f => f.PropertyMapperName == mp.PropertyMapperName))
                                {
                                    selectProps.Add(mp);
                                }
                            }
                        }
                        if (col.Name == "*")
                        {
                            throw new GDAException("Invalid expression {0}", se.ColumnName.Value.Text);
                        }
                    }
                    else if (se.ColumnName.Type == GDA.Sql.InterpreterExpression.Enums.SqlExpressionType.Function)
                    {
                        throw new QueryException("NativeQuery not support function in select part");
                    }
                }
            }
            return(new QueryReturnInfo(query, this.Parameters, selectProps));
        }
Пример #2
0
        /// <summary>
        /// Recupera as propriedades chave da model.
        /// </summary>
        /// <param name="type">Tipo a ser usada para recupera as propriedades.</param>
        /// <returns></returns>
        public static List <PropertyInfo> GetPropertiesKey(Type type)
        {
            var result = new List <PropertyInfo>();

            foreach (var i in MappingManager.GetMappers(type, new PersistenceParameterType[] {
                PersistenceParameterType.Key,
                PersistenceParameterType.IdentityKey
            }, null))
            {
                result.Add(i.PropertyMapper);
            }
            return(result);
        }
Пример #3
0
        /// <summary>
        /// Recupera os dados do objeto submetido tendo como base os valores
        /// da chave contidos no objeto submetido.
        /// </summary>
        /// <param name="session">Sess�o utilizada para a execu��o do comando.</param>
        /// <param name="objData">Objeto contendo os dados das chaves.</param>
        /// <returns>Model com os dados recuperados.</returns>
        public Model RecoverData(GDASession session, Model objData)
        {
            string        sqlParam   = "";
            StringBuilder buf        = new StringBuilder("SELECT ");
            List <Mapper> properties = Keys;

            if (properties.Count == 0)
            {
                throw new GDAException("In model {0} not found keys for to recover data.", objData.GetType().FullName);
            }
            DirectionParameter[] dp = new DirectionParameter[] {
                DirectionParameter.Input,
                DirectionParameter.InputOutput,
                DirectionParameter.OutputOnlyInsert
            };
            List <Mapper> columns = MappingManager.GetMappers <Model>(null, dp);

            foreach (Mapper column in columns)
            {
                buf.Append(UserProvider.QuoteExpression(column.Name)).Append(",");
            }
            buf.Remove(buf.Length - 1, 1);
            buf.Append(" FROM ").Append(SystemTableName).Append(" ");
            GDAParameter[] parameters = new GDAParameter[properties.Count];
            int            i          = 0;

            foreach (Mapper mapper in properties)
            {
                if (sqlParam != "")
                {
                    sqlParam += " AND ";
                }
                parameters[i] = new GDAParameter(UserProvider.ParameterPrefix + mapper.Name + UserProvider.ParameterSuffix, typeof(Model).GetProperty(mapper.PropertyMapper.Name).GetValue(objData, null));
                sqlParam     += UserProvider.QuoteExpression(mapper.Name) + "=" + parameters[i].ParameterName;
                i++;
            }
            buf.Append("WHERE ").Append(sqlParam);
            return(RecoverData(session, objData, buf.ToString(), parameters));
        }
Пример #4
0
        /// <summary>
        /// Remove o item do BD baseando na chave passada.
        /// </summary>
        /// <param name="key">Valor da chave da model.</param>
        /// <returns>N�mero de linhas afetadas.</returns>
        /// <exception cref="GDAException"></exception>
        public int DeleteByKey(uint key)
        {
            List <Mapper> listAttr = MappingManager.GetMappers <Model>(new PersistenceParameterType[] {
                PersistenceParameterType.Key,
                PersistenceParameterType.IdentityKey
            }, new DirectionParameter[] {
                DirectionParameter.Output,
                DirectionParameter.InputOptionalOutput,
                DirectionParameter.InputOutput
            });

            if (listAttr.Count == 0)
            {
                throw new GDAException("There isn't more one primary key identify for object \"" + typeof(Model).FullName + "\"");
            }
            else if (listAttr.Count > 1)
            {
                throw new GDAException("There is more one primary key identify for object \"" + typeof(Model).FullName + "\"");
            }
            Model  objDelete = new Model();
            object val       = null;

            try
            {
                val = typeof(Convert).GetMethod("To" + listAttr[0].PropertyMapper.PropertyType.Name, new Type[] {
                    typeof(uint)
                }).Invoke(null, new object[] {
                    key
                });
            }
            catch (Exception ex)
            {
                throw new GDAException("Type key not compatible with uint.", ex);
            }
            listAttr[0].PropertyMapper.SetValue(objDelete, val, null);
            return(Delete(objDelete));
        }
Пример #5
0
        /// <summary>
        /// Recupera os dados do objeto submetido com base na consulta fornecida.
        /// </summary>
        /// <param name="session">Sess�o utilizada para a execu��o do comando.</param>
        /// <param name="objData">Objeto onde os valores ser�o atribuidos.</param>
        /// <param name="sqlQuery">Consulta para a recupera��o dos dados.</param>
        /// <param name="parameters">Parametros utilizados na consulta.</param>
        /// <returns>Objecto com os valores da recupera��o j� atribu�dos.</returns>
        public Model RecoverData(GDASession session, Model objData, string sqlQuery, params GDAParameter[] parameters)
        {
            IDbConnection conn    = CreateConnection(session);
            IDbCommand    cmd     = CreateCommand(session, conn);
            string        newName = null;

            if (parameters != null)
            {
                for (int i = 0; i < parameters.Length; i++)
                {
                    try
                    {
                        newName = (parameters[i].ParameterName[0] != '?' ? parameters[i].ParameterName : UserProvider.ParameterPrefix + parameters[i].ParameterName.Substring(1) + UserProvider.ParameterSuffix);
                    }
                    catch (Exception ex)
                    {
                        throw new GDAException("Error on make parameter name '" + parameters[i].ParameterName + "'.", ex);
                    }
                    sqlQuery = sqlQuery.Replace(parameters[i].ParameterName, newName);
                    cmd.Parameters.Add(GDA.Helper.GDAHelper.ConvertGDAParameter(cmd, parameters[i], UserProvider));
                }
            }
            cmd.CommandText = sqlQuery;
            if (session == null && conn.State != ConnectionState.Open)
            {
                try
                {
                    conn.Open();
                }
                catch (Exception ex)
                {
                    throw new GDAException(ex);
                }
                GDAConnectionManager.NotifyConnectionOpened(conn);
            }
            IDataReader dReader = null;

            try
            {
                SendMessageDebugTrace("CommandText: " + cmd.CommandText);
                using (var executionHandler = Diagnostics.GDATrace.CreateExecutionHandler(cmd))
                    try
                    {
                        dReader = cmd.ExecuteReader();
                    }
                    catch (Exception ex)
                    {
                        ex = new GDAException(ex);
                        executionHandler.Fail(ex);
                        throw ex;
                    }
                if (dReader.Read())
                {
                    var mapping = new TranslatorDataInfoCollection(MappingManager.GetMappers <Model>(null, null));
                    mapping.ProcessFieldsPositions(dReader);
                    IDataRecord record = dReader;
                    RecoverValueOfResult(ref record, mapping, ref objData, false);
                }
                else
                {
                    throw new ItemNotFoundException("Item not found with submited parameters.");
                }
            }
            finally
            {
                if (dReader != null)
                {
                    dReader.Close();
                }
                if (session == null)
                {
                    try
                    {
                        conn.Close();
                        conn.Dispose();
                    }
                    catch
                    {
                        SendMessageDebugTrace("Error close connection.");
                    }
                }
            }
            return(objData);
        }
Пример #6
0
 /// <summary>
 /// Constrói o resultado com as informações que serão processadas.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <returns></returns>
 public override QueryReturnInfo BuildResultInfo <T>(GDA.Interfaces.IProviderConfiguration configuration)
 {
     return(new QueryReturnInfo(Parser2(configuration.Provider, parameters), parameters, MappingManager.GetMappers <T>(null, null)));
 }