fandanGO-db 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Fragment Screen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,107 @@
1
+ Metadata-Version: 2.4
2
+ Name: fandanGO-db
3
+ Version: 0.1.0
4
+ Summary: A small library for FandanGO to manage SQLite DB connections
5
+ Author: FragmentScreen
6
+ Requires-Python: >=3.8
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: pytest>=8.0.0
10
+ Dynamic: license-file
11
+
12
+ # FandanGO - SQLite database library
13
+
14
+ [![OSV Scanner](https://github.com/FragmentScreen/fandanGO-db/actions/workflows/osv-scanner.yml/badge.svg)](https://github.com/FragmentScreen/fandanGO-db/actions/workflows/osv-scanner.yml)
15
+
16
+ A small library that provides a simple SQLite Database API for FandanGO plugins.
17
+
18
+ ## Installation
19
+
20
+ Install using PIP:
21
+
22
+ ```bash
23
+ # Install from PyPI
24
+ python3 -m pip install fandanGO-db
25
+
26
+ # Or install directly from the GitHub repository
27
+ python3 -m pip install git+https://github.com/FragmentScreen/fandanGO-db.git
28
+ ```
29
+
30
+ ## Configuration
31
+
32
+ The library expects a configuration file (e.g. `core.cfg` or `plugin.cfg`) containing the database location directory under the `[DDBB]` section.
33
+
34
+ ### Sample `core.cfg` or `plugin.cfg`
35
+ ```ini
36
+ [DDBB]
37
+ DDBB_PATH = /path/to/database/directory
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ The library provides a simple `SQLiteDB` wrapper that handles connection pooling and cursor management, as well as models that implement CRUD operations for FandanGO's database tables.
43
+
44
+ `Project` manages data about the FandanGO projects. `ProjectInfo` manages metadata used by the plugins. Each of these will typically have its own separate SQLite database file. For example, the core plugin will have a database file containing project data, and the plugin manager will have a database file containing plugin metadata.
45
+
46
+ A plugin may implement its own database structure by implementing a custom `Model` subclass.
47
+
48
+ ### Connecting to a Database
49
+
50
+ ```python
51
+ from pathlib import Path
52
+ from fGOdb import SQLiteDB
53
+
54
+ # Initialize the connection helper with the config file and target database file name
55
+ db = SQLiteDB(Path("path/to/core.cfg"), "project.db")
56
+ ```
57
+
58
+ ### Using Models
59
+
60
+ ```python
61
+ from fGOdb import Project, ProjectInfo
62
+
63
+ # Initialize the model with the database helper
64
+ project_info = ProjectInfo(db)
65
+
66
+ # Set, get, list, and delete metadata
67
+ project_info.set("project1", "key1", "value1")
68
+ value = project_info.get("project1", "key1")
69
+ project_info.list_by_project("project1")
70
+ project_info.delete("project1", "key1")
71
+ ```
72
+
73
+ ## Development and Testing
74
+
75
+ To run the test suite locally:
76
+
77
+ 1. Clone the repository and install the development dependencies:
78
+ ```bash
79
+ pip install -e .[dev]
80
+ ```
81
+ 2. Run tests with `pytest`:
82
+ ```bash
83
+ pytest
84
+ ```
85
+
86
+ ## Security Scanning
87
+
88
+ This repo uses [OSV Scanner](https://github.com/google/osv-scanner) for vulnerability detection.
89
+
90
+ **When it runs:**
91
+ - Daily at 03:00 UTC (full scan)
92
+ - On PRs targeting main (changed deps only)
93
+ - On push to main (full scan)
94
+
95
+ **If vulnerabilities are found:**
96
+ 1. Check the [Security tab](../../security) for alerts
97
+ 2. To ignore false positives, add entries to `osv-scanner.toml`:
98
+ ```toml
99
+ [[IgnoredVulns]]
100
+ id = "GHSA-xxxx-xxxx-xxxx"
101
+ reason = "Justification"
102
+ ```
103
+
104
+ **References:**
105
+ - [OSV Scanner docs](https://google.github.io/osv-scanner/)
106
+ - [GitHub Action](https://github.com/google/osv-scanner-action)
107
+ - [OSV Database](https://osv.dev/)
@@ -0,0 +1,96 @@
1
+ # FandanGO - SQLite database library
2
+
3
+ [![OSV Scanner](https://github.com/FragmentScreen/fandanGO-db/actions/workflows/osv-scanner.yml/badge.svg)](https://github.com/FragmentScreen/fandanGO-db/actions/workflows/osv-scanner.yml)
4
+
5
+ A small library that provides a simple SQLite Database API for FandanGO plugins.
6
+
7
+ ## Installation
8
+
9
+ Install using PIP:
10
+
11
+ ```bash
12
+ # Install from PyPI
13
+ python3 -m pip install fandanGO-db
14
+
15
+ # Or install directly from the GitHub repository
16
+ python3 -m pip install git+https://github.com/FragmentScreen/fandanGO-db.git
17
+ ```
18
+
19
+ ## Configuration
20
+
21
+ The library expects a configuration file (e.g. `core.cfg` or `plugin.cfg`) containing the database location directory under the `[DDBB]` section.
22
+
23
+ ### Sample `core.cfg` or `plugin.cfg`
24
+ ```ini
25
+ [DDBB]
26
+ DDBB_PATH = /path/to/database/directory
27
+ ```
28
+
29
+ ## Usage
30
+
31
+ The library provides a simple `SQLiteDB` wrapper that handles connection pooling and cursor management, as well as models that implement CRUD operations for FandanGO's database tables.
32
+
33
+ `Project` manages data about the FandanGO projects. `ProjectInfo` manages metadata used by the plugins. Each of these will typically have its own separate SQLite database file. For example, the core plugin will have a database file containing project data, and the plugin manager will have a database file containing plugin metadata.
34
+
35
+ A plugin may implement its own database structure by implementing a custom `Model` subclass.
36
+
37
+ ### Connecting to a Database
38
+
39
+ ```python
40
+ from pathlib import Path
41
+ from fGOdb import SQLiteDB
42
+
43
+ # Initialize the connection helper with the config file and target database file name
44
+ db = SQLiteDB(Path("path/to/core.cfg"), "project.db")
45
+ ```
46
+
47
+ ### Using Models
48
+
49
+ ```python
50
+ from fGOdb import Project, ProjectInfo
51
+
52
+ # Initialize the model with the database helper
53
+ project_info = ProjectInfo(db)
54
+
55
+ # Set, get, list, and delete metadata
56
+ project_info.set("project1", "key1", "value1")
57
+ value = project_info.get("project1", "key1")
58
+ project_info.list_by_project("project1")
59
+ project_info.delete("project1", "key1")
60
+ ```
61
+
62
+ ## Development and Testing
63
+
64
+ To run the test suite locally:
65
+
66
+ 1. Clone the repository and install the development dependencies:
67
+ ```bash
68
+ pip install -e .[dev]
69
+ ```
70
+ 2. Run tests with `pytest`:
71
+ ```bash
72
+ pytest
73
+ ```
74
+
75
+ ## Security Scanning
76
+
77
+ This repo uses [OSV Scanner](https://github.com/google/osv-scanner) for vulnerability detection.
78
+
79
+ **When it runs:**
80
+ - Daily at 03:00 UTC (full scan)
81
+ - On PRs targeting main (changed deps only)
82
+ - On push to main (full scan)
83
+
84
+ **If vulnerabilities are found:**
85
+ 1. Check the [Security tab](../../security) for alerts
86
+ 2. To ignore false positives, add entries to `osv-scanner.toml`:
87
+ ```toml
88
+ [[IgnoredVulns]]
89
+ id = "GHSA-xxxx-xxxx-xxxx"
90
+ reason = "Justification"
91
+ ```
92
+
93
+ **References:**
94
+ - [OSV Scanner docs](https://google.github.io/osv-scanner/)
95
+ - [GitHub Action](https://github.com/google/osv-scanner-action)
96
+ - [OSV Database](https://osv.dev/)
@@ -0,0 +1,4 @@
1
+ from .col import TableCol
2
+ from .table import Table
3
+ from .conn import SQLiteDB
4
+ from .models import Model, Project, ProjectInfo
@@ -0,0 +1,21 @@
1
+ class TableCol:
2
+ def __init__(self, name: str, type: str, nullable: bool):
3
+ self._name = name
4
+ self._nullable = nullable
5
+ self._type = type
6
+
7
+ @property
8
+ def name(self) -> str:
9
+ return self._name
10
+
11
+ @property
12
+ def type(self) -> str:
13
+ return self._type
14
+
15
+ @property
16
+ def nullable(self) -> bool:
17
+ return self._nullable
18
+
19
+ def __str__(self):
20
+ return f"{self.name} {self.type}" + (" NOT NULL" if not self._nullable else "")
21
+
@@ -0,0 +1,79 @@
1
+ import os
2
+ import configparser
3
+ import traceback
4
+ from pathlib import Path
5
+ from typing import Optional
6
+ from contextlib import contextmanager
7
+ from sqlite3 import dbapi2 as sqlite, Connection, Cursor
8
+ from .table import Table
9
+
10
+ class SQLiteDB:
11
+ def __init__(self, config_file: Path, db_name: str):
12
+ self._config = configparser.ConfigParser()
13
+ self._config.read(config_file)
14
+ # Expected config section DDBB with option DDBB_PATH
15
+ self._db_path = self._config.get("DDBB", "DDBB_PATH")
16
+ self._db_name = db_name
17
+
18
+ @property
19
+ def db_path(self) -> str:
20
+ return self._db_path
21
+
22
+ @property
23
+ def db_name(self) -> str:
24
+ return self._db_name
25
+
26
+ @property
27
+ def config(self) -> configparser.ConfigParser:
28
+ return self._config
29
+
30
+ def connect(self) -> Connection:
31
+ """Open a SQLite connection to *name* inside the configured DDBB directory.
32
+
33
+ Args:
34
+ name: Filename of the SQLite database (e.g. ``"project.db"``).
35
+ """
36
+ path = os.path.join(self._db_path, self.db_name)
37
+ os.makedirs(os.path.dirname(path), exist_ok=True)
38
+ return sqlite.connect(database=path)
39
+
40
+ def close(self, connection: Connection):
41
+ connection.close()
42
+
43
+ def create_table(self, connection: Connection, table: Table):
44
+ cursor = connection.cursor()
45
+ cols = ", ".join([str(col) for col in table.cols])
46
+ cursor.execute(f"CREATE TABLE IF NOT EXISTS {table.name} ({cols});")
47
+ connection.commit()
48
+
49
+ def update_table(self, connection: Connection, table: Table):
50
+ cursor = connection.cursor()
51
+ cursor.execute(
52
+ f"UPDATE {table.name} SET key = ?, value = ? WHERE project_name = ?;",
53
+ (table.key, table.value, table.project_name),
54
+ )
55
+ connection.commit()
56
+
57
+ @contextmanager
58
+ def db_session(self, error_message: str = "could not perform database action") -> Optional[tuple[Cursor, Connection]]:
59
+ """Context manager yielding ``(cursor, connection)`` for *db_name*.
60
+
61
+ Args:
62
+ error_message: Human-readable description logged on failure.
63
+ db_name: Filename of the SQLite database.
64
+
65
+ Yields:
66
+ A tuple of (cursor, connection) if the database connection is successful.
67
+ """
68
+ connection = None
69
+ try:
70
+ connection = self.connect()
71
+ yield connection.cursor(), connection
72
+ except Exception as e:
73
+ print(f"... {error_message} because of: {e}")
74
+ if os.getenv("DEV") == "LOCAL":
75
+ print(traceback.format_exc())
76
+ finally:
77
+ if connection:
78
+ self.close(connection)
79
+
@@ -0,0 +1,252 @@
1
+ """Database model classes for the FandanGO SQLite library.
2
+
3
+ This module provides high-level, object-oriented wrappers around the low-level
4
+ `SQLiteDB` helper. Each model knows its own table schema and implements basic
5
+ CRUD operations that are useful for the library's public API.
6
+ """
7
+
8
+ from typing import Union
9
+ from abc import ABC, abstractmethod
10
+ from typing import List, Tuple, Optional
11
+
12
+ from .conn import SQLiteDB
13
+ from .table import Table
14
+ from .col import TableCol
15
+
16
+
17
+ class Model(ABC):
18
+ """Abstract base class for table-specific models.
19
+
20
+ Sub-classes must implement ``_define_table`` to return a :class:`Table`
21
+ describing the schema. The constructor creates the table if it does not
22
+ already exist.
23
+
24
+ Args:
25
+ db: The :class:`SQLiteDB` connection wrapper.
26
+ """
27
+
28
+ def __init__(self, db: SQLiteDB):
29
+ self._db = db
30
+ self._table: Table = self._define_table()
31
+ # Ensure the table exists in the .sqlite file.
32
+ with self._db.connect() as connection:
33
+ self._db.create_table(connection, self._table)
34
+
35
+ @property
36
+ def db(self) -> SQLiteDB:
37
+ return self._db
38
+
39
+ @property
40
+ def table(self) -> Table:
41
+ return self._table
42
+
43
+ @abstractmethod
44
+ def _define_table(self) -> Table:
45
+ """Return the :class:`Table` definition for the model."""
46
+ raise NotImplementedError
47
+
48
+ def _session(self, error_message: str = "database error"):
49
+ """Obtain a fresh cursor/connection pair via the SQLiteDB context manager."""
50
+ return self._db.db_session(error_message)
51
+
52
+
53
+ class Project(Model):
54
+ """Model for the ``project`` table.
55
+
56
+ Columns:
57
+ - project_name (TEXT, primary identifier)
58
+ - start_date (INTEGER, Unix timestamp)
59
+ - plugin_manager (TEXT)
60
+
61
+ Args:
62
+ db: The :class:`SQLiteDB` connection wrapper.
63
+ """
64
+
65
+ def __init__(self, db: SQLiteDB):
66
+ super().__init__(db)
67
+
68
+ def _define_table(self) -> Table:
69
+ return Table(
70
+ name="project",
71
+ cols=[
72
+ TableCol("project_name", "TEXT", False),
73
+ TableCol("start_date", "INTEGER", False),
74
+ TableCol("plugin_manager", "TEXT", False),
75
+ ],
76
+ )
77
+
78
+ # ---------------------------------------------------------------------
79
+ # CRUD operations
80
+ # ---------------------------------------------------------------------
81
+ def insert(self, project_name: str, start_date: int, plugin_manager: str) -> None:
82
+ """Insert a new project row. Raises if the project already exists."""
83
+ with self._session("could not insert project") as (cursor, connection):
84
+ cursor.execute(
85
+ "INSERT INTO project (project_name, start_date, plugin_manager) VALUES (?,?,?)",
86
+ (project_name, start_date, plugin_manager),
87
+ )
88
+ connection.commit()
89
+
90
+ def get(self, project_name: str) -> Optional[Tuple[str, int, str]]:
91
+ """Return a single project row or ``None`` if it does not exist.
92
+ The return value is ``(project_name, start_date, plugin_manager)``.
93
+ """
94
+ with self._session("could not fetch project") as (cursor, _):
95
+ cursor.execute(
96
+ "SELECT project_name, start_date, plugin_manager FROM project WHERE project_name = ?",
97
+ (project_name,),
98
+ )
99
+ row = cursor.fetchone()
100
+ return row if row else None
101
+
102
+ def update(self, project_name: str, **kwargs) -> bool:
103
+ """Update one or more fields of a project.
104
+ ``kwargs`` may contain ``start_date`` and/or ``plugin_manager``.
105
+ Returns ``True`` if a row was modified.
106
+ """
107
+ fields = []
108
+ values = []
109
+ if "start_date" in kwargs:
110
+ fields.append("start_date = ?")
111
+ values.append(kwargs["start_date"])
112
+ if "plugin_manager" in kwargs:
113
+ fields.append("plugin_manager = ?")
114
+ values.append(kwargs["plugin_manager"])
115
+ if not fields:
116
+ return False
117
+ values.append(project_name)
118
+ sql = f"UPDATE project SET {', '.join(fields)} WHERE project_name = ?"
119
+ with self._session("could not update project") as (cursor, connection):
120
+ cursor.execute(sql, tuple(values))
121
+ connection.commit()
122
+ return cursor.rowcount > 0
123
+
124
+ def delete(self, project_name: str) -> bool:
125
+ """Delete a project row. Returns ``True`` if a row was removed."""
126
+ with self._session("could not delete project") as (cursor, connection):
127
+ cursor.execute("DELETE FROM project WHERE project_name = ?", (project_name,))
128
+ connection.commit()
129
+ return cursor.rowcount > 0
130
+
131
+ def list_all(self) -> List[Tuple[str, int, str]]:
132
+ """Return a list of all projects ordered by name."""
133
+ with self._session("could not list projects") as (cursor, _):
134
+ cursor.execute(
135
+ "SELECT project_name, start_date, plugin_manager FROM project ORDER BY project_name"
136
+ )
137
+ return list(cursor.fetchall())
138
+
139
+
140
+ class ProjectInfo(Model):
141
+ """Model for the ``project_info`` table.
142
+
143
+ Columns:
144
+ - project_name (TEXT)
145
+ - key (TEXT)
146
+ - value (TEXT)
147
+
148
+ Args:
149
+ db: The :class:`SQLiteDB` connection wrapper.
150
+ """
151
+
152
+ def __init__(self, db: SQLiteDB):
153
+ super().__init__(db)
154
+
155
+ def _define_table(self) -> Table:
156
+ return Table(
157
+ name="project_info",
158
+ cols=[
159
+ TableCol("project_name", "TEXT", False),
160
+ TableCol("key", "TEXT", False),
161
+ TableCol("value", "TEXT", False),
162
+ ],
163
+ )
164
+
165
+ # ---------------------------------------------------------------------
166
+ # CRUD / helper operations
167
+ # ---------------------------------------------------------------------
168
+ def set(self, project_name: str, key: str, value: str) -> None:
169
+ """
170
+ Insert or replace a metadata entry for a project.
171
+ The table does not enforce uniqueness, so we simply ``INSERT`` - callers can
172
+ decide whether to delete first if they need strict replacement.
173
+
174
+ Args:
175
+ project_name (str): The name of the project.
176
+ key (str): The key of the metadata.
177
+ value (str): The value of the metadata.
178
+ """
179
+ with self._session("could not set project info") as (cursor, connection):
180
+ cursor.execute(
181
+ "INSERT INTO project_info (project_name, key, value) VALUES (?,?,?)",
182
+ (project_name, key, value),
183
+ )
184
+ connection.commit()
185
+
186
+ def get(self, project_name: str, *key: str, all: bool = False) -> Optional[Union[str, List[str]]]:
187
+ """
188
+ Retrieve a single metadata value or ``None`` if missing.
189
+
190
+ Args:
191
+ project_name (str): The name of the project.
192
+ *key (str): The key(s) of the metadata. Multiple keys are supported.
193
+ all (bool): If True, return all values for the keys. If False, return only the first value (default).
194
+
195
+ Returns:
196
+ Optional[Union[str, List[str]]]: The value of the key or ``None`` if missing.
197
+ """
198
+ with self._session("could not get project info") as (cursor, _):
199
+ placeholders = ",".join(["?"] * len(key))
200
+ cursor.execute(
201
+ f"SELECT value FROM project_info WHERE project_name = ? AND key IN ({placeholders}) ORDER BY ROWID DESC",
202
+ (project_name, *key),
203
+ )
204
+ if all:
205
+ rows = cursor.fetchall()
206
+ return [row[0] for row in rows] if rows else None
207
+ else:
208
+ row = cursor.fetchone()
209
+ return row[0] if row else None
210
+
211
+ def list_by_project(self, project_name: str) -> List[Tuple[str, str]]:
212
+ """
213
+ Return all ``(key, value)`` pairs for a given project.
214
+
215
+ Args:
216
+ project_name (str): The name of the project.
217
+
218
+ Returns:
219
+ List[Tuple[str, str]]: A list of ``(key, value)`` pairs for the given project.
220
+ """
221
+ with self._session("could not list project info") as (cursor, _):
222
+ cursor.execute(
223
+ "SELECT key, value FROM project_info WHERE project_name = ?",
224
+ (project_name,),
225
+ )
226
+ return list(cursor.fetchall())
227
+
228
+ def delete(self, project_name: str, key: Optional[str] = None) -> int:
229
+ """
230
+ Delete metadata entries.
231
+ If ``key`` is ``None`` all rows for the project are removed.
232
+ Returns the number of rows deleted.
233
+
234
+ Args:
235
+ project_name (str): The name of the project.
236
+ key (Optional[str]): The key of the metadata. If ``None`` all rows for the project are removed.
237
+
238
+ Returns:
239
+ int: The number of rows deleted.
240
+ """
241
+ with self._session("could not delete project info") as (cursor, connection):
242
+ if key is None:
243
+ cursor.execute(
244
+ "DELETE FROM project_info WHERE project_name = ?", (project_name,)
245
+ )
246
+ else:
247
+ cursor.execute(
248
+ "DELETE FROM project_info WHERE project_name = ? AND key = ?",
249
+ (project_name, key),
250
+ )
251
+ connection.commit()
252
+ return cursor.rowcount
@@ -0,0 +1,14 @@
1
+ from .col import TableCol
2
+
3
+ class Table:
4
+ def __init__(self, name: str, cols: list[TableCol]):
5
+ self._name = name
6
+ self._cols = cols
7
+
8
+ @property
9
+ def name(self) -> str:
10
+ return self._name
11
+
12
+ @property
13
+ def cols(self) -> list[TableCol]:
14
+ return self._cols
@@ -0,0 +1,107 @@
1
+ Metadata-Version: 2.4
2
+ Name: fandanGO-db
3
+ Version: 0.1.0
4
+ Summary: A small library for FandanGO to manage SQLite DB connections
5
+ Author: FragmentScreen
6
+ Requires-Python: >=3.8
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: pytest>=8.0.0
10
+ Dynamic: license-file
11
+
12
+ # FandanGO - SQLite database library
13
+
14
+ [![OSV Scanner](https://github.com/FragmentScreen/fandanGO-db/actions/workflows/osv-scanner.yml/badge.svg)](https://github.com/FragmentScreen/fandanGO-db/actions/workflows/osv-scanner.yml)
15
+
16
+ A small library that provides a simple SQLite Database API for FandanGO plugins.
17
+
18
+ ## Installation
19
+
20
+ Install using PIP:
21
+
22
+ ```bash
23
+ # Install from PyPI
24
+ python3 -m pip install fandanGO-db
25
+
26
+ # Or install directly from the GitHub repository
27
+ python3 -m pip install git+https://github.com/FragmentScreen/fandanGO-db.git
28
+ ```
29
+
30
+ ## Configuration
31
+
32
+ The library expects a configuration file (e.g. `core.cfg` or `plugin.cfg`) containing the database location directory under the `[DDBB]` section.
33
+
34
+ ### Sample `core.cfg` or `plugin.cfg`
35
+ ```ini
36
+ [DDBB]
37
+ DDBB_PATH = /path/to/database/directory
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ The library provides a simple `SQLiteDB` wrapper that handles connection pooling and cursor management, as well as models that implement CRUD operations for FandanGO's database tables.
43
+
44
+ `Project` manages data about the FandanGO projects. `ProjectInfo` manages metadata used by the plugins. Each of these will typically have its own separate SQLite database file. For example, the core plugin will have a database file containing project data, and the plugin manager will have a database file containing plugin metadata.
45
+
46
+ A plugin may implement its own database structure by implementing a custom `Model` subclass.
47
+
48
+ ### Connecting to a Database
49
+
50
+ ```python
51
+ from pathlib import Path
52
+ from fGOdb import SQLiteDB
53
+
54
+ # Initialize the connection helper with the config file and target database file name
55
+ db = SQLiteDB(Path("path/to/core.cfg"), "project.db")
56
+ ```
57
+
58
+ ### Using Models
59
+
60
+ ```python
61
+ from fGOdb import Project, ProjectInfo
62
+
63
+ # Initialize the model with the database helper
64
+ project_info = ProjectInfo(db)
65
+
66
+ # Set, get, list, and delete metadata
67
+ project_info.set("project1", "key1", "value1")
68
+ value = project_info.get("project1", "key1")
69
+ project_info.list_by_project("project1")
70
+ project_info.delete("project1", "key1")
71
+ ```
72
+
73
+ ## Development and Testing
74
+
75
+ To run the test suite locally:
76
+
77
+ 1. Clone the repository and install the development dependencies:
78
+ ```bash
79
+ pip install -e .[dev]
80
+ ```
81
+ 2. Run tests with `pytest`:
82
+ ```bash
83
+ pytest
84
+ ```
85
+
86
+ ## Security Scanning
87
+
88
+ This repo uses [OSV Scanner](https://github.com/google/osv-scanner) for vulnerability detection.
89
+
90
+ **When it runs:**
91
+ - Daily at 03:00 UTC (full scan)
92
+ - On PRs targeting main (changed deps only)
93
+ - On push to main (full scan)
94
+
95
+ **If vulnerabilities are found:**
96
+ 1. Check the [Security tab](../../security) for alerts
97
+ 2. To ignore false positives, add entries to `osv-scanner.toml`:
98
+ ```toml
99
+ [[IgnoredVulns]]
100
+ id = "GHSA-xxxx-xxxx-xxxx"
101
+ reason = "Justification"
102
+ ```
103
+
104
+ **References:**
105
+ - [OSV Scanner docs](https://google.github.io/osv-scanner/)
106
+ - [GitHub Action](https://github.com/google/osv-scanner-action)
107
+ - [OSV Database](https://osv.dev/)
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ fGOdb/__init__.py
5
+ fGOdb/col.py
6
+ fGOdb/conn.py
7
+ fGOdb/models.py
8
+ fGOdb/table.py
9
+ fandanGO_db.egg-info/PKG-INFO
10
+ fandanGO_db.egg-info/SOURCES.txt
11
+ fandanGO_db.egg-info/dependency_links.txt
12
+ fandanGO_db.egg-info/requires.txt
13
+ fandanGO_db.egg-info/top_level.txt
14
+ tests/test_conn_models.py
@@ -0,0 +1 @@
1
+ pytest>=8.0.0
@@ -0,0 +1,18 @@
1
+ [project]
2
+ name = "fandanGO-db"
3
+ version = "0.1.0"
4
+ description = "A small library for FandanGO to manage SQLite DB connections"
5
+ readme = "README.md"
6
+ requires-python = ">=3.8"
7
+ authors = [{ name = "FragmentScreen" }]
8
+ dependencies = ["pytest>=8.0.0"]
9
+
10
+ [dependency-groups]
11
+ dev = ["pre-commit>=3.5.0", "pytest>=8.0.0", "pytest-cov>=4.0.0", "ruff>=0.3.0"]
12
+
13
+ [build-system]
14
+ requires = ["setuptools>=61.0", "wheel"]
15
+ build-backend = "setuptools.build_meta"
16
+
17
+ [tool.setuptools.packages.find]
18
+ include = ["fGOdb*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,93 @@
1
+ # tests/test_conn_models.py
2
+ """Unit tests for the SQLiteDB connection and the Project / ProjectInfo models.
3
+
4
+ The tests create a temporary SQLite database and a temporary db.cfg file that points
5
+ the library's DDBB_PATH to a writable temporary directory.
6
+ """
7
+
8
+ import configparser
9
+ import pytest
10
+ from pathlib import Path
11
+
12
+ # Import the library under test
13
+ from fGOdb.conn import SQLiteDB
14
+ from fGOdb.models import Project, ProjectInfo
15
+
16
+ @pytest.fixture(scope="function")
17
+ def temp_db(tmp_path: Path):
18
+ """Create a temporary SQLite database and a config file.
19
+
20
+ The SQLiteDB class reads a ``db.cfg`` file located at the project root. This
21
+ fixture writes such a file into the repository root (two levels up from this test
22
+ file) and points the ``DDBB_PATH`` option to a temporary directory.
23
+ """
24
+ # Repository root – two levels up from the test file (tests/ -> project root)
25
+ repo_root = Path(__file__).parent.parent
26
+ config_path = repo_root / "db.cfg"
27
+ ddbb_path = tmp_path / "out"
28
+ ddbb_path.mkdir()
29
+ config = configparser.ConfigParser()
30
+ config["DDBB"] = {"DDBB_PATH": str(ddbb_path)}
31
+ with open(config_path, "w") as f:
32
+ config.write(f)
33
+
34
+ # Models write to "<plugin_name>.sqlite" inside ddbb_path
35
+ db_name = "test.sqlite"
36
+ db_file = ddbb_path / db_name
37
+ db = SQLiteDB(config_file="db.cfg", db_name=db_name)
38
+ yield db, db_file
39
+
40
+ # Clean up the temporary config file after the test
41
+ if config_path.exists():
42
+ config_path.unlink()
43
+
44
+ def test_connection_and_table_creation(temp_db):
45
+ db, db_file = temp_db
46
+
47
+ with db.db_session() as (cur, conn):
48
+ cur.execute("CREATE TABLE IF NOT EXISTS _probe (id INTEGER);")
49
+ conn.commit()
50
+ cur.execute("SELECT sqlite_version();")
51
+ version = cur.fetchone()[0]
52
+ assert version is not None
53
+ assert db_file.exists()
54
+
55
+ def test_project_crud(temp_db):
56
+ db, _ = temp_db
57
+ project = Project(db)
58
+ # Insert a new project
59
+ project.insert(project_name="demo", start_date=1234567890, plugin_manager="default")
60
+ # Retrieve it back
61
+ fetched = project.get("demo")
62
+ assert fetched[0] == "demo"
63
+ assert fetched[1] == 1234567890
64
+ assert fetched[2] == "default"
65
+ # Update a field
66
+ project.update("demo", plugin_manager="updated")
67
+ updated = project.get("demo")
68
+ assert updated[2] == "updated"
69
+ # List projects – should contain exactly one entry
70
+ all_projects = project.list_all()
71
+ assert len(all_projects) == 1
72
+ assert all_projects[0][0] == "demo"
73
+ # Delete the project and ensure it disappears
74
+ project.delete("demo")
75
+ assert project.get("demo") is None
76
+
77
+ def test_project_info_crud(temp_db):
78
+ db, _ = temp_db
79
+ info = ProjectInfo(db)
80
+ # Insert key/value pairs for a project
81
+ info.set(project_name="demo", key="author", value="alice")
82
+ info.set(project_name="demo", key="version", value="1.0")
83
+ # Retrieve specific value
84
+ author = info.get("demo", "author")
85
+ assert author == "alice"
86
+ # List all info for a project
87
+ kv_pairs = info.list_by_project("demo")
88
+ assert len(kv_pairs) == 2
89
+ keys = {pair[0] for pair in kv_pairs}
90
+ assert keys == {"author", "version"}
91
+ # Delete a key
92
+ info.delete("demo", key="version")
93
+ assert info.get("demo", "version") is None