Created
October 28, 2013 04:39
-
-
Save zackmdavis/7191527 to your computer and use it in GitHub Desktop.
proposed revisions to SerpentineRecord
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
def has_many(self, association, class_name, foreign_key = None, primary_key = "id"): | |
foreign_key = foreign_key or self.__class__.__name__.lower()+"_id" | |
search = lambda: eval(class_name).where({foreign_key: self.__dict_[primary_key]}) | |
setattr(self, association, search) | |
def belongs_to(self, association, class_name, foreign_key = None, primary_key = "id"): | |
foreign_key = foreign_key or class_name.lower()+"_id" | |
search = lambda: eval(class_name).where({primary_key: self.__dict__[foreign_key]}) | |
setattr(self, association, search) | |
def all(self): | |
query = "SELECT * FROM {0};".format(self.table_name) | |
results = self.db_connection.execute(query).fetchall() | |
result_dicts = [self.dict_from_row(row) for row in results] | |
return [SqlObject(self.db_connection, self.table_name, rd, rd["id"]) for rd in result_dicts] | |
def find(self, id): | |
query = "SELECT * FROM {0} WHERE id = ?;".format(self.table_name) | |
result = self.db_connection.execute(query, (id,)).fetchone() | |
result_dict = self.dict_from_row(result) | |
return SqlObject(self.db_connection, self.table_name, result_dict, id) | |
def where(self, search_parameters): | |
where_string = ["{0} = ?".format(k) for k in search_parameters] | |
where_string = ", ".join(where_string) | |
query = "SELECT * FROM {0} WHERE {1}".format(self.table_name, where_string) | |
results = self.db_connection.execute(query, tuple(search_parameters.values())).fetchall() | |
result_dicts = [self.dict_from_row(row) for row in results] | |
return [SqlObject(self.db_connection, self.table_name, rd, rd["id"]) for rd in result_dicts] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment