mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-25 09:26:17 -05:00
Tags can be created and deleted in UI. Adding tag_file using id to avoid session error. Using UTC in test. Matching tag_names style in test. Tag icon is displayed on file rows. Archives, Videos and Files can be filtered by their tags. Tags can be added and removed from UI. Tags are displayed in VideoPlayer. The tags of a file are returned in it's JSON. Video favorites are converted to Favorite tag on channel config import. Updating tests to match frontend usage. PDF creator and modification time are displayed. Reworking file search to use Video.__json__ for complex video relations. Archives can be viewed. Removing ebook.title. Reworking alembic migration to be an upgrade rather than a replace. Skipping test on circleci. Clearing out video caption index only if extract_subtitles if off. Channel tests pass. Some video tests pass. Missing videos can be found. A video can be downloaded. Orphaned files can be found. Videos can be tagged. Videos can be searched. Videos can be modeled. Converting some tests to use FileGroup.primary_path. Adding archive and domains to alembic migration. Testing cascading Archive titles. Archives now uses FileGroup. archive.lib tests pass. Archive is partially converted to FileGroup. Calculating FileGroup.primary file on refresh, rather than on select. wrolpi tests pass. Using FilesType to convert between str/pathlib.Path for FileGroup.files. Using list of files in FileGroup.files instead of dictionary. Storing files in dedicated FileGroup.files to avoid overwriting them. Adding comment explaining CASE. Not overwriting FileGroup.data on refresh if no change has been detected. Removing File model in favor of FileGroup.data. Adding typing to Files methods. Files are indexed using the primary mimetype of the FileGroup. files test_lib tests pass. Removing file_group_file in favor of simple one-to-many relationship. PDF files are indexed during refresh. Adding Tag and TagFile to tag files with specific tags. Only iterating when full_stem_ids has contents. Testing that FileGroups are related to their Files. Files and file_groups are created and linked. Bump webpack from 5.75.0 to 5.76.1 in /app (#160) Bumps [webpack](https://github.com/webpack/webpack) from 5.75.0 to 5.76.1. - [Release notes](https://github.com/webpack/webpack/releases) - [Commits](https://github.com/webpack/webpack/compare/v5.75.0...v5.76.1) --- updated-dependencies: - dependency-name: webpack dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
181 lines
6.1 KiB
Python
181 lines
6.1 KiB
Python
import pathlib
|
|
import types
|
|
from contextlib import contextmanager
|
|
from functools import wraps
|
|
from typing import ContextManager, Tuple, List, Union, Type, Generator
|
|
|
|
import psycopg2
|
|
import psycopg2.extensions
|
|
import sqlalchemy.exc
|
|
from psycopg2._psycopg import cursor
|
|
from sqlalchemy import create_engine, inspect
|
|
from sqlalchemy.orm import sessionmaker, Session
|
|
from sqlalchemy.pool import NullPool
|
|
|
|
from wrolpi.common import logger, Base, partition
|
|
from wrolpi.vars import DB_NAME, DB_USER, DB_PASSWORD, DB_HOST, DB_PORT, DOCKERIZED, PYTEST
|
|
|
|
logger = logger.getChild(__name__)
|
|
|
|
|
|
def get_db_args(dbname: str = None):
|
|
db_args = dict(
|
|
dbname=dbname or DB_NAME,
|
|
user=DB_USER,
|
|
password=DB_PASSWORD,
|
|
host=DB_HOST,
|
|
port=DB_PORT,
|
|
)
|
|
if DOCKERIZED:
|
|
# Deployed in docker, use the docker database.
|
|
db_args['user'] = 'postgres'
|
|
db_args['host'] = 'db'
|
|
elif PYTEST:
|
|
# Pytest is running, but we're not in docker, use the exposed docker container port.
|
|
db_args['user'] = 'postgres'
|
|
|
|
return db_args
|
|
|
|
|
|
# This engine is used to modify the databases.
|
|
connect_args = dict(application_name='wrolpi_api_super')
|
|
postgres_args = get_db_args('postgres')
|
|
postgres_engine = create_engine('postgresql://{user}:{password}@{host}:{port}/{dbname}'.format(**postgres_args),
|
|
execution_options={'isolation_level': 'AUTOCOMMIT'}, connect_args=connect_args)
|
|
|
|
# This engine is used for all normal tasks (except testing).
|
|
db_args = get_db_args()
|
|
connect_args = dict(application_name='wrolpi_api', connect_timeout=1)
|
|
uri = 'postgresql://{user}:{password}@{host}:{port}/{dbname}'.format(**db_args)
|
|
engine = create_engine(uri, poolclass=NullPool, connect_args=connect_args)
|
|
session_maker = sessionmaker(bind=engine)
|
|
|
|
LOGGED_ARGS = False
|
|
|
|
|
|
def _get_db_session():
|
|
"""
|
|
This function allows the database to be wrapped during testing. See: api.test.common.wrap_test_db
|
|
"""
|
|
global LOGGED_ARGS
|
|
if LOGGED_ARGS is False:
|
|
# Print the DB args for troubleshooting.
|
|
LOGGED_ARGS = True
|
|
logging_args = db_args.copy()
|
|
logging_args['password'] = '***'
|
|
logger.debug(f'DB args: {logging_args}')
|
|
|
|
session = session_maker()
|
|
return engine, session
|
|
|
|
|
|
def get_db_context() -> Tuple[create_engine, Session]:
|
|
"""
|
|
Get a DB engine and session.
|
|
"""
|
|
local_engine, session = _get_db_session()
|
|
if PYTEST and not local_engine.url.database.startswith('wrolpi_testing_'):
|
|
raise ValueError(f'Running tests, but a test database is not being used!! {local_engine.url=}')
|
|
return local_engine, session
|
|
|
|
|
|
# logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
|
|
|
|
|
|
@contextmanager
|
|
def get_db_session(commit: bool = False) -> ContextManager[Session]:
|
|
"""
|
|
Context manager that creates a DB session. This will automatically rollback changes, unless `commit` is True.
|
|
"""
|
|
_, session = get_db_context()
|
|
try:
|
|
yield session
|
|
if commit:
|
|
session.commit()
|
|
except sqlalchemy.exc.DatabaseError:
|
|
session.rollback()
|
|
raise
|
|
finally:
|
|
# Rollback only if a transaction hasn't been committed.
|
|
if session.transaction.is_active:
|
|
session.rollback()
|
|
|
|
|
|
@contextmanager
|
|
def get_db_curs(commit: bool = False):
|
|
"""
|
|
Context manager that yields a DictCursor to execute raw SQL statements.
|
|
"""
|
|
local_engine, session = get_db_context()
|
|
connection = local_engine.raw_connection()
|
|
curs = connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
|
|
try:
|
|
yield curs
|
|
if commit:
|
|
connection.commit()
|
|
except sqlalchemy.exc.DatabaseError:
|
|
session.rollback()
|
|
raise
|
|
finally:
|
|
# Rollback only if a transaction hasn't been committed.
|
|
if session.transaction.is_active:
|
|
connection.rollback()
|
|
|
|
|
|
def optional_session(commit: Union[callable, bool] = False):
|
|
"""
|
|
Wraps a function, if a Session is passed it will be used. Otherwise, a new session will be
|
|
created and passed to the function.
|
|
"""
|
|
|
|
def find_session(*f_args, session: Session = None, **f_kwargs):
|
|
session = f_kwargs.get('session', session)
|
|
if not session:
|
|
# Find the session in the args.
|
|
session, new_args = partition(lambda i: isinstance(i, Session), f_args)
|
|
if session:
|
|
session = session[0]
|
|
f_args = tuple(new_args)
|
|
return session, f_args, f_kwargs
|
|
|
|
def call_func(func, session, args, kwargs):
|
|
if session:
|
|
return func(*args, session=session, **kwargs)
|
|
else:
|
|
with get_db_session() as session:
|
|
return func(*args, session=session, **kwargs)
|
|
|
|
def wrapper(*w_args, **w_kwargs):
|
|
if len(w_args) == 1 and len(w_kwargs) == 0 and callable(w_args[0]):
|
|
func = w_args[0]
|
|
|
|
@wraps(func)
|
|
def wrapped(*args, session: Session = None, **kwargs):
|
|
session, args, kwargs = find_session(*args, session=session, **kwargs)
|
|
return call_func(func, session, args, kwargs)
|
|
|
|
return wrapped
|
|
else:
|
|
session_, w_args, w_kwargs = find_session(*w_args, **w_kwargs)
|
|
return call_func(commit, session_, w_args, w_kwargs)
|
|
|
|
return wrapper
|
|
|
|
|
|
@optional_session
|
|
def get_ranked_models(ranked_primary_keys: List, model: Type[Base], session: Session = None) -> List[Base]:
|
|
"""Get all objects whose primary keys are in the `ranked_primary_keys`, preserve their order."""
|
|
pkey = inspect(model).primary_key[0]
|
|
pkey_name = pkey.name
|
|
results = list(session.query(model).filter(pkey.in_(ranked_primary_keys)).all())
|
|
results = sorted(results, key=lambda i: ranked_primary_keys.index(getattr(i, pkey_name)))
|
|
return results
|
|
|
|
|
|
def mogrify(curs: cursor, values: Union[List, Generator]) -> str:
|
|
values = list(values) if isinstance(values, types.GeneratorType) else values.copy()
|
|
count = len(values[0])
|
|
# If `count = 3`, then s = '(%s,%s,%s)'
|
|
s = '(' + ','.join("%s" for _ in range(count)) + ')'
|
|
result = ',\n'.join([curs.mogrify(s, i).decode() for i in values])
|
|
return result
|