Re: [pysqlite] Strings coming back as Unicode.

Gerhard Häring <[email protected]> Mon, 24 Nov 2008 10:14:35 +0100
Newsgroups gmane.comp.python.db.pysqlite.user
Message-ID <[email protected]>
Harish Vishwanath wrote:
> Hello All,
> 
> I am using Pysqlite2.5.0 on top of Python 2.5 with Elixir and SqlAlchemy 
> as ORM packages.
> 
>  >>> from elixir import *
>  >>> class A(Entity):
> ...     name = Field(String(40))
> ...
>  >>> metadata.bind = "sqlite:///c:\\temp.sqlite"
>  >>> metadata.bind.echo = True
>  >>> setup_all(True)
>  >>> a = A(name="Ascii")
>  >>> session.flush()
>  >>> session.commit()
>  >>> b = session.query(A)[0]
>  >>> b.name <http://b.name>
> u'Ascii'
>  >>>
>  >>> type(b.name <http://b.name>)
> <type 'unicode'>
> 
> 
> I have set proper options in SqlAlchemy/Elixir to NOT TO Convert strings 
> to Unicode automatically. [...]

Which ones? I don't see any in your code.

> I went through PySqlite's docs and found that 
> there is a connection.text_factory option which I can set to 'str' to 
> avoid this conversion. But since I use SQLAlchemy, I have no control 
> over the connection it obtains from Sqlite3 Dialect.

Sure you have, you can still get at the raw DB-API connection object. 
Something like this might work:

from elixir import *
from sqlalchemy import create_engine

def my_create_engine():
     engine = create_engine("sqlite:///") # :memory:
     engine.engine.connect().connection.connection.text_factory = str
     return engine

metadata.bind = my_create_engine()
...

> Is there any way, to set connection.text_factory=str by default? Kindly 
> let me know.

There isn't. And I agree with Roger: Unicode is the way to go for new 
applications.

-- Gerhard