Understanding stored procedure languages

When it comes to stored procedures and functions, PostgreSQL differs quite significantly from other database systems. Most database engines force you to use a certain programming language to write server-side code. Microsoft SQL Server offers Transact-SQL, while Oracle encourages you to use PL/SQL. PostgreSQL doesn't force you to use a certain language; instead, it allows you to decide on what you know and like the best.

The reason PostgreSQL is so flexible is actually quite interesting in a historical sense, too. Many years ago, one of the most well-known PostgreSQL developers, Jan Wieck, who had written countless patches back in its early days, came up with the idea of using Tool Command Language (Tcl) as the server-side programming language. The trouble was that nobody wanted to use Tcl and nobody wanted to have this stuff in the database engine. The solution to the problem was to make the language interface so flexible that basically any language can be easily integrated with PostgreSQL. At this point, the CREATE LANGUAGE clause was born. Here is the syntax of CREATE LANGUAGE:

test=# h CREATE LANGUAGE 
Command: CREATE LANGUAGE
Description: define a new procedural language
Syntax:
CREATE [ OR REPLACE ] [ PROCEDURAL ] LANGUAGE name
CREATE [ OR REPLACE ] [ TRUSTED ] [ PROCEDURAL ] LANGUAGE name
HANDLER call_handler [ INLINE inline_handler ] [ VALIDATOR valfunction ]

URL: https://www.postgresql.org/docs/12/sql-createlanguage.html

Nowadays, many different languages can be used to write functions and stored procedures. The flexibility that's been added to PostgreSQL has really paid off; we can now choose from a rich set of programming languages.

How exactly does PostgreSQL handle languages? If we take a look at the syntax of the CREATE LANGUAGE clause, we will see a few keywords:

  • HANDLER: This function is actually the glue between PostgreSQL and any external language that you want to use. It is in charge of mapping PostgreSQL data structures to whatever is needed by the language, and it helps pass the code around.
  • VALIDATOR: This is the police officer of the infrastructure. If it is available, it will be in charge of delivering tasty syntax errors to the end user. Many languages are able to parse code before actually executing it. PostgreSQL can use that and tell you whether a function is correct or not when you create it. Unfortunately, not all languages can do this, so in some cases, you will still be left with problems showing up at runtime.
  • INLINE: If this is present, PostgreSQL will be able to run anonymous code blocks utilizing this handler function.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset