Re: How to insert either a value or the column default?

Поиск
Список
Период
Сортировка
От Daniele Varrazzo
Тема Re: How to insert either a value or the column default?
Дата
Msg-id CA+mi_8ZQx-vMm6PMAw72a0sRATEh3RBXu5rwHHhNNpQk0YHwQg@mail.gmail.com
обсуждение исходный текст
Ответ на How to insert either a value or the column default?  ("W. Matthew Wilson" <matt@tplus1.com>)
Ответы Re: How to insert either a value or the column default?  (Adrian Klaver <adrian.klaver@aklaver.com>)
Re: How to insert either a value or the column default?  ("W. Matthew Wilson" <matt@tplus1.com>)
Список pgsql-general
On Sat, Aug 23, 2014 at 7:10 PM, W. Matthew Wilson <matt@tplus1.com> wrote:
> I have a table that looks sort of like this:
>
>     create table tasks
>     (
>         task_id serial primary key,
>         title text,
>         status text not null default 'planned'
>     );
>
> In python, I have a function like this:
>
>     def insert_task(title, status=None):
>         ....
>
> and when status is passed in, I want to run a SQL insert statement like this:
>
>     insert into tasks
>     (title, status)
>     values
>     (%s, %s)
>
> but when status is not passed in, I want to run this SQL insert instead:
>
>     insert into tasks
>     (title, status)
>     values
>     (%s, default)

You can "easily" do that in psycopg with:

    class Default(object):
        def __conform__(self, proto):
            if proto is psycopg2.extensions.ISQLQuote:
                return self
        def getquoted(self):
            return 'DEFAULT'

    DEFAULT = Default()

    >>> print cur.mogrify('insert into place values (%s, %s)',
['adsf', DEFAULT])
    insert into place values ('adsf', DEFAULT)

You can find more details at
http://initd.org/psycopg/docs/advanced.html#adapting-new-python-types-to-sql-syntax

It should be added to the library (it was first discussed in 2003...),
but it's one of these things that will stop working when psycopg will
start using the "extended query protocol" (together with other nifty
features such as string literals for table/columns names) so in my
mind it can only be included when psycopg will be able to do both
client-side parameter interpolation and server-side arguments passing,
and when the distinction between the two strategies will be clear
(this is planned for a future psycopg3 but there is no timeline for it
yet).

-- Daniele


В списке pgsql-general по дате отправления:

Предыдущее
От: Tom Lane
Дата:
Сообщение: Re: Failure to load plpgsql.so
Следующее
От: Adrian Klaver
Дата:
Сообщение: Re: How to insert either a value or the column default?