Database¶
SQLite persistence for bus types, branch types and entire networks.
gi.Database(path) is a database object: it owns its SQLAlchemy engine
and session factory and offers the persistence operations as methods.
The module-level helpers (gi.start_dbsession, gi.save_network_to_db,
...) work as before and delegate to a default Database. The ORM mirror
classes live next to the Pydantic models in
groundinsight.models.database_models and expose from_pydantic /
to_pydantic converters. For a single network in a file of its own, see
the JSON project file.
Physical / modelling context¶
The persistence layer is a side-channel to the in-memory
Pydantic model. Every Pydantic class has an ORM counterpart with
suffix DB (BusDB, BranchDB, NetworkDB, ...). Many-to-many
relationships (e.g. a BranchType shared by several Network
instances, or a Path composed of many Branch segments) are
modelled through association tables (network_buses,
path_segments, ...). Two design choices are worth noting:
- Frequency lists are stored as a JSON array. They are
conceptually atomic — a network has one frequency list, never
shared, never queried element-wise — so a child table is not
justified. Up to 0.6.0 the column was a
PickleType, which meant that reading a database file executed whatever the blob contained, before any Pydantic validator saw it. A.dbfile is a shared artefact — it gets mailed around and checked into repositories — so that is the same trust problem the formula guard inutils.validationsexists for. Existing files are converted bygi.migrate_database(...)with an unpickler that resolves nothing butlist,floatandint; anything else aborts the migration and leaves the file untouched. - Impedance dicts \(Z(f) \in \mathbb{C}\) are stored as JSON
with stringified frequency keys, because SQLite has no native
complex type. The
ComplexNumberPydantic helper guarantees symmetric round-trips on read-back.
The database object¶
# fragment: assumes a bus type `bus_type` and a network `net` named "demo"
import groundinsight as gi
with gi.Database("library.db") as db:
# 1. Persist a re-usable BusType
db.save_bustype(bus_type, overwrite=True)
# 2. Persist an entire fault-ready network
db.save_network(net, overwrite=True)
# 3. Read back, list, delete
recovered_types = db.load_bustypes() # dict[name -> BusType]
recovered_net = db.load_network("demo")
db.list_networks() # ['demo', ...]
db.delete_network("old variant") # its types stay
| Method | Purpose |
|---|---|
save_bustype(t, overwrite=False), load_bustypes(), delete_bustype(name) |
bus-type catalogue |
save_branchtype(t, overwrite=False), load_branchtypes(), delete_branchtype(name) |
branch-type catalogue |
save_network(net, overwrite=False, overwrite_types=False), load_network(name) |
networks with all elements and their stored results |
list_networks(), delete_network(name) |
stored network names; delete a network and its elements |
needs_migration(), migrate(backup=True) |
schema check / conversion of a file opened with migrate=False |
session() |
context manager yielding a short-lived SQLAlchemy Session for direct ORM work |
close(), closed, path, engine |
lifetime and introspection; the object is also a context manager |
A type that a stored network still uses cannot be deleted; the error names
the networks. gi.Database(path, migrate=True) converts a file written by an
earlier release before opening it (keeping a .bak copy); with
migrate=False the file stays untouched and the first read or write of a
legacy file raises an error that names migrate(). gi.Database(":memory:")
gives a private in-memory database, handy for tests.
Several files, several threads¶
Every method runs in its own short-lived session, so no SQLAlchemy Session
is ever shared between threads. Two Database objects on two files are
independent and can be used from two threads at the same time — a GUI with
two open projects, or a server that serves two users. One Database can be
used from several threads as well: operations on the same file are
serialised by a lock that every Database object of the process shares for
that file, because SQLite allows one writer at a time and two unserialised
writers race on shared rows (a second insert of the same bus type) or fail
with database is locked. Operations on different files never wait for each
other. Separate processes on one file rely on SQLite's own locking.
The module-level helpers¶
# fragment: assumes a network `net` named "demo"
db = gi.start_dbsession("library.db") # returns the default Database
gi.save_network_to_db(network=net, overwrite=True)
recovered_net = gi.load_network_from_db(name="demo")
db.list_networks() # the same object, all methods
gi.close_dbsession()
gi.start_dbsession(path) opens the default database, and
gi.save_bustype_to_db, gi.load_bustypes_from_db,
gi.save_branchtype_to_db, gi.load_branchtypes_from_db,
gi.save_network_to_db and gi.load_network_from_db use it. Names,
arguments, messages and errors are those of 0.6.0: without a started session
they raise RuntimeError, and a second start_dbsession for another file
raises unless force=True. Since the default is a Database, the call now
returns it. The lower-level CRUD functions in groundinsight.database.crud
take an explicit SQLAlchemy Session argument; use them with
with db.session() as session:.
Deprecated: gi.session and gi.db_session¶
Up to 0.6.0 the session lived in module globals: gi.session, its alias
gi.db_session, gi.engine and gi.SessionLocal. They still resolve —
to the default database's thread-local scoped session (the same object for
both names), its engine and its session factory, or None without a started
session — but every access raises a DeprecationWarning. They will be
removed no earlier than two releases and six months after the release that
deprecated them. session and db_session are no longer in __all__, so a
star import does not trigger the warning.
| Before | Now |
|---|---|
crud.save_network(net, gi.session) |
db.save_network(net), or with db.session() as s: crud.save_network(net, s) |
gi.session() (a thread-local Session) |
with db.session() as s: ... (a short-lived Session) |
gi.engine |
db.engine |
gi.SessionLocal() |
with db.session() as s: ... |
db is a gi.Database(path), or the object returned by
gi.start_dbsession(path).
Cross-repo version helper: gi.show_versions()¶
Returns a dictionary with the installed versions of groundinsight,
the active Python and platform, and — if importable — the peer
packages groundfield and groundmeas. The companion packages
offer the same helper, so a bug report can include the full
earthing-platform stack with a single call:
>>> import groundinsight as gi
>>> gi.show_versions()
{'groundinsight': '<installed version>',
'python': '<running interpreter>',
'platform': 'Linux-...-x86_64-...'}
Database object and module-level helpers¶
store ¶
The SQLite store as an object: :class:Database.
Persistence through module globals -- an engine, a SessionLocal and
one scoped session -- would allow exactly one database per process, and
every caller would share one thread-local session registry. A desktop
application with two open projects, a server that serves two users, or a
study that writes results while the GUI reads the type catalogue cannot work
like that. The module-level names survive only as deprecated aliases of the
default instance (groundinsight.session, groundinsight.engine, ...).
:class:Database owns its engine and its session factory. Every method opens
a short-lived session, does one operation and closes it again, so no
SQLAlchemy Session -- which is not thread-safe -- is ever shared between
threads. Two Database objects on two files are fully independent and can
be used from two threads at the same time.
One file, several threads
SQLite allows one writer at a time. Two threads that write the same file
through separate connections race: the second INSERT of a shared bus type
fails with an IntegrityError, or a write waits for the busy timeout and
fails with database is locked. Operations on the same file are therefore
serialised with a re-entrant lock that is shared by every Database object
of this process on that file (keyed by the resolved path), not only by one
object. Operations on different files never wait for each other. Separate
processes on one file rely on SQLite's own locking, as before.
The default instance
The module-level functions -- :func:start_dbsession,
:func:close_dbsession, :func:save_bustype_to_db,
:func:load_bustypes_from_db, :func:save_branchtype_to_db,
:func:load_branchtypes_from_db, :func:save_network_to_db,
:func:load_network_from_db -- delegate to a default Database that
:func:start_dbsession creates for the configured path and returns; without
one they raise RuntimeError rather than silently creating
grounding.db in the working directory.
The globals groundinsight.session, db_session, engine and
SessionLocal are deprecated aliases resolved through the package's
module-level __getattr__ (PEP 562); see :func:deprecated_attribute.
Database ¶
A SQLite database of bus types, branch types and networks.
The object owns its SQLAlchemy engine and session factory; each method
runs in its own short-lived session. Several Database objects -- on
the same or on different files -- can be open at the same time, and one
object can be used from several threads.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str or PathLike
|
The SQLite file; created if it does not exist. |
required |
migrate
|
(bool, optional, keyword - only)
|
If |
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the automatic migration refuses the file (for example a pickled frequency list that is not a list of numbers). |
RuntimeError
|
If the automatic migration cannot convert the file. |
DatabaseError
|
If the file is not a SQLite database. |
Notes
Bus and branch types are a global catalogue inside one database: every
stored network references its types by name. Saving a network whose type
formulas differ from the stored ones, while another stored network uses
that type, is refused unless overwrite_types=True.
Operations on the same file are serialised by a lock that every
Database object of the process shares for that file; operations on
different files run in parallel. Use the object as a context manager, or
call :meth:close, to release the file.
Examples:
>>> import groundinsight as gi
>>> with gi.Database("library.db") as db:
... db.save_network(net)
... db.list_networks()
['demo']
>>> with gi.Database(":memory:") as db:
... db.list_networks()
[]
Source code in src/groundinsight/database/store.py
closed
property
¶
Whether :meth:close has run (bool).
Returns:
| Type | Description |
|---|---|
bool
|
|
engine
property
¶
The SQLAlchemy engine this database owns.
For direct SQL access. Prefer :meth:session for ORM work; do not
dispose the engine yourself -- :meth:close does that.
Returns:
| Type | Description |
|---|---|
Engine
|
The engine of the SQLite file. |
path
property
¶
The database file as given to the constructor (str).
Returns:
| Type | Description |
|---|---|
str
|
The path of the SQLite file. |
__enter__ ¶
__exit__ ¶
__repr__ ¶
close ¶
Release the database: drop the connections and dispose the engine.
Idempotent and never raises; problems while tearing down are logged at
WARNING. Every later operation raises RuntimeError.
Source code in src/groundinsight/database/store.py
delete_branchtype ¶
Delete a stored BranchType that no stored network uses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the type. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the type is not stored, or a stored network still uses it. |
RuntimeError
|
If the database is closed, or still uses the legacy schema. |
Source code in src/groundinsight/database/store.py
delete_bustype ¶
Delete a stored BusType that no stored network uses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the type. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the type is not stored, or a stored network still uses it. |
RuntimeError
|
If the database is closed, or still uses the legacy schema. |
Source code in src/groundinsight/database/store.py
delete_network ¶
Delete a stored network and all of its elements; types stay.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the network. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no network of that name is stored. |
RuntimeError
|
If the database is closed, or still uses the legacy schema. |
Source code in src/groundinsight/database/store.py
list_networks ¶
Names of the stored networks.
Returns:
| Type | Description |
|---|---|
list of str
|
Sorted names. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the database is closed, or still uses the legacy schema. |
Source code in src/groundinsight/database/store.py
load_branchtypes ¶
Load every stored BranchType.
Returns:
| Type | Description |
|---|---|
dict of str to BranchType
|
The types, keyed by name. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the database is closed. |
Source code in src/groundinsight/database/store.py
load_bustypes ¶
Load every stored BusType.
Returns:
| Type | Description |
|---|---|
dict of str to BusType
|
The types, keyed by name. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the database is closed. |
Source code in src/groundinsight/database/store.py
load_network ¶
Load a stored network by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the network. |
required |
Returns:
| Type | Description |
|---|---|
Network
|
The network, with the results stored with it. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no network of that name is stored. |
RuntimeError
|
If the database is closed, or still uses the legacy schema. |
Source code in src/groundinsight/database/store.py
migrate ¶
Convert the file to the current schema (for migrate=False).
The engine's pooled connections are released first, because the conversion may replace the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backup
|
bool
|
Copy the unmodified file to |
True
|
Returns:
| Type | Description |
|---|---|
MigrationReport
|
What was done, and what could not be recovered. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the database is closed, or the file cannot be converted. |
ValueError
|
If the file carries a payload the migration refuses. |
Source code in src/groundinsight/database/store.py
needs_migration ¶
Classify the file against the current schema.
Returns:
| Type | Description |
|---|---|
str
|
|
Source code in src/groundinsight/database/store.py
save_branchtype ¶
Save a BranchType to the catalogue.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
branch_type
|
BranchType
|
The type to save. |
required |
overwrite
|
bool
|
Replace a stored type of the same name. Defaults to |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the type exists and |
RuntimeError
|
If the database is closed. |
Source code in src/groundinsight/database/store.py
save_bustype ¶
Save a BusType to the catalogue.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bus_type
|
BusType
|
The type to save. |
required |
overwrite
|
bool
|
Replace a stored type of the same name. Defaults to |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the type exists and |
RuntimeError
|
If the database is closed. |
Source code in src/groundinsight/database/store.py
save_network ¶
Save a network with all of its elements and results, in one transaction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
network
|
Network
|
The network to save. Its stored results ( |
required |
overwrite
|
bool
|
Replace a stored network of the same name. Defaults to |
False
|
overwrite_types
|
bool
|
Allow this save to rewrite the formulas of bus/branch types that
other stored networks also use. Defaults to |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the network exists and |
RuntimeError
|
If the database is closed, or still uses the legacy schema. |
See Also
groundinsight.database.crud.save_network : The transaction itself.
Source code in src/groundinsight/database/store.py
session ¶
A short-lived SQLAlchemy session for direct ORM access.
The session is closed -- not committed -- when the block ends; commit explicitly if you write. Operations on this file wait until the block has finished.
Yields:
| Type | Description |
|---|---|
Session
|
A new session bound to this database. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the database is closed. |
Examples:
>>> from groundinsight.database.crud import load_network
>>> with db.session() as session:
... net = load_network("demo", session)
Source code in src/groundinsight/database/store.py
close_dbsession ¶
Close the default database opened by :func:start_dbsession.
Never raises. Logs at WARNING if no session is active and at INFO
when one was closed. :class:Database objects created directly are not
affected.
Examples:
Source code in src/groundinsight/database/store.py
default_database ¶
The database the module-level functions use, if one is open.
Returns:
| Type | Description |
|---|---|
Database or None
|
The object :func: |
Source code in src/groundinsight/database/store.py
deprecated_attribute ¶
The value behind a deprecated package global.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
One of :data: |
required |
Returns:
| Type | Description |
|---|---|
object or None
|
|
Raises:
| Type | Description |
|---|---|
AttributeError
|
If |
Source code in src/groundinsight/database/store.py
deprecation_message ¶
The DeprecationWarning text for a former package global.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
One of :data: |
required |
Returns:
| Type | Description |
|---|---|
str
|
Message naming the replacement and the removal policy. |
Source code in src/groundinsight/database/store.py
load_branchtypes_from_db ¶
Load all BranchTypes from the default database.
Returns:
| Type | Description |
|---|---|
dict of str to BranchType
|
A dictionary of BranchType instances keyed by their names. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the database session is not started. |
Examples:
>>> import groundinsight as gi
>>> gi.start_dbsession("grid.db")
>>> sorted(gi.load_branchtypes_from_db())
['cable']
Source code in src/groundinsight/database/store.py
load_bustypes_from_db ¶
Load all BusTypes from the default database.
Returns:
| Type | Description |
|---|---|
dict of str to BusType
|
A dictionary of BusType instances keyed by their names. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the database session is not started. |
Examples:
>>> import groundinsight as gi
>>> gi.start_dbsession("grid.db")
>>> sorted(gi.load_bustypes_from_db())
['station']
Source code in src/groundinsight/database/store.py
load_network_from_db ¶
Load a Network from the default database by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the Network to load. |
required |
Returns:
| Type | Description |
|---|---|
Network
|
The loaded Network instance. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the database session is not started. |
ValueError
|
If the Network with the specified name does not exist. |
Examples:
>>> import groundinsight as gi
>>> gi.start_dbsession("grid.db")
>>> net = gi.load_network_from_db("SmokeTest")
>>> sorted(net.buses)
['bus1', 'bus2', 'bus3']
Source code in src/groundinsight/database/store.py
save_branchtype_to_db ¶
Save a BranchType to the default database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
branch_type
|
BranchType
|
The BranchType instance to save. |
required |
overwrite
|
bool
|
Whether to overwrite an existing BranchType with the same name.
Defaults to |
False
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the database session is not started. |
ValueError
|
If the BranchType already exists and |
Examples:
>>> import groundinsight as gi
>>> cable = gi.BranchType(name="cable", grounding_conductor=True,
... self_impedance_formula="(0.25 + j * f * 0.012) * l",
... mutual_impedance_formula="j * f * 0.012 * l")
>>> gi.start_dbsession("grid.db")
>>> gi.save_branchtype_to_db(cable)
Source code in src/groundinsight/database/store.py
save_bustype_to_db ¶
Save a BusType to the default database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bus_type
|
BusType
|
The BusType instance to save. |
required |
overwrite
|
bool
|
Whether to overwrite an existing BusType with the same name.
Defaults to |
False
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the database session is not started. |
ValueError
|
If the BusType already exists and |
Examples:
>>> import groundinsight as gi
>>> station = gi.BusType(name="station", system_type="Substation",
... voltage_level=20.0, impedance_formula="rho * 0.01")
>>> gi.start_dbsession("grid.db")
>>> gi.save_bustype_to_db(station)
Source code in src/groundinsight/database/store.py
save_network_to_db ¶
save_network_to_db(
network: Network,
overwrite: bool = False,
overwrite_types: bool = False,
) -> None
Save a Network to the default database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
network
|
Network
|
The Network instance to save. |
required |
overwrite
|
bool
|
Whether to overwrite an existing Network with the same name.
Defaults to |
False
|
overwrite_types
|
bool
|
Whether this save may rewrite the formulas of bus/branch types that
other stored networks also reference. Bus and branch types are a
global catalogue keyed by name, so such a change reaches those
networks as well. Defaults to |
False
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the database session is not started. |
ValueError
|
If the Network already exists and |
Examples:
>>> import groundinsight as gi
>>> from groundinsight.api.examples import build_minimal
>>> net = build_minimal()
>>> gi.start_dbsession("grid.db")
>>> gi.save_network_to_db(net, overwrite=True)
Source code in src/groundinsight/database/store.py
start_dbsession ¶
start_dbsession(
sqlite_path: str = "grounding.db",
force: bool = False,
migrate: bool = True,
) -> Database
Open the default database used by the module-level persistence functions.
Idempotent in the safe direction: if a session is already active for the
same sqlite_path, it is kept and a WARNING is logged. Binding to
a different file raises RuntimeError unless force=True, in which
case the previous database is closed first. To work with several files at
once, use :class:Database objects instead.
A file written by an earlier release is migrated to the current schema
before it is opened, after the unmodified file has been copied to
<sqlite_path>.bak; see
:func:groundinsight.database.migration.migrate_database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sqlite_path
|
str
|
The SQLite file. Defaults to |
'grounding.db'
|
force
|
bool
|
Close an active default database for another file and rebind.
Defaults to |
False
|
migrate
|
bool
|
Convert a database written by an earlier release (the default). Set
to |
True
|
Returns:
| Type | Description |
|---|---|
Database
|
The default database. Its methods ( |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If a session is already active for a different |
Examples:
>>> import groundinsight as gi
>>> db = gi.start_dbsession("library.db")
>>> gi.save_network_to_db(net)
>>> db.list_networks()
['demo']
>>> gi.close_dbsession()
Source code in src/groundinsight/database/store.py
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 | |
Migration of older files¶
gi.needs_migration(path) classifies a file, gi.migrate_database(path,
backup=True) converts it in place after keeping a .bak copy and returns a
gi.MigrationReport; gi.Database(path) does both when it opens a file.
Save, load and migrate walks
through a migration.
migration ¶
Schema migration for existing SQLite databases.
The legacy schema -- files written by groundinsight 0.4.0 and earlier -- keys
buses, branches, faults, sources and paths by element
name alone and links them to their network through the association tables
network_buses, network_branches, network_faults,
network_sources and network_paths. Two networks that contain an
element of the same name therefore share one physical row, so saving one
network silently rewrites the other. The current schema keys the element
tables by (network_name, name).
Base.metadata.create_all only ever creates missing tables — it never adds
a column to an existing one — so an old database file opens without complaint
and then fails deep inside a query with a bare OperationalError: no such
column: buses.network_name. This module converts such a file instead, so an
existing user keeps working:
- :func:
needs_migrationreports what, if anything, has to change. - :func:
migrate_databaseperforms the conversion, after copying the file to a.baksibling.
:func:groundinsight.start_dbsession calls :func:migrate_database
automatically; pass migrate=False to get the diagnostic error instead.
Two properties of the legacy schema cannot be recovered and are reported rather than guessed:
Shared elements
A bus that two networks both referenced existed once. Splitting the row
per network can only duplicate the one surviving definition into each of
them. If the networks meant different things by that name, the older
definition is already gone — it was overwritten on the last save, before
this migration ever ran. Every such name is listed in
:attr:MigrationReport.shared_elements and logged at WARNING.
Path segment order
The legacy path_segments table had no position column; a path was
an unordered set of (path_name, branch_name) rows. Order is therefore
reconstructed from SQLite's rowid, which reflects insertion order and
hence the original segment sequence. The result is verified by walking
each path bus-by-bus; paths whose segments do not form a chain are listed
in :attr:MigrationReport.broken_paths and must be rebuilt with
:func:groundinsight.create_paths.
Pickled frequency lists
In a legacy file networks.frequencies is a SQLAlchemy PickleType.
Loading such a file through the ORM would execute it: pickle.loads
runs before any Pydantic validator sees the value, so a .db received
from someone else would be arbitrary code execution. The current column
is a JSON list, and the legacy blobs are converted here with a
restrictive unpickler that only ever
resolves builtins.list / float / int. Anything else aborts the
migration with a :class:ValueError and leaves the file untouched; the
payload is then a hostile file, not a frequency list.
MigrationReport ¶
Bases: BaseModel
What :func:migrate_database did, and what a user has to check afterwards.
Attributes:
| Name | Type | Description |
|---|---|---|
migrated |
bool
|
|
path |
str
|
The database file the report refers to. |
backup_path |
Optional[str]
|
Where the pre-migration file was copied to, or |
kind |
str
|
|
networks |
List[str]
|
Networks found in the file. |
rows |
Dict[str, int]
|
Rows written per table. |
shared_elements |
Dict[str, List[str]]
|
|
orphaned |
Dict[str, List[str]]
|
|
missing_rows |
Dict[str, List[str]]
|
|
broken_paths |
List[str]
|
|
defaulted_cells |
Dict[str, int]
|
|
added_columns |
Dict[str, List[str]]
|
|
converted_frequencies |
List[str]
|
Networks whose pickled |
unloadable |
Dict[str, str]
|
|
Examples:
>>> from groundinsight import MigrationReport
>>> report = MigrationReport(migrated=True, path="grid.db", kind="legacy",
... networks=["netA"])
>>> report.needs_attention
False
needs_attention
property
¶
True if the migration had to guess or drop something.
Returns:
| Type | Description |
|---|---|
bool
|
Whether the report lists shared, dropped or unloadable elements. |
needs_migration ¶
Classify an existing database file against the current schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sqlite_path
|
str
|
Path to the SQLite file. A path that does not exist, or an empty
file, counts as |
required |
Returns:
| Type | Description |
|---|---|
str
|
|
Examples:
Source code in src/groundinsight/database/migration.py
migrate_database ¶
Bring an existing database file up to the current schema.
Safe to call on a file that is already current: it then does nothing, takes
no backup, and returns a report with migrated=False.
The legacy conversion is written to a temporary sibling file and moved over
the original with :func:os.replace, so an interruption leaves either the
old file or the new one — never a half-converted database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sqlite_path
|
str
|
Path to the SQLite file. |
required |
backup
|
bool
|
Copy the file to |
True
|
Returns:
| Type | Description |
|---|---|
MigrationReport
|
What was done, and what could not be recovered. Check
:attr: |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If a |
ValueError
|
If the legacy pickled |
Examples:
Source code in src/groundinsight/database/migration.py
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 | |
CRUD functions¶
crud ¶
CRUD Operations Module.
This module provides functions for creating, reading, updating, and deleting (CRUD) entities in the GroundInsight database using SQLAlchemy sessions. It facilitates the management of core electrical network components such as BusTypes, BranchTypes, Networks, Buses, Branches, Faults, Sources, and Paths. The functions convert between Pydantic models and SQLAlchemy database models to ensure seamless data manipulation and persistence.
delete_branchtype ¶
Delete a stored BranchType that no stored network uses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the BranchType. |
required |
session
|
Session
|
The SQLAlchemy session used for database operations. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no BranchType of that name is stored, or if a stored network still has a branch of that type (the message names the networks). |
RuntimeError
|
If the database still uses the legacy, globally-keyed element tables. |
Source code in src/groundinsight/database/crud.py
delete_bustype ¶
Delete a stored BusType that no stored network uses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the BusType. |
required |
session
|
Session
|
The SQLAlchemy session used for database operations. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no BusType of that name is stored, or if a stored network still has a bus of that type (the message names the networks). |
RuntimeError
|
If the database still uses the legacy, globally-keyed element tables. |
Source code in src/groundinsight/database/crud.py
delete_network ¶
Delete a stored network together with all of its elements.
Buses, branches, faults, sources and paths are scoped to their network
and go with it (the relationships cascade). Bus and branch types are a
global catalogue and stay; delete them with :func:delete_bustype /
:func:delete_branchtype once no network uses them any more.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the network to delete. |
required |
session
|
Session
|
The SQLAlchemy session used for database operations. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no network of that name is stored. |
RuntimeError
|
If the database still uses the legacy, globally-keyed element tables. |
Exception
|
If the commit fails; the transaction is rolled back first. |
Source code in src/groundinsight/database/crud.py
ensure_current_schema ¶
Reject databases written by the pre-network-scoped schema.
buses, branches, faults, sources and paths are keyed
by (network_name, name). A file of the association-table schema keys
them by element name alone and links them to their network through
network_buses & co.; two networks containing an element of the same
name share one row there, so saving one network would silently rewrite
the other.
Base.metadata.create_all only ever creates missing tables -- it never
adds a column to an existing one -- so an old database file opens without
complaint and only fails deep inside a query with a bare
OperationalError: no such column: buses.network_name. This helper turns
that into an actionable message before any row is read or written.
This is the last line of defence, not the normal path:
:func:groundinsight.start_dbsession converts such a file automatically
(keeping a .bak copy) before the engine is bound. The error is reached
when the caller passed migrate=False, or built its own engine and
session without going through start_dbsession.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
Session
|
The SQLAlchemy session whose bind is inspected. |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the connected database still uses the legacy, globally-keyed
element tables. The message names
:func: |
See Also
groundinsight.database.migration.migrate_database : performs the conversion this function refuses to do implicitly.
Source code in src/groundinsight/database/crud.py
list_networks ¶
List the names of all networks stored in the database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
Session
|
The SQLAlchemy session used for database operations. |
required |
Returns:
| Type | Description |
|---|---|
List[str]
|
Network names, sorted. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the database still uses the legacy, globally-keyed element tables. |
Source code in src/groundinsight/database/crud.py
load_branchtypes ¶
Load all BranchTypes from the database.
This function retrieves all BranchType entries from the database and converts them into a dictionary mapping BranchType names to their corresponding Pydantic models.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
Session
|
The SQLAlchemy session used for database operations. |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, BranchType]
|
A dictionary where keys are BranchType names and values are BranchType instances. |
Source code in src/groundinsight/database/crud.py
load_bustypes ¶
Load all BusTypes from the database.
This function retrieves all BusType entries from the database and converts them into a dictionary mapping BusType names to their corresponding Pydantic models.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
Session
|
The SQLAlchemy session used for database operations. |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, BusType]
|
A dictionary where keys are BusType names and values are BusType instances. |
Source code in src/groundinsight/database/crud.py
load_network ¶
Load a Network from the database.
This function retrieves a Network instance by its name from the database and converts it
into a Pydantic Network model. It ensures that all related entities such as Buses, Branches,
Faults, Sources, and Paths are properly associated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the network to load. |
required |
session
|
Session
|
The SQLAlchemy session used for database operations. |
required |
Returns:
| Type | Description |
|---|---|
Network
|
The loaded |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the specified network does not exist in the database. |
RuntimeError
|
If the database still uses the legacy, globally-keyed element tables. |
Source code in src/groundinsight/database/crud.py
save_branchtype ¶
Save a BranchType to the database.
This function converts a Pydantic BranchType model to its corresponding SQLAlchemy
BranchTypeDB model and saves it to the database. If a BranchType with the same name
already exists, it will be updated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
branch_type
|
BranchType
|
The BranchType instance to be saved. |
required |
session
|
Session
|
The SQLAlchemy session used for database operations. |
required |
Raises:
| Type | Description |
|---|---|
Exception
|
If there is an error during the database commit. |
Source code in src/groundinsight/database/crud.py
save_bustype ¶
Save a BusType to the database.
This function converts a Pydantic BusType model to its corresponding SQLAlchemy
BusTypeDB model and saves it to the database. If a BusType with the same name
already exists, it will be updated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bus_type
|
BusType
|
The BusType instance to be saved. |
required |
session
|
Session
|
The SQLAlchemy session used for database operations. |
required |
Raises:
| Type | Description |
|---|---|
Exception
|
If there is an error during the database commit. |
Source code in src/groundinsight/database/crud.py
save_network ¶
save_network(
network: Network,
session: Session,
overwrite: bool = False,
overwrite_types: bool = False,
)
Save a Network to the database.
This function saves a comprehensive Network instance to the database, including all
associated BusTypes, BranchTypes, Buses, Branches, Faults, Sources, and Paths. It handles
the creation or updating of related entities and ensures referential integrity. If overwrite
is set to True, an existing network with the same name will be deleted and replaced.
BusTypes and BranchTypes are a global catalogue: they are merged, exactly
as :func:save_bustype and :func:save_branchtype do, so re-saving a
network with an edited type definition updates the stored type instead of
silently keeping the old one. Because the catalogue is shared, a type whose
formulas changed and which another network also references is refused
unless overwrite_types=True -- see :func:_check_type_merge. Every
other element is scoped to this network
and is written under the composite key (network.name, element.name), so
saving one network can never rewrite another's buses, branches, faults,
sources or paths.
The whole operation runs in a single transaction. On overwrite, the delete of the previous revision is flushed but not committed before the replacement rows are written, so a failure anywhere in the save rolls the delete back as well and leaves the stored network untouched.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
network
|
Network
|
The Network instance to be saved. |
required |
session
|
Session
|
The SQLAlchemy session used for database operations. |
required |
overwrite
|
bool
|
If |
False
|
overwrite_types
|
bool
|
If |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the network already exists and |
RuntimeError
|
If the database still uses the legacy, globally-keyed element tables. |
Exception
|
If there is an error during the database commit. The transaction is rolled back before the exception is re-raised. |
Source code in src/groundinsight/database/crud.py
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 | |
ORM models¶
database_models ¶
Database Models Module.
This module defines the SQLAlchemy ORM (Object-Relational Mapping) models corresponding to the core electrical network components in the GroundInsight package. Each database model facilitates the storage, retrieval, and manipulation of data related to BusTypes, BranchTypes, Buses, Branches, Faults, Sources, Paths, and Networks. The models include methods to convert between Pydantic models and SQLAlchemy database models, ensuring seamless data integration and persistence.
Ownership model
BusTypeDB and BranchTypeDB form a global catalogue: a type is identified by its
name alone and is deliberately shared between networks, so re-saving an edited type updates
every network that references it.
Every other element -- BusDB, BranchDB, FaultDB, SourceDB, PathDB and the
PathSegmentDB rows -- belongs to exactly one network. This mirrors the Pydantic
:class:~groundinsight.models.core_models.Network, whose element dictionaries only require
uniqueness within a network. The primary key of those tables is therefore the composite
(network_name, name); the relationships from NetworkDB are plain one-to-many
collections with delete-orphan cascade, so dropping a network (or shrinking one on
overwrite) removes its child rows instead of leaving them behind.
Earlier revisions keyed the child tables by name alone and linked them to their network
through network_buses / network_branches / network_faults / network_sources /
network_paths association tables. Two networks that happened to contain an element of the
same name -- the default case for create_paths, which names every path path_1,
path_2, ... -- then shared a single row, so saving one network silently rewrote the other.
Databases written by those revisions are not readable by this schema; they are detected and
rejected with an actionable error by
:func:groundinsight.database.crud.ensure_current_schema.
Collection order is preserved explicitly through position columns rather than being left to
the database. PathDB.segments in particular is order-sensitive: the solver walks the
segments from the source bus onwards and fails if consecutive segments do not connect.
BranchDB ¶
Bases: Base
BranchDB Model.
Represents a Branch in the database, including its properties, type, connected buses, the frequency-domain impedance dicts and -- when the type defines them -- the lumped RLCM dicts used by the transient solvers.
A branch belongs to exactly one network; the primary key is the
composite (network_name, name). from_bus_name / to_bus_name
reference buses of the same network, hence the composite foreign keys.
from_pydantic
classmethod
¶
Build a BranchDB row from a Pydantic :class:Branch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
branch
|
Branch
|
The branch to convert. |
required |
network_name
|
str
|
Name of the owning network. Part of the composite primary key. |
None
|
position
|
int
|
Zero-based index of the branch inside |
0
|
Returns:
| Type | Description |
|---|---|
BranchDB
|
The unattached database row. |
Source code in src/groundinsight/models/database_models.py
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 | |
to_pydantic ¶
Convert the row back into a Pydantic :class:Branch.
Returns:
| Type | Description |
|---|---|
Branch
|
The reconstructed branch. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/groundinsight/models/database_models.py
BranchTypeDB ¶
Bases: Base
BranchTypeDB Model.
Represents a BranchType in the database, including the mandatory
self_impedance_formula / mutual_impedance_formula and the
optional lumped RLCM formulas for the transient solvers
(R_self_formula, L_self_formula, C_self_formula,
R_mutual_formula, M_mutual_formula).
from_pydantic
classmethod
¶
Build a BranchTypeDB row from a Pydantic :class:BranchType.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
branch_type
|
BranchType
|
The model to convert. |
required |
Returns:
| Type | Description |
|---|---|
BranchTypeDB
|
The unattached database row. |
Source code in src/groundinsight/models/database_models.py
to_pydantic ¶
Convert the row back into a Pydantic :class:BranchType.
Returns:
| Type | Description |
|---|---|
BranchType
|
A fresh model object. |
Source code in src/groundinsight/models/database_models.py
BusDB ¶
Bases: Base
BusDB Model.
Represents a Bus in the database. Carries the frequency-domain
impedance dict and -- when the type defines them -- the lumped
R, L and C dicts used by the transient solvers.
A bus belongs to exactly one network; the primary key is the composite
(network_name, name) so two networks may each own a bus of the same
name. position records the insertion order of Network.buses so a
round-trip through the database returns the dictionary in the order it
was written.
from_pydantic
classmethod
¶
Build a BusDB row from a Pydantic :class:Bus.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bus
|
Bus
|
The bus to convert. |
required |
network_name
|
str
|
Name of the owning network. Part of the composite primary key;
may be left out when the row is appended to
|
None
|
position
|
int
|
Zero-based index of the bus inside |
0
|
Returns:
| Type | Description |
|---|---|
BusDB
|
The unattached database row. |
Source code in src/groundinsight/models/database_models.py
to_pydantic ¶
Convert the row back into a Pydantic :class:Bus.
Returns:
| Type | Description |
|---|---|
Bus
|
The reconstructed bus. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/groundinsight/models/database_models.py
BusTypeDB ¶
Bases: Base
BusTypeDB Model.
Represents a BusType in the database, including its properties, the
mandatory frequency-domain impedance_formula, the optional
lumped RLC formulas for the transient solvers (R_formula,
L_formula, C_formula) and the optional thermal-limit data of
the earthing conductor and the earth electrode (EN 50522 /
IEC 60949), consumed by
:func:groundinsight.check_node_limits.
from_pydantic
classmethod
¶
Build a BusTypeDB row from a Pydantic :class:BusType.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bus_type
|
BusType
|
The model to convert. |
required |
Returns:
| Type | Description |
|---|---|
BusTypeDB
|
The unattached database row. |
Source code in src/groundinsight/models/database_models.py
to_pydantic ¶
Convert the row back into a Pydantic :class:BusType.
Returns:
| Type | Description |
|---|---|
BusType
|
A fresh model object. |
Source code in src/groundinsight/models/database_models.py
ComplexNumberDB ¶
Bases: Base
ComplexNumberDB Model.
Represents a complex number with real and imaginary parts for storage in the database.
from_pydantic
classmethod
¶
Build a ComplexNumberDB row from a Pydantic :class:ComplexNumber.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
complex_number
|
ComplexNumber
|
The model to convert. |
required |
Returns:
| Type | Description |
|---|---|
ComplexNumberDB
|
The unattached database row. |
Source code in src/groundinsight/models/database_models.py
to_pydantic ¶
Convert the row back into a Pydantic :class:ComplexNumber.
Returns:
| Type | Description |
|---|---|
ComplexNumber
|
A fresh model object. |
FaultDB ¶
Bases: Base
FaultDB Model.
Represents a Fault in the database, including its properties and associated bus.
A fault belongs to exactly one network; the primary key is the composite
(network_name, name) and bus_name references a bus of the same
network.
from_pydantic
classmethod
¶
Build a FaultDB row from a Pydantic :class:Fault.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fault
|
Fault
|
The fault to convert. |
required |
network_name
|
str
|
Name of the owning network. Part of the composite primary key. |
None
|
position
|
int
|
Zero-based index of the fault inside |
0
|
Returns:
| Type | Description |
|---|---|
FaultDB
|
The unattached database row. |
Source code in src/groundinsight/models/database_models.py
to_pydantic ¶
Convert the row back into a Pydantic :class:Fault.
Returns:
| Type | Description |
|---|---|
Fault
|
A fresh model object. |
Source code in src/groundinsight/models/database_models.py
NetworkDB ¶
Bases: Base
NetworkDB Model.
Represents a Network in the database, including its properties and associated components such as buses, branches, faults, sources, and paths. It also tracks the active fault within the network.
The element collections are one-to-many with delete-orphan cascade: a
bus, branch, fault, source or path row is owned by exactly one network,
so deleting a network -- or replacing a collection on overwrite -- removes
the rows it no longer contains instead of orphaning them in a global
table. Each collection is ordered by the element's position column so
the Pydantic dictionaries come back in insertion order.
from_pydantic
classmethod
¶
Build a NetworkDB row from a Pydantic :class:Network.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
network
|
Network
|
The model to convert. |
required |
Returns:
| Type | Description |
|---|---|
NetworkDB
|
The unattached database row. |
Source code in src/groundinsight/models/database_models.py
to_pydantic ¶
Convert the row back into a Pydantic :class:Network.
Buses, branches, faults, sources, paths and stored results are converted with it.
Returns:
| Type | Description |
|---|---|
Network
|
A fresh model object. |
Source code in src/groundinsight/models/database_models.py
PathDB ¶
Bases: Base
PathDB Model.
Represents a Path in the database, including its properties, associated source and fault, and connected branches (segments).
A path belongs to exactly one network; the primary key is the composite
(network_name, name). This matters in practice because
:func:groundinsight.create_paths names every path path_1,
path_2, ..., so path-name collisions between two saved networks are
the rule rather than the exception.
from_pydantic
classmethod
¶
Build a PathDB row from a Pydantic :class:Path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
The path to convert. |
required |
network_name
|
str
|
Name of the owning network. Part of the composite primary key. |
None
|
position
|
int
|
Zero-based index of the path inside |
0
|
Returns:
| Type | Description |
|---|---|
PathDB
|
The unattached database row. |
Source code in src/groundinsight/models/database_models.py
to_pydantic ¶
Convert the row back into a Pydantic :class:Path.
Returns:
| Type | Description |
|---|---|
Path
|
The reconstructed path, with |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a stored segment references a branch that is not present in the owning network -- a corrupt or hand-edited database. |
Source code in src/groundinsight/models/database_models.py
PathSegmentDB ¶
Bases: Base
PathSegmentDB Model.
One ordered segment of a :class:PathDB, pointing at a branch of the same
network. Segment order is semantically meaningful -- the solver walks the
segments from the source bus onwards and raises if a segment does not
connect to the current bus -- hence the explicit position column,
which is part of the primary key and drives PathDB.segments'
order_by. A plain association table would return Path.segments in
an unspecified order.
SourceDB ¶
Bases: Base
SourceDB Model.
Represents a Source in the database. Both the current-source mode and
the Thevenin (voltage-source) mode are persisted in the same row.
The source_type column selects which of values and the pair
(voltage, source_impedance) carries the actual data; the other
fields are stored as NULL.
A source belongs to exactly one network; the primary key is the
composite (network_name, name) and bus_name references a bus of
the same network.
from_pydantic
classmethod
¶
Build a SourceDB row from a Pydantic :class:Source.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Source
|
The source to convert. |
required |
network_name
|
str
|
Name of the owning network. Part of the composite primary key. |
None
|
position
|
int
|
Zero-based index of the source inside |
0
|
Returns:
| Type | Description |
|---|---|
SourceDB
|
The unattached database row. |
Source code in src/groundinsight/models/database_models.py
to_pydantic ¶
Convert the row back into a Pydantic :class:Source.
Returns:
| Type | Description |
|---|---|
Source
|
A fresh model object. |