· 6 years ago · Apr 10, 2019, 05:22 PM
1# Sqlite3 File System via FUSE (fusepy) and Python 3
2
3import os
4import sys
5import sqlite3
6from fuse import FUSE, Operations
7
8
9INIT_QUERY = """
10CREATE TABLE IF NOT EXISTS Files (
11 id integer primary key autoincrement not null,
12 filename char(255) not null,
13 content text null
14)
15"""
16
17class SqliteFS(Operations):
18
19 def __init__(self, db_path):
20
21 self.connection = sqlite3.connect(db_path)
22 self.connection.cursor().execute(INIT_QUERY)
23
24 def destroy(self, path):
25
26 self.connection.commit()
27 self.connection.close()
28
29 def create(self, path, mode):
30
31 print("SqliteFS: create() path: {0}, mode: {1}".format(path, mode))
32
33 res = self.connection.cursor().execute("INSERT INTO Files (filename) VALUES (?)", (os.path.basename(path),))
34
35 print("SqliteFS: Backend res: {0}".format(res))
36
37 return 0
38
39 def read(self, path, size, offset, fh):
40
41 print("SqliteFS: read() path: {0}, size: {1}, offset: {2}, fh: {3}".format(path, size, offset, fh))
42
43 res = self.connection.cursor().execute()("SELECT content FROM Files WHERE filename = ?", (path,)).fetchone()
44
45 print("SqliteFS: Backend res: {0}".format(res))
46
47 return res
48
49 def readdir(self, path, fh):
50
51 print("SqliteFS: readdir() path: {0}, fh: {1}".format(path, fh))
52
53 res = [item[0] for item in self.connection.cursor().execute("SELECT filename FROM Files").fetchall()]
54
55 print("SqliteFS: Backend res: {0}".format(res))
56
57 return [".", "..", "test.bin"] + res
58
59 def write(self, path, data, offset, fh):
60
61 print("SqliteFS: write() path: {0}, data: {1}, offset: {2}, fh: {3}".format(path, data, offset, fh))
62
63 res = self.connection.cursor().execute("UPDATE Files SET content = ? WHERE filename = ?", (data, path))
64
65 print("SqliteFS: Backend res: {0}".format(res))
66
67 return len(data)
68
69
70if __name__ == "__main__":
71
72 fuse = FUSE(SqliteFS(sys.argv[1]), sys.argv[2], foreground=True, nothreads=True)