Skip to content

Instantly share code, notes, and snippets.

@SegFaultAX
Created May 22, 2013 10:07
Show Gist options
  • Save SegFaultAX/5626533 to your computer and use it in GitHub Desktop.
Save SegFaultAX/5626533 to your computer and use it in GitHub Desktop.
Quick and dirty EAV (for cryosphere, #python)
#!/usr/bin/env python
import sqlite3
SQL_EAV_TABLE = """
CREATE TABLE IF NOT EXISTS eav (
entity TEXT NOT NULL,
attr TEXT NOT NULL,
value BLOB,
PRIMARY KEY(entity, attr)
);
"""
SQL_INSERT_ATTR = """
INSERT INTO eav (entity, attr, value) VALUES (?, ?, ?);
"""
SQL_SELECT_ENTITY = """
SELECT attr, value FROM eav WHERE entity = ?;
"""
def create_table(conn):
cur = conn.cursor()
cur.execute(SQL_EAV_TABLE)
return conn.commit()
def save_entity(conn, name, entity):
cur = conn.cursor()
vals = [(name, ) + i for i in entity.items()]
cur.executemany(SQL_INSERT_ATTR, vals)
return conn.commit()
def load_entity(conn, name):
cur = conn.cursor()
return dict(cur.execute(SQL_SELECT_ENTITY, (name, )))
if __name__ == "__main__":
conn = sqlite3.connect(":memory:")
create_table(conn)
entity = {
"name": "jim",
"health": 100
}
save_entity(conn, "player", entity)
print load_entity(conn, "player")
print load_entity(conn, "foobar")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment