Skip to content

Instantly share code, notes, and snippets.

@macrat
Created Dec 6, 2018
Embed
What would you like to do?
SQL上にファイルシステム的なもの
import hashlib
import pathlib
import sqlite3
class Tree:
def __init__(self, db, tag):
self.db = db
self.tag = tag
def __getitem__(self, path):
return self.db.execute('SELECT content FROM tree, objects WHERE tag=? AND path=? AND tree.hash = objects.hash', (self.tag, path)).fetchone()[0]
def __setitem__(self, path, content):
hash_ = hashlib.sha1(content).hexdigest()
self.db.execute('INSERT OR REPLACE INTO objects VALUES (?, ?)', (
hash_,
content,
))
self.db.execute('INSERT OR REPLACE INTO tree VALUES (?, ?, ?)', (
self.tag,
path,
hash_,
))
self.db.commit()
def __iter__(self):
yield from (x[0] for x in self.db.execute('SELECT path FROM tree WHERE tag=?', (self.tag, )))
class FileSystem:
def __init__(self, path='test.db'):
self.db = sqlite3.connect('test.db')
self.db.execute('CREATE TABLE IF NOT EXISTS objects (hash TEXT PRIMARY KEY, content BLOB)')
self.db.execute('CREATE TABLE IF NOT EXISTS tree (tag TEXT, path TEXT, hash TEXT, PRIMARY KEY (tag, path))')
def __getitem__(self, tag):
return Tree(self.db, tag)
if __name__ == '__main__':
fs = FileSystem()
head = fs['HEAD']
for path in pathlib.Path('test').glob('**/*'):
head[str(path)] = path.open('rb').read()
for x in head:
print(x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment