finished writing to database

This commit is contained in:
Hellow 2023-02-19 23:35:52 +01:00
parent 6531bf7022
commit 87dcfdb54b
5 changed files with 145 additions and 12 deletions

View File

@ -44,6 +44,7 @@ class Album(BaseModel):
title: str = CharField(null=True) title: str = CharField(null=True)
label: str = CharField(null=True) label: str = CharField(null=True)
album_status: str = CharField(null=True) album_status: str = CharField(null=True)
album_type: str = CharField(null=True)
language: str = CharField(null=True) language: str = CharField(null=True)
date: str = CharField(null=True) date: str = CharField(null=True)
date_format: str = CharField(null=True) date_format: str = CharField(null=True)
@ -57,6 +58,7 @@ class Artist(BaseModel):
"""A class representing an artist in the music database.""" """A class representing an artist in the music database."""
name: str = CharField() name: str = CharField()
notes: str = CharField()
class Song(BaseModel): class Song(BaseModel):

View File

@ -1,12 +1,20 @@
from typing import Optional, Union # Standard library
from typing import Optional, Union, List
from enum import Enum from enum import Enum
# third party modules
from peewee import ( from peewee import (
SqliteDatabase, SqliteDatabase,
MySQLDatabase, MySQLDatabase,
PostgresqlDatabase, PostgresqlDatabase,
) )
from . import data_models # own modules
from . import (
data_models,
write,
objects,
)
class DatabaseType(Enum): class DatabaseType(Enum):
@ -66,7 +74,7 @@ class Database:
port=self.db_port, port=self.db_port,
) )
raise ValueError("define a Valid database type") raise ValueError("Invalid database type specified.")
def initialize_database(self): def initialize_database(self):
""" """
@ -91,6 +99,60 @@ class Database:
# add the missing column to the table # add the missing column to the table
self.database.add_column(model._meta.db_table, field_name, field_obj) self.database.add_column(model._meta.db_table, field_name, field_obj)
def push(self, database_object: objects.MusicObject):
"""
Adds a new music object to the database using the corresponding method from the `write` session.
When possible, rather use the `push_many` function.
This gets even more important, when using a remote database server.
Args:
database_object (objects.MusicObject): The music object to add to the database.
Returns:
The newly added music object.
"""
with write.WritingSession(self.database) as writing_session:
if isinstance(database_object, objects.Song):
return writing_session.add_song(database_object)
if isinstance(database_object, objects.Album):
return writing_session.add_album(database_object)
if isinstance(database_object, objects.Artist):
return writing_session.add_artist(database_object)
def push_many(self, database_objects: List[objects.MusicObject]) -> None:
"""
Adds a list of MusicObject instances to the database.
This function sends only needs one querry for each type of table added.
Beware that if you have for example an object like this:
- Album
- Song
- Song
you already have 3 different Tables.
Unlike the function `push`, this function doesn't return the added database objects.
Args:
database_objects: List of MusicObject instances to be added to the database.
"""
with write.WritingSession(self.database) as writing_session:
for obj in database_objects:
if isinstance(obj, objects.Song):
writing_session.add_song(obj)
continue
if isinstance(obj, objects.Album):
writing_session.add_album(obj)
continue
if isinstance(obj, objects.Artist):
writing_session.add_artist(obj)
continue
def __del__(self): def __del__(self):
self.database.close() self.database.close()

View File

