Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql Compress() with sqlalchemy

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?

like image 384
Giorgos Komnino Avatar asked Jun 05 '12 09:06

Giorgos Komnino


1 Answers

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.

like image 119
zzzeek Avatar answered Oct 05 '22 17:10

zzzeek