This question is specific to libpqxx.
Given an SQL statement like the following:
string s = "SELECT a.foo, b.bar FROM tableOne a, tableTwo b WHERE a.X=b.X"
and sending it to a pqxx transaction:
trans.exec(s.c_str(), s.c_str());
What names will the columns have in the result field?
In other words, assuming 1 row is selected:
pqxx::result::const_iterator row = result.begin();
int foo = row->at(FOO_COLUMN).as<int>();
int bar = row->at(BAR_COLUMN).as<int>();
What values should FOO_COLUMN and BAR_COLUMN have? Would they be "a.foo" and "b.bar", respectively?
If the SQL statement renamed the variables using the "as" keyword, then I suppose the column name would be whatever "as" set it to, is that right?
Normally I would try an SQL and print the column values, but as I am developing both the software and the database itself, doing that test is not very easy right now.
Thanks!
The names are going to be foo and bar. If they were aliases in the query, then the aliases would be returned, the original names being lost.
Column names in results never include table names.
If they were named tablename.colname, it would be ambiguous anyway because SELECT 1 as "foo.colname" is valid and produces a column foo.colname despite the fact there is no foo table.
The way to identify the table from which a column originates, when it applies, is to call pqxx::result::column_table(column_number) which returns the oid of the table. The table's name is not available directly but could be queried in pg_class with the oid.
Also note that column names don't have to be unique within a resultset. SELECT 1 AS a, 2 AS a is valid and produces two columns with exactly the same name.
Related
I feel the need to get the column names and data types of the table returned by any function that has a 'record' return data type, because...
A key process in an existing SQL Server-based system makes use of a stored procedure that takes a user-defined function as a parameter. An initial step gets the column names and types of the table returned by the function that was passed as a parameter.
In Postgres 13 I can use pg_proc.prorettype and the corresponding pg_type to find functions that return record types...that's a start. I can also use pg_get_function_result() to get the string containing the information I need. But, it's a string, and while I ultimately will have to assemble a very similar string, this is just one application of the info. Is there a tabular equivalent containing (column_name, data_type, ordinal_position), or do I need to do that myself?
Is there access to a composite data type the system may have created when such a function is created?
One option that I think will work for me, but I think it's a little weird, is to:
> create temp table t as select * from function() limit 0;
then look that table up in info_schema.columns, assemble what I need and drop the temp table...putting all of this into a function.
You can query the catalog table pg_proc, which contains all the required information:
SELECT coalesce(p.na, 'column' || p.i),
p.ty::regtype,
p.i
FROM pg_proc AS f
CROSS JOIN LATERAL unnest(
coalesce(f.proallargtypes, ARRAY[f.prorettype]),
f.proargmodes,
f.proargnames
)
WITH ORDINALITY AS p(ty,mo,na,i)
WHERE f.proname = 'interval_ok'
AND coalesce(p.mo, 'o') IN ('o', 't')
ORDER BY p.i;
Query:
Select x classifier from tabx x
returns rows with one column named 'classifier' with list of values from the row.
Does anybody know where such features are documented? Is it the only usage of the keyword? I tried to google it but I've found only list of postgresql reserved keywords without explanation.
Example
It works like String_agg with ',' delimiter, but for a row.
It's called a column alias.
For columns it's documented here and for tables it's documented here
The name of the alias is irrelevant and bears no special meaning (including the word "classifier"). It just has to be a valid SQL identifier. Using an alias won't change anything in the resulting data.
If you use the (optional) AS keyword, it might be a bit more obvious:
select some_column as something_else
from some_table as another_name;
The reference x refers to the table alias specified in the FROM clause and refers to the complete row/record. It's not the column alias ("classifier") that does this, it's the reference to the table.
This behaviour is documented here in the manual
Edit after a new query was shown.
select a classifier, a.classifier
from t_attribute a;
The part a classifier still gives an alias to the record column (as explained above). a.classifier simply accesses a column from the table t_attribute.
It could also have been written as:
select a as the_complete_row, a.classifier as classifier
from t_attribute a;
The software I used created tables in postgres with Capitalizations, and I know that postgres and caps are a pain to deal with. I am using a multi-table query but they have Caps and I am not sure how to get the query down correctly to make it work.
I have two databases TBLS and DBS. I want to get the column TBL_NAME where the two DB_ID's are the same.
Here is what I thought might work:
select '"t.TBL_NAME"' from "TBLS" t, "DBS" d where '"t.DB_ID"'='"d.DB_ID"';
Any way I try and place the " or ' I can't seem to get the query to work correctly.
"tablename"."columnname"
See the manual on SQL syntax.
'"X.COL"' is a string literal with content string "X.COL".
"X.COL" is a single unqualified identifier for the object named X.COL. Yes, table, column, etc names can have a . in them.
"X"."COL" is a qualified identifier for COL in object X. Depending on context it can mean "the table COL in schema X", "the column COL in table X", etc. This is the one you want.
I am using Ubuntu and PostgreSql 8.4.9.
Now, for any table in my database, if I do select table_name.name from table_name, it shows a result of concatenated columns for each row, although I don't have any name column in the table. For the tables which have name column, no issue. Any idea why?
My results are like this:
select taggings.name from taggings limit 3;
---------------------------------------------------------------
(1,4,84,,,PlantCategory,soil_pref_tags,"2010-03-18 00:37:55")
(2,5,84,,,PlantCategory,soil_pref_tags,"2010-03-18 00:37:55")
(3,6,84,,,PlantCategory,soil_pref_tags,"2010-03-18 00:37:55")
(3 rows)
select name from taggings limit 3;
ERROR: column "name" does not exist
LINE 1: select name from taggings limit 3;
This is a known confusing "feature" with a bit of history. Specifically, you could refer to tuples from the table as a whole with the table name, and then appending .name would invoke the name function on them (i.e. it would be interpreted as select name(t) from t).
At some point in the PostgreSQL 9 development, Istr this was cleaned up a bit. You can still do select t from t explicitly to get the rows-as-tuples effect, but you can't apply a function in the same way. So on PostgreSQL 8.4.9, this:
create table t(id serial primary key, value text not null);
insert into t(value) values('foo');
select t.name from t;
produces the bizarre:
name
---------
(1,foo)
(1 row)
but on 9.1.1 produces:
ERROR: column t.name does not exist
LINE 1: select t.name from t;
^
as you would expect.
So, to specifically answer your question: name is a standard type in PostgreSQL (used in the catalogue for table names etc) and also some standard functions to convert things to the name type. It's not actually reserved, just the objects that exist called that, plus some historical strange syntax, made things confusing; and this has been fixed by the developers in recent versions.
According to the PostgreSQL documentation, name is a "non-reserved" keyword in PostgreSQL, SQL:2003, SQL:1999, or SQL-92.
SQL distinguishes between reserved and non-reserved key words. According to the standard, reserved key words are the only real key words; they are never allowed as identifiers. Non-reserved key words only have a special meaning in particular contexts and can be used as identifiers in other contexts. Most non-reserved key words are actually the names of built-in tables and functions specified by SQL. The concept of non-reserved key words essentially only exists to declare that some predefined meaning is attached to a word in some contexts.
The suggested fix when using keywords is:
As a general rule, if you get spurious parser errors for commands that contain any of the listed key words as an identifier you should try to quote the identifier to see if the problem goes away.
The following query, when executed in AdventureWords and tempdb, will give different results.
SELECT o.type_desc,
OBJECT_NAME(m.object_id) name,
definition
FROM [AdventureWorks].sys.sql_modules m
INNER JOIN [AdventureWorks].sys.objects o ON m.object_id = o.object_id;
When you execute it in the tempdb context, the name column will be NULLs, not the real object name.
What's the reason for this problem?
By default OBJECT_NAME looks at objects in the current database as specified by a USE statement; change your call to specify the specific database you want object information for:
OBJECT_NAME(m.object_id, DB_ID('AdventureWorks')) AS [name]