Exemple #1
0
        /// <summary>
        /// Creates an instance of a dialect based on current connection instance.
        /// </summary>
        /// <param name="connection">Connection instance</param>
        internal static GeneralDialect CreateDialect(DbConnection connection)
        {
            Dictionary <string, Type> dialects = GetAvailableDialectsAndTypes();
            Type connectionType = connection.GetType();

            Exception notSupportedEx = null;

            foreach (Type dialectType in dialects.Values)
            {
                GeneralDialect dialect = (GeneralDialect)Activator.CreateInstance(dialectType);
                try
                {
                    if (dialect.ConnectionType.Equals(connectionType))
                    {
                        return(dialect);
                    }
                }
                catch (NotSupportedException ex)
                {
                    notSupportedEx = ex;
                }
            }

            throw new NotSupportedException("The connection type '" + connectionType.FullName + "' is not supported yet or its provider is not correctly installed.", notSupportedEx);
        }
        internal static Join[] GetPlainJoins(SearchOptions options, GeneralDialect dialect)
        {
            List <Join> list = new List <Join>();

            GetPlainJoins(options.Conditions, list);

            if (dialect != null)
            {
                foreach (ForeignKeyInfo fkInfo in options.eagerLoading.Keys)
                {
                    Join j = new Join(options.eagerLoading[fkInfo]);
                    j.ParentAlias      = null;              //will be used in future to make joins of other levels.
                    j.JoinMode         = JoinMode.LeftJoin; //left? are you right?
                    j.PropertyName     = fkInfo.RelatedProperty.Name;
                    j.ForeignTableInfo = TableInfo.CreateTableInfo(fkInfo.ElementType);
                    if (!list.Contains(j))
                    {
                        list.Add(j);
                    }
                }
            }

            foreach (Join join in list)
            {
                if (join.ForeignKey == null)
                {
                    SetProperty(list, join, options.baseType);
                }
            }
            return(list.ToArray());
        }
        /// <summary>
        /// Deletes instances of the passed type that match the conditions passed
        /// </summary>
        /// <param name="type">Type</param>
        /// <param name="conditions">Conditions</param>
        /// <param name="transaction">Transaction, in case the operation must belong to one</param>
        public static void Delete(Type type, ConditionCollection conditions, Transaction transaction)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            if (!type.IsSubclassOf(typeof(EntityBase)))
            {
                throw new InvalidTypeException(type, "type");
            }

            TableInfo table = TableInfo.CreateTableInfo(type);
            ConnectionStringSettings connection = table.GetConnection();
            GeneralDialect           dialect    = DialectFactory.CreateDialect(connection);

            Join[] joins = GetPlainJoins(conditions, type);

            TenorParameter[] parameters = null;
            string           query      = dialect.CreateDeleteSql(type, conditions, joins, out parameters);

            if (transaction != null && transaction.dbTransaction != null)
            {
                Helper.ExecuteQuery(query, parameters, transaction.dbTransaction, dialect);
            }
            else
            {
                Helper.UpdateData(connection, query, parameters);
            }
        }
Exemple #4
0
        internal static DbConnection CreateConnection(ConnectionStringSettings connection)
        {
            if (connection == null)
            {
                throw new NullReferenceException("connection");
            }
            GeneralDialect dialect = DialectFactory.CreateDialect(connection);

            return(CreateConnection(dialect, connection));
        }
