What are PostgreSQL functions and when do I have to use them? - postgresql

I want to know what PostgreSQL functions are.
When do I have to write them?
How can I write them?
And how can I call them?

Definition, from wikipedia:
A stored procedure is a subroutine available to applications that
access a relational database system.
Advantages of stored procedures in general, from wikipedia:
Overhead: Because stored procedure statements are stored directly in
the database, they may remove all or part of the compilation overhead
that is typically required in situations where software applications
send inline (dynamic) SQL queries to a database. (...)
Avoidance of network traffic: A major advantage with stored procedures
is that they can run directly within the database engine. In a
production system, this typically means that the procedures run
entirely on a specialized database server, which has direct access to
the data being accessed. The benefit here is that network
communication costs can be avoided completely. This becomes
particularly important for complex series of SQL statements.
Encapsulation of business logic: Stored procedures allow programmers
to embed business logic as an API in the database, which can simplify
data management and reduce the need to encode the logic elsewhere in
client programs. (...)
Delegation of access-rights: In many systems, stored procedures can be
granted access rights to the database that users who execute those
procedures do not directly have.
Some protection from SQL injection attacks: Stored procedures can be
used to protect against injection attacks. Stored procedure parameters
will be treated as data even if an attacker inserts SQL commands. (...)
In PostgresSQL stored procedures are called user defined functions.
Definition example:
CREATE FUNCTION somefunc(quantity integer) RETURNS integer AS $$
DECLARE
myvariable integer := 2;
BEGIN
RETURN quantity * myvariable;
END;
$$ LANGUAGE plpgsql;
(You can use other languages to define stored functions in PostgreSQL)
Calling example:
SELECT somefunc(100);
More info: http://www.postgresql.org/docs/9.1/static/server-programming.html

PostgreSQL runs stored procedures in more than a dozen programming languages, including Java, Perl, Python, Ruby, Tcl, C/C++, and its own
PL/pgSQL, which is similar to Oracle's PL/SQL.
The use of stored procedure depends on your needs and depends on the logic of your program, in my opinion stored procedure are useful only in some cases and not ever...
I've used stored procedure in a multi database server application, in this case the use of stored procedure could be extremely useful for example in the case you have a query that need to be modified for run in another database server type, in that case you can write a stored procedure in each database server and call it from your program being sure that it run and retrieve the wanted resultset without any changes in the client code.
To learn how to create stored procedure in PostgreSQL refer to this page of the documentation.

the main advantage is reducing network traffic overhead. Stored procedure is almost same (not exactly) as business logic or logic tire. Its main advantage is making dynamic enterprise application.You can find 100s of good product failed just because lack of dynamic database structure. Stores procedures,Functions,Triggers,Sequences,indexes and relational nature of database are the real keys to create great applications.My company always try to reduce client side logic layers with the help of stored procedures. Most of the critical logics are store in stored procedures which makes programmers and testers happy and meet their timelines.

Related

Stored procedure implementation instead of hard coded queries In Postgres

Aurora Postgres 11.9
In SQL Server we strictly follow the good programming practice that "every single call land on DB from the application will be a stored procedure instead of simple queries". In Oracle, we haven't experienced the same thing may be due to select stored procedures required additional cursors, and so on.
Can any expert Postgres person advise me what practice should we follow in progress in this regard and what are pros and cons in this case of Postgres?
In addition in SQL Server we use "rowversion" for data sync with BI and other external modules, is there any built-in alternate available in Postgres or should we have to do it with manual triggers?

Postgresql : What is the maximum number of stored procedures can be written for the postgresql database?

