I am implementing a class that resembles a typical database table:
I decided to implement the class directly rather than use a wrapper around sqlite.
What would be a good data structure to use?
Just as an example, one approach I was thinking about is a dictionary. Its keys are the values in the primary key column of the table; its values are the rows implemented in one of these ways:
As lists. Column numbers are mapped into column titles (using a list for one direction and a map for the other). Here, a retrieval operation would first convert column title into column number, and then find the corresponding element in the list.
As dictionaries. Column titles are the keys of this dictionary.
Not sure about the pros/cons of the two.
The reasons I want to write my own code are:
You might want to consider creating a class which uses an in-memory sqlite table under the hood:
import sqlite3
class MyTable(object):
def __init__(self):
self.conn=sqlite3.connect(':memory:')
self.cursor=self.conn.cursor()
sql='''\
CREATE TABLE foo ...
'''
self.execute(sql)
def execute(self,sql,args):
self.cursor.execute(sql,args)
def delete(self,id,reason):
sql='UPDATE table SET softdelete = 1, reason = %s where tableid = %s'
self.cursor.execute(sql,(reason,id,))
def verify(self):
# Check that certain conditions are true
# Report (or raise exception?) if violated
def build_index(self):
self.verify()
...
Soft-delete can be implemented by having a softdelete
column (of bool type).
Similarly, you can have a column to store reason for deletion.
Undeleting would simply involve updating the row and changing the softdelete
value.
Selecting rows that have not been deleted could be achieved with the SQL condition WHERE softdelete != 1
.
You could write a verify
method to verify conditions on your data are satisfied. And you could call that method from within your build_index
method.
Another alternative is to use a numpy structured masked array.
It's hard to say what would be fastest. Perhaps the only sure way to tell would be to write code for each and benchmark on real-world data with timeit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With