PostgreSQL – How PostgreSQL Names Tablespace Directories

postgresqltablespaces

Using the psql CLI tool with a PostgreSQL 9.6.1 server running on localhost, I created a new tablespace with

create tablespace my_tablespace location /tmp/data;

and found that this created a directory called PG_9.6_201608131.

I can see that 9.6 is the version, but what is the last string of numbers? I'd like to use this to create databases in a Makefile, so it will be helpful to know how that number is derived (rather than just hard-coding it).

Best Answer

I look at the source code of postgres9.6.

/* tablespace.c */

create_tablespace_directories(const char *location, const Oid tablespaceoid)
{
    ....
    location_with_version_dir = psprintf("%s/%s", location,TABLESPACE_VERSION_DIRECTORY);
    ....
    if (mkdir(location_with_version_dir, S_IRWXU) < 0)
    {
        ....
    }
}

/* catalog.h */

#define TABLESPACE_VERSION_DIRECTORY    "PG_" PG_MAJORVERSION"_" \
                                CppAsString2(CATALOG_VERSION_NO)

/* catversion.h */

#define CATALOG_VERSION_NO  201608131

I found PG_9.6_201608131 is made up of three parts.

'PG_' + PG_MAJORVERSION + '_' + CATALOG_VERSION_NO

In PostgreSQL9.6

PG_MAJORVERSION is 9.6

CATALOG_VERSION_NO is 201608131

PG_MAJORVERSION and CATALOG_VERSION_NO both are macro definition in c, it won't change.

source code here