I would like to know how to pass a list/set/tuple from python (via psycopg2) to a postgres query as a one-column table. For example, if the list is ['Alice', 'Bob'], I want the table to be:
| Temp |
+-------+
| Alice |
| Bob |
If anybody has alternate suggestions to achieve my result after reading the section below, that would be fine as well.
Background
I have an SQL table which has three columns of interest:
ID | Members | Group
---+---------+----------
1 | Alice | 1
2 | Alice | 1
3 | Bob | 1
4 | Charlie | 1
5 | Alice | 2
6 | Bob | 2
7 | Alice | 3
8 | Bob | 4
9 | Charlie | 3
I want a table of groups with certain combinations of members. Note that a member may have multiple items in a group (e.g. IDs 1 and 2).
For an input of ['Alice'] I would want which groups she is in (present) and which contain only her (unique), as below:
Group | Type
------+--------
1 | present
2 | present
3 | present
For an input of ['Alice', 'Bob']:
Group | Type
------+--------
1 | present
2 | unique
From reading it looks like I am looking for relational division as described here, for which I need to do what the original question asks as the input is taken from a web form processed in python. Again, alternative solutions are also welcome.
You need to make a subquery where you create member counts, then do a simple divisor query with a
GROUP BYstatement, but against aIN static_setclause instead of against another table. Because this is python, you already know the size of the static set.I’ll assume you already have a database cursor, and the table is called
GroupMembers:There is thus no need to use a TEMP table to execute this query.
If you do need a TEMP table for other purposes, inserting a set of rows is easiest with
.executemany():Note that
.executemany()expects a sequence of sequences; each entry is a sequence of row data, which in this case only holds one name each. I generate a list of single-item tuples to fill the table.Alternatively, you can use a sequence of mappings too and use the
%(name)sparameter syntax (so the row data sequence becomes[dict(name=name) for name in members]).