Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1jjnSH-0007mI-R6 for pgsql-hackers@arkaria.postgresql.org; Fri, 12 Jun 2020 17:27:02 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1jjnSF-0002FF-62 for pgsql-hackers@arkaria.postgresql.org; Fri, 12 Jun 2020 17:26:59 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1jjnSE-0002DO-Js for pgsql-hackers@lists.postgresql.org; Fri, 12 Jun 2020 17:26:58 +0000 Received: from mail-ot1-x330.google.com ([2607:f8b0:4864:20::330]) by magus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.92) (envelope-from ) id 1jjnSA-0001vq-IK for pgsql-hackers@lists.postgresql.org; Fri, 12 Jun 2020 17:26:57 +0000 Received: by mail-ot1-x330.google.com with SMTP id s13so7928751otd.7 for ; Fri, 12 Jun 2020 10:26:54 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=2ndquadrant-com.20150623.gappssmtp.com; s=20150623; h=date:from:to:subject:message-id:mime-version:content-disposition; bh=rTB8r8NIlKZE50tT7pCD+HhN1Kz/2i32JcpZC4oxjzs=; b=RUkzGfuC2/tr97YHvrAhHvip0t3zAiRjQM4S4e/miT7AUorNUUsjuBfQJaMH6TOJSi GnGwzyaUPxOLcnvtPIgMGdG3YnNlVJQCddntMxu+VESKGSd7dzaEYVkwHE0WiyVMR1AY bV/vpYU+UcoTERZHjLNu9KhQgu5KQmydj+3j6qul6L0SgLrbOxZM7Hi7YLO43zUNHiV8 dKJ5TIPiL2QTz7yFkwMf8DUllSWznjvD1F/Jt3RlttkoRcMdAVTsXFHIDTjcU7voL3XH LAhlI5lPmXkOJoPIrDsmV6h4FVQR30RgYeimdpRZI76Iolo7jCeBR6Bjh8Rz/LfMl0P9 I00w== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:date:from:to:subject:message-id:mime-version :content-disposition; bh=rTB8r8NIlKZE50tT7pCD+HhN1Kz/2i32JcpZC4oxjzs=; b=p5wngtRNhf08GC+KDRZP8ClyOnm+HeJIe4hzv78WkYYqjf94NEIlKfKz9ZdmzZfjNk RnGlCDy/pd26kEFRkBzPewWSKOda/KJlBBjdUkfuvaHQygaQVktKA6QbGfe0zRY9iCUO +A/c5PqVg1oQ/IUnXJZH7XXans++uBN0KT74XhaRr9IFycDMDxpUTJL77hl+dZSVvMmc nUm7480iZRbfaLiYwANs14c6ySsPuAH5eQsGVxf7vwD3LKNEtN29/vK0wQMbaQkyJ4+L P7eeHy4WYfHDB0hcE1t5Xmz6OJlfQM/kwKQ2/bryY1mI53MSEOOvmaxU3GWrpFaUlj2z or7w== X-Gm-Message-State: AOAM531swoqpH9kEE2cSykztG3r/q+yQU4E3yw0HvNPhm5yAv7e3ykOv sx3UWKGQ/qf0NAvKrhNqm8CXrd69vyIWK9wzXN+3JMPIc0x8SbOb7eqbl8R2PK/j3Ku/SGuByoh U7BEWN1Ar19Cu7rl71xSv2IALnKicwnIBPYJH7oD4qlPlm3FutHeuumkfnJMDsru1DDyN1s9PRg 9sgY7bxU3m X-Google-Smtp-Source: ABdhPJyXIxmOR1JoqAqK44vJlptEFrBO/lrWBdVmrkCGJTlFdFOF+g8A7kbjNmd44fIxWxIYl7tOrQ== X-Received: by 2002:a05:6830:18db:: with SMTP id v27mr11918276ote.75.1591982811260; Fri, 12 Jun 2020 10:26:51 -0700 (PDT) Received: from 2ndQuadrant.com (c-67-169-212-172.hsd1.or.comcast.net. [67.169.212.172]) by smtp.gmail.com with ESMTPSA id x6sm299686ooe.5.2020.06.12.10.26.50 for (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 12 Jun 2020 10:26:50 -0700 (PDT) Date: Fri, 12 Jun 2020 10:26:48 -0700 From: Mark Wong To: pgsql-hackers@lists.postgresql.org Subject: doc examples for pghandler Message-ID: <20200612172648.GA3327@2ndQuadrant.com> MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="GvXjxJ+pjyke8COw" Content-Disposition: inline List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk --GvXjxJ+pjyke8COw Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Hi everyone, Would some additional procedure language handler code examples in the documentation be good to add? I've put some together in the attached patch, and can log it to a future commitfest if people think it would be a good addition. Regards, Mark -- Mark Wong 2ndQuadrant - PostgreSQL Solutions for the Enterprise https://www.2ndQuadrant.com/ --GvXjxJ+pjyke8COw Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="doc-pghandler-v1.patch" diff --git a/doc/src/sgml/plhandler.sgml b/doc/src/sgml/plhandler.sgml index e1b0af7a60..0287d424cb 100644 --- a/doc/src/sgml/plhandler.sgml +++ b/doc/src/sgml/plhandler.sgml @@ -241,4 +241,560 @@ CREATE LANGUAGE plsample reference page also has some useful details. + + The following subsections contain additional examples to help build a + complete procedural language handler. + + + + Minimal Example + + + Here is a complete minimal example that builds a procedural language + handler PL/Sample as an extension. Functions + can be created and called for PL/Sample but + they will not be able to perform any usefule actions. + + + + The plsample--0.1.sql file: + +CREATE FUNCTION plsample_call_handler() +RETURNS language_handler +AS 'MODULE_PATHNAME' +LANGUAGE C; + +CREATE LANGUAGE plsample +HANDLER plsample_call_handler; + +COMMENT ON LANGUAGE plsample IS 'PL/Sample procedural language'; + + + + + The control file plsample.control looks like this: + +comment = 'PL/Sample' +default_version = '0.1' +module_pathname = '$libdir/plsample' +relocatable = false +schema = pg_catalog +superuser = false + + See for more information about writing + control files. + + + + The following Makefile relies on + PGXS. + +PGFILEDESC = "PL/Sample - procedural language" + +EXTENSION = plsample +EXTVERSION = 0.1 + +MODULE_big = plsample + +OBJS = plsample.o + +DATA = plsample.control plsample--0.1.sql + +plsample.o: plsample.c + +PG_CONFIG = pg_config +PGXS := $(shell $(PG_CONFIG) --pgxs) +include $(PGXS) + + See for more information on makefiles with + PGXS. + + + + Here is the minimal C code in plsample.c that will + handle calls to this sample procedural language: + +#include <postgres.h> +#include <fmgr.h> + +PG_MODULE_MAGIC; + +PG_FUNCTION_INFO_V1(plsample_call_handler); + +/* + * Handle function, procedure, and trigger calls. + */ +Datum +plsample_call_handler(PG_FUNCTION_ARGS) +{ + return 0; +} + + + + + The following sections will continue building upon this example to + describe how to add additional functionality to a call handler for a + procedural language. + + + + + Fetching the source of a function + + + Additional code is added to plsample.c from to include additional headers for the + additional code that fetches the source text of the function. The + resulting file now looks like: + +#include <postgres.h> +#include <fmgr.h> +#include <funcapi.h> +#include <access/htup_details.h> +#include <catalog/pg_proc.h> +#include <catalog/pg_type.h> +#include <utils/memutils.h> +#include <utils/builtins.h> +#include <utils/syscache.h> + +MemoryContext TopMemoryContext = NULL; + +PG_MODULE_MAGIC; + +PG_FUNCTION_INFO_V1(plsample_call_handler); + +/* + * Handle function, procedure, and trigger calls. + */ + +Datum +plsample_call_handler(PG_FUNCTION_ARGS) +{ + HeapTuple pl_tuple; + Datum pl_datum; + const char *source; + bool isnull; + + /* Fetch the source of the function. */ + + pl_tuple = SearchSysCache(PROCOID, + ObjectIdGetDatum(fcinfo->flinfo->fn_oid), 0, 0, 0); + if (!HeapTupleIsValid(pl_tuple)) + elog(ERROR, "cache lookup failed for function %u", + fcinfo->flinfo->fn_oid); + + pl_datum = SysCacheGetAttr(PROCOID, pl_tuple, Anum_pg_proc_prosrc, + &isnull); + if (isnull) + elog(ERROR, "null prosrc"); + ReleaseSysCache(pl_tuple); + + source = DatumGetCString(DirectFunctionCall1(textout, pl_datum)); + elog(LOG, "source text:\n%s", source); + + return 0; +} + + The variable source containes the source that + needs to be interpreted and executed by the procedurual language handler + itself, or by an existing inplementation of the programming language that + the source text is written with. + + + + The following CREATE FUNCTION will set the source text + of the function to This is function's source text.: + +CREATE FUNCTION plsample_func() +RETURNS VOID +AS $$ + This is function's source text. +$$ LANGUAGE plsample; + + + + + Calling the function with the following command will log the function's + source text because of the elog() statement towards + the end of plsample_call_handler() function: + +SELECT plsample_func(); + + and emits the following to the log file: + +LOG: source text: + + This is function's source text. + + + + + + + Analyzing function arguments + + + This example introduces new code to plsample.c from + to demonstrate one method for analyzing + the arguments passed to the function. This code iterates through all of + the arguments to log its position, name and value as text, regardless of + its actual data type for ease of demonstration. + + + + Call get_func_arg_info() to get a pointer to the + argument types, names, and modes before iterating through them to retrieve + the value of each argument: + + get_func_arg_info(pl_tuple, &argtypes, &argnames, &argmodes); + + + + + The pointer to FunctionCallInfoBaseData + struct contains the number of argument passed to the function + flinfo->nargs. The following code + demostrates how to iterate through each argument and retrieve its value as + text: + + elog(LOG, "number of arguments : %d", fcinfo->nargs); + for (i = 0; i < fcinfo->nargs; i++) + { + Oid argtype = pl_struct->proargtypes.values[i]; + type_tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(argtype)); + if (!HeapTupleIsValid(type_tuple)) + elog(ERROR, "cache lookup failed for type %u", argtype); + + type_struct = (Form_pg_type) GETSTRUCT(type_tuple); + fmgr_info_cxt(type_struct->typoutput, &(arg_out_func[i]), proc_cxt); + ReleaseSysCache(type_tuple); + + value = OutputFunctionCall(&arg_out_func[i], fcinfo-<args[i].value); + + elog(LOG, "argument position: %d; name: %s; value: %s", i, argnames[i], + value); + } + + + + + Let's now create a function with three arugments consiting of a number, + text and an array of integers: + +CREATE FUNCTION plsample_func(a1 NUMERIC, a2 TEXT, a3 INTEGER[]) +RETURNS VOID +AS $$ + This is function's source text. +$$ LANGUAGE plsample; + + Then let's call the function with the following commands: + +SELECT plsample_func(1.23, 'abc', '{4, 5, 6}'); + + The elog() statements in the example will emit the + number of arguments, and the position, name and value of each argument + to the log file: + +LOG: number of arguments : 3 +LOG: argument position: 0; name: a1; value: 1.23 +LOG: argument position: 1; name: a2; value: abc +LOG: argument position: 2; name: a3; value: {4,5,6} + + + + + The complete example of plsample.c follows: + +#include <postgres.h> +#include <fmgr.h> +#include <funcapi.h> +#include <access/htup_details.h> +#include <catalog/pg_proc.h> +#include <catalog/pg_type.h> +#include <utils/memutils.h> +#include <utils/builtins.h> +#include <utils/syscache.h> + +MemoryContext TopMemoryContext = NULL; + +PG_MODULE_MAGIC; + +PG_FUNCTION_INFO_V1(plsample_call_handler); + +/* + * Handle function, procedure, and trigger calls. + */ +Datum +plsample_call_handler(PG_FUNCTION_ARGS) +{ + HeapTuple pl_tuple; + Datum pl_datum; + const char *source; + bool isnull; + + int i; + FmgrInfo *arg_out_func; + Form_pg_type type_struct; + HeapTuple type_tuple; + Form_pg_proc pl_struct; + volatile MemoryContext proc_cxt = NULL; + Oid *argtypes; + char **argnames; + char *argmodes; + char *value; + + /* Fetch the source of the function. */ + + pl_tuple = SearchSysCache(PROCOID, + ObjectIdGetDatum(fcinfo->flinfo->fn_oid), 0, 0, 0); + if (!HeapTupleIsValid(pl_tuple)) + elog(ERROR, "cache lookup failed for function %u", + fcinfo->flinfo->fn_oid); + pl_struct = (Form_pg_proc) GETSTRUCT(pl_tuple); + + pl_datum = SysCacheGetAttr(PROCOID, pl_tuple, Anum_pg_proc_prosrc, + &isnull); + if (isnull) + elog(ERROR, "null prosrc"); + ReleaseSysCache(pl_tuple); + + source = DatumGetCString(DirectFunctionCall1(textout, pl_datum)); + elog(LOG, "source text:\n%s", source); + + arg_out_func = (FmgrInfo *) palloc0(fcinfo->nargs * sizeof(FmgrInfo)); + proc_cxt = AllocSetContextCreate(TopMemoryContext, + "PL/Sample function", 0, (1 * 1024), (8 * 1024)); + get_func_arg_info(pl_tuple, &argtypes, &argnames, &argmodes); + + /* Iterate through all of the function arguments. */ + elog(LOG, "number of arguments : %d", fcinfo->nargs); + for (i = 0; i < fcinfo->nargs; i++) + { + Oid argtype = pl_struct->proargtypes.values[i]; + type_tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(argtype)); + if (!HeapTupleIsValid(type_tuple)) + elog(ERROR, "cache lookup failed for type %u", argtype); + + type_struct = (Form_pg_type) GETSTRUCT(type_tuple); + fmgr_info_cxt(type_struct->typoutput, &(arg_out_func[i]), proc_cxt); + ReleaseSysCache(type_tuple); + + value = OutputFunctionCall(&arg_out_func[i], fcinfo->args[i].value); + + elog(LOG, "argument position: %d; name: %s; value: %s", i, argnames[i], + value); + } + + return 0; +} + + + + + + Returning data + + + This example introduces new code to plsample.c from + to demonstrate how to return data + from the function. This code fetches the function's return type and + attempts to return the function's source text. + + + + The follow code segments fetches the return type of the function: + + type_tuple = SearchSysCache1(TYPEOID, + ObjectIdGetDatum(pl_struct->prorettype)); + if (!HeapTupleIsValid(type_tuple)) + elog(ERROR, "cache lookup failed for type %u", pl_struct->prorettype); + + + + + The follow code segments takes the function source text, fetched in a + previous section, and attempts to return that data: + + ret = InputFunctionCall(&result_in_func, source, result_typioparam, -1); + PG_RETURN_DATUM(ret); + + + + + The following function can be used to help demostrate the new + functionality: + +CREATE FUNCTION plsample_func(a1 NUMERIC, a2 TEXT, a3 INTEGER[]) +RETURNS TEXT +AS $$ + This is function's source text. +$$ LANGUAGE plsample; + + It is built upon the function used in the previous examples to now return + TEXT. Running the following command returns the source text + of the function: + +SELECT plsample_func(1.23, 'abc', '{4, 5, 6}'); + + + plsample_func +----------------------------------- + + + This is function's source text.+ + +(1 row) + + + + + The complete example of plsample.c follows: + +#include <postgres.h> +#include <fmgr.h> +#include <funcapi.h> +#include <access/htup_details.h> +#include <catalog/pg_proc.h> +#include <catalog/pg_type.h> +#include <utils/memutils.h> +#include <utils/builtins.h> +#include <utils/lsyscache.h> +#include <utils/syscache.h> + +MemoryContext TopMemoryContext = NULL; + +PG_MODULE_MAGIC; + +PG_FUNCTION_INFO_V1(plsample_call_handler); + +/* + * Handle function, procedure, and trigger calls. + */ +Datum +plsample_call_handler(PG_FUNCTION_ARGS) +{ + HeapTuple pl_tuple; + Datum ret; + char *source; + bool isnull; + + int i; + FmgrInfo *arg_out_func; + Form_pg_type type_struct; + HeapTuple type_tuple; + Form_pg_proc pl_struct; + volatile MemoryContext proc_cxt = NULL; + Oid *argtypes; + char **argnames; + char *argmodes; + char *value; + + Form_pg_type pg_type_entry; + Oid result_typioparam; + FmgrInfo result_in_func; + + /* Fetch the source of the function. */ + + pl_tuple = SearchSysCache(PROCOID, + ObjectIdGetDatum(fcinfo->flinfo->fn_oid), 0, 0, 0); + if (!HeapTupleIsValid(pl_tuple)) + elog(ERROR, "cache lookup failed for function %u", + fcinfo->flinfo->fn_oid); + pl_struct = (Form_pg_proc) GETSTRUCT(pl_tuple); + + ret = SysCacheGetAttr(PROCOID, pl_tuple, Anum_pg_proc_prosrc, &isnull); + if (isnull) + elog(ERROR, "null prosrc"); + ReleaseSysCache(pl_tuple); + + source = DatumGetCString(DirectFunctionCall1(textout, ret)); + elog(LOG, "source text:\n%s", source); + + arg_out_func = (FmgrInfo *) palloc0(fcinfo->nargs * sizeof(FmgrInfo)); + proc_cxt = AllocSetContextCreate(TopMemoryContext, + "PL/Sample function", 0, (1 * 1024), (8 * 1024)); + get_func_arg_info(pl_tuple, &argtypes, &argnames, &argmodes); + + /* Iterate through all of the function arguments. */ + elog(LOG, "number of arguments : %d", fcinfo->nargs); + for (i = 0; i < fcinfo->nargs; i++) + { + Oid argtype = pl_struct->proargtypes.values[i]; + type_tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(argtype)); + if (!HeapTupleIsValid(type_tuple)) + elog(ERROR, "cache lookup failed for type %u", argtype); + + type_struct = (Form_pg_type) GETSTRUCT(type_tuple); + fmgr_info_cxt(type_struct->typoutput, &(arg_out_func[i]), proc_cxt); + ReleaseSysCache(type_tuple); + + value = OutputFunctionCall(&arg_out_func[i], fcinfo->args[i].value); + + elog(LOG, "argument position: %d; name: %s; value: %s", i, argnames[i], + value); + } + + /* Fetch the return type of the function. */ + + type_tuple = SearchSysCache1(TYPEOID, + ObjectIdGetDatum(pl_struct->prorettype)); + if (!HeapTupleIsValid(type_tuple)) + elog(ERROR, "cache lookup failed for type %u", pl_struct->prorettype); + + pg_type_entry = (Form_pg_type) GETSTRUCT(type_tuple); + + proc_cxt = AllocSetContextCreate(TopMemoryContext, "PL/Sample function", + ALLOCSET_SMALL_SIZES); + + result_typioparam = getTypeIOParam(type_tuple); + + fmgr_info_cxt(pg_type_entry->typinput, &result_in_func, proc_cxt); + ReleaseSysCache(type_tuple); + + /* Simply return the function source text. */ + ret = InputFunctionCall(&result_in_func, source, result_typioparam, -1); + PG_RETURN_DATUM(ret); + + return 0; +} + + + + + + Additional notes + + + The examples provided in this sections for developing a procedural + language handler do not cover all aspects that may need to be considered + when introducing a new language. Here are some additional considerations: + + + + + + Caching the source text of the function for performance reasons. + + + + + + Handling trigger functions. + + + + + + Validating the source text. + + + + + + Handling returning sets of rows. + + + + + --GvXjxJ+pjyke8COw--