Re: psycopg3, prepared statements

From: Adrian Klaver <adrian(dot)klaver(at)aklaver(dot)com>
To: Daniele Varrazzo <daniele(dot)varrazzo(at)gmail(dot)com>, Vladimir Ryabtsev <greatvovan(at)gmail(dot)com>
Cc: psycopg(at)postgresql(dot)org
Subject: Re: psycopg3, prepared statements
Date: 2020-12-24 16:41:25
Message-ID: 3a5a5655-51f6-4251-bbb9-64964e423e5b@aklaver.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: psycopg

On 12/23/20 4:14 PM, Daniele Varrazzo wrote:
> On Wed, 23 Dec 2020 at 23:23, Vladimir Ryabtsev <greatvovan(at)gmail(dot)com> wrote:
>>
>> Cause (query, types) can give more combinations than (query,)?
>
> Yes, that's the reason
>
> In [1]: import psycopg3
> In [2]: cnn = psycopg3.connect()
> In [3]: cnn.prepare_threshold = 2
>
> In [4]: cnn.execute("select 1 + %s", [1]).fetchone()
> Out[4]: (2,)
> In [5]: cnn.execute("select 1 + %s", [None]).fetchone()
> Out[5]: (None,)
> In [7]: cnn.execute("select 1 + %s", [2]).fetchone()
> Out[7]: (3,)

Alright, I was misunderstanding. I thought you where referring to
something like:

cur.execute("select * from some table where id > %s and user_name = %s
and current = %s", [2, 'aklaver', True])

>
> After 3 times the expression should have been prepared, but the tally
> has been spread in two values (0 is unknown oid, 20 is int oid).
>
> In [8]: cnn._prepared_statements
> Out[8]: OrderedDict([((b'select 1 + $1', (0,)), 1), ((b'select 1 +
> $1', (20,)), 2)])
>
> In [9]: cnn.execute("select 1 + %s", [3]).fetchone()
> Out[9]: (4,)
>
> However, when either key passes the threshold, eventually preparation happens.
>
> In [10]: cnn._prepared_statements
> Out[10]:
> OrderedDict([((b'select 1 + $1', (0,)), 1),
> ((b'select 1 + $1', (20,)), b'_pg3_0')])
>
> _pg3_0 is the name under which that combination of query and types is
> now prepared (it is local per session).
>
> -- Daniele
>

--
Adrian Klaver
adrian(dot)klaver(at)aklaver(dot)com

In response to

Browse psycopg by date

  From Date Subject
Next Message Daniele Varrazzo 2021-01-18 12:04:31 Designing a better connection pool for psycopg3
Previous Message Daniele Varrazzo 2020-12-24 00:14:23 Re: psycopg3, prepared statements