Skip to content

Instantly share code, notes, and snippets.

@hmans
Created June 29, 2014 12:07
Show Gist options
  • Save hmans/cf18d182c51fb9191df6 to your computer and use it in GitHub Desktop.
Save hmans/cf18d182c51fb9191df6 to your computer and use it in GitHub Desktop.
PostgreSQL Large Object Data Store for Dragonfly
# This is a Dragonfly data store using PostgreSQL Large Objects. It appears to work fine,
# but I ended up using a different solution in my project. Anyway, here you go.
#
class PostgresDataStore
def write(content, opts={})
data_oid = store_lo(content.data)
meta_oid = store_lo(Marshal.dump(content.meta))
"#{data_oid}/#{meta_oid}"
end
def read(uid)
data_oid, meta_oid = uid.split('/')
data = fetch_lo(data_oid)
meta = Marshal.load(fetch_lo(meta_oid))
data && [data, meta]
end
def destroy(uid)
data_oid, meta_oid = uid.split('/')
remove_lo(data_oid)
remove_lo(meta_oid)
end
private
def store_lo(data)
ActiveRecord::Base.transaction do
identifier = connection.lo_creat
lo = connection.lo_open(identifier, ::PG::INV_WRITE)
connection.lo_truncate(lo, 0)
connection.lo_write(lo, data)
connection.lo_close(lo)
return identifier
end
end
def fetch_lo(identifier)
ActiveRecord::Base.transaction do
lo = connection.lo_open(identifier.to_i)
size = connection.lo_lseek(lo, 0, 2)
connection.lo_lseek(lo, 0, 0)
content = connection.lo_read(lo, size)
connection.lo_close(lo)
return content
end
end
def remove_lo(identifier)
ActiveRecord::Base.transaction do
connection.lo_unlink(identifier.to_i)
end
end
def connection
ActiveRecord::Base.connection.raw_connection
end
end
@KlausTrainer
Copy link

See this comment for some background information regarding its usability.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment