Does each database have their own built-in or system objects (functions, procedures, views, etc) in PostgreSQL?

55 views Asked by At

For example, there are built-in functions as shown below:

pi()
round()
random()
...

And, there are system functions as shown below:

current_catalog()
current_database()
current_query()
...

And, there are system views as shown below:

pg_available_extensions
pg_available_extension_versions
pg_backend_memory_contexts
...

So, does each database have their own built-in or system objects like functions, procedures, views, etc in PostgreSQL? Or, each database has shared built-in or system objects which means one built-in or system object is used(shared) in all databases?

I know that each database has their own user-defined objects like functions, procedures, views, triggers, event-triggers, etc which means one user-defined object is not used(shared) in all databases.

1

There are 1 answers

0
Erwin Brandstetter On

So, does each database have their own built-in or system objects like functions, procedures, views, etc.

Yes and no.

Built-in functions (including all you mentioned) are implemented in core Postgres with C code once. Not once per DB cluster, but once per Postgres installation. Each is registered in the system catalog pg_proc once in every database separately. (Occupies only a couple bytes per entry.)

Postgres comes with a given set of those functions collected in the default template databases template0 and template1. Every new database is created as copy of a template on the OS level (which makes it a very fast operation). You can customize much of this food chain - with the necessary privileges at OS or DB level.

So each database has its own functions, but all (belonging to the same Postgres installation) reference the same code base.

You can identify built-in functions in the system catalog: those have been created with LANGUAGE internal. LANGUAGE c functions have a similar food chain, many of those are added by additional modules. (Again, customizable with superuser privileges.)

PL/pgSQL and SQL (and other PL) functions are different in that they actually store the function body per object. Nothing shared across DB cluster or Postgres installation.

Only few system catalogs are shared as a single instance across a database cluster ("global" objects), in particular roles and tablespaces. The manual:

Most system catalogs are copied from the template database during database creation and are thereafter database-specific. A few catalogs are physically shared across all databases in a cluster; these are noted in the descriptions of the individual catalogs.

pg_dumpall has the dedicated switch --globals-only to backup only global objects.