Exemple #5
0
        internal static DbConnection CreateConnection(GeneralDialect dialect, ConnectionStringSettings connection)
        {
            if (dialect == null)
            {
                throw new NullReferenceException("dialect");
            }
            if (connection == null)
            {
                throw new NullReferenceException("connection");
            }

            string value = connection.ConnectionString;

            if (string.IsNullOrEmpty(value))
            {
                throw new ConfigurationErrorsException("An invalid (empty) connection string was set.");
            }

            if (value.Contains("{0}"))
            {
                string path = typeof(Helper).Assembly.GetName().CodeBase;

                if (path.StartsWith("file:///"))
                {
                    if (Path.DirectorySeparatorChar == '/')
                    {
                        path = new FileInfo(path.Substring(7)).DirectoryName;
                    }
                    else
                    {
                        path = new FileInfo(path.Substring(8).Replace("/", Path.DirectorySeparatorChar.ToString())).DirectoryName;
                    }
                }
                else
                {
                    path = Environment.CurrentDirectory;
                }
                value = string.Format(value, path);
            }

            DbConnection conn = dialect.Factory.CreateConnection();

            conn.ConnectionString = value;

            return(conn);
        }
        /// <summary>
        /// Saves this entity data on the persistence layer.
        /// </summary>
        /// <param name="isUpdate">Force an Update instead of an Insert statement.</param>
        /// <param name="connection">The connection.</param>
        /// <remarks>This method calls the Validate method and only continue if True is returned. You can override the Validate method to create entity validation logic.</remarks>
        public virtual void Save(bool isUpdate, ConnectionStringSettings connection)
        {
            if (Validate())
            {
                TableInfo table = TableInfo.CreateTableInfo(this.GetType());
                if (table == null)
                {
                    throw new MissingTableMetaDataException(this.GetType());
                }

                if (connection == null)
                {
                    connection = table.GetConnection();
                }

                TenorParameter[] parameters   = null;
                FieldInfo        autoKeyField = null;

                GeneralDialect dialect = null;
                string         query   = GetSaveSql(isUpdate, connection, null, out autoKeyField, out parameters, out dialect);

                string secondQuery = string.Empty;

                if (!isUpdate && autoKeyField != null && !dialect.GetIdentityOnSameCommand &&
                    !string.IsNullOrEmpty(dialect.IdentityAfterQuery))
                {
                    secondQuery = string.Format(dialect.IdentityAfterQuery, autoKeyField.InsertSQL);
                }


                object result;
                if (this.tenorTransaction != null && this.tenorTransaction.dbTransaction != null)
                {
                    result = Helper.ExecuteQuery(query + Helper.GoStatement + secondQuery, parameters, tenorTransaction.dbTransaction, dialect);
                }
                else
                {
                    result = Helper.UpdateData(connection, query + Helper.GoStatement + secondQuery, parameters);
                }

                if (!isUpdate && autoKeyField != null)
                {
                    autoKeyField.SetPropertyValue(this, Convert.ChangeType(result, autoKeyField.FieldType));
                }
            }
        }
Exemple #7
0
        internal static void OpenConnection(DbConnection connection, GeneralDialect dialect)
        {
            connection.Open();

            if (!string.IsNullOrEmpty(dialect.OnConnectCommand))
            {
                try
                {
                    using (System.Data.Common.DbCommand command = connection.CreateCommand())
                    {
                        command.CommandText    = dialect.OnConnectCommand;
                        command.CommandTimeout = Helper.DefaultTimeout;
                        command.ExecuteNonQuery();
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Unable to execute on connect command.", ex);
                }
            }
        }
Exemple #8
0
        /*
         * /// <summary>
         * /// Executes a query on the database.
         * /// </summary>
         * /// <param name="query">A SQL query to execute.</param>
         * /// <param name="parameters">Parameters collection.</param>
         * /// <param name="connection">The connection.</param>
         * public static object UpdateData(string query, TenorParameter[] parameters, ConnectionStringSettings connection)
         * {
         *  return UpdateData(query, parameters, connection, (string)null);
         * }
         */

        /// <summary>
        /// Executes a query on the database.
        /// </summary>
        /// <param name="query">A SQL query to execute.</param>
        /// <param name="parameters">Parameters collection.</param>
        /// <param name="connection">The connection.</param>
        public static object UpdateData(ConnectionStringSettings connection, string query, params TenorParameter[] parameters)
        {
            if (connection == null)
            {
                connection = EntityBase.SystemConnection;
            }

            GeneralDialect dialect = DialectFactory.CreateDialect(connection);

            DbConnection conn = CreateConnection(dialect, connection);

            DbTransaction transaction = null;

            try
            {
                OpenConnection(conn, dialect);
                transaction =
                    conn.BeginTransaction();
                object retVal = ExecuteQuery(query, parameters, transaction, dialect);

                transaction.Commit();
                return(retVal);
            }
            catch
            {
                if (transaction != null)
                {
                    transaction.Rollback();
                }
                throw;
            }
            finally
            {
                if (conn.State == System.Data.ConnectionState.Open)
                {
                    conn.Close();
                }
                conn.Dispose();
            }
        }
Exemple #9
0
        /// <summary>
        /// Persists a list on the database.
        /// </summary>
        /// <param name="propertyName">The name of a many-to-many property on this class.</param>
        public virtual void SaveList(string propertyName)
        {
            if (propertyName == null)
            {
                throw new ArgumentNullException("propertyName");
            }
            System.Reflection.PropertyInfo prop = this.GetType().GetProperty(propertyName);
            if (prop == null)
            {
                throw new ArgumentException(string.Format("The property '{0}' was not found on '{1}'.", propertyName, this.GetType().FullName), "propertyName");
            }
            ForeignKeyInfo fkInfo = ForeignKeyInfo.Create(prop);

            if (fkInfo == null)
            {
                throw new InvalidMappingException(this.GetType());
            }

            if (!fkInfo.IsManyToMany)
            {
                throw new TenorException("Currently, only many-to-many relations are supported");
            }


            TableInfo table = TableInfo.CreateTableInfo(this.GetType());

            if (table == null)
            {
                throw new InvalidMappingException(this.GetType());
            }

            ConnectionStringSettings connection = (tenorTransaction == null ? table.GetConnection() : tenorTransaction.Connection);
            GeneralDialect           dialect    = DialectFactory.CreateDialect(connection);

            TenorParameter[] parameters;
            DbTransaction    t = (tenorTransaction == null ? null : tenorTransaction.dbTransaction);

            //if (dialect.GetType() == typeof(Tenor.Data.Dialects.TSql.TSql))
            //{
            //    //oh god! do you have a better idea on where to write this code?
            //    System.Data.SqlClient.SqlBulkCopy bulk;
            //    if (t == null)
            //        bulk = new System.Data.SqlClient.SqlBulkCopy(tenorTransaction.Connection.ConnectionString);
            //    else
            //        bulk = new System.Data.SqlClient.SqlBulkCopy((System.Data.SqlClient.SqlConnection)t.Connection, System.Data.SqlClient.SqlBulkCopyOptions.Default, (System.Data.SqlClient.SqlTransaction)t);

            //    bulk.DestinationTableName = dialect.GetPrefixAndTable(fkInfo.ManyToManyTablePrefix, fkInfo.ManyToManyTable);
            //    System.Data.DataTable data;
            //    string sql = dialect.CreateSaveList(table, fkInfo, this, out parameters, out data);
            //    foreach (DataColumn col in data.Columns)
            //    {
            //        bulk.ColumnMappings.Add(col.ColumnName, col.ColumnName);
            //    }

            //    Helper.ExecuteQuery(sql, parameters, t, dialect);
            //    bulk.WriteToServer(data);
            //    bulk.Close();
            //}
            //else
            //{
            string sql = dialect.CreateSaveListSql(table, fkInfo, this, out parameters);

            Helper.ExecuteQuery(sql, parameters, t, dialect);
            //}
        }
Exemple #10
0
        /// <summary>
        /// Creates the SQL query based on conditions using the current dialect.
        /// Generally, you can call this method for debugging reasons.
        /// </summary>
        /// <param name="searchOptions">The search definitions.</param>
        /// <param name="connection">The Connection.</param>
        /// <param name="justCount">Indicates that this is a COUNT query.</param>
        /// <param name="skip">Number of rows to skip when paging</param>
        /// <param name="take">Number of rows to take when paging</param>
        /// <param name="parameters">Outputs the generated parameters.</param>
        /// <returns>A SQL query.</returns>
        public static string GetSearchSql(SearchOptions searchOptions, bool justCount, int?skip, int?take, ConnectionStringSettings connection, out TenorParameter[] parameters)
        {
            GeneralDialect dialect = DialectFactory.CreateDialect(connection);

            if (searchOptions == null)
            {
                throw (new ArgumentNullException("searchOptions", "You must specify a SearchOptions instance."));
            }

            TableInfo table = TableInfo.CreateTableInfo(searchOptions.baseType);

            if (connection == null)
            {
                connection = table.GetConnection();
            }

            //Read Projections
            List <Projection> projections = new List <Projection>();

            foreach (Projection p in searchOptions.Projections)
            {
                projections.Add(p);
            }

            //Read Joins

            List <Join> joins = new List <Join>();

            joins.AddRange(GetPlainJoins(searchOptions, dialect));



            //Get necessary fields to create the select statement.
            StringBuilder           sqlFields  = new StringBuilder();
            List <FieldInfo>        fieldInfos = new List <FieldInfo>();
            List <SpecialFieldInfo> spFields   = new List <SpecialFieldInfo>();
            List <FieldInfo>        lenFields  = new List <FieldInfo>();

            FieldInfo[] allFields;
            if (justCount)
            {
                allFields = EntityBase.GetFields(searchOptions.baseType, true); //lets count using distinct subquery
            }
            else if (searchOptions.Projections.Count > 0)
            {
                allFields = ReadProjections <FieldInfo>(projections, null, EntityBase.GetFields(searchOptions.baseType));
            }
            else
            {
                allFields = EntityBase.GetFields(searchOptions.baseType); //lets get all fields
            }
            foreach (FieldInfo f in allFields)
            {
                if (f.PrimaryKey || (!f.LazyLoading && !justCount)) //primary keys and eager fields must be loaded
                {
                    fieldInfos.Add(f);
                }
                else if (!justCount && f.LazyLoading && f.FieldType.IsAssignableFrom(typeof(BinaryStream)))
                {
                    lenFields.Add(f);
                }

                // when paging, at least one sorting criterion is needed
                if (skip.HasValue && take.HasValue && searchOptions.Sorting.Count == 0 && f.PrimaryKey)
                {
                    searchOptions.Sorting.Add(f.RelatedProperty.Name);
                }
            }

            if (!justCount) //we don't need it on counting
            {
                SpecialFieldInfo[] fields = EntityBase.GetSpecialFields(searchOptions.baseType);
                if (searchOptions.Projections.Count > 0)
                {
                    fields = ReadProjections <SpecialFieldInfo>(projections, null, fields);
                }

                spFields.AddRange(fields);
            }

            sqlFields.Append(dialect.CreateSelectSql(table.RelatedTable, null, fieldInfos.ToArray(), spFields.ToArray(), lenFields.ToArray()));


            //adding values from eager loading types
            foreach (ForeignKeyInfo fkInfo in searchOptions.eagerLoading.Keys)
            {
                fieldInfos = new List <FieldInfo>();
                spFields   = new List <SpecialFieldInfo>();
                lenFields  = new List <FieldInfo>();

                //select all fields, or only the projection.
                FieldInfo[] allEagerFields = EntityBase.GetFields(fkInfo.ElementType);
                if (searchOptions.Projections.Count > 0)
                {
                    allEagerFields = ReadProjections <FieldInfo>(projections, fkInfo.RelatedProperty.Name, allEagerFields);
                }

                foreach (FieldInfo f in allEagerFields)
                {
                    if (f.PrimaryKey || !f.LazyLoading)
                    {
                        fieldInfos.Add(f);
                    }
                    else if (f.LazyLoading && f.FieldType.IsAssignableFrom(typeof(BinaryStream)))
                    {
                        lenFields.Add(f);
                    }
                }
                //spfields
                SpecialFieldInfo[] allSpFields = EntityBase.GetSpecialFields(fkInfo.ElementType);
                if (searchOptions.Projections.Count > 0)
                {
                    allSpFields = ReadProjections <SpecialFieldInfo>(projections, fkInfo.RelatedProperty.Name, allSpFields);
                }

                spFields.AddRange(allSpFields);
                //joins: joins was made on GetPlainJoins.

                sqlFields.Append(", ");
                sqlFields.Append(dialect.CreateSelectSql(fkInfo.ElementType, searchOptions.eagerLoading[fkInfo], fieldInfos.ToArray(), spFields.ToArray(), lenFields.ToArray()));
            }


            //Sorting (not necessary for count queries)
            string sqlSort = string.Empty;

            if (!justCount)
            {
                string appendToSelect = null;

                sqlSort = dialect.CreateSortSql(searchOptions.Sorting, table.RelatedTable, joins.ToArray(), searchOptions.Distinct, skip.HasValue && take.HasValue, out appendToSelect);

                if (!string.IsNullOrEmpty(appendToSelect))
                {
                    sqlFields.Append(appendToSelect);
                }
            }

            //Check if we found all projections:
            if (projections.Count > 0)
            {
                throw new InvalidProjectionException(projections[0]);
            }


            //Creates the where part
            string sqlWhere = dialect.CreateWhereSql(searchOptions.Conditions, searchOptions.baseType, joins.ToArray(), out parameters);

            // Creates the join parts
            string sqlJoins = dialect.CreateJoinsSql(joins.ToArray());


            // Creates the entire sql string
            string sql = dialect.CreateFullSql(searchOptions.baseType, searchOptions.Distinct, justCount, searchOptions.Top, skip, take, sqlFields.ToString(), sqlJoins, sqlSort, sqlWhere);


            Tenor.Diagnostics.Debug.DebugSQL("GetSearchSql()", sql, parameters, connection);
#if DEBUG
            LastSearches.Push(sql);
#endif

            return(sql);
        }
Exemple #11
0
        /// <summary>
        /// Creates an update query of this entity data.
        /// </summary>
        /// <param name="isUpdate">Determines whether to update an existing record or create a new record.</param>
        /// <param name="parameters">Outputs an array of TenorParameter with required parameters.</param>
        /// <param name="autoKeyField">Outputs the autonumber FieldInfo.</param>
        /// <param name="specialValues">The special values can contains sql sentences/sequences/etc</param>
        /// <param name="connection">The Connection.</param>
        /// <param name="dialect"></param>
        /// <returns>Return a SQL query string.</returns>
        internal string GetSaveSql(bool isUpdate, ConnectionStringSettings connection, System.Collections.Specialized.NameValueCollection specialValues, out FieldInfo autoKeyField, out TenorParameter[] parameters, out GeneralDialect dialect)
        {
            Dictionary <FieldInfo, object> data = new Dictionary <FieldInfo, object>();

            TableInfo table = TableInfo.CreateTableInfo(this.GetType());

            if (connection == null)
            {
                connection = table.GetConnection();
            }

            dialect = DialectFactory.CreateDialect(connection);

            autoKeyField = null;
            ConditionCollection conditions = new ConditionCollection();

            List <FieldInfo> fieldInfos = new List <FieldInfo>(GetFields(this.GetType()));

            for (int i = fieldInfos.Count - 1; i >= 0; i--)
            {
                if (isUpdate && fieldInfos[i].PrimaryKey)
                {
                    if (conditions.Count != 0)
                    {
                        conditions.Add(LogicalOperator.And);
                    }
                    conditions.Add(fieldInfos[i].RelatedProperty.Name, fieldInfos[i].PropertyValue(this));

                    if (fieldInfos[i].AutoNumber)
                    {
                        autoKeyField = fieldInfos[i];
                        data.Add(fieldInfos[i], null);
                    }
                    else
                    {
                        fieldInfos.RemoveAt(i);
                    }
                }
                else if (fieldInfos[i].AutoNumber)
                {
                    autoKeyField = fieldInfos[i];
                    data.Add(fieldInfos[i], null);
                }
                else if (fieldInfos[i].LazyLoading && !propertyData.ContainsKey(fieldInfos[i].RelatedProperty.Name))
                {
                    fieldInfos.RemoveAt(i);
                }
                else
                {
                    var lazyValue = fieldInfos[i].PropertyValue(this);
                    if (lazyValue != null && lazyValue.GetType() == typeof(BinaryStream))
                    {
                        //binary stream will never change
                        fieldInfos.RemoveAt(i);
                    }
                    else
                    {
                        data.Add(fieldInfos[i], lazyValue);
                    }
                }
            }

            string sql = dialect.CreateSaveSql(this.GetType(), data, specialValues, conditions, out parameters) + dialect.LineEnding;

            if (dialect.GetIdentityOnSameCommand && !isUpdate && autoKeyField != null)
            {
                string queryFormat = @"{0}
{1}
{2}";

                string before = string.Empty;
                if (!string.IsNullOrEmpty(dialect.IdentityBeforeQuery))
                {
                    before = dialect.IdentityBeforeQuery + dialect.LineEnding;
                }

                string after = string.Empty;
                if (!string.IsNullOrEmpty(dialect.IdentityAfterQuery))
                {
                    after = string.Format(dialect.IdentityAfterQuery, autoKeyField.InsertSQL) + dialect.LineEnding;
                }

                sql = string.Format(queryFormat, before, sql, after);
            }

            return(sql);
        }
Exemple #12
0
        internal static object ExecuteQuery(string sql, TenorParameter[] parameters, DbTransaction transaction, GeneralDialect dialect)
        {
            DbConnection conn = transaction.Connection;
            DbCommand    cmd;

            try
            {
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    System.Text.StringBuilder traceInfo = new System.Text.StringBuilder();
                    traceInfo.AppendLine("Tenor.Data.Helper.ExecuteQuery()");
                    traceInfo.AppendLine(" > " + conn.ConnectionString);
                    if (parameters != null)
                    {
                        foreach (TenorParameter p in parameters)
                        {
                            if (p.Value == null)
                            {
                                traceInfo.AppendLine(" > " + p.ParameterName + ": (null)");
                            }
                            else
                            {
                                traceInfo.AppendLine(" > " + p.ParameterName + ": " + p.Value.ToString());
                            }
                        }
                    }
                    traceInfo.AppendLine(sql);

                    string st = Environment.StackTrace;
                    string endOfWhatDoesntMatter = "get_StackTrace()" + Environment.NewLine;
                    int    i = st.IndexOf(endOfWhatDoesntMatter);
                    if (i > 0)
                    {
                        st = st.Substring(i + endOfWhatDoesntMatter.Length);
                    }

                    traceInfo.AppendLine("Stack Trace:");
                    traceInfo.AppendLine(st);
                    traceInfo.AppendLine("---------------------");

                    System.Diagnostics.Trace.TraceInformation(traceInfo.ToString());
                }
            }
            catch (Exception ex)
            {
                Diagnostics.Debug.HandleError(ex);
            }

            string[] queries     = sql.Split(new string[] { GoStatement }, StringSplitOptions.RemoveEmptyEntries);
            object   returnValue = 0;
            bool     mustCommit  = false;

            if (transaction == null)
            {
                transaction = conn.BeginTransaction();
                mustCommit  = true;
            }
            try
            {
                foreach (string query in queries)
                {
                    cmd = conn.CreateCommand();

                    cmd.Transaction    = transaction;
                    cmd.CommandText    = query;
                    cmd.CommandTimeout = Helper.DefaultTimeout;

                    if (parameters != null)
                    {
                        foreach (TenorParameter param in parameters)
                        {
                            cmd.Parameters.Add(param.ToDbParameter(dialect.Factory));
                        }
                    }
                    object result = cmd.ExecuteScalar();
                    if (result != null && !result.Equals(DBNull.Value))
                    {
                        returnValue = result;
                    }
                }
            }
            catch
            {
                if (mustCommit)
                {
                    transaction.Rollback();
                }
                throw;
            }

            if (mustCommit)
            {
                transaction.Commit();
            }

            return(returnValue);
        }
Exemple #13
0
        /// <summary>
        /// Executes a query on the database and them returns a datatable.
        /// </summary>
        /// <param name="connectionString">The connection parameters.</param>
        /// <param name="sqlSelect">A SQL query to execute.</param>
        /// <param name="parameters">Parameters collection.</param>
        /// <returns>A <see cref="System.Data.DataTable">DataTable</see> with results of the query.</returns>
        public static DataTable QueryData(ConnectionStringSettings connectionString, string sqlSelect, params TenorParameter[] parameters)
        {
            if (connectionString == null)
            {
                throw new ArgumentNullException("connectionString");
            }
            GeneralDialect dialect = DialectFactory.CreateDialect(connectionString);


            DataTable dtRetorno = null;

            DbConnection conn = CreateConnection(dialect, connectionString);

            DbCommand    cmd = null;
            DbDataReader reader;

            try
            {
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    Tenor.Diagnostics.Debug.DebugSQL("Helper: ConsultarBanco()", sqlSelect, parameters, connectionString);
                }
            }
            catch (Exception ex)
            {
                Diagnostics.Debug.HandleError(ex);
            }


            try
            {
                cmd                = conn.CreateCommand();
                cmd.CommandText    = sqlSelect;
                cmd.CommandTimeout = Helper.DefaultTimeout;
                if (parameters != null)
                {
                    foreach (TenorParameter param in parameters)
                    {
                        cmd.Parameters.Add(param.ToDbParameter(dialect.Factory));
                    }
                }

                OpenConnection(conn, dialect);

                reader = cmd.ExecuteReader();
                if (reader != null)
                {
                    dtRetorno = new DataTable();
                    dtRetorno.Load(reader);
                }
            }
            catch (Exception up)
            {
                if (cmd != null && !up.Data.Contains("CommandText"))
                {
                    up.Data.Add("CommandText", cmd.CommandText);
                }
                throw (up);
            }
            finally
            {
                if (conn.State == System.Data.ConnectionState.Open)
                {
                    conn.Close();
                }
                conn.Dispose();
            }

            return(dtRetorno);
        }
        /// <summary>
        /// Checks if the entity already exists based on the properties passed and inserts if it doesn't. In case of canUpdate is true and the entity already exists, updates it to the current values.
        /// </summary>
        /// <param name="conditionalProperties">Properties to be considered when checking existence of the entity.</param>
        /// <param name="canUpdate">If true, specifies that if a record exists, it will be updated.</param>
        /// <param name="connection">The connection.</param>
        public virtual bool SaveConditional(string[] conditionalProperties, bool canUpdate, ConnectionStringSettings connection)
        {
            if (Validate())
            {
                if (conditionalProperties == null || conditionalProperties.Length == 0)
                {
                    throw new ArgumentNullException("conditionalProperties");
                }

                TableInfo table = TableInfo.CreateTableInfo(this.GetType());
                if (connection == null)
                {
                    connection = table.GetConnection();
                }


                FieldInfo[] fields = EntityBase.GetFields(this.GetType(), null, conditionalProperties);
                if (fields.Length != conditionalProperties.Length)
                {
                    throw new MissingFieldsException(this.GetType(), true);

                    /*
                     * throw (new ArgumentException("Cannot find one or more ConditionalFields", "conditionalProperties"));
                     */
                }


                FieldInfo[] fieldsPrimary = EntityBase.GetFields(this.GetType(), true);


                FieldInfo autoKeyField = null;

                TenorParameter[] parameters = null;

                GeneralDialect dialect = null;

                string insertQuery = GetSaveSql(false, connection, null, out autoKeyField, out parameters, out dialect);

                //updateQuery doesn't need parameters cause it's already set.\
                TenorParameter[] parameters2 = null;
                string           updateQuery = GetSaveSql(true, connection, null, out autoKeyField, out parameters2, out dialect);
                parameters2 = null;

                string query = dialect.CreateConditionalSaveSql(insertQuery, updateQuery, conditionalProperties, fieldsPrimary);

                DataTable result = Helper.QueryData(connection, query.ToString(), parameters);

                if (!canUpdate && System.Convert.ToInt32(result.Rows[0][0]) == -1)
                {
                    return(false);
                }
                else if (canUpdate && System.Convert.ToInt32(result.Rows[0][0]) == -1)
                {
                    return(false);
                }
                else
                {
                    if (autoKeyField != null)
                    {
                        autoKeyField.SetPropertyValue(this, Convert.ChangeType(result.Rows[0][0], autoKeyField.FieldType));
                    }
                    return(true);
                }
            }
            else
            {
                return(false);
            }
        }
Exemple #15
0
        /// <summary>
        /// Gets the value of a lazy tagged property.
        /// This call can do a database access.
        /// </summary>
        internal virtual object GetPropertyValue(string propertyName, bool forceGetBinary)
        {
            //only loads if not loaded yet.
            //TODO: provide a way to reload from database.
            lock (propertyData)
            {
                if (forceGetBinary || !propertyData.ContainsKey(propertyName))
                {
                    //Getting class metadata.

                    TableInfo table = TableInfo.CreateTableInfo(this.GetType());

                    System.Reflection.PropertyInfo fieldP = this.GetType().GetProperty(propertyName);
                    if (fieldP == null)
                    {
                        throw new Tenor.Data.MissingFieldException(this.GetType(), propertyName);
                    }

                    ForeignKeyInfo fkInfo = null;

                    fkInfo = ForeignKeyInfo.Create(fieldP);

                    if (fkInfo != null)
                    {
                        // this is an FK, so, route to fk loading
                        return(LoadForeign(fieldP, null));
                    }
                    else
                    {
                        //Continue to the lazy property (lazy fields like byte[]) loading
                        FieldInfo field = FieldInfo.Create(fieldP);
                        if (field == null)
                        {
                            throw new Tenor.Data.MissingFieldException(this.GetType(), fieldP.Name);
                        }

                        if (!forceGetBinary && (field.FieldType == typeof(BinaryStream) || field.FieldType == typeof(BinaryStream).BaseType))
                        {
                            propertyData[propertyName] = new BinaryStream(this, propertyName);
                        }
                        else
                        {
                            GeneralDialect dialect = DialectFactory.CreateDialect(table.GetConnection());


                            ConditionCollection conditions = new ConditionCollection();

                            foreach (FieldInfo f in GetFields(this.GetType(), true))
                            {
                                conditions.Add(f.RelatedProperty.Name, f.PropertyValue(this));
                            }
                            if (conditions.Count == 0)
                            {
                                throw (new Tenor.Data.MissingPrimaryKeyException(this.GetType()));
                            }

                            TenorParameter[] parameters = null;
                            string           fieldsPart = dialect.CreateSelectSql(table.RelatedTable, null, new FieldInfo[] { field }, null, null);
                            string           wherePart  = dialect.CreateWhereSql(conditions, table.RelatedTable, null, out parameters);
                            string           sql        = dialect.CreateFullSql(table.RelatedTable,
                                                                                false, false,
                                                                                0, fieldsPart, null, null, wherePart);

                            Tenor.Diagnostics.Debug.DebugSQL("GetPropertyValue()", sql, parameters, table.GetConnection());
#if DEBUG
                            LastSearches.Push(sql);
#endif
                            Tenor.Data.DataTable rs = new Tenor.Data.DataTable(sql, parameters, table.GetConnection());
                            rs.Bind();

                            if (rs.Rows.Count == 0)
                            {
                                throw (new RecordNotFoundException());
                            }
                            else if (rs.Rows.Count > 1)
                            {
                                throw new ManyRecordsFoundException();
                            }
                            else
                            {
                                var obj = rs.Rows[0][field.DataFieldName];
                                if (obj == DBNull.Value)
                                {
                                    obj = null;
                                }

                                if (forceGetBinary)
                                {
                                    if (obj == null)
                                    {
                                        return new byte[] { }
                                    }
                                    ;
                                    else
                                    {
                                        return(obj);
                                    }
                                }
                                else
                                {
                                    propertyData[propertyName] = obj;
                                }
                            }
                        }
                    }
                }
                return(propertyData[propertyName]);
            }
        }