Created
May 22, 2013 10:07
-
-
Save SegFaultAX/5626533 to your computer and use it in GitHub Desktop.
Quick and dirty EAV (for cryosphere, #python)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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