Need to know the Best practice to write the stored procedures for the database. So what is the maximum number of stored procedures can be written for postgresql database for readability and maintainability. Also please let me know if there is any standards for writing stored procedures.
There is no limit (within reason). The key for maintainability is to separate stored procedures into logical functional areas (business units) using schemas and naming conventions. For example, in a over-simplified business database you could create three schemas: finance, customers, inventory. Then organize your stored procedures into those schemas. For example:
finance.calculate_year_end_report
finance.update_finance_record
customer.create_customer
inventory.update_current_inventory
You can create smaller organization sets under these using naming conventions. For example you could do this inside finance:
finance.tax_calculate_estimated_taxes
finance.tax_aggregate_sales_tax
finance.report_calculate_year_end
finance.report_ytd_revenue
finance.update_finance_record

Execute function returning data in remote PostgreSQL database from local PostgreSQL database

Postgres version: 9.3.4
I have the need to execute a function which resides in a remote database. The function returns a table of statistic data based on the parameters given.
I am in effect only mirroring the function in my local database to lock down access to this function using my database roles and grants.
I have found the following which seem to only provide table-based access.
http://www.postgresql.org/docs/9.3/static/postgres-fdw.html
http://multicorn.org/foreign-data-wrappers/#idsqlalchemy-foreign-data-wrapper
First question: is that correct or are there ways to use these libraries for non-table based operations?
I have found the following which seems to provide me with any SQL operation on the foreign database. The negative seems to be increased complexity and reduced performance due to manual connection and error handling.
http://www.postgresql.org/docs/9.3/static/dblink.html
Second question: are these assumptions correct, and are there any ways to bypass these concerns or libraries/samples one can begin from?
The fdw interface provides a way to make a library which can allow a postgresql database to query any external data source as though it was a table. From that point of view, it could do what you want.
The inbuilt postgresql_fdw driver, however, does not allow you to specify a function as a remote table.
You could write your own fdw driver, possibly using the multicorn library, or some other language. That is likely to be a bit of work though, and would have some specific disadvantages, in particular I don't know how you would pass parameters to the function.
dblink is probably going to be the easiest solution. It allows you to execute arbitrary SQL on the remote server, returning a set of records.
SELECT *
FROM dblink('dbname=mydb', 'SELECT * FROM thefunction(1,2,3)')
AS t1(col1 INTEGER, col2 INTEGER);
There are other potential solutions but they would all be more effort to set up.

How compatible is Blackfish database with TSQL?

I'm using a sqlServer database that has stored procedures, and I want to use an in-memory database to unit test my code.
I've looked at a few - including VistaDB which looks amazing but expensive - and Blackfish seems to be the only possiblity so far. Before using it though i'd like to know exactly how compatible it is with TSQL - obviously if I have a lot of existing stored procedures these will use TSQL, so it's important that the in-memory db I use can handle this.
Thanks
Short Answer: Not Very
Long Answer:
Whilst Blackfish is SQL-92 compliant, you’re bound to run into stuff that worked on your T-SQL database that won’t work on BlackFish.
I'd strongly recommend SQL Server Compact 4.0 (or Express at a crunch), Compact can be easily bundled, has a tiny footprint (3mb installer? [18mb on disk ish]).
For instance, T-SQL Flow control might differ to Blackfish flow control - not really relevant for selects, inserts & updates etc, but if you have T-SQL logic gates in stored procedures, i don’t think these will port to Blackfish? Blackfish supports stored procedures, but they are compiled in other native languages (Delphi mainly). Good example from the documentation:
http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/bfsql/storedprocedures_xml.html
Very different from the T-SQL procedures used in MS SQL

How to decide when use ADO.NET and when to connect to the database?

I'm learning some ADO.NET. I noticed quite a few Database functionality can also be found in ADO.NET.
I'm kind of confused. Do I use ADO.NET to manage all the interactions or should I make call to the Database?
I don't know what should be done by ADO.NET and what should be done at the database level.
Thanks for helping.
If you mean what should be handled in SQL statements issued from ADO.NET, and what should be done in stored procedures stored at the database level, as much as possible in stored procedures, at least that's what I live by. In addition to eliminating the chance of SQL injection, stored procedures allow you to modify sql calls without having to recompile and deploy your code as well as they enable execution plan re-use by the query optimizer.