using schemas in postgresql - postgresql

I have developed an application using postgresql and it works well.
Now I need to create several instances of the same application but I have only one database. So I am thinking about using schemas, so that I can group each instance tables in a different schema.
Now, I wouldn't like to rewrite all my functions and script, thus I am wondering if I can just use some directive to instruct the database to operate on a specific schema. Just to try to make it clearer, do you know when in c++ you do
using namespace std;
so that you can use cout instead of std::cout ? I would like to use someting similar if possible.

The parameter you are looking for is search_path - that lists the schemas a query will look in. So, you can do something like:
CREATE TABLE schema1.tt ...
CREATE TABLE schema2.tt ...
CREATE FUNCTION schema1.foo() ...
CREATE FUNCTION schema2.foo() ...
SET search_path = schema1, something_else;
SELECT * FROM tt; -- schema1.tt
SELECT * FROM schema2.tt -- schema2.tt
SELECT foo(); -- calls schema1.foo
SELECT schema2.foo(); -- calls schema2.foo
Note that if a query's plan gets saved inside the body of foo() then you may get an unexpected results. I would recommend you always explicitly list schemas for referenced tables in plpgsql functions if you are using duplicated tables. If not, make sure you have testing in place to check behaviour with a chaning search_path.
Oh - you can explicitly set search_path for a function's body too - see the manual's CREATE FUNCTION reference for details.

Related

Replacement of DBA_Source in Postgres to find DB objects

How can I know table (table_1) is being used in which all UDF?
Below query gives me table's details:
SELECT * FROM information_schema.tables;
Below Query gives UDF details:
select * FROM pg_proc;
But how can I know that table1 is used in which all UDF?
A string search in the prosrc column of pg_proc is the only way if you want to find dependencies between functions and tables.
Of course that is not very satisfying, because it would be rather difficult to say if – say – an occurrence of table_1 is a reference to the table or a variable name. Also, you cannot find the source of C functions in the catalog.
To get a reliable answer, you would need insight into the language in which the function is written, and here is the core of the problem: PostgreSQL does not have any insight into the language! PostgreSQL's fabled extensibility allows you to define new languages for functions, and only the language handler knows how to interpret the string that is the function body. That also holds for PL/pgSQL which is shipped with PostgreSQL.
That is also the reason why there are no pg_depend entries for objects used in functions.

Loading Postgres functions with dependencies

I'm using quite a few Postgres functions (both sql and pl/pgsql) in a particular application. Some of the sql functions depend on other sql functions, e.g.
create or replace function my_function ()
returns table (a text, b text) as
$$
select * from my_other_function();
$$
language sql;
For my_function to load properly, my_other_function has to be loaded first, else I get a my_other_function does not exist error. To manage this, I have been manually ensuring that my_other_function does get loaded first, but it would be nice not to have to do that.
In other words, is there a way to load all of my functions without regard to order and somehow check that all the necessary dependencies are available (function objects) after the fact?
I'm using Postgres 9.6.
You can use SETcheck_function_bodies= false; prior creating your functions to suppress the error.

What does this select statement actually do?

I'm reviewing log of executed PostgreSQL statements and stumble upon one statement I can't totally understand. Can somebody explain what PostgreSQL actually do when such query is executed? What is siq_query?
select *
from siq_query('', '21:1', '', '("my search string")', False, True, 'http://siqfindex:8080/storediq/findex')
I'm running PostgreSQL 9.2
siq_query(...) is a server-side function taking 7 input parameters (or more). It's not part of any standard Postgres distribution I know (certainly not mainline Postgres 9.2), so it has to be user-defined or part of some extension you installed. It does whatever is defined in the function. This can include basically anything your Postgres user is allowed to do. Unless it's a SECURITY DEFINER function, then it ca do whatever the owner of the function is allowed to do.
The way it is called (SELECT * FROM), only makes sense if it returns multiple rows and/or columns, most likely a set of rows, making it a "set-returning function", which can be used almost like a table in SQL queries.
Since the function name is not schema-qualified, it has to reside in a visible schema. See:
How does the search_path influence identifier resolution and the "current schema"
Long story short, you need to see the function definition to know what it does exactly. You can use psql (\df+ siq_query), pgAdmin (browse and select it to see its definition in the SQL pane) or any other client tool to look it up. Or query the system catalog pg_proc directly:
SELECT * FROM pg_proc WHERE proname = 'siq_query';
Pay special attention to the column prosrc, which holds the function body for some languages like plpgsql.
There might be multiple variants of that name, Postgres allows function overloading.

Postgres Rules Preventing CTE Queries

Using Postgres 9.3:
I am attempting to automatically populate a table when an insert is performed on another table. This seems like a good use for rules, but after adding the rule to the first table, I am no longer able to perform inserts into the second table using the writable CTE. Here is an example:
CREATE TABLE foo (
id INT PRIMARY KEY
);
CREATE TABLE bar (
id INT PRIMARY KEY REFERENCES foo
);
CREATE RULE insertFoo AS ON INSERT TO foo DO INSERT INTO bar VALUES (NEW.id);
WITH a AS (SELECT * FROM (VALUES (1), (2)) b)
INSERT INTO foo SELECT * FROM a
When this is run, I get the error
"ERROR: WITH cannot be used in a query that is rewritten by rules
into multiple queries".
I have searched for that error string, but am only able to find links to the source code. I know that I can perform the above using row-level triggers instead, but it seems like I should be able to do this at the statement level. Why can I not use the writable CTE, when queries like this can (in this case) be easily re-written as:
INSERT INTO foo SELECT * FROM (VALUES (1), (2)) a
Does anyone know of another way that would accomplish what I am attempting to do other than 1) using rules, which prevents the use of "with" queries, or 2) using row-level triggers? Thanks,
        
TL;DR: use triggers, not rules.
Generally speaking, prefer triggers over rules, unless rules are absolutely necessary. (Which, in practice, they never are.)
Using rules introduces heaps of problems which will needlessly complicate your life down the road. You've run into one here. Another (major) one is, for instance, that the number of affected rows will correspond to that of the very last query -- if you're relying on FOUND somewhere and your query is incorrectly reporting that no rows were affected by a query, you'll be in for painful bugs.
Moreover, there's occasional talk of deprecating Postgres rules outright:
http://postgresql.nabble.com/Deprecating-RULES-td5727689.html
As the other answer I definitely recommend using INSTEAD OF triggers before RULEs.
However if for some reason you don't want to change existing VIEW RULEs and still want use WITH you can do so by wrapping the VIEW in a stored procedure:
create function insert_foo(int) returns void as $$
insert into foo values ($1)
$$ language sql;
WITH a AS (SELECT * FROM (VALUES (1), (2)) b)
SELECT insert_foo(a.column1) from a;
This could be useful when using some legacy db through some system that wraps statements with CTEs.

How do I store a set of queries inside PostgreSQL so I can easily run it again?

I want to save a set of queries (multiple SQL updates) as a single element that I can execute using pgAdmin3 (PostgreSQL 9.1).
I know that I can save single SELECTS as views but how about multiple UPDATE queries?
Example:
BEGIN;
UPDATE ...;
UPDATE ...;
COMMIT;
Update: What I looking for is a step-by-step guide of adding a stored procedure using the GUI, not running a SQL query that creates it.
So far, I encountered two problems with "New function...": the return type is required and found that NULL is not acceptable, so tried integer. Also, set the type to SQL but I don't know what exactly to write inside the SQL tab, whatever I try the OK button is still disabled and the statusbar says: Please enter function source code.
Do you know or did you try stored procedure (well, stored-procedure-like functions) ?
http://www.postgresql.org/docs/9.1/interactive/plpgsql-structure.html
To call it
select <name of function>(<param1>, <param2>) as result;
Here is the missing guide for a basic SQL stored procedure, one that does return 1.
right click on Functions and choose New Function...
complete name as my_procedure, return type as integer, language as sql
select Definition tab and write SELECT 1;
done
It would be nice to know if you can create queries that are returning nothing.