-
-
Save datavudeja/d9dd9e294720303792ac7ff6615194a4 to your computer and use it in GitHub Desktop.
Walk through the filesystem, store in sqlite db
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
| """Walk through the filesystem, store in sqlite db | |
| Utility script for walking a filesystem, and storing file information in a sqlite | |
| database. | |
| Goals/Design Notes: | |
| - [x] Pure standard library | |
| - [x] Name, Path as seprate columns | |
| - [x] Store the datetime that a file pth was inserted | |
| - [x] Implement fulltext search of both filenames and paths | |
| - Use `sqlite-utils` enable-fts as a reference (or use code directly?) | |
| - Answer - Wound up mostly relying on sqlite3 docs | |
| - [x] Add stats for how many files scanned in how long | |
| - [ ] Strech goal: figure out how to hash metadata and see what's changed | |
| Example of querying the FTS table: | |
| -- Search both directory and filename | |
| SELECT * FROM fileinfo_fts WHERE fileinfo_fts MATCH 'needle' ORDER BY rank LIMIT 10; | |
| -- Search just filename | |
| SELECT * FROM fileinfo_fts WHERE filename MATCH 'needle' ORDER BY rank LIMIT 10; | |
| MIT License | |
| Copyright © 2024 Joe Kerhin | |
| Permission is hereby granted, free of charge, to any person obtaining a copy of this | |
| software and associated documentation files (the “Software”), to deal in the Software | |
| without restriction, including without limitation the rights to use, copy, modify, | |
| merge, publish, distribute, sublicense, and/or sell copies of the Software, and to | |
| permit persons to whom the Software is furnished to do so, subject to the following | |
| conditions: | |
| The above copyright notice and this permission notice shall be included in all copies or | |
| substantial portions of the Software. | |
| THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, | |
| INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | |
| PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT | |
| HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF | |
| CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR | |
| THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
| """ | |
| import sqlite3 | |
| import os | |
| import json | |
| from datetime import datetime | |
| from typing import Iterable | |
| DB_FILE = "fileinfo.sqlite3" | |
| # In normal use, this would be a bunch of network mounts | |
| TO_SEARCH = [ | |
| "\\\\some\\fileshare\\location", | |
| ] | |
| def stat_to_dict(s_obj: os.stat_result) -> dict[str, int]: | |
| return {k: getattr(s_obj, k) for k in dir(s_obj) if k.startswith("st_")} | |
| def db_connect(db_name: str = DB_FILE) -> sqlite3.Connection: | |
| con = sqlite3.connect(db_name) | |
| cur = con.cursor() | |
| cur.execute( | |
| """CREATE TABLE IF NOT EXISTS fileinfo( | |
| processed_timestamp TEXT, | |
| directory TEXT, | |
| filename TEXT, | |
| stats JSON, | |
| error TEXT | |
| ) | |
| """ | |
| ) | |
| con.commit() | |
| return con | |
| def populate_fts(con: sqlite3.Connection): | |
| con.execute( | |
| """CREATE VIRTUAL TABLE IF NOT EXISTS fileinfo_fts USING FTS5( | |
| directory, filename, content=fileinfo | |
| ) | |
| """ | |
| ) | |
| con.commit() | |
| # NB: "Rows are assigned contiguously ascending rowid values, starting with 1, in | |
| # the order that they are returned by the SELECT statement." | |
| con.execute( | |
| """INSERT INTO fileinfo_fts (rowid, directory, filename) | |
| SELECT rowid, directory, filename FROM fileinfo""" | |
| ) | |
| con.commit() | |
| def walk_dirs(con: sqlite3.Connection, to_crawl: Iterable[str]): | |
| for root_dir in to_crawl: | |
| for dirname, _, files in os.walk(root_dir): | |
| for filename in files: | |
| pth = os.path.join(dirname, filename) | |
| error_str, stats = None, None | |
| try: | |
| stat_dict = stat_to_dict(os.stat(pth)) | |
| stats = json.dumps(stat_dict, indent=None) | |
| except KeyboardInterrupt as e: | |
| # Don't catch keyboard interrupt, throw back up the stack | |
| raise e | |
| except Exception as e: | |
| error_str = str(e) | |
| proc_ts = datetime.now().isoformat() | |
| con.execute( | |
| "INSERT INTO fileinfo VALUES(?, ?, ?, ?, ?)", | |
| (proc_ts, dirname, filename, stats, error_str), | |
| ) | |
| con.commit() | |
| def main(): | |
| con = db_connect(DB_FILE) | |
| start_scan = datetime.now() | |
| try: | |
| walk_dirs(con, TO_SEARCH) | |
| except KeyboardInterrupt: | |
| print("Exiting without completing scan...") | |
| end_scan = datetime.now() | |
| scan_dur = end_scan - start_scan | |
| (n_files,) = con.execute( | |
| "SELECT count(*) FROM fileinfo WHERE processed_timestamp >= ?", | |
| (start_scan.isoformat(),), | |
| ).fetchone() | |
| populate_fts(con) | |
| print(f"Scanned {n_files} in {scan_dur}") | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment