Files
fn-serverless/examples/postgres/func.go
Reed Allman 2341456334 FN_ prefix env vars
this adds `FN_` in front of env vars that we are injecting into calls, for
namespacing reasons. this will break code relying on the current variables but
if we want to do this, the chance is now really. alternatively, we could
maintain both the old and new for a short period of time to ease the
adjustment (speak now...). updated the docs, as well.

this also adds tests for the notoriously finicky configuration of the env vars
and headers when setting up a call. this won't test the container / request
for the call is actually receiving them, but it's a decent start and will yell
loudly enough upon formatting breakage.

added back FXLB_WAIT to a couple places so the lb can ride again

one thing for feedback:

headers are a bit confusing at the moment (not from this change, but that
behavior is kept here for now), we've a chance to fix them. currently, headers
in the request __are not__ prefixed with `FN_HEADER_`, i.e. 'hot'+sync containers
will receive `Content-Length` in the http request headers, yet a 'cold'
container from the same request would receive `FN_HEADER_Content-Length` in
its environment. This is additionally confusing because if this function were
hot+async, it would receive `FN_HEADER_Content-Length` in the headers, where
just changing it to sync goes back to `Content-Length`. If that was confusing,
then point made ;)

I propose to remove the `FN_HEADER_` prefix for request headers in the
environment, so that the request headers and env will match, as request
headers already are of this format (not prefixed). please lmk thoughts here

Would be fine with going back to the 'plain' vars too, then this patch will
mostly just be adding tests and changing `FN_FORMAT` to `FORMAT`. obviously,
from the examples, it's a bit ingrained now. anyway, entirely up to y'all.
2017-09-06 07:24:50 -07:00

104 lines
2.2 KiB
Go

package main
import (
"bytes"
"database/sql"
"encoding/json"
"io/ioutil"
"log"
"os"
"strconv"
"github.com/pkg/errors"
_ "github.com/lib/pq"
)
var (
// command to execute, 'SELECT' or 'INSERT'
command = os.Getenv("FN_HEADER_COMMAND")
// postgres host:port, e.g. 'postgres:5432'
server = os.Getenv("FN_HEADER_SERVER")
// postgres table name
table = os.Getenv("FN_HEADER_TABLE")
)
func main() {
req, err := ioutil.ReadAll(os.Stdin)
if err != nil {
log.Fatal(errors.Wrap(err, "failed to read stdin"))
}
db, err := sql.Open("postgres", "postgres://postgres@"+server+"?sslmode=disable")
if err != nil {
log.Println("Failed to connect to postgres server")
log.Fatal(err)
return
}
switch command {
case "SELECT":
if resp, err := selectCommand(req, db); err != nil {
log.Fatal(errors.Wrap(err, "select command failed"))
} else {
log.Println(resp)
}
case "INSERT":
if err := insertCommand(req, db); err != nil {
log.Fatal(errors.Wrap(err, "insert command failed"))
}
default:
log.Fatalf("invalid command: %q", command)
}
}
func selectCommand(req []byte, db *sql.DB) (string, error) {
// Parse request JSON
var params map[string]interface{}
if err := json.Unmarshal(req, &params); err != nil {
return "", errors.Wrap(err, "failed to parse json")
}
// Build query and gather arguments
var query bytes.Buffer
var args []interface{}
query.WriteString("SELECT json_agg(t) FROM (SELECT * FROM ")
query.WriteString(table)
query.WriteString(" WHERE")
first := true
arg := 1
for k, v := range params {
args = append(args, v)
if !first {
query.WriteString(" AND")
}
query.WriteString(" ")
query.WriteString(k)
query.WriteString("=$")
query.WriteString(strconv.Itoa(arg))
arg += 1
first = false
}
query.WriteString(") AS t")
// Execute query
r := db.QueryRow(query.String(), args...)
var resp string
if err := r.Scan(&resp); err != nil {
return "", errors.Wrap(err, "failed to execute select query")
}
return resp, nil
}
func insertCommand(req []byte, db *sql.DB) error {
q := "INSERT INTO " + table + " SELECT * FROM json_populate_record(null::" + table + ", $1)"
_, err := db.Exec(q, req)
if err != nil {
return errors.Wrap(err, "Failed to execute insert query")
}
return nil
}