How to use Rails with uppercase column name? - ruby-on-rails

I have the following as part of an AR query:
.having('COUNT(foo.id) > bar.maxUsers')
This generates an error:
ActiveRecord::StatementInvalid:
PG::UndefinedColumn: ERROR: column bar.maxusers does not exist
^
HINT: Perhaps you meant to reference the column "bar.maxUsers".
I am referencing the column bar.maxUsers.
So, apparently AR downcases the query. How to suppress this behavior?
Rails 4.2.10
PostgreSQL
EDIT: SQL:
SELECT ... HAVING COUNT(foo.id) > bar.maxUsers
So it is happening after the to_sql. Maybe from the execute?

This isn't an ActiveRecord or AREL issue, this is just how case sensitivity works in SQL and PostgreSQL.
Identifiers in SQL (such as table and column names) are case-insensitive unless they're quoted. Standard SQL says that unquoted identifiers are folded to upper case, PostgreSQL folds them to lower case, hence the bar.maxusers in the error message.
The solution is to quote the offending column name:
.having('COUNT(foo.id) > bar."maxUsers"')
Note that you must use double quotes for quoting the identifier as single quotes are only for string literals. Also note that identifier quoting is database-specific: standard SQL and PostgreSQL use double quotes, MySQL uses backticks, SQL Server uses brackets, ...

Related

Postgres weird PG::UndefinedColumn: ERROR: on value

While executing a simple select - where operation using activerecord execute,
ActiveRecord::Base.connection.execute('select * from spree_variants where sku = "1SB-E4196-00";')
I got this error:
from /Users/abc/.rvm/gems/ruby-2.7.2#cboparts/gems/activerecord-6.0.3.5/lib/active_record/connection_adapters/postgresql/database_statements.rb:92:in `exec'
Caused by PG::UndefinedColumn: ERROR: column "1SB-E4196-00" does not exist
LINE 1: select * from spree_variants where sku = "1SB-E4196-00";
Why it is considering "1SB-E4196-00" as a column but not SKU? The error seems misleading.
Because PostgreSQL expects strings to be bounded in single quotes. While double quotes have a different meaning:
There is a second kind of identifier: the delimited identifier or quoted identifier. It is formed by enclosing an arbitrary sequence of characters in double-quotes ("). A delimited identifier is always an identifier, never a key word.
That means if the following query should work:
ActiveRecord::Base.connection.execute(
"select * from spree_variants where sku = '1SB-E4196-00';"
)
Btw you if you are using Rails and have a SpreeVariant model then you can see in the console how Rails formats and escapes the query like this:
puts SpreeVariant.where(sku: '1SB-E4196-00').to_sql

Informix select into external syntax error

Can somebody please tell me what is the problem with the following informix statement :
SELECT * FROM
(some big query here)
INTO EXTERNAL empdata(selected_date date, land char, grund integer, some_user varchar, nr decimal(15))
USING (DATAFILES("DISK:/usr1/tbodan.out"))
I get a syntax error near INTO EXTERNAL empdata.
UPDATE
Informix version is 11.7 and omitting the column definition only brings the following error Error: Virtual column must have explicit name.
You need to follow the documented syntax at INTO EXTERNAL clause.
I think your problem is that you tried to provide column names and data types for the table.
This SQL worked for me:
SELECT * FROM elements
INTO EXTERNAL ext_elements
USING (DATAFILES("DISK:/Users/jleffler/tmp/ext-elements.table"))
This SQL did not, generating a -201 "A syntax error has occurred" error:
SELECT * FROM elements
INTO EXTERNAL ext_elements(atomic_number INTEGER, symbol CHAR(3),
name CHAR(20), atomic_weight DECIMAL(8,4),
pt_period SMALLINT, pt_group CHAR(2), stable CHAR(1))
USING (DATAFILES("DISK:/Users/jleffler/tmp/ext-elements.table"))
Testing on a Mac running macOS Sierra 10.12.5, using Informix 12.10.FC4.
Ok,so the problem was actually in the select query.
The query returns more columns that do not have an explicit name and are tagged as "expression" that is why the Error: Virtual column must have explicit name. popped up.
I solved this by using aliases for those columns. Then used the syntax suggested here.

How do I order results by hstore attribute in Rails 4?

How can I order query results by an hstore attribute?
#items = Item.includes(:product).order('products.properties #> hstore("platform")')
Causes
PG::Error: ERROR: column "platform" does not exist
LINE 1: ...oduct_id" ORDER BY products.properties #> hstore("platform"...
platform is a hstore key, stored in the properties column, which is an hstore type.
Double quotes are used to quote identifiers (such as table and column names) in PostgreSQL (and other databases that follow the standard). So when you say:
hstore("platform")
PostgreSQL sees "platform" as a quoted column name and since there is no platform column, you get an error.
Strings in standard SQL are quoted with single quotes, you want to say:
.order("products.properties #> hstore('platform')")
This will probably still fail though, hstore('platform') doesn't make much sense and neither does using #> here; a #> b means
does the hstore a contain the hstore b
If you're trying to sort on the value of the 'platform' key in the properties hstore then you'd want to use -> to lookup the 'platform' key like this:
.order("products.properties -> 'platform'")

Rails reports can't find a column that is there

I am currently trying to do a complicated WHERE search on a table using Rails, the trouble is I get the error:
PG::Error: ERROR: column "email" does not exist
LINE 1: SELECT "bans".* FROM "bans" WHERE (Email='' AND IP='' AND (...
^
: SELECT "bans".* FROM "bans" WHERE (Email='' AND IP='' AND (Username='NULL' ))
And I know that column actually exists, and doing a rails dbconsole gives me the following:
Jungle=> select * from bans;
id | Username | IP | Email | Reason | Length | created_at | updated_at
----+----------+----+-------+--------+--------+------------+------------
(0 rows)
So this is definatly in the database, has anyone had any experience with this?
SQL column names are case insensitive unless quoted, the standard says that identifiers should be normalized to upper case but PostgreSQL normalizes to lower case:
Quoting an identifier also makes it case-sensitive, whereas unquoted names are always folded to lower case. For example, the identifiers FOO, foo, and "foo" are considered the same by PostgreSQL, but "Foo" and "FOO" are different from these three and each other. (The folding of unquoted names to lower case in PostgreSQL is incompatible with the SQL standard, which says that unquoted names should be folded to upper case. Thus, foo should be equivalent to "FOO" not "foo" according to the standard. If you want to write portable applications you are advised to always quote a particular name or never quote it.)
You're referencing Email in your SQL:
SELECT "bans".* FROM "bans" WHERE (Email='' ...
but PostgreSQL is complaining about email:
column "email" does not exist
Your unquoted Email is being treated as email because PostgreSQL normalizes identifiers to lower case. Sounds like you created the columns with capitalized names by double quoting them:
create table "bans" (
"Email" varchar(...)
...
)
or by using :Email to identify the column in a migration. If you quote a column name when it is created, then it is not normalized to lower case (or upper case in the SQL standard case) and you'll have to double quote it and match the case forever:
SELECT "bans".* FROM "bans" WHERE ("Email"='' ...
Once you fix Email, you'll have the same problem with IP, Username, Reason, and Length: you'll have to double quote them all in any SQL that references them.
The best practise is to use lower case column and table names so that you don't have to worry about quoting things all the time. I'd recommend that you fix your table to have lower case column names.
As an aside, your 'NULL' string literal:
SELECT "bans".* FROM "bans" WHERE (Email='' AND IP='' AND (Username='NULL' ))
-- -------------------->------------------>---------->---------------^^^^^^
looks odd, are you sure that you don't mean "Username" is null? The 'NULL' string literal and the NULL value are entirely different things and you can't use = or != to compare things against NULL, you have to use is null, is not null, is distinct from, or is not distinct from (depending on your intent) when NULLs might be in play.
It doesn't look like you're error is from a test database but if so try rake db:test:prepare.
In general, be aware that you have 3 databases - Test, Development, Production. So it's easy to get them mixed up and check the wrong one.
I had the same problem here,
but as mu-is-too-short said, PostgreSql can be told to
search with case sensitivity on columns names.
So by implemented this code I managed to bypass the same error that you're facing:
Transaction.find(:all,:conditions => ["(date between ? and ?) AND \"Membership_id\" = ?", Time.now.at_beginning_of_month, Time.now.end_of_month,membership.id])
Noticed the \" sign srrounding the column name? Well.. as annoying as it is, that's the fix to this problem.

ActiveRecord sum errors with postgresql

I am using AR's sum method for a query and seeing this error when using PostgreSQL:
PGError: ERROR: function sum(character varying) does not exist
LINE 1: SELECT sum("assets".asset_file_size) AS sum_asset_file_size ...
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
SELECT sum("assets".asset_file_size) AS sum_asset_file_size FROM "assets" [0m
I am using the following in my code, which works with MySQL:
Asset.sum(:asset_file_size)
I am trying to get a sum of the asset_file_size column.
What am I missing here?
OH.
In writing my question I worked out this issue.
I had accidentally made the column Varchar rather than an Integer. Hence the request to "explicitly type cast".
We apologise for the incovenience.

Resources