Firebird 2.5.x. Extract column names and column datatypes of a result from stored procedure - firebird

I have a Firebird 2.5 database .As an example I have stored procedure with a name QRESULT which expected return is:
Parameter - DATATYPE
a - date
b - numeric(18,0)
c - integer
d - varchar(50)
and so on....
I use PHP - PDO to query the firebird database using the procedure QRESULT like this:
SELECT a,b,d from QRESULT() where a = "some value"
I need to run some query before QRESULT procedure and i need it to return the datatype of all the columns that QRESULT would return if it was ran. So i can help user to type proper value for my "where" clause.I know i can set that manually in the user interface, but in the real project there are lots of procedures and if there is a way i can make my filter interface generate dynamically i would be happy about that.If this is not possible for a stored procedure i can make it with select statements.I just need some lead.

The information you want is in the RDB$PROCEDURE_PARAMETERS table, basically what you need is query
SELECT r.RDB$PARAMETER_NAME ParName, F.RDB$FIELD_TYPE ParType
FROM RDB$PROCEDURE_PARAMETERS r
JOIN RDB$FIELDS F ON(F.RDB$FIELD_NAME = R.RDB$FIELD_SOURCE)
WHERE r.RDB$PROCEDURE_NAME = 'QRESULT'
AND r.RDB$PARAMETER_TYPE = 1
ORDER BY r.RDB$PARAMETER_TYPE, r.RDB$PARAMETER_NUMBER
Note that the SP name should be in upper case as this is how it is stored into system tables (unless you use quoted identifiers). If you want to get both input and output parameters the delete the r.RDB$PARAMETER_TYPE = 1 predicate from the WHERE (type 0 is input parameters and 1 is output).
The type returned by this query is integer id for the type, quick googling found this:
14,"TEXT "
7,"SHORT "
8,"LONG "
9,"QUAD "
10,"FLOAT "
27,"DOUBLE "
35,"TIMESTAMP "
37,"VARYING "
261,"BLOB "
40,"CSTRING "
45,"BLOB_ID "
12,"DATE "
13,"TIME "
16,"INT64 "
but if you want to have more precise type then see this SO post.

Related

PostgreSQL execute SELECT * FROM (t as a); return ERROR: syntax error at or near ")"

Why these SQLs can't work in PostgreSQL?
SELECT * FROM (t as a);
or
SELECT * FROM (t);
ERROR: syntax error at or near ")"
Those SQLs work well in MySQL.
Well, it's invalid SQL.
If you want to give the table an alias you need to use from t as a.
The form from (....) requires a valid query inside the parentheses and t as a (or just t) is not a valid query. Additionally: a derived table (which is what (...) defines) requires an alias. So at least it has to be from (...) as bla
To get all rows and all columns from a table the SQL standard provides the shortcut table some_table which is supported by Postgres.
So the following would be valid:
select * from (table t) as a
Typically, table alias' are applied where there is a join. For example:
SELECT alias1.login_name, alias2.name
FROM tablename1 AS alias1
JOIN tablename2 AS alias2
ON alias1.id = alias2.role_id;
To apply an alias to a single table:
SELECT * FROM tablename AS alias;
..will do it for you, no need for parentheses.
You can confirm/test by example below if value is an integer:
SELECT * FROM tablename AS alias
WHERE alias.colum = value;
..or if value is a string:
SELECT * FROM tablename AS alias
WHERE alias.colum = 'value';
postgreSQL is strongly-typed, so the first example above will work for Int and Bool values, however if you have Date or other values, you may need to apply type casting. See this link for helpful info*: www.postgresqltutorial.com/postgresql-tutorial/postgresql-cast.
**Remember: For psql strings, always use single quotes for values, use double quotes for table names and column names.

Cast a PostgreSQL column to stored type

I am creating a viewer for PostgreSQL. My SQL needs to sort on the type that is normal for that column. Take for example:
Table:
CREATE TABLE contacts (id serial primary key, name varchar)
SQL:
SELECT id::text FROM contacts ORDER BY id;
Gives:
1
10
100
2
Ok, so I change the SQL to:
SELECT id::text FROM contacts ORDER BY id::regtype;
Which reults in:
1
2
10
100
Nice! But now I try:
SELECT name::text FROM contacts ORDER BY name::regtype;
Which results in:
invalid type name "my first string"
Google is no help. Any ideas? Thanks
Repeat: the error is not my problem. My problem is that I need to convert each column to text, but order by the normal type for that column.
regtype is a object identifier type and there is no reason to use it when you are not referring to system objects (types in this case).
You should cast the column to integer in the first query:
SELECT id::text
FROM contacts
ORDER BY id::integer;
You can use qualified column names in the order by clause. This will work with any sortable type of column.
SELECT id::text
FROM contacts
ORDER BY contacts.id;
So, I found two ways to accomplish this. The first is the solution #klin provided by querying the table and then constructing my own query based on the data. An untested psycopg2 example:
c = conn.cursor()
c.execute("SELECT * FROM contacts LIMIT 1")
select_sql = "SELECT "
for row in c.description:
if row.name == "my_sort_column":
if row.type_code == 23:
sort_by_sql = row.name + "::integer "
else:
sort_by_sql = row.name + "::text "
c.execute("SELECT * FROM contacts " + sort_by_sql)
A more elegant way would be like this:
SELECT id::text AS _id, name::text AS _name AS n FROM contacts ORDER BY id
This uses aliases so that ORDER BY still picks up the original data. The last option is more readable if nothing else.

