Skip to content

Commit a341d17

Browse files
committed
Check if a file ID already exists before creating a new record
1 parent 3a9d49f commit a341d17

File tree

1 file changed

+21
-8
lines changed

1 file changed

+21
-8
lines changed

jupyter_server_fileid/manager.py

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -312,21 +312,21 @@ def _from_normalized_path(self, path: Optional[str]) -> Optional[str]:
312312

313313
def _create(self, path: str) -> str:
314314
path = self._normalize_path(path)
315+
row = self.con.execute("SELECT id FROM Files WHERE path = ?", (path,)).fetchone()
316+
existing_id = row and row[0]
317+
318+
if existing_id:
319+
return existing_id
320+
315321
id = self._uuid()
316322
self.con.execute("INSERT INTO Files (id, path) VALUES (?, ?)", (id, path))
317323
return id
318324

319325
def index(self, path: str) -> str:
326+
# create new record
320327
with self.con:
321-
path = self._normalize_path(path)
322-
row = self.con.execute("SELECT id FROM Files WHERE path = ?", (path,)).fetchone()
323-
existing_id = row and row[0]
324-
325-
if existing_id:
326-
return existing_id
327-
328-
# create new record
329328
id = self._create(path)
329+
self.con.commit()
330330
return id
331331

332332
def get_id(self, path: str) -> Optional[str]:
@@ -612,6 +612,7 @@ def _sync_file(self, path, stat_info):
612612
"SELECT id, path, crtime FROM Files WHERE ino = ?", (stat_info.ino,)
613613
).fetchone()
614614

615+
615616
# if ino is not in database, return None
616617
if src is None:
617618
return None
@@ -625,6 +626,7 @@ def _sync_file(self, path, stat_info):
625626
# otherwise update existing record with new path, moving any indexed
626627
# children if necessary. then return its id
627628
self._update(id, path=path)
629+
628630
if stat_info.is_dir and old_path != path:
629631
self._move_recursive(old_path, path)
630632
self._update_cursor = True
@@ -671,6 +673,17 @@ def _create(self, path, stat_info):
671673
dangerous and may throw a runtime error if the file is not guaranteed to
672674
have a unique `ino`.
673675
"""
676+
# If the path exists
677+
existing_id, ino = None, None
678+
row = self.con.execute("SELECT id, ino FROM Files WHERE path = ?", (path,)).fetchone()
679+
if row:
680+
existing_id, ino = row
681+
682+
# If the file ID already exists and the current file matches our records
683+
# return the file ID instead of creating a new one.
684+
if existing_id and stat_info.ino == ino:
685+
return existing_id
686+
674687
id = self._uuid()
675688
self.con.execute(
676689
"INSERT INTO Files (id, path, ino, crtime, mtime, is_dir) VALUES (?, ?, ?, ?, ?, ?)",

0 commit comments

Comments
 (0)