Make a built-in solution for storing lists in the database.
Do this with tables. Here is a working example but this needs to get implemented into Ask as a built-in behind the scenes feature.
db_class GenericList:
id = _db.col(_db.int, _db.pk)
def set_list(self, entry):
if entry:
for item in entry:
self.push(item)
def s(self):
return {
id: self.id,
list: self.list()
}
def list(self):
return [self.get(item.index) for item in GenericListItem._db.get_by(parent_id=self.id)]
def push(self, item):
new_item = GenericListItem(item, self.id)
_db.add(new_item)
return self.s()
def get(self, index):
item = GenericListItem._db.get_by(parent_id=self.id, index=index).first()
return item.in_type()
def remove(self, index):
item = GenericListItem._db.get_by(parent_id=self.id, index=index).first()
_db.delete(item)
db_class GenericListItem:
id = _db.col(_db.int, _db.pk)
index = _db.col(_db.int)
item = _db.col(_db.bytes)
parent_id = _db.col(_db.int)
def _init(self, item, parent_id):
self.item = pickle.dumps(item)
self.parent_id = parent_id
self.index = self.get_last_index() + 1
def s(self):
return {
id: self.id,
index: self.index,
item: self.in_type(),
parent_id: self.parent_id
}
def get_last_index(self):
last_item = GenericListItem._db.get_by(parent_id=self.parent_id).order_by(_db.desc(GenericListItem.id)).first()
if _db.exists(last_item):
return last_item.index
return -1
def in_type(self):
return pickle.loads(self.item)
def generic_list_factory(entry):
generic_list = GenericList()
_db.add(generic_list)
generic_list.set_list(entry)
return generic_list
Usage
my_list = generic_list_factory([1, 2, 3, 4])
print(my_list).list() # [1, 2, 3, 4]
my_list.push(5)
print(my_list).list() # [1, 2, 3, 4, 5]
my_list.remove(4)
print(my_list).list() # [1, 2, 3, 4]
print(my_list.get(0)) # 1
How it should work when it's built-in to Ask
my_list = _db.list([1, 2, 3, 4]) # or a single function e.g. my_list = make_list([1, 2, 3, 4])
my_list.push(5)
my_list.remove(4)
my_list.get(0)
my_list.list()
Another thought is that maybe we should add an alias for the _db.int
type e.g. _db.list_id
just for readabilities sake.