Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add StatiqueImporter and related import-statique CLI command #139

Merged
merged 1 commit into from
Sep 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ services:
restart: always
volumes:
- ./src/api:/app
- ./data:/data
depends_on:
- postgresql

Expand Down
5 changes: 5 additions & 0 deletions src/api/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ and this project adheres to

## [Unreleased]

### Added

- Implement Pandas-based `StatiqueImporter`
- CLI: add `import-statique` command

### Changed

- Upgrade fastapi to `0.112.2`
Expand Down
1 change: 1 addition & 0 deletions src/api/Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ black = "==24.8.0"
csvkit = "==2.0.1"
honcho = "==1.1.0"
mypy = "==1.11.2"
pandas-stubs = "==2.2.2.240807"
polyfactory = "==2.16.2"
pytest = "==8.3.2"
pytest-cov = "==5.0.0"
Expand Down
89 changes: 82 additions & 7 deletions src/api/Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

32 changes: 32 additions & 0 deletions src/api/qualicharge/cli.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,34 @@
"""QualiCharge CLI."""

import logging
from pathlib import Path
from typing import Optional, Sequence, cast

import pandas as pd
import questionary
import typer
from psycopg import Error as PGError
from rich import print
from rich.console import Console
from rich.logging import RichHandler
from rich.table import Table
from sqlalchemy import Column as SAColumn
from sqlalchemy.exc import IntegrityError, OperationalError, ProgrammingError
from sqlmodel import Session as SMSession
from sqlmodel import select

from .auth.models import UserCreate
from .auth.schemas import Group, ScopesEnum, User
from .conf import settings
from .db import get_session
from .exceptions import IntegrityError as QCIntegrityError
from .fixtures.operational_units import prefixes
from .schemas.core import OperationalUnit
from .schemas.sql import StatiqueImporter

logging.basicConfig(
level=logging.INFO, format="%(message)s", datefmt="[%X]", handlers=[RichHandler()]
)
app = typer.Typer(name="qualicharge", no_args_is_help=True)
console = Console()

Expand Down Expand Up @@ -416,6 +427,27 @@ def delete_user(ctx: typer.Context, username: str, force: bool = False):
print(f"[bold yellow]User {username} deleted.[/bold yellow]")


@app.command()
def import_static(ctx: typer.Context, input_file: Path):
"""Import Statique file (parquet format)."""
session: SMSession = ctx.obj

# Load dataset
console.log(f"Reading input file: {input_file}")
static = pd.read_parquet(input_file)
console.log(f"Read {len(static.index)} rows")
importer = StatiqueImporter(static, session.connection())

console.log("Save to configured database")
try:
importer.save()
except (ProgrammingError, IntegrityError, OperationalError, PGError) as err:
session.rollback()
raise QCIntegrityError("Input file importation failed. Rolling back.") from err
session.commit()
console.log("Saved (or updated) all entries successfully.")


@app.callback()
def main(ctx: typer.Context):
"""Attach database session to the context object."""
Expand Down
4 changes: 4 additions & 0 deletions src/api/qualicharge/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,7 @@ class IntegrityError(QualiChargeExceptionMixin, Exception):

class ObjectDoesNotExist(QualiChargeExceptionMixin, Exception):
"""Raised when queried object does not exist."""


class ProgrammingError(QualiChargeExceptionMixin, Exception):
"""Raised when QC object API is badly used."""
Loading