its been a while since ive posted.
Im migrating our rails server from 4 to 7, and I'm running into an issue where some now gone developers made a change to get Active Record to convert values to their bit versions for bit fields. But now that I've made the change I doesn't seem to be registering anymore. here's the fix that used to work:
ActiveRecord::ConnectionAdapters::Mysql2Adapter::NATIVE_DATABASE_TYPES[:binary][:name] = "bit"
# -- Don't quote the binary that gets dumped
ActiveRecord::ConnectionAdapters::Mysql2Adapter.class_eval do
def quote(value, column=nil)
if column && column.type.to_s == :binary.to_s
byebug
# TODO we should normalize our handling of "b'0' and "b'1'""
value = false if value == "\x00" # || "b'0'"
value = true if value == "\x01"# || "b'1'"
# ASCII-8BIT strings (that aren't already bit strings) should be converted to MSB bit strings
value = "b'#{value.unpack('B*')[0]}'" if Encoding.compatible?(value, Encoding::ASCII_8BIT) && !value.match(/^b'[01]+'$/)
# HACK: because our _version tables do not have a default value
# for is_deleted, a NOT NULL column, we need this hack until they are added
# The :NULL symbol is needed because nil is not recognized
# Once redacted is completed, we can just do value || :NULL and remove the hack
value || :NULL
value || 0
elsif !column && value == "b'0'"
false
elsif !column && value == "b'1'"
true
else
super(value)
end
end
end
Now when i debug i can see it going into quote... but it never goes into if column && column.type.to_s == :binary.to_s... and when printing it out it seems that column is always nil. Im not sure what to do to get this going for bit types.
EDIT: without this working, this is the kind of sql that gets produced, and you can see, somehow true/false gets turned into x'74727566':
SELECT `user`.* FROM `user` INNER JOIN `definer` ON `definer`.`is_deleted` = x'66616c7365' AND `definer`.`id` = `user`.`employer_id` WHERE `user`.`is_enabled` = x'74727565' AND `definer`.`is_active` = x'74727565' AND `user`.`id` = 1 LIMIT 1
edit2: this is exactly what i want: Rails / ActiveRecord working with mysql BIT
But there's too much code to add this to every bit property for every model i work with, i need to do this for every bit type, even raw sql.
Im trying to replicate the searching list style of crunchbase using ruby on rails.
I have an array of filters that looks something like this:
[
{
"id":"0",
"className":"Company",
"field":"name",
"operator":"starts with",
"val":"a"
},
{
"id":"1",
"className":"Company",
"field":"hq_city",
"operator":"equals",
"val":"Karachi"
},
{
"id":"2",
"className":"Category",
"field":"name",
"operator":"does not include",
"val":"ECommerce"
}
]
I send this json string to my ruby controller where I have implemented this logic:
filters = params[:q]
table_names = {}
filters.each do |filter|
filter = filters[filter]
className = filter["className"]
fieldName = filter["field"]
operator = filter["operator"]
val = filter["val"]
if table_names[className].blank?
table_names[className] = []
end
table_names[className].push({
fieldName: fieldName,
operator: operator,
val: val
})
end
table_names.each do |k, v|
i = 0
where_string = ''
val_hash = {}
v.each do |field|
if i > 0
where_string += ' AND '
end
where_string += "#{field[:fieldName]} = :#{field[:fieldName]}"
val_hash[field[:fieldName].to_sym] = field[:val]
i += 1
end
className = k.constantize
puts className.where(where_string, val_hash)
end
What I do is, I loop over the json array and create a hash with keys as table names and values are the array with the name of the column, the operator and the value to apply that operator on. So I would have something like this after the table_names hash is created:
{
'Company':[
{
fieldName:'name',
operator:'starts with',
val:'a'
},
{
fieldName:'hq_city',
operator:'equals',
val:'karachi'
}
],
'Category':[
{
fieldName:'name',
operator:'does not include',
val:'ECommerce'
}
]
}
Now I loop over the table_names hash and create a where query using the Model.where("column_name = :column_name", {column_name: 'abcd'}) syntax.
So I would be generating two queries:
SELECT "companies".* FROM "companies" WHERE (name = 'a' AND hq_city = 'b')
SELECT "categories".* FROM "categories" WHERE (name = 'c')
I have two problems now:
1. Operators:
I have many operators that can be applied on a column like 'starts with', 'ends with', 'equals', 'does not equals', 'includes', 'does not includes', 'greater than', 'less than'. I am guessing the best way would be to do a switch case on the operator and use the appropriate symbol while building the where string. So for example, if the operator is 'starts with', i'd do something like where_string += "#{field[:fieldName]} like %:#{field[:fieldName]}" and likewise for others.
So is this approach correct and is this type of wildcard syntax allowed in this kind of .where?
2. More than 1 table
As you saw, my approach builds 2 queries for more than 2 tables. I do not need 2 queries, I need the category name to be in the same query where the category belongs to the company.
Now what I want to do is I need to create a query like this:
Company.joins(:categories).where("name = :name and hq_city = :hq_city and categories.name = :categories[name]", {name: 'a', hq_city: 'Karachi', categories: {name: 'ECommerce'}})
But this is not it. The search can become very very complex. For example:
A Company has many FundingRound. FundingRound can have many Investment and Investment can have many IndividualInvestor. So I can select create a filter like:
{
"id":"0",
"className":"IndividualInvestor",
"field":"first_name",
"operator":"starts with",
"val":"za"
}
My approach would create a query like this:
SELECT "individual_investors".* FROM "individual_investors" WHERE (first_name like %za%)
This query is wrong. I want to query the individual investors of the investments of the funding round of the company. Which is a lot of joining tables.
The approach that I have used is applicable to a single model and cannot solve the problem that I stated above.
How would I solve this problem?
You can create a SQL query based on your hash. The most generic approach is raw SQL, which can be executed by ActiveRecord.
Here is some concept code that should give you the right idea:
query_select = "select * from "
query_where = ""
tables = [] # for selecting from all tables
hash.each do |table, values|
table_name = table.constantize.table_name
tables << table_name
values.each do |q|
query_where += " AND " unless query_string.empty?
query_where += "'#{ActiveRecord::Base.connection.quote(table_name)}'."
query_where += "'#{ActiveRecord::Base.connection.quote(q[fieldName)}'"
if q[:operator] == "starts with" # this should be done with an appropriate method
query_where += " LIKE '#{ActiveRecord::Base.connection.quote(q[val)}%'"
end
end
end
query_tables = tables.join(", ")
raw_query = query_select + query_tables + " where " + query_where
result = ActiveRecord::Base.connection.execute(raw_query)
result.to_h # not required, but raw results are probably easier to handle as a hash
What this does:
query_select specifies what information you want in the result
query_where builds all the search conditions and escapes input to prevent SQL injections
query_tables is a list of all the tables you need to search
table_name = table.constantize.table_name will give you the SQL table_name as used by the model
raw_query is the actual combined sql query from the parts above
ActiveRecord::Base.connection.execute(raw_query) executes the sql on the database
Make sure to put any user submitted input in quotes and escape it properly to prevent SQL injections.
For your example the created query will look like this:
select * from companies, categories where 'companies'.'name' LIKE 'a%' AND 'companies'.'hq_city' = 'karachi' AND 'categories'.'name' NOT LIKE '%ECommerce%'
This approach might need additional logic for joining tables that are related.
In your case, if company and category have an association, you have to add something like this to the query_where
"AND 'company'.'category_id' = 'categories'.'id'"
Easy approach: You can create a Hash for all pairs of models/tables that can be queried and store the appropriate join condition there. This Hash shouldn't be too complex even for a medium-sized project.
Hard approach: This can be done automatically, if you have has_many, has_one and belongs_to properly defined in your models. You can get the associations of a model using reflect_on_all_associations. Implement a Breath-First-Search or Depth-First Search algorithm and start with any model and search for matching associations to other models from your json input. Start new BFS/DFS runs until there are no unvisited models from the json input left. From the found information, you can derive all join conditions and then add them as expressions in the where clause of the raw sql approach as explained above. Even more complex, but also doable would be reading the database schema and using a similar approach as defined here by looking for foreign keys.
Using associations: If all of them are associated with has_many / has_one, you can handle the joins with ActiveRecord by using the joins method with inject on the "most significant" model like this:
base_model = "Company".constantize
assocations = [:categories] # and so on
result = assocations.inject(base_model) { |model, assoc| model.joins(assoc) }.where(query_where)
What this does:
it passes the base_model as starting input to Enumerable.inject, which will repeatedly call input.send(:joins, :assoc) (for my example this would do Company.send(:joins, :categories) which is equivalent to `Company.categories
on the combined join, it executes the where conditions (constructed as described above)
Disclaimer The exact syntax you need might vary based on the SQL implementation you use.
Full blown SQL string is a security issue, because it exposes your application to a SQL injection attack. If you can get your way around this, it is completely ok to make those query concatenations, as long as you make them compatible with your DB(yes, this solution is DB specific).
Other than that you can make some field that marks some querys as joined, as I have mentioned in the comment, you would have some variable to mark the desired table to be the output of the query, something like:
[
{
"id":"1",
"className":"Category",
"field":"name",
"operator":"does not include",
"val":"ECommerce",
"queryModel":"Company"
}
]
Which, when processing the query, you would use to output the result of this query as the queryModel instead of the className, in those cases the className would be used only to join the table conditions.
I would suggest altering your JSON data. Right now you only send name of the model, without the context, it would be easier if your model would have context.
In your example data would have to look like
data = [
{
id: '0',
className: 'Company',
relation: 'Company',
field: 'name',
operator: 'starts with',
val: 'a'
},
{
id: '1',
className: 'Category',
relation: 'Company.categories',
field: 'name',
operator: 'equals',
val: '12'
},
{
id: '3',
className: 'IndividualInvestor',
relation: 'Company.founding_rounds.investments.individual_investors',
field: 'name',
operator: 'equals',
val: '12'
}
]
And you send this data to QueryBuilder
query = QueryBuilder.new(data)
results = query.find_records
Note: find_records returns array of hashes per model on which you execute query.
For example it would return [{Company: [....]]
class QueryBuilder
def initialize(data)
#data = prepare_data(data)
end
def find_records
queries = #data.group_by {|e| e[:model]}
queries.map do |k, v|
q = v.map do |f|
{
field: "#{f[:table_name]}.#{f[:field]} #{read_operator(f[:operator])} ?",
value: value_based_on_operator(f[:val], f[:operator])
}
end
db_query = q.map {|e| e[:field]}.join(" AND ")
values = q.map {|e| e[:value]}
{"#{k}": k.constantize.joins(join_hash(v)).where(db_query, *values)}
end
end
private
def join_hash(array_of_relations)
hash = {}
array_of_relations.each do |f|
hash.merge!(array_to_hash(f[:joins]))
end
hash.map do |k, v|
if v.nil?
k
else
{"#{k}": v}
end
end
end
def read_operator(operator)
case operator
when 'equals'
'='
when 'starts with'
'LIKE'
end
end
def value_based_on_operator(value, operator)
case operator
when 'equals'
value
when 'starts with'
"%#{value}"
end
end
def prepare_data(data)
data.each do |record|
record.tap do |f|
f[:model] = f[:relation].split('.')[0]
f[:joins] = f[:relation].split('.').drop(1)
f[:table_name] = f[:className].constantize.table_name
end
end
end
def array_to_hash(array)
if array.length < 1
{}
elsif array.length == 1
{"#{array[0]}": nil}
elsif array.length == 2
{"#{array[0]}": array[1]}
else
{"#{array[0]}": array_to_hash(array.drop(1))}
end
end
end
I feel you are over complicating things by having one single controller for everything. I would create a controller for every model or entity that you would want to show and then implement the filters like you said.
Implementing a dynamic where and order by is not very hard but if, as you said, you need to have also the logic to implement some joins you are not only over complicating the solution (because you will have to keep this controller updated every time you add a new model, entity or change the basic logic) but you are also enabling people start playing with your data.
I am not very familiar with Rails so sadly I cannot give you any specific cde other than saying that your approach seems OK to me. I would explode it into multiple controllers.
I am wondering if it is possible to use a mathematical operator for a variable in a prepared mysql statement? I have written what I think it would look like below (albeit it doesn't work, I get "Call to a member function bind_param() on a non-object").
$result = $mysqli->prepare("SELECT t.column FROM table t WHERE t.value ( ? ) ( ? );");
$result->bind_param('ss', $operator, $value);
$result->execute();
I am using this along with an if statement that changes the operator value based on if a radio button is checked on the greater or less than value. Like below.
if (isset($_POST["abovebelow"]) && $_POST["abovebelow"] == "Above"){
$operator = ">";
}
elseif (isset($_POST["abovebelow"]) && $_POST["abovebelow"] == "Below"){
$operator = "<";
}
elseif (!isset($_POST["abovebelow"])){
$operator = "=";
}
You have only 2 variables in your query string but you bind 3 values, so that isn't right in the first place.Then you shouldn't add the operator like that, better do like this:
if (isset($_POST["abovebelow"]) && $_POST["abovebelow"] == "Above"){
$operator = ">";
}
elseif (isset($_POST["abovebelow"]) && $_POST["abovebelow"] == "Below"){
$operator = "<";
}
elseif (!isset($_POST["abovebelow"])){
$operator = "=";
}
$result = $mysqli->prepare("SELECT t.column FROM table t WHERE t.value".$operator." ? ;");
$result->bind_param($value);
$result->execute();
The short answer is, "No, you can't do that."
The long answer is, "No, you can't do that." Among other reasons is that the complier must be able to parse the complete query, which means it must know the operators at parse time.
Emil Borconi suggests a good work-around, that you could insert the operator into the text of the query, and then prepare it.
No, it's not possible. Placeholders in a prepared statement are only allowed in places where expressions are allowed. So you can't use a placeholder for a table or column name, and you can't use it for syntactical elements like operators.
If you need to substitute those things dynamically, you need to use string operations in PHP, not prepared statement placeholders.
This question already has answers here:
ActiveRecord OR query Hash notation
(2 answers)
Closed 7 years ago.
I am trying to specify the index view in my controller with a where or clause. Right now, the code is only returning the condition before the ||, if it finds that.
My code:
def index
#trades = Trade.where(grower_id: session[:user_id]) ||
Trade.where(consumer_id: session[:user_id])
end
I've tried:
#trades = Trade.where(grower_id: session[:user_id]).or(Trade.where(consumer_id: session[:user_id]))
and:
#trades = Trade.where(grower_id: session[:user_id]) ||=(Trade.where(consumer_id: session[:user_id]))
I also checked out this response, but those suggestions aren't working.
Any help would be greatly appreciated!
Active Record Query does not support or clause in Rails 4. But, it's coming in Rails 5. If you want to use or clause in your >= Rails 4.2 application for Active Record queries, you can use the where-or gem. Then, you can have your Active Record query like this:
#trades = Trade.where(grower_id: session[:user_id]).or(Trade.where(consumer_id: session[:user_id]))
To explain the behaviour of this code:
def index
#trades = Trade.where(grower_id: session[:user_id]) ||
Trade.where(consumer_id: session[:user_id])
end
|| (logical or operator) will look at the value of the first expression, if it's present i.e. if it's not nil or false, then will return the value. If not, only then it goes to the next expression to evaluate. That's why you are seeing that behavior which is expected. See this post for some more details on how logical or operator (||) works.
Now, to fix your problem, you can re-write your query using SQL:
def index
#trades = Trade.where('trades.grower_id = ? OR trades.consumer_id = ?', session[:user_id], session[:user_id])
end
As mu is too short pointed in the comment section, to avoid repetition in your code, you can also write the query this way:
def index
#trades = Trade.where('trades.grower_id = :user_id OR trades.consumer_id = :user_id', user_id: session[:user_id])
end
example model Users :
create_table "users"
t.string "name"
t.boolean "admin"
t.boolean "internal"
end
needs to be queried with "admin" or "internal" in the where clause of the SQL query. At the time of writing the query, it is not known which boolean will be used, so a variable, say usertype, is used to store the string "admin" or "internal". It basically means I would like to use a referenced attribute in my where clause.
Doing the following query :
User.select("id").where("#{usertype} = 't'")
works fine in my development sqlite database (since sqlite stores true as 't' and false as 'f'), but I guess that using the same query on another database (Mysql or Postrgres e.g.) might not work.
Alternatively I tried
User.select("id").where("#{usertype} = ?", true)
it also works and does not use the sqlite-specific 't'. However, is this a good and database independent solution ?
You should always use true or false (or variables or code which will evaluate 'truthy' or 'falsy`) and let rails handle the translation into however your DBMS stores booleans.
You do this in your second example
User.select("id").where("#{usertype} = ?", true)
So, the answer is "yes this is a good, database-independent solution". But, you can make it a bit neater: if all your conditions are of the "=" variety then you can use a hash, like
{:foo => "bar"}
{"foo" => "bar"}
which are both equivalent to
["foo = ?", "bar"]
This means in your case you can dispense with the string evalution and just pass your variable in.
User.select("id").where({usertype => true})
or, if you want to skip the optional { & }
User.select("id").where(usertype => true)
Edit: reply to comment about using a dynamically defined method in your ruby code, to get a value from an object.
You can use the send method to call the appropriate accessor on the object. For example,
#foo.bar == 123
is equivalent to
#foo.send("bar") == 123
So, in your example you would say
a.send(usertype)
As a sidenote, if you wanted to set the value of usertype (which i don't think would make sense in your case, but just an an illustration), you would need to call the "setter" version of the method, which would be either admin= or internal=. So, in this case you would need to use string evaluation:
#user.send("#{usertype}=", "foo")
which is like saying
#user.admin = "foo"
or
#user.internal = "foo"