6

table:
id(integer primary key)
data(blob)

I use mysql and sqlalchemy. To insert data I use:

o = Demo()
o.data = mydata
session.add(o)
session.commit()

I would like to insert to table like that:

INSERT INTO table(data) VALUES(COMPRESS(mydata))

How can I do this using sqlalchemy?

1
  • object = object() seems not a good idea to me. You are overwriting the type name object... Commented Jul 10, 2012 at 11:02

1 Answer 1

1

you can assign a SQL function to the attribute:

from sqlalchemy import func
object.data = func.compress(mydata)
session.add(object)
session.commit()

Here's an example using a more DB-agnostic lower() function:

from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

Base= declarative_base()

class A(Base):
    __tablename__ = "a"

    id = Column(Integer, primary_key=True)
    data = Column(String)

e = create_engine('sqlite://', echo=True)
Base.metadata.create_all(e)
s = Session(e)

a1 = A()
a1.data = func.lower("SomeData")
s.add(a1)
s.commit()

assert a1.data == "somedata"

you can make it automatic with @validates:

from sqlalchemy.orm import validates
class MyClass(Base):
    # ...
    data = Column(BLOB)

    @validates("data")
    def _set_data(self, key, value):
        return func.compress(value)

if you want it readable in python before the flush, you'd need to memoize it locally and use a descriptor to access it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.