mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-01 04:16:24 -05:00
Converting JSON columns to JSONB for performance.
This commit is contained in:
parent
ce9f12da42
commit
1d9b794fca
7 changed files with 68 additions and 15 deletions
50
alembic/versions/76add63ed225_json_to_jsonb.py
Normal file
50
alembic/versions/76add63ed225_json_to_jsonb.py
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
"""json_to_jsonb
|
||||
|
||||
Revision ID: 76add63ed225
|
||||
Revises: 26c5a62ec683
|
||||
Create Date: 2026-01-06 06:13:14.044016
|
||||
|
||||
"""
|
||||
import os
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import text
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '76add63ed225'
|
||||
down_revision = '26c5a62ec683'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
# Convert FileGroup columns from JSON to JSONB
|
||||
session.execute(text('ALTER TABLE file_group ALTER COLUMN data TYPE jsonb USING data::jsonb'))
|
||||
session.execute(text('ALTER TABLE file_group ALTER COLUMN files TYPE jsonb USING files::jsonb'))
|
||||
|
||||
# Convert Video column from JSON to JSONB
|
||||
session.execute(text('ALTER TABLE video ALTER COLUMN ffprobe_json TYPE jsonb USING ffprobe_json::jsonb'))
|
||||
|
||||
# Convert Channel column from JSON to JSONB
|
||||
session.execute(text('ALTER TABLE channel ALTER COLUMN info_json TYPE jsonb USING info_json::jsonb'))
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
# Revert FileGroup columns from JSONB to JSON
|
||||
session.execute(text('ALTER TABLE file_group ALTER COLUMN data TYPE json USING data::json'))
|
||||
session.execute(text('ALTER TABLE file_group ALTER COLUMN files TYPE json USING files::json'))
|
||||
|
||||
# Revert Video column from JSONB to JSON
|
||||
session.execute(text('ALTER TABLE video ALTER COLUMN ffprobe_json TYPE json USING ffprobe_json::json'))
|
||||
|
||||
# Revert Channel column from JSONB to JSON
|
||||
session.execute(text('ALTER TABLE channel ALTER COLUMN info_json TYPE json USING info_json::json'))
|
||||
|
|
@ -2,7 +2,8 @@ import json
|
|||
import pathlib
|
||||
from typing import Optional, Dict, List
|
||||
|
||||
from sqlalchemy import Column, Integer, String, Boolean, JSON, Date, ForeignKey, BigInteger, Index, text
|
||||
from sqlalchemy import Column, Integer, String, Boolean, Date, ForeignKey, BigInteger, Index, text
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.orm import relationship, Session, deferred
|
||||
from sqlalchemy.orm.collections import InstrumentedList
|
||||
|
||||
|
|
@ -33,7 +34,7 @@ class Video(ModelHelper, Base):
|
|||
|
||||
source_id = Column(String) # The id from yt-dlp
|
||||
view_count = Column(Integer) # The view count from the ChannelDownloader (or from initial download)
|
||||
ffprobe_json = deferred(Column(JSON)) # Data that is fetched once from ffprobe (ffmpeg)
|
||||
ffprobe_json = deferred(Column(JSONB)) # Data that is fetched once from ffprobe (ffmpeg)
|
||||
have_comments = Column(Boolean, default=False) # see `get_missing_videos_comments`
|
||||
comments_failed = Column(Boolean, default=False) # see `get_missing_videos_comments`
|
||||
|
||||
|
|
@ -547,7 +548,7 @@ class Channel(ModelHelper, Base):
|
|||
total_size = Column(BigInteger, default=0, nullable=False) # update_channel_size
|
||||
minimum_frequency = Column(Integer) # update_channel_minimum_frequency
|
||||
|
||||
info_json = deferred(Column(JSON))
|
||||
info_json = deferred(Column(JSONB))
|
||||
info_date = Column(Date)
|
||||
|
||||
videos: InstrumentedList = relationship('Video', primaryjoin='Channel.id==Video.channel_id')
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ def get_incomplete_videos(limit: int, offset: int, channel_id: int) -> List[dict
|
|||
-- {'streams': [{'codec_type': 'video'}, {'codec_type': 'audio'}]} -> {video,audio}
|
||||
select v.id, array_agg(s ->> 'codec_type')::TEXT[] AS codec_types
|
||||
from video v
|
||||
cross join lateral json_array_elements(ffprobe_json -> 'streams') s
|
||||
cross join lateral jsonb_array_elements(ffprobe_json -> 'streams') s
|
||||
where channel_id = %(channel_id)s
|
||||
group by v.id)
|
||||
SELECT all_videos.id AS video_id, fg.primary_path, all_videos.codec_types
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ from datetime import timedelta, datetime
|
|||
from enum import Enum
|
||||
from http import HTTPStatus
|
||||
from itertools import filterfalse
|
||||
from typing import List, Dict, Generator, Iterable, Coroutine
|
||||
from typing import List, Dict, Generator, Iterable, Coroutine, Any
|
||||
from typing import Tuple, Optional
|
||||
from urllib.parse import urlparse
|
||||
|
||||
|
|
@ -1483,7 +1483,7 @@ TEST_DOWNLOAD_MANAGER_CONFIG: DownloadManagerConfig = None
|
|||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def downloads_manager_config_context() -> DownloadManagerConfig:
|
||||
def downloads_manager_config_context() -> Generator[DownloadManagerConfig, Any, None]:
|
||||
"""Used to create a test config."""
|
||||
global TEST_DOWNLOAD_MANAGER_CONFIG
|
||||
TEST_DOWNLOAD_MANAGER_CONFIG = DownloadManagerConfig()
|
||||
|
|
|
|||
|
|
@ -591,7 +591,7 @@ def _upsert_files(files: List[pathlib.Path], idempotency: datetime.datetime):
|
|||
WHEN
|
||||
file_group.modification_datetime = EXCLUDED.modification_datetime
|
||||
AND file_group.size = EXCLUDED.size
|
||||
AND json_array_length(file_group.files) = json_array_length(EXCLUDED.files)
|
||||
AND jsonb_array_length(file_group.files) = jsonb_array_length(EXCLUDED.files)
|
||||
THEN file_group.files
|
||||
ELSE EXCLUDED.files
|
||||
END
|
||||
|
|
@ -601,7 +601,7 @@ def _upsert_files(files: List[pathlib.Path], idempotency: datetime.datetime):
|
|||
file_group.indexed = true
|
||||
AND file_group.modification_datetime = EXCLUDED.modification_datetime
|
||||
AND file_group.size = EXCLUDED.size
|
||||
AND json_array_length(file_group.files) = json_array_length(EXCLUDED.files)
|
||||
AND jsonb_array_length(file_group.files) = jsonb_array_length(EXCLUDED.files)
|
||||
)
|
||||
RETURNING id, file_group.indexed AS old_indexed, indexed
|
||||
'''
|
||||
|
|
@ -1160,7 +1160,7 @@ def get_file_statistics():
|
|||
curs.execute('''
|
||||
SELECT
|
||||
-- All items in file_group.files are real individual files.
|
||||
SUM(json_array_length(files)) AS "total_count",
|
||||
SUM(jsonb_array_length(files)) AS "total_count",
|
||||
COUNT(id) FILTER (WHERE file_group.mimetype = 'application/pdf') AS "pdf_count",
|
||||
COUNT(id) FILTER (WHERE file_group.mimetype = 'application/zip') AS "zip_count",
|
||||
COUNT(id) FILTER (WHERE file_group.mimetype LIKE 'video/%') AS "video_count",
|
||||
|
|
@ -1295,7 +1295,7 @@ def get_refresh_progress() -> RefreshProgress:
|
|||
stmt = '''
|
||||
SELECT
|
||||
-- Sum all the files in each FileGroup.
|
||||
SUM(json_array_length(files)) FILTER (WHERE idempotency = %(idempotency)s) AS "total_file_groups",
|
||||
SUM(jsonb_array_length(files)) FILTER (WHERE idempotency = %(idempotency)s) AS "total_file_groups",
|
||||
COUNT(id) FILTER (WHERE indexed IS TRUE AND idempotency = %(idempotency)s) AS "indexed",
|
||||
COUNT(id) FILTER (WHERE indexed IS FALSE AND idempotency = %(idempotency)s) AS "unindexed",
|
||||
COUNT(id) FILTER (WHERE model IS NOT NULL AND idempotency = %(idempotency)s) AS "modeled"
|
||||
|
|
@ -1306,7 +1306,7 @@ def get_refresh_progress() -> RefreshProgress:
|
|||
stmt = '''
|
||||
SELECT
|
||||
-- Sum all the files in each FileGroup.
|
||||
SUM(json_array_length(files)) AS "total_file_groups",
|
||||
SUM(jsonb_array_length(files)) AS "total_file_groups",
|
||||
COUNT(id) FILTER (WHERE indexed IS TRUE) AS "indexed",
|
||||
COUNT(id) FILTER (WHERE indexed IS FALSE) AS "unindexed",
|
||||
COUNT(id) FILTER (WHERE model IS NOT NULL) AS "modeled"
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ from typing import List, Type, Optional, Iterable
|
|||
|
||||
from sqlalchemy import Column, String, Computed, BigInteger, Boolean, event, Index
|
||||
from sqlalchemy import types
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.orm import deferred, relationship, Session
|
||||
|
||||
from wrolpi.common import Base, ModelHelper, tsvector, logger, recursive_map, get_media_directory, \
|
||||
|
|
@ -48,7 +49,7 @@ class FancyJSON(types.TypeDecorator):
|
|||
|
||||
Converts datetime to ISO strings when moving into DB, and vice versa.
|
||||
"""
|
||||
impl = types.JSON
|
||||
impl = JSONB
|
||||
|
||||
def process_bind_param(self, value, dialect):
|
||||
if value:
|
||||
|
|
|
|||
|
|
@ -695,7 +695,8 @@ async def test_get_refresh_progress(async_client, test_session):
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_refresh_files_no_groups(async_client, test_session, test_directory, make_files_structure, zip_file_factory):
|
||||
async def test_refresh_files_no_groups(async_client, test_session, test_directory, make_files_structure,
|
||||
zip_file_factory):
|
||||
"""Files that share a name, but cannot be grouped into a FileGroup have their own FileGroups."""
|
||||
foo_txt, foo_zip = make_files_structure({
|
||||
'foo.txt': 'text',
|
||||
|
|
@ -1442,7 +1443,7 @@ def test_sanitize_filename_surrogates_renames_file(test_directory):
|
|||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rename_file_with_associated_files_twice(async_client, test_session, test_directory, make_files_structure,
|
||||
video_bytes, srt_text):
|
||||
video_bytes, srt_text):
|
||||
"""
|
||||
Renaming a FileGroup twice should rename all associated files both times.
|
||||
|
||||
|
|
@ -1508,7 +1509,7 @@ async def test_rename_file_with_associated_files_twice(async_client, test_sessio
|
|||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rename_non_primary_file_renames_filegroup(async_client, test_session, test_directory,
|
||||
make_files_structure, video_bytes, srt_text):
|
||||
make_files_structure, video_bytes, srt_text):
|
||||
"""
|
||||
Renaming a non-primary file (like a subtitle) should rename the entire FileGroup.
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue