Exemplo n.º 1
0
        /// <summary>
        /// Sum Query Builder
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="conditionalOptions"></param>
        /// <param name="column"></param>
        /// <param name="fields"></param>
        /// <param name="values"></param>
        /// <returns></returns>
        internal static int BuildSum <T>(ConditionalOptions conditionalOptions, string column, string[] fields, object[] values)
        {
            string query;

            query = $"SELECT SUM(`{column}`) AS `Sum` FROM ";

            Type type = typeof(T);

            // Table Name

            if (!(type.GetCustomAttributes(typeof(SqlTableAttribute), true).FirstOrDefault() is SqlTableAttribute table))
            {
                Logger.Verbose($"SqlTableAttribute was not found on object type: {type}");
                return(0);
            }

            SqlObject sqlObject = new SqlObject
            {
                Table = table.TableName
            };

            query += $"`{Configuration.MySqlDatabase}`.`{sqlObject.Table}`";

            int iter = 1;

            switch (conditionalOptions)
            {
            case ConditionalOptions.NONE:
                break;

            case ConditionalOptions.BY_ID:
                query += $" WHERE {Converter.GetPrimaryPropertyColumnName(type)} = @param1;";
                break;

            case ConditionalOptions.WHERE:
                query += $" WHERE ";

                iter = 1;
                foreach (string fie in fields)
                {
                    if (iter != 1)
                    {
                        query += " AND ";
                    }

                    query += $"`{fie}` = @param{iter}";
                    iter++;
                }
                break;

            case ConditionalOptions.WHERENULL:
                query += $" WHERE ";

                iter = 1;
                foreach (string fie in fields)
                {
                    if (iter != 1)
                    {
                        query += " AND ";
                    }

                    query += $"`{fie}` IS NULL";
                    iter++;
                }
                break;

            default:
                break;
            }

            query += ";";

            sqlObject.CommandText = query;

            return(SqlFunc.Sum(sqlObject, values));
        }
Exemplo n.º 2
0
        /// <summary>
        /// Update Record by ID
        /// </summary>
        /// <param name="sqlObject"></param>
        internal static void Row_Update_ID(SqlObject sqlObject, string singleField)
        {
            using (MySqlConnection sqlConnection = new MySqlConnection(ConnectionString))
            {
                sqlConnection.Open();

                using (MySqlCommand Command = sqlConnection.CreateCommand())
                {
                    Command.CommandText = sqlObject.CommandText;

                    if (string.IsNullOrEmpty(singleField))
                    {
                        int paramCount = 1;
                        foreach (SqlColumn col in sqlObject.Items)
                        {
                            MySqlParameter param = new MySqlParameter
                            {
                                ParameterName = $"@param{paramCount}",
                                MySqlDbType   = col.Type,
                                Value         = col.Value
                            };
                            Command.Parameters.Add(param);
                            paramCount++;
                        }
                    }
                    else
                    {
                        foreach (SqlColumn col in sqlObject.Items)
                        {
                            if (col.PropertyName.Contains(singleField))
                            {
                                MySqlParameter param = new MySqlParameter
                                {
                                    ParameterName = $"@param1",
                                    MySqlDbType   = col.Type,
                                    Value         = col.Value
                                };
                                Command.Parameters.Add(param);
                                break;
                            }
                        }
                    }

                    Logger.Verbose(Command.CommandText);

                    try
                    {
                        if (Command.ExecuteNonQuery() > 0)
                        {
                            return;
                        }
                    }
                    catch (MySqlException ex)
                    {
                        Logger.Verbose($"MySQL Error Code: {ex.Number}");
                        Logger.Error(ex);

                        if (ex.Number == 1054)
                        {
                            // Unknown column 'field' in 'field list'
                            string columnName = "";
                            foreach (SqlColumn col in sqlObject.Items)
                            {
                                if (ex.Message.Contains($"'{col.ColumnName}'"))
                                {
                                    columnName = col.ColumnName; break;
                                }
                            }
                            Logger.Verbose($"Looks like we don't have a column for `{sqlObject.Table}.{columnName}`, let's create that.");
                            bool tableCreated = Table_Alter_Add_Column(sqlObject.Table, columnName, sqlObject);
                            Logger.Verbose($"MySql Table `{Configuration.MySqlDatabase}`.`{sqlObject.Table}` Altered: Column {columnName} Added");
                            Row_Update_ID(sqlObject, singleField);
                        }

                        return;
                    }

                    return;
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Select Query Builder
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="selectOptions"></param>
        /// <param name="convertTo"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        internal static List <T> BuildSelect <T>(SelectOptions selectOptions, ConditionalOptions conditionalOptions, string[] columns, string[] fields, object[] values, Type convertTo = null, WhereOption whereOption = WhereOption.EQUAL, SelectLimiter limit = null)
        {
            string query;

            if (selectOptions == SelectOptions.FIELDS)
            {
                query = $"SELECT `{string.Join("`, `", columns)}` FROM ";
            }
            else
            {
                query = $"SELECT * FROM ";
            }

            Type type = convertTo ?? typeof(T);

            // Table Name

            if (!(type.GetCustomAttributes(typeof(SqlTableAttribute), true).FirstOrDefault() is SqlTableAttribute table))
            {
                Logger.Verbose($"SqlTableAttribute was not found on object type: {type}");
                return(new List <T>());
            }

            SqlObject sqlObject = new SqlObject
            {
                Table = table.TableName
            };

            query += $"`{Configuration.MySqlDatabase}`.`{sqlObject.Table}`";

            switch (conditionalOptions)
            {
            case ConditionalOptions.NONE:
                break;

            case ConditionalOptions.BY_ID:
                query += $" WHERE {Converter.GetPrimaryPropertyColumnName(type)} = @param1";
                break;

            case ConditionalOptions.WHERE:
                query += $" WHERE ";

                int iter = 1;
                foreach (string fie in fields)
                {
                    if (iter != 1)
                    {
                        query += " AND ";
                    }

                    switch (whereOption)
                    {
                    case WhereOption.EQUAL:
                        query += $"`{fie}` = @param{iter}";
                        break;

                    case WhereOption.NOTEQUAL:
                        query += $"`{fie}` != @param{iter}";
                        break;

                    case WhereOption.GREATERTHAN:
                        query += $"`{fie}` > @param{iter}";
                        break;

                    case WhereOption.LESSTHAN:
                        query += $"`{fie}` < @param{iter}";
                        break;

                    default:
                        throw new ArgumentNullException("Invalid or Missing WhereOption");
                    }

                    iter++;
                }
                break;

            case ConditionalOptions.WHERENULL:
                query += $" WHERE `{fields[0]}` IS NULL";
                break;

            default:
                break;
            }

            if (limit != null)
            {
                query += limit.QueryData;
            }
            else
            {
                query += ";";
            }

            sqlObject.CommandText = query;

            List <T> objects;

            switch (selectOptions)
            {
            case SelectOptions.ALL:
                switch (conditionalOptions)
                {
                case ConditionalOptions.NONE:
                    objects = SqlFunc.Select <T>(sqlObject, null);
                    break;

                case ConditionalOptions.BY_ID:
                    objects = SqlFunc.Select <T>(sqlObject, null, values);
                    break;

                case ConditionalOptions.WHERE:
                    objects = SqlFunc.Select <T>(sqlObject, null, values);
                    break;

                case ConditionalOptions.WHERENULL:
                    objects = SqlFunc.Select <T>(sqlObject, null, values);
                    break;

                default:
                    Logger.Verbose("Conditional Select Error");
                    objects = new List <T>();
                    break;
                }
                break;

            case SelectOptions.FIELDS:
                switch (conditionalOptions)
                {
                case ConditionalOptions.NONE:
                    objects = SqlFunc.Select <T>(sqlObject, columns);
                    break;

                case ConditionalOptions.BY_ID:
                    objects = SqlFunc.Select <T>(sqlObject, columns, values);
                    break;

                case ConditionalOptions.WHERE:
                    objects = SqlFunc.Select <T>(sqlObject, columns, values);
                    break;

                case ConditionalOptions.WHERENULL:
                    objects = SqlFunc.Select <T>(sqlObject, columns, values);
                    break;

                default:
                    Logger.Verbose("Conditional Select Error");
                    objects = new List <T>();
                    break;
                }
                break;

            default:
                Logger.Verbose("Select Type Error");
                objects = new List <T>();
                break;
            }

            foreach (T obj in objects)
            {
                foreach (PropertyInfo property in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
                {
                    object[] attributes = property.GetCustomAttributes(false);

                    object column = attributes
                                    .FirstOrDefault(x => x.GetType() == typeof(SqlColumnAttribute));

                    if (column != null)
                    {
                        SqlColumnAttribute col = column as SqlColumnAttribute;

                        // Should we be getting this derived property? If not, skip
                        if (selectOptions == SelectOptions.FIELDS && !columns.Contains(col.ColumnName))
                        {
                            continue;
                        }

                        if (col.IsTable)
                        {
                            List <object> data = BuildSelect <object>(SelectOptions.ALL, ConditionalOptions.WHERE, null, new string[] { col.AttachedTable }, new string[] { SqlFunc.ReflectPrimary(obj).ToString() }, property.PropertyType);
                            if (data.Count > 0)
                            {
                                property.SetValue(obj, data[0]);
                            }
                            else
                            {
                                Logger.Verbose($"Dataset for {property.PropertyType} had no value...");
                            }
                        }
                        else if (property.PropertyType != typeof(byte[]) && typeof(IList).IsAssignableFrom(property.PropertyType))
                        {
                            Type listOf = property.PropertyType.GetGenericArguments()[0];
                            property.SetValue(obj, Activator.CreateInstance(property.PropertyType));

                            foreach (object item in BuildSelect <object>(SelectOptions.ALL, ConditionalOptions.WHERE, null, new string[] { col.AttachedTable }, new string[] { SqlFunc.ReflectPrimary(obj).ToString() }, listOf))
                            {
                                (property.GetValue(obj) as IList).Add(item);
                            }
                        }
                    }
                }
            }

            return(objects);
        }