2-to-3 Question about adapter using AsIs

From: Ams Fwd <ams(dot)fwd(at)gmail(dot)com>
To: psycopg(at)postgresql(dot)org
Subject: 2-to-3 Question about adapter using AsIs
Date: 2023-11-20 18:57:52
Message-ID: CAP80KYqSayFXWFAG59==tX+cH+_vi1eiYuW8KQdDYsD1JE-YZg@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: psycopg

Hi,

I am working on migrating our django codebase from ver 2 to ver 3+ and
have run into a code conversion issue that I have not quite been able
to figure out.

Previously for a generated column in our schema (dealing with accented
names) we used to have:

from django.db import models
from psycopg2.extensions import AsIs, register_adapter

class PostgresDefaultValueType:
pass

register_adapter(PostgresDefaultValueType, lambda _: AsIs("DEFAULT"))

class PostgresHandledTextField(models.TextField):
def get_prep_value(self, value):
return PostgresDefaultValueType()

This was based off of a comment on a ticket
(https://code.djangoproject.com/ticket/21454#comment:28) to be able to
handle DEFAULT columns in postgres when using Django.

Trying to convert this to psycopg3's updated adapter framework, what I
have tried so far is this:

from django.db import models
from psycopg import adapters, sql
from psycopg.adapt import Dumper

class PostgresDefaultValueType:
pass

class PostgresDefaultValueTypeDumper(Dumper):
def dump(self, obj):
return sql.DEFAULT

adapters.register_dumper(PostgresDefaultValueType,
PostgresDefaultValueTypeDumper)

class PostgresHandledTextField(models.TextField):
def get_prep_value(self, value):
return PostgresDefaultValueType()

As far as I can tell from the documentation the `sql.DEFAULT` should
be the appropriate thing to put in the dumper so that generated query
uses `'DEFAULT'` in the correct place during query generation.

However when I do use this I run into

> ???
E TypeError: bytes or buffer expected, got <class 'psycopg.sql.SQL'>

psycopg_binary/pq/pqbuffer.pyx:111: TypeError

which in some ways makes sense as `AsIs` previously did something
special and it's not the same? Looking at the code, it should merely
be doing `PyUnicode_AsUTF8String` but I am assuming that `sql.DEFAULT`
is not generating the appropriate quoted string?

Any help in debugging this would be greatly appreciated

TIA.
AM

Responses

Browse psycopg by date

  From Date Subject
Next Message Daniele Varrazzo 2023-11-20 22:46:21 Re: 2-to-3 Question about adapter using AsIs
Previous Message Daniele Varrazzo 2023-10-24 22:16:50 Improving `Connection.notifies()` in Psycopg 3.2