grz-db 0.1.0__py3-none-any.whl

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.
grz_db/__init__.py ADDED
@@ -0,0 +1,530 @@
1
+ import datetime
2
+ import enum
3
+ import logging
4
+ import os
5
+ from collections.abc import Generator
6
+ from contextlib import contextmanager
7
+ from typing import Any, ClassVar, Generic, TypeVar
8
+
9
+ import cryptography
10
+ from alembic import command as alembic_command
11
+ from alembic.config import Config as AlembicConfig
12
+ from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes, PublicKeyTypes
13
+ from pydantic import ConfigDict
14
+ from sqlalchemy import JSON, Column
15
+ from sqlalchemy.exc import IntegrityError
16
+ from sqlalchemy.orm import selectinload
17
+ from sqlmodel import DateTime, Field, Relationship, Session, SQLModel, create_engine, select
18
+
19
+ __version__ = "0.1.0"
20
+
21
+ log = logging.getLogger(__name__)
22
+
23
+
24
+ class CaseInsensitiveStrEnum(enum.StrEnum):
25
+ """
26
+ A StrEnum that is case-insensitive for member lookup and comparison with strings.
27
+ """
28
+
29
+ @classmethod
30
+ def _missing_(cls, value):
31
+ """
32
+ Override to allow case-insensitive lookup of enum members by value.
33
+ e.g., MyEnum('value') will match MyEnum.VALUE.
34
+ """
35
+ if isinstance(value, str):
36
+ for member in cls:
37
+ if member.value.casefold() == value.casefold():
38
+ return member
39
+ return None
40
+
41
+ def __eq__(self, other):
42
+ """
43
+ Override to allow case-insensitive comparison of enum members by value.
44
+ """
45
+ if isinstance(other, enum.Enum):
46
+ return self is other
47
+ if isinstance(other, str):
48
+ return self.value.casefold() == other.casefold()
49
+ return NotImplemented
50
+
51
+ def __hash__(self):
52
+ """
53
+ Override to make hash consistent with eq.
54
+ """
55
+ return hash(self.value.casefold())
56
+
57
+
58
+ def serialize_datetime_to_iso_z(dt: datetime.datetime) -> str:
59
+ """
60
+ Serializes a datetime object to a canonical ISO 8601 string format with 'Z' for UTC.
61
+ """
62
+ if dt.tzinfo is None:
63
+ dt = dt.replace(tzinfo=datetime.UTC)
64
+
65
+ if dt.tzinfo != datetime.UTC and dt.utcoffset() != datetime.timedelta(0):
66
+ dt = dt.astimezone(datetime.UTC)
67
+
68
+ return dt.isoformat()
69
+
70
+
71
+ class ListableEnum(enum.StrEnum):
72
+ """Mixin for enum classes whose members can be listed."""
73
+
74
+ @classmethod
75
+ def list(cls) -> list[str]:
76
+ """Returns a list of enum members."""
77
+ return list(map(lambda c: c.value, cls))
78
+
79
+
80
+ class SubmissionStateEnum(CaseInsensitiveStrEnum, ListableEnum):
81
+ """Submission state enum."""
82
+
83
+ UPLOADING = "Uploading"
84
+ UPLOADED = "Uploaded"
85
+ DOWNLOADING = "Downloading"
86
+ DOWNLOADED = "Downloaded"
87
+ DECRYPTING = "Decrypting"
88
+ DECRYPTED = "Decrypted"
89
+ VALIDATING = "Validating"
90
+ VALIDATED = "Validated"
91
+ ENCRYPTING = "Encrypting"
92
+ ENCRYPTED = "Encrypted"
93
+ ARCHIVING = "Archiving"
94
+ ARCHIVED = "Archived"
95
+ REPORTED = "Reported"
96
+ QCING = "QCing"
97
+ QCED = "QCed"
98
+ CLEANING = "Cleaning"
99
+ CLEANED = "Cleaned"
100
+ FINISHED = "Finished"
101
+ ERROR = "Error"
102
+
103
+
104
+ class ChangeRequestEnum(CaseInsensitiveStrEnum, ListableEnum):
105
+ """Change request enum."""
106
+
107
+ MODIFY = "Modify"
108
+ DELETE = "Delete"
109
+ TRANSFER = "Transfer"
110
+
111
+
112
+ class BaseSignablePayload(SQLModel):
113
+ """
114
+ Base class for SQLModel based payloads
115
+ that can be signed and can be converted to bytes for verification.
116
+ Provides a default `to_bytes` method using pydantic's JSON serialization.
117
+ Provides a default `sign` method using the private key of the author.
118
+ """
119
+
120
+ model_config = ConfigDict(
121
+ json_encoders={datetime.datetime: serialize_datetime_to_iso_z},
122
+ populate_by_name=True,
123
+ )
124
+
125
+ def to_bytes(self) -> bytes:
126
+ """
127
+ Default serialization: JSON string encoded to UTF-8.
128
+ """
129
+ payload_json = self.model_dump_json(by_alias=True)
130
+ return payload_json.encode("utf8")
131
+
132
+ def sign(self, private_key: PrivateKeyTypes) -> bytes:
133
+ """Sign this payload using the given private key."""
134
+ bytes_to_sign = self.to_bytes()
135
+ signature = private_key.sign(bytes_to_sign)
136
+ public_key_of_private = private_key.public_key()
137
+ public_key_of_private.verify(signature, bytes_to_sign)
138
+ return signature
139
+
140
+
141
+ P = TypeVar("P", bound=BaseSignablePayload)
142
+
143
+
144
+ class VerifiableLog(Generic[P]):
145
+ """
146
+ Mixin class for SQLModels that store a signature and can be verified.
147
+ Subclasses MUST:
148
+ 1. Define `payload_model_class: ClassVar[type[P]]`.
149
+ 2. Have an instance attribute `signature: str`.
150
+ """
151
+
152
+ signature: str
153
+ payload_model_class: ClassVar[type[P]]
154
+
155
+ def __init_subclass__(cls, **kwargs: Any) -> None:
156
+ super().__init_subclass__(**kwargs)
157
+ if not hasattr(cls, "payload_model_class"):
158
+ raise TypeError(f"Class {cls.__name__} lacks 'payload_model_class' attribute required by VerifiableLog.")
159
+ if not (isinstance(cls.payload_model_class, type) and issubclass(cls.payload_model_class, BaseSignablePayload)):
160
+ raise TypeError(
161
+ f"'payload_model_class' in {cls.__name__} must be a class and a subclass of BaseSignedPayload. "
162
+ f"Got: {cls.payload_model_class}"
163
+ )
164
+
165
+ def verify(self, public_key: PublicKeyTypes) -> bool:
166
+ """Verify the signature of this log entry."""
167
+ if not hasattr(self, "signature") or not isinstance(self.signature, str) or not self.signature:
168
+ log.warning(f"Missing/invalid signature for {self.__class__.__name__} (id: {getattr(self, 'id', 'N/A')}).")
169
+ return False
170
+
171
+ signature_bytes = bytes.fromhex(self.signature)
172
+ data_for_payload = self.model_dump(by_alias=True, exclude={"signature", "payload_model_class"})
173
+ payload_to_verify = self.payload_model_class(**data_for_payload)
174
+ bytes_to_verify = payload_to_verify.to_bytes()
175
+
176
+ try:
177
+ public_key.verify(signature_bytes, bytes_to_verify)
178
+ except cryptography.exceptions.InvalidSignature:
179
+ return False
180
+ except:
181
+ raise
182
+ return True
183
+
184
+
185
+ class SubmissionBase(SQLModel):
186
+ """Submission base model."""
187
+
188
+ tan_g: str | None = Field(default=None, unique=True, index=True, alias="tanG")
189
+ pseudonym: str | None = Field(default=None, index=True)
190
+
191
+
192
+ class Submission(SubmissionBase, table=True):
193
+ """Submission table model."""
194
+
195
+ __tablename__ = "submissions"
196
+
197
+ id: str = Field(primary_key=True, index=True)
198
+
199
+ states: list["SubmissionStateLog"] = Relationship(back_populates="submission")
200
+
201
+ changes: list["ChangeRequestLog"] = Relationship(back_populates="submission")
202
+
203
+
204
+ class SubmissionStateLogBase(SQLModel):
205
+ """
206
+ Submission state log base model.
207
+ Holds state information for each submission.
208
+ Timestamped.
209
+ Can optionally have associated JSON data.
210
+ """
211
+
212
+ state: SubmissionStateEnum
213
+ data: dict[str, Any] | None = Field(default=None, sa_column=Column(JSON))
214
+ timestamp: datetime.datetime = Field(
215
+ default_factory=lambda: datetime.datetime.now(datetime.UTC),
216
+ sa_column=Column(DateTime(timezone=True), nullable=False),
217
+ )
218
+
219
+ model_config = ConfigDict(
220
+ json_encoders={datetime.datetime: serialize_datetime_to_iso_z},
221
+ populate_by_name=True,
222
+ )
223
+
224
+
225
+ class SubmissionStateLogPayload(SubmissionStateLogBase, BaseSignablePayload):
226
+ """
227
+ Used to bundle data for signature calculation.
228
+ """
229
+
230
+ submission_id: str
231
+ author_name: str
232
+
233
+
234
+ class SubmissionStateLog(SubmissionStateLogBase, VerifiableLog[SubmissionStateLogPayload], table=True):
235
+ """Submission state log table model."""
236
+
237
+ __tablename__ = "submission_states"
238
+
239
+ payload_model_class = SubmissionStateLogPayload
240
+
241
+ id: int | None = Field(default=None, primary_key=True, index=True)
242
+ submission_id: str = Field(foreign_key="submissions.id", index=True)
243
+
244
+ author_name: str = Field(index=True)
245
+ signature: str
246
+
247
+ submission: Submission | None = Relationship(back_populates="states")
248
+
249
+
250
+ class SubmissionStateLogCreate(SubmissionStateLogBase):
251
+ """Submission state log create model."""
252
+
253
+ submission_id: str
254
+ author_name: str
255
+ signature: str
256
+
257
+
258
+ class SubmissionCreate(SubmissionBase):
259
+ """Submission create model."""
260
+
261
+ id: str
262
+
263
+
264
+ class ChangeRequestLogBase(SQLModel):
265
+ """
266
+ Base model for change request logs.
267
+ Timestamped.
268
+ Can optionally have associated JSON data.
269
+ """
270
+
271
+ change: ChangeRequestEnum
272
+ data: dict[str, Any] | None = Field(default=None, sa_column=Column(JSON))
273
+ timestamp: datetime.datetime = Field(
274
+ default_factory=lambda: datetime.datetime.now(datetime.UTC),
275
+ sa_column=Column(DateTime(timezone=True), nullable=False),
276
+ )
277
+
278
+ model_config = ConfigDict(
279
+ json_encoders={datetime.datetime: serialize_datetime_to_iso_z},
280
+ populate_by_name=True,
281
+ )
282
+
283
+
284
+ class ChangeRequestLogPayload(ChangeRequestLogBase, BaseSignablePayload):
285
+ """
286
+ Used to bundle data for signature calculation.
287
+ """
288
+
289
+ submission_id: str
290
+ author_name: str
291
+
292
+
293
+ class ChangeRequestLog(ChangeRequestLogBase, VerifiableLog[ChangeRequestLogPayload], table=True):
294
+ """Change-request log table model."""
295
+
296
+ __tablename__ = "submission_change_requests"
297
+
298
+ payload_model_class = ChangeRequestLogPayload
299
+
300
+ id: int | None = Field(default=None, primary_key=True, index=True)
301
+ submission_id: str = Field(foreign_key="submissions.id", index=True)
302
+
303
+ author_name: str = Field(index=True)
304
+ signature: str
305
+
306
+ submission: Submission | None = Relationship(back_populates="changes")
307
+
308
+
309
+ class SubmissionNotFoundError(ValueError):
310
+ """Exception for when a submission is not found in the database."""
311
+
312
+ def __init__(self, submission_id: str):
313
+ super().__init__(f"Submission not found for ID {submission_id}")
314
+
315
+
316
+ class DuplicateSubmissionError(ValueError):
317
+ """Exception for when a submission ID already exists in the database."""
318
+
319
+ def __init__(self, submission_id: str):
320
+ super().__init__(f"Duplicate submission ID {submission_id}")
321
+
322
+
323
+ class DuplicateTanGError(ValueError):
324
+ """Exception for when a tanG is already in use."""
325
+
326
+ def __init__(self, tan_g: str):
327
+ super().__init__(f"Duplicate tanG {tan_g}")
328
+
329
+
330
+ class DatabaseConfigurationError(Exception):
331
+ """Exception for database configuration issues."""
332
+
333
+ pass
334
+
335
+
336
+ class Author:
337
+ def __init__(self, name: str, private_key_bytes: bytes):
338
+ self.name = name
339
+ self.private_key_bytes = private_key_bytes
340
+
341
+ def private_key(self) -> PrivateKeyTypes:
342
+ from functools import partial
343
+ from getpass import getpass
344
+
345
+ from cryptography.hazmat.primitives.serialization import load_ssh_private_key
346
+
347
+ passphrase = os.getenv("GRZ_DB_AUTHOR_PASSPHRASE")
348
+ passphrase_callback = (lambda: passphrase) if passphrase else None
349
+
350
+ if not passphrase:
351
+ passphrase_callback = partial(getpass, prompt=f"Passphrase for GRZ DB author ({self.name}'s) private key: ")
352
+ log.info(f"Loading private key of {self.name}…")
353
+ private_key = load_ssh_private_key(
354
+ self.private_key_bytes,
355
+ password=passphrase_callback().encode("utf-8"),
356
+ )
357
+ return private_key
358
+
359
+
360
+ class SubmissionDb:
361
+ """
362
+ API entrypoint for managing submissions.
363
+ """
364
+
365
+ def __init__(self, db_url: str, author: Author | None, debug: bool = False):
366
+ """
367
+ Initializes the SubmissionDb.
368
+
369
+ Args:
370
+ db_url: Database URL.
371
+ debug: Whether to echo SQL statements.
372
+ """
373
+ self.engine = create_engine(db_url, echo=debug)
374
+ self._author = author
375
+
376
+ @contextmanager
377
+ def get_session(self) -> Generator[Session, Any, None]:
378
+ """Get an sqlmodel session."""
379
+ with Session(self.engine) as session:
380
+ yield session
381
+
382
+ def _get_alembic_config(self, alembic_ini_path: str) -> AlembicConfig:
383
+ """
384
+ Loads the alembic configuration.
385
+
386
+ Args:
387
+ alembic_ini_path: Path to alembic ini file.
388
+ """
389
+ if not alembic_ini_path or not os.path.exists(alembic_ini_path):
390
+ raise ValueError(f"Alembic configuration file not found at: {alembic_ini_path}")
391
+
392
+ alembic_cfg = AlembicConfig(alembic_ini_path)
393
+ alembic_cfg.set_main_option("sqlalchemy.url", str(self.engine.url))
394
+ alembic_cfg.set_main_option("script_location", "grz_db:migrations")
395
+ return alembic_cfg
396
+
397
+ def initialize_schema(self):
398
+ """Initialize the database."""
399
+ SQLModel.metadata.create_all(self.engine, checkfirst=True)
400
+
401
+ def upgrade_schema(self, alembic_ini_path: str, revision: str = "head"):
402
+ """
403
+ Upgrades the database schema using alembic.
404
+
405
+ Args:
406
+ alembic_ini_path: Path to the alembic.ini file.
407
+ revision: The Alembic revision to upgrade to (default: 'head').
408
+
409
+ Raises:
410
+ RuntimeError: For underlying Alembic errors.
411
+ """
412
+ alembic_cfg = self._get_alembic_config(alembic_ini_path)
413
+ try:
414
+ alembic_command.upgrade(alembic_cfg, revision)
415
+ except Exception as e:
416
+ raise RuntimeError(f"Alembic upgrade failed: {e}") from e
417
+
418
+ def add_submission(
419
+ self,
420
+ submission_id: str,
421
+ tan_g: str | None = None,
422
+ pseudonym: str | None = None,
423
+ ) -> Submission:
424
+ """
425
+ Adds a submission to the database.
426
+
427
+ Args:
428
+ submission_id: Submission ID.
429
+ tan_g: tanG if in phase 0
430
+ pseudonym: pseudonym if phase >= 0
431
+
432
+ Returns:
433
+ An instance of Submission.
434
+ """
435
+ with self.get_session() as session:
436
+ existing_submission = session.get(Submission, submission_id)
437
+ if existing_submission:
438
+ raise DuplicateSubmissionError(submission_id)
439
+
440
+ submission_create = SubmissionCreate(id=submission_id, tan_g=tan_g, pseudonym=pseudonym)
441
+ db_submission = Submission.model_validate(submission_create)
442
+
443
+ session.add(db_submission)
444
+ try:
445
+ session.commit()
446
+ session.refresh(db_submission)
447
+ return db_submission
448
+ except IntegrityError as e:
449
+ session.rollback()
450
+ if "UNIQUE constraint failed: submissions.tanG" in str(e) and tan_g:
451
+ raise DuplicateTanGError(tan_g) from e
452
+ raise
453
+ except Exception:
454
+ session.rollback()
455
+ raise
456
+
457
+ def update_submission_state(
458
+ self,
459
+ submission_id: str,
460
+ state: SubmissionStateEnum,
461
+ data: dict | None = None,
462
+ ) -> SubmissionStateLog:
463
+ """
464
+ Updates a submission's state to the specified state.
465
+
466
+ Args:
467
+ submission_id: Submission ID of the submission to update.
468
+ state: New state of the submission.
469
+ data: Optional data to attach to the update.
470
+
471
+ Returns:
472
+ An instance of SubmissionStateLog.
473
+ """
474
+ with self.get_session() as session:
475
+ submission = session.get(Submission, submission_id)
476
+ if not submission:
477
+ raise SubmissionNotFoundError(submission_id)
478
+
479
+ state_log_payload = SubmissionStateLogPayload(
480
+ submission_id=submission_id, author_name=self._author.name, state=state, data=data
481
+ )
482
+ signature = state_log_payload.sign(self._author.private_key())
483
+
484
+ state_log_create = SubmissionStateLogCreate(**state_log_payload.model_dump(), signature=signature.hex())
485
+ db_state_log = SubmissionStateLog.model_validate(state_log_create)
486
+ session.add(db_state_log)
487
+
488
+ # Remove tanG once it has been reported?
489
+ if state == SubmissionStateEnum.REPORTED and submission.tan_g is not None:
490
+ submission.tan_g = None
491
+ session.add(submission)
492
+
493
+ try:
494
+ session.commit()
495
+ session.refresh(db_state_log)
496
+ if state == SubmissionStateEnum.REPORTED and submission.tan_g is None:
497
+ session.refresh(submission)
498
+ return db_state_log
499
+ except Exception:
500
+ session.rollback()
501
+ raise
502
+
503
+ def get_submission(self, submission_id: str) -> Submission | None:
504
+ """
505
+ Retrieves a submission and its state history.
506
+
507
+ Args:
508
+ submission_id: Submission ID of the submission to retrieve.
509
+
510
+ Returns:
511
+ An instance of Submission or None.
512
+ """
513
+ with self.get_session() as session:
514
+ statement = (
515
+ select(Submission).where(Submission.id == submission_id).options(selectinload(Submission.states))
516
+ )
517
+ submission = session.exec(statement).first()
518
+ return submission
519
+
520
+ def list_submissions(self) -> list[Submission]:
521
+ """
522
+ Lists all submissions in the database.
523
+
524
+ Returns:
525
+ A list of all submissions in the database, ordered by their ID.
526
+ """
527
+ with self.get_session() as session:
528
+ statement = select(Submission).options(selectinload(Submission.states)).order_by(Submission.id)
529
+ submissions = session.exec(statement).all()
530
+ return submissions
@@ -0,0 +1 @@
1
+ pyproject configuration, based on the generic configuration.
@@ -0,0 +1,78 @@
1
+ """alembic migrations env.py"""
2
+
3
+ from logging.config import fileConfig
4
+
5
+ from alembic import context
6
+ from grz_db import * # noqa: F403
7
+ from sqlalchemy import engine_from_config, pool
8
+ from sqlmodel import SQLModel
9
+
10
+ # this is the Alembic Config object, which provides
11
+ # access to the values within the .ini file in use.
12
+ config = context.config
13
+
14
+ # Interpret the config file for Python logging.
15
+ # This line sets up loggers basically.
16
+ if config.config_file_name is not None:
17
+ fileConfig(config.config_file_name)
18
+
19
+ # add your model's MetaData object here
20
+ # for 'autogenerate' support
21
+ # from myapp import mymodel
22
+ # target_metadata = mymodel.Base.metadata
23
+ target_metadata = SQLModel.metadata
24
+
25
+ # other values from the config, defined by the needs of env.py,
26
+ # can be acquired:
27
+ # my_important_option = config.get_main_option("my_important_option")
28
+ # ... etc.
29
+
30
+
31
+ def run_migrations_offline() -> None:
32
+ """Run migrations in 'offline' mode.
33
+
34
+ This configures the context with just a URL
35
+ and not an Engine, though an Engine is acceptable
36
+ here as well. By skipping the Engine creation
37
+ we don't even need a DBAPI to be available.
38
+
39
+ Calls to context.execute() here emit the given string to the
40
+ script output.
41
+
42
+ """
43
+ url = config.get_main_option("sqlalchemy.url")
44
+ context.configure(
45
+ url=url,
46
+ target_metadata=target_metadata,
47
+ literal_binds=True,
48
+ dialect_opts={"paramstyle": "named"},
49
+ )
50
+
51
+ with context.begin_transaction():
52
+ context.run_migrations()
53
+
54
+
55
+ def run_migrations_online() -> None:
56
+ """Run migrations in 'online' mode.
57
+
58
+ In this scenario we need to create an Engine
59
+ and associate a connection with the context.
60
+
61
+ """
62
+ connectable = engine_from_config(
63
+ config.get_section(config.config_ini_section, {}),
64
+ prefix="sqlalchemy.",
65
+ poolclass=pool.NullPool,
66
+ )
67
+
68
+ with connectable.connect() as connection:
69
+ context.configure(connection=connection, target_metadata=target_metadata)
70
+
71
+ with context.begin_transaction():
72
+ context.run_migrations()
73
+
74
+
75
+ if context.is_offline_mode():
76
+ run_migrations_offline()
77
+ else:
78
+ run_migrations_online()
@@ -0,0 +1,29 @@
1
+ """${message}
2
+
3
+ Revision ID: ${up_revision}
4
+ Revises: ${down_revision | comma,n}
5
+ Create Date: ${create_date}
6
+
7
+ """
8
+ from typing import Sequence, Union
9
+
10
+ from alembic import op
11
+ import sqlalchemy as sa
12
+ import sqlmodel
13
+ ${imports if imports else ""}
14
+
15
+ # revision identifiers, used by Alembic.
16
+ revision: str = ${repr(up_revision)}
17
+ down_revision: Union[str, None] = ${repr(down_revision)}
18
+ branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
19
+ depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
20
+
21
+
22
+ def upgrade() -> None:
23
+ """Upgrade schema."""
24
+ ${upgrades if upgrades else "pass"}
25
+
26
+
27
+ def downgrade() -> None:
28
+ """Downgrade schema."""
29
+ ${downgrades if downgrades else "pass"}
@@ -0,0 +1,88 @@
1
+ """initial
2
+
3
+ Revision ID: 82607cdce6ee
4
+ Revises:
5
+ Create Date: 2025-05-28 13:40:18.414894
6
+
7
+ """
8
+
9
+ from collections.abc import Sequence
10
+
11
+ import sqlalchemy as sa
12
+ import sqlmodel
13
+ from alembic import op
14
+
15
+ # revision identifiers, used by Alembic.
16
+ revision: str = "82607cdce6ee"
17
+ down_revision: str | None = None
18
+ branch_labels: str | Sequence[str] | None = None
19
+ depends_on: str | Sequence[str] | None = None
20
+
21
+
22
+ def upgrade() -> None:
23
+ """Upgrade schema."""
24
+ # ### commands auto generated by Alembic - please adjust! ###
25
+ op.create_table(
26
+ "submissions",
27
+ sa.Column("tan_g", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
28
+ sa.Column("pseudonym", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
29
+ sa.Column("id", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
30
+ sa.PrimaryKeyConstraint("id"),
31
+ )
32
+ op.create_index(op.f("ix_submissions_id"), "submissions", ["id"], unique=False)
33
+ op.create_index(op.f("ix_submissions_pseudonym"), "submissions", ["pseudonym"], unique=False)
34
+ op.create_index(op.f("ix_submissions_tan_g"), "submissions", ["tan_g"], unique=True)
35
+ op.create_table(
36
+ "submission_states",
37
+ sa.Column(
38
+ "state",
39
+ sa.Enum(
40
+ "UPLOADING",
41
+ "UPLOADED",
42
+ "DOWNLOADING",
43
+ "DOWNLOADED",
44
+ "DECRYPTING",
45
+ "DECRYPTED",
46
+ "VALIDATING",
47
+ "VALIDATED",
48
+ "ENCRYPTING",
49
+ "ENCRYPTED",
50
+ "ARCHIVING",
51
+ "ARCHIVED",
52
+ "REPORTED",
53
+ "QCING",
54
+ "QCED",
55
+ "CLEANING",
56
+ "CLEANED",
57
+ "FINISHED",
58
+ "ERROR",
59
+ name="submissionstateenum",
60
+ ),
61
+ nullable=False,
62
+ ),
63
+ sa.Column("data", sa.JSON(), nullable=True),
64
+ sa.Column("timestamp", sa.DateTime(), nullable=False),
65
+ sa.Column("id", sa.Integer(), nullable=False),
66
+ sa.Column("submission_id", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
67
+ sa.ForeignKeyConstraint(
68
+ ["submission_id"],
69
+ ["submissions.id"],
70
+ ),
71
+ sa.PrimaryKeyConstraint("id"),
72
+ )
73
+ op.create_index(op.f("ix_submission_states_id"), "submission_states", ["id"], unique=False)
74
+ op.create_index(op.f("ix_submission_states_submission_id"), "submission_states", ["submission_id"], unique=False)
75
+ # ### end Alembic commands ###
76
+
77
+
78
+ def downgrade() -> None:
79
+ """Downgrade schema."""
80
+ # ### commands auto generated by Alembic - please adjust! ###
81
+ op.drop_index(op.f("ix_submission_states_submission_id"), table_name="submission_states")
82
+ op.drop_index(op.f("ix_submission_states_id"), table_name="submission_states")
83
+ op.drop_table("submission_states")
84
+ op.drop_index(op.f("ix_submissions_tan_g"), table_name="submissions")
85
+ op.drop_index(op.f("ix_submissions_pseudonym"), table_name="submissions")
86
+ op.drop_index(op.f("ix_submissions_id"), table_name="submissions")
87
+ op.drop_table("submissions")
88
+ # ### end Alembic commands ###
grz_db/py.typed ADDED
File without changes
@@ -0,0 +1,24 @@
1
+ Metadata-Version: 2.4
2
+ Name: grz-db
3
+ Version: 0.1.0
4
+ Summary: SQL models for grz-cli and grz-watchdog.
5
+ Project-URL: Homepage, https://github.com/BfArM-MVH/grz-tools
6
+ Project-URL: Repository, https://github.com/BfArM-MVH/grz-tools/tree/main/packages/grz-db
7
+ Project-URL: Documentation, https://github.com/BfArM-MVH/grz-tools
8
+ Project-URL: Issues, https://github.com/BfArM-MVH/grz-tools/issues
9
+ Author-email: Till Hartmann <till.hartmann@bih-charite.de>
10
+ License-File: LICENSE
11
+ Keywords: python
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
+ Requires-Python: <4.0,>=3.12
19
+ Requires-Dist: alembic>=1.16.1
20
+ Requires-Dist: cryptography>=45.0.3
21
+ Requires-Dist: sqlmodel>=0.0.24
22
+ Description-Content-Type: text/markdown
23
+
24
+ Libraries, SQL models and alembic migrations for GRZ DB.
@@ -0,0 +1,10 @@
1
+ grz_db/__init__.py,sha256=Pu8d4IpKlQRtUlXGJJR5L-ypM7PHYLJ-BLBEEJUxwV8,17200
2
+ grz_db/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ grz_db/migrations/README,sha256=dMhIiFoeM7EdeaOXBs3mVQ6zXACMyGXDb_UBB6sGRA0,60
4
+ grz_db/migrations/env.py,sha256=FQB_cK7WqNMKd1gC2MYABbHc9Y0F33O3cSmMSg7pWz8,2169
5
+ grz_db/migrations/script.py.mako,sha256=ddnLy1SfBVgOAsRoDcfXT2LVfxxADUJUn5sHXkir22o,705
6
+ grz_db/migrations/versions/82607cdce6ee_initial.py,sha256=s1mtYTzEvbc6s4oz-Ov0dn-bMw2aMd3gyeIciWeZdjk,3145
7
+ grz_db-0.1.0.dist-info/METADATA,sha256=9bz07Vb9_4sadC_VMMH5z9x00e8Cq3Ztqvwrc16TcAs,1019
8
+ grz_db-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
9
+ grz_db-0.1.0.dist-info/licenses/LICENSE,sha256=y8AftXce0Ne8jKczrAZvysqhg9zE5lFB5g7gLZL9FdU,1070
10
+ grz_db-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Till Hartmann
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.