@ -1,4 +1,4 @@
from typing import Union, Set, Optional, Dict, DefaultDict from typing import Union, Optional, Dict, DefaultDict, Type, List
from collections import defaultdict from collections import defaultdict
import traceback import traceback
from peewee import ( from peewee import (
@ -15,7 +15,7 @@ from . import data_models
Database = Union[SqliteDatabase, PostgresqlDatabase, MySQLDatabase] Database = Union[SqliteDatabase, PostgresqlDatabase, MySQLDatabase]
class Session: class WritingSession:
""" """
Context manager for a database session Context manager for a database session
@ -43,9 +43,9 @@ class Session:
self.added_album_ids: Dict[str] = dict() self.added_album_ids: Dict[str] = dict()
self.added_artist_ids: Dict[str] = dict() self.added_artist_ids: Dict[str] = dict()
self.db_objects: DefaultDict[data_models.BaseModel, list] = defaultdict(list) self.db_objects: DefaultDict[data_models.BaseModel, List[data_models.BaseModel]] = defaultdict(list)
def __enter__(self, database: Database): def __enter__(self) -> Type['WritingSession']:
""" """
Enter the context of the database session Enter the context of the database session
@ -55,7 +55,7 @@ class Session:
Returns: Returns:
self: The instance of the session object self: The instance of the session object
""" """
self.__init__(database=database) # self.__init__(database=database)
return self return self
def __exit__(self, exc_type, exc_val, exc_tb): def __exit__(self, exc_type, exc_val, exc_tb):
@ -138,7 +138,7 @@ class Session:
).use(self.database) ).use(self.database)
self.db_objects[data_models.Song].append(db_song) self.db_objects[data_models.Song].append(db_song)
self.added_song_ids[song.id] = db_song self.added_song_ids[song.id].append(db_song)
for source in song.source_list: for source in song.source_list:
self.add_source(source=source, connected_to=db_song) self.add_source(source=source, connected_to=db_song)
@ -153,6 +153,8 @@ class Session:
is_feature=False is_feature=False
) )
self.db_objects[data_models.SongArtist].append(db_song_artist)
for feature_artist in song.feature_artist_collection: for feature_artist in song.feature_artist_collection:
db_song_artist = data_models.SongArtist( db_song_artist = data_models.SongArtist(
song=db_song, song=db_song,
@ -160,12 +162,16 @@ class Session:
is_feature=True is_feature=True
) )
self.db_objects[data_models.SongArtist].append(db_song_artist)
for album in [song.album]: for album in [song.album]:
db_album_song = data_models.AlbumSong( db_album_song = data_models.AlbumSong(
song=db_song, song=db_song,
album=self.add_album(album) album=self.add_album(album)
) )
self.db_objects[data_models.AlbumSong] = db_album_song
return db_song return db_song
def add_album(self, album: objects.Album) -> Optional[data_models.Album]: def add_album(self, album: objects.Album) -> Optional[data_models.Album]:
@ -180,11 +186,43 @@ class Session:
if album.id in self.added_album_ids: if album.id in self.added_album_ids:
return self.added_album_ids[album.id] return self.added_album_ids[album.id]
db_album = data_models.Album().use(self.database) db_album = data_models.Album(
title = album.title,
label = album.label,
album_status = album.album_status,
album_type = album.album_type,
language = album.iso_639_2_language,
date = album.date.timestamp,
date_format = album.date.timeformat,
country = album.country,
barcode = album.barcode,
albumsort = album.albumsort,
is_split = album.is_split
).use(self.database)
self.db_objects[data_models.Album].append(db_album) self.db_objects[data_models.Album].append(db_album)
self.added_album_ids.add(album.id) self.added_album_ids.add(album.id)
for source in album.source_list:
self.add_source(source, db_album)
for song in album.tracklist:
db_song_album = data_models.AlbumSong(
id = album.id,
album = album,
song = self.add_song(song)
)
self.db_objects[data_models.AlbumSong].append(db_song_album)
for artist in album.artists:
db_album_artist = data_models.AlbumArtist(
album = album,
artist = self.add_artist(artist)
)
self.db_objects[data_models.Artist].append(db_album_artist)
return db_album return db_album
def add_artist(self, artist: objects.Artist) -> Optional[data_models.Artist]: def add_artist(self, artist: objects.Artist) -> Optional[data_models.Artist]:
@ -199,11 +237,35 @@ class Session:
if artist.id in self.added_artist_ids: if artist.id in self.added_artist_ids:
return self.added_artist_ids[artist.id] return self.added_artist_ids[artist.id]
db_artist = data_models.Artist() db_artist = data_models.Artist(
id = artist.id,
name = artist.name,
notes = artist.notes.json
)
self.db_objects[data_models.Artist].append(db_artist) self.db_objects[data_models.Artist].append(db_artist)
self.added_artist_ids[artist.id] = db_artist self.added_artist_ids[artist.id] = db_artist
for source in artist.source_list:
self.add_source(source, db_artist)
for album in artist.main_albums:
db_album_artist = data_models.AlbumArtist(
artist = artist,
album = self.add_album(album)
)
self.db_objects[data_models.AlbumArtist].append(db_album_artist)
for song in artist.feature_songs:
db_artist_song = data_models.SongArtist(
artist = artist,
song = self.add_song(song),
is_feature = True
)
self.db_objects[data_models.SongArtist].append(db_artist_song)
return db_artist return db_artist
def commit(self, reset: bool = True): def commit(self, reset: bool = True):
@ -219,5 +281,5 @@ class Session:
if __name__ == "__main__": if __name__ == "__main__":
with Session(SqliteDatabase(":memory:")) as session: with WritingSession(SqliteDatabase(":memory:")) as session:
session.add_song(objects.Song(title="Hs")) session.add_song(objects.Song(title="Hs"))

View File

@ -52,6 +52,12 @@ class FormattedText:
return None return None
return pandoc.write(self.doc, format="plain").strip() return pandoc.write(self.doc, format="plain").strip()
@property
def json(self) -> str:
if self.doc is None:
return None
return pandoc.write(self.doc, format="json")
plaintext = property(fget=get_plaintext, fset=set_plaintext) plaintext = property(fget=get_plaintext, fset=set_plaintext)
markdown = property(fget=get_markdown, fset=set_markdown) markdown = property(fget=get_markdown, fset=set_markdown)
html = property(fget=get_html, fset=set_html) html = property(fget=get_html, fset=set_html)

View File

@ -252,6 +252,7 @@ class ID3Timestamp:
return self.timestamp return self.timestamp
timestamp: str = property(fget=get_timestamp) timestamp: str = property(fget=get_timestamp)
timeformat: str = property(fget=get_time_format)
class MetadataAttribute: class MetadataAttribute: