Skip to content
Dr. Alan U. Kennington edited this page Sep 7, 2017 · 4 revisions

Go package: psqlbuild.
Imports packages s2list, elist.
Dr. Alan U. Kennington.

A Go-package to build PostgreSQL query strings safely and conveniently.

This Go-package is a work-in-progress. It isn't really ready to use yet. But it does work as designed though!

The convenience is most noticeable for very long complex queries. The safety is essential for preventing SQL injections. In principle, no SQL should ever be written by hand. The SQL language is too dangerous!

Example (with error-handling omitted):

    var query0 Psql_select;
    var str0 string;
    var E error;
    // The select-item list.
    E = query0.SelectAppendExprAs(Xfld("h", "time"), "time");
    E = query0.SelectAppendExpr(Xfld("h", "gm"));
    E = query0.SelectAppendExprAs(Xfn("round", Xop("/",
        Xop("*",
            Xfld("h", "gm"),
            Xfld("i", "kj_kg")),
        Xnum("1000.0")) ),
        "kJ");
    E = query0.SelectAppendExprAs(Xfld("i", "sname"), "food type");
    E = query0.SelectAppendExprAs(Xfld("i", "kj_kg"), "kJ/kg");
    E = query0.SelectAppendExprAs(Xfld("i", "index"), "info");
    // The from-item list.
    E = query0.FromAppendItem(Xtable("food_hist", "h"));
    E = query0.FromAppendItem(Xtable("food_info", "i"));
    // The where-condition.
    E = query0.WhereSetExpr(
    Xop("and",
        Xop("=",
            Xfld("h", "type"),
            Xfld("i", "index")),
        Xop("and",
            Xop(">=",
                Xfld("h", "time"),
                Xnum(times.jd0unixMelb0)),
            Xop("<",
                Xfld("h", "time"),
                Xnum(times.jd0unixMelb1)) )));
    // The order-list.
    E = query0.OrderAppend(Xfld("h", "time"));
    // Find out what this query produces.
    str0, E = query0.Build();
    // Execute the SQL string.
    rows2, E := db.Query(str0);

The output of the query-string build-command is:

    SELECT "h"."time" AS "time",
        "h"."gm",
        "round"((("h"."gm") * ("i"."kj_kg")) / (1000.0)) AS "kJ",
        "i"."sname" AS "food type",
        "i"."kj_kg" AS "kJ/kg",
        "i"."index" AS "info"
    FROM "food_hist" AS "h", "food_info" AS "i"
    WHERE (("h"."type") = ("i"."index")) 
        and ((("h"."time") >= (1504188000))
        and (("h"."time") < (1504274400)))
    ORDER BY "h"."time";
Clone this wiki locally