-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
110 lines (90 loc) · 3.38 KB
/
Copy pathdatabase.py
File metadata and controls
110 lines (90 loc) · 3.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
"""
データベース - NotsqlDBメインクラス
"""
import os
from typing import Dict, List
from .collection import Collection
class NotsqlDB:
"""NotsqlDBメインクラス"""
def __init__(self, db_name: str, db_path: str = None):
"""
データベースを初期化
Args:
db_name: データベース名
db_path: データベースファイルの保存パス(デフォルト: ./data)
"""
self.db_name = db_name
# データベースごとに別のディレクトリを作成
if db_path:
self.db_path = os.path.join(db_path, db_name)
else:
self.db_path = os.path.join(os.getcwd(), 'data', db_name)
self.collections: Dict[str, Collection] = {}
# データベースディレクトリを作成
os.makedirs(self.db_path, exist_ok=True)
def collection(self, name: str) -> Collection:
"""
コレクションを取得(存在しない場合は作成)
Args:
name: コレクション名
Returns:
Collection: コレクションオブジェクト
"""
if name not in self.collections:
self.collections[name] = Collection(name, self.db_path)
return self.collections[name]
def list_collections(self) -> List[str]:
"""
コレクションのリストを取得
Returns:
List[str]: コレクション名のリスト
"""
collections = []
for filename in os.listdir(self.db_path):
if filename.endswith('.json') and not filename.endswith('_indexes.json'):
collection_name = filename[:-5] # .jsonを除去
collections.append(collection_name)
return collections
def drop_collection(self, name: str) -> bool:
"""
コレクションを削除
Args:
name: コレクション名
Returns:
bool: 成功した場合はTrue
"""
collection_file = os.path.join(self.db_path, f"{name}.json")
if name in self.collections:
self.collections[name].drop()
del self.collections[name]
return True
elif os.path.exists(collection_file):
# メモリ上になくてもファイルが存在する場合
collection = Collection(name, self.db_path)
collection.drop()
return True
return False
def drop_database(self):
"""データベース全体を削除"""
import shutil
if os.path.exists(self.db_path):
shutil.rmtree(self.db_path)
self.collections.clear()
def get_stats(self) -> Dict[str, any]:
"""
データベースの統計情報を取得
Returns:
Dict[str, any]: 統計情報
"""
stats = {
'db_name': self.db_name,
'db_path': self.db_path,
'collections': {}
}
for collection_name in self.list_collections():
collection = self.collection(collection_name)
stats['collections'][collection_name] = {
'count': collection.count_documents(),
'indexes': collection.list_indexes()
}
return stats