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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318 | class Database:
"""Thin wrapper around an SQLite connection for the library."""
def __init__(self, path: Path | str | None = None):
self.path = Path(path) if path else _DEFAULT_DB
self.conn = sqlite3.connect(str(self.path), check_same_thread=False)
self.conn.execute("PRAGMA journal_mode=WAL")
self.conn.execute("PRAGMA foreign_keys=ON")
self.conn.executescript(_SCHEMA)
self._run_migrations()
def _run_migrations(self):
for sql in _MIGRATIONS:
try:
self.conn.execute(sql)
except sqlite3.OperationalError:
pass
# ── Works ──────────────────────────────────────────────────────────
def add_work(
self,
openalex_id: str,
title: str,
*,
doi: str | None = None,
publication_year: int | None = None,
work_type: str | None = None,
cited_by_count: int = 0,
abstract: str | None = None,
journal: str | None = None,
authors: list[dict] | None = None,
keywords: list[str] | None = None,
relationships: list[dict] | None = None,
) -> None:
with self.conn:
self.conn.execute(
"""INSERT OR IGNORE INTO works
(id, doi, title, publication_year, type, cited_by_count, abstract, journal)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
(openalex_id, doi, title, publication_year, work_type,
cited_by_count, abstract, journal),
)
if authors:
for author in authors:
aid = author.get("id")
name = author.get("name", "")
orcid = author.get("orcid")
pos = author.get("position")
self.conn.execute(
"INSERT OR IGNORE INTO authors (id, name, orcid) VALUES (?, ?, ?)",
(aid, name, orcid),
)
self.conn.execute(
"INSERT OR IGNORE INTO work_authors (work_id, author_id, position) VALUES (?, ?, ?)",
(openalex_id, aid, pos),
)
if keywords:
for kw in keywords:
self.conn.execute(
"INSERT OR IGNORE INTO work_keywords (work_id, keyword) VALUES (?, ?)",
(openalex_id, kw),
)
if relationships:
for rel in relationships:
self.conn.execute(
"INSERT OR IGNORE INTO work_relationships (work_id, related_id, relationship) VALUES (?, ?, ?)",
(openalex_id, rel["id"], rel["type"]),
)
def remove_work(self, openalex_id: str) -> None:
with self.conn:
self.conn.execute("DELETE FROM works WHERE id = ?", (openalex_id,))
def remove_works(self, openalex_ids: list[str]) -> None:
with self.conn:
self.conn.executemany(
"DELETE FROM works WHERE id = ?", [(wid,) for wid in openalex_ids]
)
def get_work(self, openalex_id: str) -> dict | None:
row = self.conn.execute("SELECT * FROM works WHERE id = ?", (openalex_id,)).fetchone()
if not row:
return None
cols = [d[0] for d in self.conn.execute("SELECT * FROM works LIMIT 0").description]
return dict(zip(cols, row))
def list_works(
self,
*,
search: str | None = None,
sort_by: str = "date_added",
keyword: str | None = None,
tag: str | None = None,
) -> list[dict]:
order_cols = {"title", "publication_year", "cited_by_count", "date_added"}
if sort_by not in order_cols:
sort_by = "date_added"
sql = f"SELECT DISTINCT w.* FROM works w"
params: list = []
joins: list[str] = []
conditions: list[str] = []
if keyword:
joins.append("JOIN work_keywords wk ON w.id = wk.work_id")
conditions.append("wk.keyword = ?")
params.append(keyword)
if tag:
joins.append("JOIN work_tags wt ON w.id = wt.work_id")
conditions.append("wt.tag = ?")
params.append(tag)
if search:
conditions.append("(w.title LIKE ? OR w.abstract LIKE ?)")
params.extend((f"%{search}%", f"%{search}%"))
if joins:
sql += " " + " ".join(joins)
if conditions:
sql += " WHERE " + " AND ".join(conditions)
sql += f" ORDER BY w.{sort_by} DESC"
rows = self.conn.execute(sql, params).fetchall()
cols = [d[0] for d in self.conn.execute("SELECT * FROM works LIMIT 0").description]
return [dict(zip(cols, r)) for r in rows]
def work_exists(self, openalex_id: str) -> bool:
return (
self.conn.execute("SELECT 1 FROM works WHERE id = ?", (openalex_id,)).fetchone()
is not None
)
def set_bibtex(self, openalex_id: str, bibtex: str) -> None:
with self.conn:
self.conn.execute(
"UPDATE works SET bibtex = ? WHERE id = ?", (bibtex, openalex_id)
)
def set_notes(self, openalex_id: str, notes: str) -> None:
with self.conn:
self.conn.execute(
"UPDATE works SET notes = ? WHERE id = ?", (notes, openalex_id)
)
def set_abstract(self, openalex_id: str, abstract: str) -> None:
with self.conn:
self.conn.execute(
"UPDATE works SET abstract = ? WHERE id = ?", (abstract, openalex_id)
)
# ── Authors ────────────────────────────────────────────────────────
def get_authors_for_work(self, openalex_id: str) -> list[dict]:
rows = self.conn.execute(
"""SELECT a.id, a.name, a.orcid, wa.position
FROM authors a JOIN work_authors wa ON a.id = wa.author_id
WHERE wa.work_id = ?
ORDER BY wa.position""",
(openalex_id,),
).fetchall()
cols = ["id", "name", "orcid", "position"]
return [dict(zip(cols, r)) for r in rows]
# ── Relationships ──────────────────────────────────────────────────
def get_relationships(self, openalex_id: str, rel_type: str | None = None) -> list[dict]:
if rel_type:
rows = self.conn.execute(
"SELECT related_id, relationship FROM work_relationships WHERE work_id = ? AND relationship = ?",
(openalex_id, rel_type),
).fetchall()
else:
rows = self.conn.execute(
"SELECT related_id, relationship FROM work_relationships WHERE work_id = ?",
(openalex_id,),
).fetchall()
return [{"id": r[0], "type": r[1]} for r in rows]
# ── Keywords ───────────────────────────────────────────────────────
def get_keywords_for_work(self, openalex_id: str) -> list[str]:
rows = self.conn.execute(
"SELECT keyword FROM work_keywords WHERE work_id = ?", (openalex_id,)
).fetchall()
return [r[0] for r in rows]
def list_all_keywords(self) -> list[str]:
rows = self.conn.execute(
"SELECT DISTINCT keyword FROM work_keywords ORDER BY keyword"
).fetchall()
return [r[0] for r in rows]
# ── Tags ───────────────────────────────────────────────────────────
def get_tags_for_work(self, openalex_id: str) -> list[str]:
rows = self.conn.execute(
"SELECT tag FROM work_tags WHERE work_id = ?", (openalex_id,)
).fetchall()
return [r[0] for r in rows]
def set_tags(self, openalex_id: str, tags: list[str]) -> None:
with self.conn:
self.conn.execute("DELETE FROM work_tags WHERE work_id = ?", (openalex_id,))
for tag in tags:
tag = tag.strip()
if tag:
self.conn.execute(
"INSERT OR IGNORE INTO work_tags (work_id, tag) VALUES (?, ?)",
(openalex_id, tag),
)
def list_all_tags(self) -> list[str]:
rows = self.conn.execute("SELECT DISTINCT tag FROM work_tags ORDER BY tag").fetchall()
return [r[0] for r in rows]
# ── Settings ───────────────────────────────────────────────────────
def get_setting(self, key: str, default: str | None = None) -> str | None:
row = self.conn.execute("SELECT value FROM settings WHERE key = ?", (key,)).fetchone()
return row[0] if row else default
def set_setting(self, key: str, value: str) -> None:
with self.conn:
self.conn.execute(
"INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)", (key, value)
)
# ── Export ─────────────────────────────────────────────────────────
def export_bibtex(self, *, ids: list[str] | None = None) -> str:
"""Return BibTeX string. If *ids* given, export only those; otherwise all."""
if ids:
placeholders = ",".join("?" for _ in ids)
rows = self.conn.execute(
f"SELECT bibtex FROM works WHERE id IN ({placeholders}) AND bibtex IS NOT NULL",
ids,
).fetchall()
else:
rows = self.conn.execute(
"SELECT bibtex FROM works WHERE bibtex IS NOT NULL ORDER BY date_added DESC"
).fetchall()
return "\n\n".join(r[0] for r in rows)
# ── Lifecycle ──────────────────────────────────────────────────────
def close(self) -> None:
self.conn.close()
|