PL/Tcl allows writing PostgreSQL functions in the Tcl programming language. As a trusted language, it restricts access to the filesystem and other system resources.
CREATEEXTENSIONpltcl;-- Simple function returning a greeting
CREATEFUNCTIONtcl_hello(nametext)RETURNStextLANGUAGEpltclAS$$return"Hello, $1!"$$;SELECTtcl_hello('world');-- Function with conditional logic
CREATEFUNCTIONtcl_max(ainteger,binteger)RETURNSintegerLANGUAGEpltclAS$$if{$1>$2}{return$1}return$2$$;-- Set-returning function
CREATEFUNCTIONtcl_sequence(countinteger)RETURNSSETOFintegerLANGUAGEpltclAS$$for{seti1}{$i<=$1}{incri}{return_next$i}$$;-- Trigger function
CREATEFUNCTIONtcl_audit()RETURNStriggerLANGUAGEpltclAS$$setNEW(modified_at)[clockformat[clockseconds]-format"%Y-%m-%d %H:%M:%S"]return[arraygetNEW]$$;
Database access from PL/Tcl uses the spi_exec command:
CREATEFUNCTIONtcl_count_rows(tbltext)RETURNSintegerLANGUAGEpltclAS$$spi_exec"SELECT count(*) AS cnt FROM $1"return$cnt$$;