How to send multiple variables using birt report?

Using the following query in db2:
select * from table where num in ('1a2334','1a43432','1a34243','1b34325','1b4545')
Now whenever I get data to report I get the rows like from the users:
1a23344
1a43432
1a34243
1b34325
1b45454
Then I use notepad++ to replace rf with ',' so it becomes
'1a2334','1a43432','1a34243','1b34325','1b4545'
What are my options for creating a report that accepts input easy enough for the average user?
This specific user has an excel sheet with multiple columns, I only use the first column (the mentioned examples above are rows from the first column).
A good solution provided by #Simulant, but I need this to get values from an excel file (preferably by copy paste). I noticed his/her solution uses static values, so I think I need dynamic values.
For the record I got the following error using the script:
Error evaluating Javascript expression. Script engine error:
TypeError: Cannot call method "replace" of null
(/report/data-sets/script-data-set[#id="12"]/method[#name="beforeOpen"]#3)
Script source:
/report/data-sets/script-data-set[#id="12"]/method[#name="beforeOpen"],
line: 0, text:
__bm_beforeOpen(). (Element ID:1) Error.ScriptEvaluationError ( 1 time(s) ) detail : org.eclipse.birt.report.engine.api.EngineException:
There are errors evaluating script "var parameters =
params["multiSelectParameter"].value; var replacesPart = "'" +
parameters.join("', '") + "'"; this.queryText =
this.queryText.replace("replaceMe", replacesPart);":
Create a Report with a Multi-Select Parameter. Create a List Box Parameter and allow multiple values. You can add static values or select dynamic and display the result of another query.
Write your query as following SQL-Statement:
select * from table where num in (replaceMe);
Select your Data-Set and select the script Tab. Enter for the beforeOpen the following script. This replaces the placeholder replaceMe in your SQL-Statement with the concatinated values of your Multi-Select Parameter enclosed with single quotes ' and separated with commas , as you need it:
var parameters = params["multiSelectParameter"].value;
var replacesPart = "'" + parameters.join("', '") + "'";
this.queryText = this.queryText.replace("replaceMe", replacesPart);

Psycopg2 functions in parameters

I'm wonder how I can pass a Postgres function to a field in an insert statement in Psycopg2. Looked everywhere in the doc but can't find the answer.
The code:
From the DBconn class:
def insert(self, table, data):
fields = data.keys()
sql = "INSERT INTO " + table + "("
sql += ",".join(fields) + ") VALUES (" + ",".join(["%s"]*len(fields)) + ");"
self.cur.execute(sql, data.values())
And when calling this function:
db.insert("tblpeople", {"person_name":"john", "org_id":"currval('tblorganisations_org_id_seq')"})
So the question is how can I tell Psycopg2 that the org_id value is a Postgres function?
Tnx!
Your code is producing the statement:
INSERT INTO tblpeople (org_id,person_name) VALUES (%s,%s);
and you are passing 2 arguments. That won't work. You want to produce this code:
INSERT INTO tblpeople (org_id,person_name)
VALUES (currval('tblorganisations_org_id_seq'),%s);
and then pass a single argument. I don't see any way of doing that with your current data structure. If you add another piece of data to your dictionary, like:
{
"text":{"person_name":"john"},
"function":{"org_id":"currval('tblorganisations_org_id_seq')"}
}
and change your constructor to produce the proper query based upon the 'function' key, or, you could 'hard code' your query builder to recognize the 'currval(' being at the beginning of the value. Anyway, the basic problem is you are passing the data as a string argument which won't be handled correctly.
-g

Scala Play Framework Anorm SQL.on disable wrapping replacements with ' '

Whenever I replace placeholders in the SQL query using on it surrounds the replacement with '', is there a way to prevent this?
It means I can't do things like
SQL("SELECT * FROM {table} blah").on("table" -> tabletouse)
because it wraps the table name with '' which causes an SQL syntax error.
you could certainly combine both approaches, using the format function for data you don't want to be escaped
SQL(
"""
select %s from %s
where
name = {name} and
date between {start} and {end}
order by %s
""".format(fields, table, order)
).on(
'name -> name,
'start -> startDate,
'end -> endDate
)
Just take into account that the data you are sending using the format function should NOT come from user input, otherwise it should be properly sanitized
You cannot do what you are trying. Anorm's replacement is based on PreparedStatements. Meaning all data will automatically be escaped, meaning you cannot use replacement for :
table names,
column names,
whatever operand, SQL keyword, etc.
The best you can do here is a String concatenation (and what is really a bad way in my opinion) :
SQL("SELECT * FROM " + tabletouse + " blah").as(whatever *)
PS : Checkout this question about table names in PreparedStatements.