mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-02 20:59:56 -05:00
Compare commits
5 commits
master
...
debian12-f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5c0109c099 | ||
|
|
2c595e6db0 | ||
|
|
73fcc24335 | ||
|
|
f0858af253 | ||
|
|
ac69ec101e |
1705 changed files with 28052 additions and 166936 deletions
205
.circleci/config.yml
Normal file
205
.circleci/config.yml
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
# Use the latest 2.1 version of CircleCI pipeline process engine.
|
||||
# See: https://circleci.com/docs/2.0/configuration-reference
|
||||
version: 2.1
|
||||
|
||||
# Define a job to be invoked later in a workflow.
|
||||
# See: https://circleci.com/docs/2.0/configuration-reference/#jobs
|
||||
jobs:
|
||||
api-tests-3-11:
|
||||
docker:
|
||||
- image: cimg/python:3.11
|
||||
- image: cimg/postgres:15.6
|
||||
environment:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_DB: wrolpi
|
||||
POSTGRES_PASSWORD: "wrolpi"
|
||||
# `large` (4 vCPU, 8 GB) so pytest-xdist's `-nauto` has room to scale.
|
||||
resource_class: large
|
||||
steps:
|
||||
- checkout
|
||||
- run: sudo apt-get update
|
||||
- run: sudo apt-get install -y ffmpeg catdoc
|
||||
- restore_cache:
|
||||
key: deps-3.11-{{ checksum "requirements.txt" }}-5
|
||||
- run:
|
||||
name: Install Requirements
|
||||
command: |
|
||||
python3 -m venv venv
|
||||
. venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
- save_cache:
|
||||
key: deps-3.11-{{ checksum "requirements.txt" }}-5
|
||||
paths:
|
||||
- "venv"
|
||||
# `-nauto` parallelizes across all available cores via pytest-xdist.
|
||||
# `-svv` was dumping the full test stdout to CircleCI logs on every run,
|
||||
# which inflated wall time and produced multi-MB log artifacts; dropped.
|
||||
- run:
|
||||
command: './venv/bin/pytest -nauto --junitxml=test-results.xml'
|
||||
- store_test_results:
|
||||
path: test-results.xml
|
||||
api-alembic-migrations:
|
||||
docker:
|
||||
- image: cimg/python:3.11
|
||||
- image: cimg/postgres:15.6
|
||||
environment:
|
||||
POSTGRES_USER: wrolpi
|
||||
POSTGRES_DB: wrolpi
|
||||
POSTGRES_PASSWORD: "wrolpi"
|
||||
resource_class: medium
|
||||
steps:
|
||||
- checkout
|
||||
- restore_cache:
|
||||
key: deps-3.11-{{ checksum "requirements.txt" }}-5
|
||||
- run:
|
||||
name: Install Requirements
|
||||
command: |
|
||||
python3 -m venv venv
|
||||
. venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
- save_cache:
|
||||
key: deps-3.11-{{ checksum "requirements.txt" }}-5
|
||||
paths:
|
||||
- "venv"
|
||||
- run:
|
||||
name: Run Alembic Migrations
|
||||
command: ./venv/bin/python ./main.py db upgrade
|
||||
- run:
|
||||
name: Check for Missing Migrations
|
||||
command: ./venv/bin/python ./main.py db check
|
||||
api-tests-3-12:
|
||||
docker:
|
||||
- image: cimg/python:3.12
|
||||
- image: cimg/postgres:15.6
|
||||
environment:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_DB: wrolpi
|
||||
POSTGRES_PASSWORD: "wrolpi"
|
||||
resource_class: large
|
||||
steps:
|
||||
- checkout
|
||||
- run: sudo apt-get update
|
||||
- run: sudo apt-get install -y ffmpeg catdoc
|
||||
- restore_cache:
|
||||
key: deps-3.12-{{ checksum "requirements.txt" }}-5
|
||||
- run:
|
||||
name: Install Requirements
|
||||
command: |
|
||||
python3 -m venv venv
|
||||
. venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
- save_cache:
|
||||
key: deps-3.12-{{ checksum "requirements.txt" }}-5
|
||||
paths:
|
||||
- "venv"
|
||||
- run:
|
||||
command: './venv/bin/pytest -nauto'
|
||||
sanic-api-start:
|
||||
docker:
|
||||
- image: cimg/python:3.11
|
||||
steps:
|
||||
- checkout
|
||||
- restore_cache:
|
||||
key: deps-3.11-{{ checksum "requirements.txt" }}-5
|
||||
- run:
|
||||
name: Install dependencies
|
||||
command: |
|
||||
python -m venv venv
|
||||
. venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
sudo mkdir -p /media/wrolpi
|
||||
- run:
|
||||
name: Start Sanic API
|
||||
command: |
|
||||
. venv/bin/activate
|
||||
sanic main:api_app -H 0.0.0.0 -p 8081
|
||||
background: true
|
||||
- run:
|
||||
name: Test Sanic API
|
||||
command: |
|
||||
sleep 20
|
||||
curl http://0.0.0.0:8081/api/echo
|
||||
- run:
|
||||
name: Stop Sanic API
|
||||
command: pkill -f sanic
|
||||
react-app-start:
|
||||
docker:
|
||||
- image: cimg/node:20.13
|
||||
resource_class: large
|
||||
steps:
|
||||
- checkout
|
||||
- restore_cache:
|
||||
key: app-{{ checksum "app/package-lock.json" }}
|
||||
- run: cd app && npm install --legacy-peer-deps
|
||||
- save_cache:
|
||||
key: app-{{ checksum "app/package-lock.json" }}
|
||||
paths:
|
||||
- ./app/node_modules
|
||||
- run:
|
||||
name: Build React App
|
||||
command: cd app && DISABLE_ESLINT_PLUGIN=true npm run build
|
||||
- run:
|
||||
name: Start React App
|
||||
command: cd app && DISABLE_ESLINT_PLUGIN=true npm run start
|
||||
background: true
|
||||
- run:
|
||||
name: Test React App
|
||||
command: |
|
||||
sleep 20
|
||||
curl http://0.0.0.0:3000/manifest.json
|
||||
- run:
|
||||
name: Stop React App
|
||||
command: pkill -f npm
|
||||
# Jest tests moved to GitHub Actions (.github/workflows/jest-tests.yml)
|
||||
cypress-e2e-tests:
|
||||
docker:
|
||||
- image: cimg/node:20.18-browsers
|
||||
resource_class: large
|
||||
steps:
|
||||
- checkout
|
||||
- restore_cache:
|
||||
key: app-browsers-{{ checksum "app/package-lock.json" }}
|
||||
- run:
|
||||
name: Install Dependencies
|
||||
command: cd app && npm install --legacy-peer-deps
|
||||
- save_cache:
|
||||
key: app-browsers-{{ checksum "app/package-lock.json" }}
|
||||
paths:
|
||||
- ./app/node_modules
|
||||
- run:
|
||||
name: Start React App in Background
|
||||
command: cd app && DISABLE_ESLINT_PLUGIN=true npm start
|
||||
background: true
|
||||
- run:
|
||||
name: Wait for React App
|
||||
command: |
|
||||
for i in {1..60}; do
|
||||
if curl -s http://localhost:3000 > /dev/null; then
|
||||
echo "React app is ready!"
|
||||
exit 0
|
||||
fi
|
||||
echo "Waiting for React app... ($i/60)"
|
||||
sleep 2
|
||||
done
|
||||
echo "React app failed to start"
|
||||
exit 1
|
||||
- run:
|
||||
name: Run Cypress Tests
|
||||
command: cd app && CI=true npx cypress run
|
||||
- store_artifacts:
|
||||
path: app/cypress/videos
|
||||
- store_artifacts:
|
||||
path: app/cypress/screenshots
|
||||
|
||||
workflows:
|
||||
wrolpi-api-tests:
|
||||
jobs:
|
||||
- sanic-api-start
|
||||
- api-tests-3-11
|
||||
- api-alembic-migrations
|
||||
# - api-tests-3-12 Sanic does not yet support 3.12.
|
||||
wrolpi-app-test:
|
||||
jobs:
|
||||
- react-app-start
|
||||
# jest-tests moved to GitHub Actions
|
||||
- cypress-e2e-tests
|
||||
45
.github/dependabot.yml
vendored
45
.github/dependabot.yml
vendored
|
|
@ -7,11 +7,6 @@ updates:
|
|||
interval: "monthly"
|
||||
target-branch: "master"
|
||||
open-pull-requests-limit: 5
|
||||
ignore:
|
||||
# SQLAlchemy 2.1 is a minor release with its own deprecations; upgrade it
|
||||
# deliberately rather than by an automatic bump.
|
||||
- dependency-name: "SQLAlchemy"
|
||||
versions: [">=2.1"]
|
||||
groups:
|
||||
python-dependencies:
|
||||
patterns:
|
||||
|
|
@ -42,46 +37,6 @@ updates:
|
|||
interval: "monthly"
|
||||
target-branch: "master"
|
||||
open-pull-requests-limit: 5
|
||||
ignore:
|
||||
# Major upgrades below need their own migration branch, not a bump PR.
|
||||
# maplibre-gl 6: /map build depends on pinned babel/terser handling.
|
||||
- dependency-name: "maplibre-gl"
|
||||
versions: [">=6"]
|
||||
# style-spec validates overlays for the renderer, so it must match the spec maplibre-gl 5.24 bundles (24.8);
|
||||
# 24.10 already accepts paint properties the renderer rejects.
|
||||
- dependency-name: "@maplibre/maplibre-gl-style-spec"
|
||||
versions: [">=24.9"]
|
||||
# react-dropzone 15+ changed the accept API; 20 requires Node >=22.
|
||||
- dependency-name: "react-dropzone"
|
||||
versions: [">=15"]
|
||||
# React 19: @react-three/fiber 8 pins react <19.
|
||||
- dependency-name: "react"
|
||||
update-types: ["version-update:semver-major"]
|
||||
- dependency-name: "react-dom"
|
||||
update-types: ["version-update:semver-major"]
|
||||
- dependency-name: "@types/react"
|
||||
update-types: ["version-update:semver-major"]
|
||||
- dependency-name: "@types/react-dom"
|
||||
update-types: ["version-update:semver-major"]
|
||||
# TypeScript 6+/7 breaks the react-scripts toolchain.
|
||||
- dependency-name: "typescript"
|
||||
versions: [">=6"]
|
||||
# Mantine 9: all @mantine packages move together with app code changes.
|
||||
- dependency-name: "@mantine/*"
|
||||
update-types: ["version-update:semver-major"]
|
||||
# Cypress 16 requires Node >=22; CI and the app image run Node 20.
|
||||
- dependency-name: "cypress"
|
||||
versions: [">=16"]
|
||||
# react-router 8 is a routing migration across ~40 files.
|
||||
- dependency-name: "react-router"
|
||||
update-types: ["version-update:semver-major"]
|
||||
# @testing-library/react 14+ async act semantics break menu/popover tests.
|
||||
- dependency-name: "@testing-library/react"
|
||||
update-types: ["version-update:semver-major"]
|
||||
# Cypress component testing resolves the top-level webpack-dev-server and only
|
||||
# accepts major 5; 6 crashes cypress.config.js ("Unexpected major version").
|
||||
- dependency-name: "webpack-dev-server"
|
||||
versions: [">=6"]
|
||||
groups:
|
||||
npm-dependencies:
|
||||
patterns:
|
||||
|
|
|
|||
146
.github/workflows/backend.yml
vendored
146
.github/workflows/backend.yml
vendored
|
|
@ -1,146 +0,0 @@
|
|||
name: Backend Tests
|
||||
|
||||
# Same triggers as jest-tests.yml: `pull_request` is unfiltered so pull requests into feature
|
||||
# branches are checked too, not only those into master.
|
||||
on:
|
||||
push:
|
||||
branches: [master, feature/*]
|
||||
pull_request:
|
||||
|
||||
# A new push to a pull request makes the run for the previous push worthless; cancel it so it
|
||||
# does not hold runners (the free plan allows 20 concurrent jobs). Runs on master always finish.
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
# The suite is split by directory so it finishes in a few minutes, and so a check's name says
|
||||
# which area broke. The groups are balanced by test time; `rest` runs everything the others do
|
||||
# not, so a new directory is tested before anyone assigns it. A path added to any other group
|
||||
# must also be added to `rest` as an --ignore, or its tests run twice.
|
||||
api-tests:
|
||||
name: api-tests (${{ matrix.name }})
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- name: core
|
||||
paths: wrolpi/test
|
||||
- name: media
|
||||
paths: modules/videos modules/zim modules/docs modules/map modules/inventory modules/flasher tiles
|
||||
- name: files
|
||||
paths: wrolpi/files wrolpi/collections
|
||||
- name: rest
|
||||
paths: >-
|
||||
--ignore=wrolpi/test
|
||||
--ignore=modules/videos --ignore=modules/zim --ignore=modules/docs --ignore=modules/map
|
||||
--ignore=modules/inventory --ignore=modules/flasher --ignore=tiles
|
||||
--ignore=wrolpi/files --ignore=wrolpi/collections
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install system packages
|
||||
# Mesa's EGL and GL drivers: the map tile service (tiles/) draws with them.
|
||||
run: sudo apt-get update && sudo apt-get install -y ffmpeg catdoc libegl1 libegl-mesa0 libgl1-mesa-dri libgles2
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
# Trixie ships 3.13.
|
||||
python-version: '3.13'
|
||||
cache: 'pip'
|
||||
cache-dependency-path: requirements.lock
|
||||
|
||||
- name: Install dependencies
|
||||
run: scripts/install_python_requirements.sh pip requirements.txt
|
||||
|
||||
# `logical`, not `auto`: with psutil installed, `auto` counts physical cores, which is two on
|
||||
# the four-vCPU runner. No `-v`: the full test output inflates wall time and logs.
|
||||
- name: Run pytest
|
||||
env:
|
||||
PATHS: ${{ matrix.paths }}
|
||||
run: pytest -n logical $PATHS --junitxml=test-results.xml
|
||||
|
||||
- name: Upload test results
|
||||
if: ${{ !cancelled() }}
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: api-test-results-${{ matrix.name }}
|
||||
path: test-results.xml
|
||||
retention-days: 30
|
||||
|
||||
# Do the API and the frontend's test fixtures still agree?
|
||||
#
|
||||
# `api-tests` runs these too, as part of the whole suite. This job exists for the signal:
|
||||
# fixture drift is silent by nature -- the frontend suite passes against a body the API stopped
|
||||
# sending -- so it is worth a check whose name says what broke, failing in under a minute rather
|
||||
# than somewhere inside seventeen hundred results. It needs no ffmpeg or catdoc.
|
||||
api-contract-tests:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.13'
|
||||
cache: 'pip'
|
||||
cache-dependency-path: requirements.lock
|
||||
|
||||
- name: Install dependencies
|
||||
run: scripts/install_python_requirements.sh pip requirements.txt
|
||||
|
||||
- name: Fixtures match the OpenAPI spec, and the spec matches the handlers
|
||||
run: pytest wrolpi/test/test_api_fixtures.py -v
|
||||
|
||||
# The migrations apply to an empty database, the models match them, and the API starts.
|
||||
api-migrations-and-start:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.13'
|
||||
cache: 'pip'
|
||||
cache-dependency-path: requirements.lock
|
||||
|
||||
- name: Install dependencies
|
||||
run: scripts/install_python_requirements.sh pip requirements.txt
|
||||
|
||||
- name: Run Alembic migrations
|
||||
env:
|
||||
MEDIA_DIRECTORY: ${{ runner.temp }}/wrolpi-media
|
||||
run: |
|
||||
mkdir -p "$MEDIA_DIRECTORY/config"
|
||||
python ./main.py db upgrade
|
||||
|
||||
- name: Check for missing migrations
|
||||
env:
|
||||
MEDIA_DIRECTORY: ${{ runner.temp }}/wrolpi-media
|
||||
run: python ./main.py db check
|
||||
|
||||
- name: Start Sanic API
|
||||
run: |
|
||||
sudo mkdir -p /media/wrolpi
|
||||
nohup sanic main:api_app -H 0.0.0.0 -p 8081 > sanic.log 2>&1 &
|
||||
for i in $(seq 1 60); do
|
||||
if curl -sf http://localhost:8081/api/echo; then
|
||||
echo
|
||||
echo "Sanic API is up"
|
||||
exit 0
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
echo "Sanic API failed to start"
|
||||
cat sanic.log
|
||||
exit 1
|
||||
|
||||
- name: Stop Sanic API
|
||||
if: ${{ always() }}
|
||||
run: pkill -f sanic || true
|
||||
12
.github/workflows/controller-tests.yml
vendored
12
.github/workflows/controller-tests.yml
vendored
|
|
@ -1,13 +1,10 @@
|
|||
name: Controller Tests
|
||||
|
||||
# `pull_request` is unfiltered for the same reason as jest-tests.yml: `branches: [master]` meant
|
||||
# this never ran on a pull request into any other branch. It is why Controller Tests is absent
|
||||
# from the checks on the pull request that moved this job to Python 3.13 -- the change to this
|
||||
# file could not be verified by the run that contained it.
|
||||
on:
|
||||
push:
|
||||
branches: [master, feature/*]
|
||||
pull_request:
|
||||
branches: [master]
|
||||
|
||||
jobs:
|
||||
controller-tests:
|
||||
|
|
@ -24,13 +21,12 @@ jobs:
|
|||
- name: Setup Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
# Trixie ships 3.13, and docker/controller/Dockerfile is python:3.13-slim-trixie.
|
||||
python-version: '3.13'
|
||||
python-version: '3.11'
|
||||
cache: 'pip'
|
||||
cache-dependency-path: controller/requirements.lock
|
||||
cache-dependency-path: controller/requirements.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: ../scripts/install_python_requirements.sh pip requirements.txt
|
||||
run: pip install -r requirements.txt
|
||||
|
||||
- name: Run pytest
|
||||
run: python -m pytest test/ -v --tb=short --confcutdir=$(pwd)
|
||||
|
|
|
|||
121
.github/workflows/cypress.yml
vendored
121
.github/workflows/cypress.yml
vendored
|
|
@ -1,121 +0,0 @@
|
|||
name: Cypress Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [master, feature/*]
|
||||
pull_request:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
# Component specs live under `src/`, so they need `cypress run --component`; the e2e job's
|
||||
# `cypress run` will not match them. Cypress starts its own dev server, so no `npm start`.
|
||||
cypress-component-tests:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
defaults:
|
||||
run:
|
||||
working-directory: app
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20.19'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: app/package-lock.json
|
||||
|
||||
# The Cypress binary lives outside node_modules, and setup-node only caches ~/.npm. Key it
|
||||
# on the lockfile so a Cypress bump fetches the matching binary.
|
||||
- name: Cache Cypress binary
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/Cypress
|
||||
key: cypress-${{ runner.os }}-${{ hashFiles('app/package-lock.json') }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm install
|
||||
|
||||
# A no-op when the cached binary matches.
|
||||
- name: Install Cypress binary
|
||||
run: npx cypress install
|
||||
|
||||
- name: Run Cypress component tests
|
||||
run: npx cypress run --component
|
||||
|
||||
- name: Upload screenshots
|
||||
if: ${{ failure() }}
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: cypress-component-screenshots
|
||||
path: app/cypress/screenshots
|
||||
retention-days: 14
|
||||
|
||||
# Waiting for `npm start` to serve the app also checks that the dev server starts.
|
||||
cypress-e2e-tests:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
defaults:
|
||||
run:
|
||||
working-directory: app
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20.19'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: app/package-lock.json
|
||||
|
||||
- name: Cache Cypress binary
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/Cypress
|
||||
key: cypress-${{ runner.os }}-${{ hashFiles('app/package-lock.json') }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm install
|
||||
|
||||
- name: Install Cypress binary
|
||||
run: npx cypress install
|
||||
|
||||
# GitHub Actions sets `CI=true`, which makes cypress.config.js use http://localhost:3000 as
|
||||
# the base URL.
|
||||
- name: Start React app
|
||||
env:
|
||||
DISABLE_ESLINT_PLUGIN: 'true'
|
||||
BROWSER: none
|
||||
run: |
|
||||
nohup npm start > react.log 2>&1 &
|
||||
for i in $(seq 1 90); do
|
||||
if curl -sf http://localhost:3000/manifest.json > /dev/null; then
|
||||
echo "React app is ready"
|
||||
exit 0
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
echo "React app failed to start"
|
||||
cat react.log
|
||||
exit 1
|
||||
|
||||
- name: Run Cypress e2e tests
|
||||
run: npx cypress run
|
||||
|
||||
- name: Upload videos and screenshots
|
||||
if: ${{ failure() }}
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: cypress-e2e-media
|
||||
path: |
|
||||
app/cypress/videos
|
||||
app/cypress/screenshots
|
||||
retention-days: 14
|
||||
if-no-files-found: ignore
|
||||
34
.github/workflows/dead-code.yml
vendored
34
.github/workflows/dead-code.yml
vendored
|
|
@ -1,34 +0,0 @@
|
|||
name: Dead Code
|
||||
|
||||
# Same triggers as backend.yml: `pull_request` is unfiltered so pull requests into feature branches
|
||||
# are checked too, not only those into master.
|
||||
on:
|
||||
push:
|
||||
branches: [master, feature/*]
|
||||
pull_request:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
# Fails when vulture finds dead code that is not in scripts/vulture_baseline.txt. vulture only
|
||||
# parses the source, so WROLPi's requirements are not installed.
|
||||
vulture:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
# Trixie ships 3.13.
|
||||
python-version: '3.13'
|
||||
|
||||
# Pinned: a new vulture release can report findings the baseline does not know about.
|
||||
- name: Install vulture
|
||||
run: pip install vulture==2.16
|
||||
|
||||
- name: Check for new dead code
|
||||
run: python scripts/check_dead_code.py
|
||||
12
.github/workflows/jest-tests.yml
vendored
12
.github/workflows/jest-tests.yml
vendored
|
|
@ -1,16 +1,10 @@
|
|||
name: Jest Tests
|
||||
|
||||
# `pull_request` is deliberately unfiltered. It was `branches: [master]`, which meant a pull
|
||||
# request into anything else ran no jest and no webpack build -- so the entire Semantic UI to
|
||||
# Mantine migration, seventy-five files of it, was reviewed and merged across nine pull requests
|
||||
# into `feature/custom-theme` without either ever running on a single one of them. The build
|
||||
# step matters most of all here: jest and tsc both pass on a named import that does not exist,
|
||||
# and only webpack rejects it. The suite did run on the branch afterwards, which is the wrong
|
||||
# side of the merge to find out.
|
||||
on:
|
||||
push:
|
||||
branches: [master, feature/*]
|
||||
pull_request:
|
||||
branches: [master]
|
||||
|
||||
jobs:
|
||||
jest-tests:
|
||||
|
|
@ -27,12 +21,12 @@ jobs:
|
|||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20.19'
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: app/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm install
|
||||
run: npm install --legacy-peer-deps
|
||||
|
||||
- name: Run Jest tests
|
||||
run: CI=true npm test -- --watchAll=false --coverage --coverageReporters=text --coverageReporters=lcov
|
||||
|
|
|
|||
7
.gitignore
vendored
7
.gitignore
vendored
|
|
@ -118,7 +118,6 @@ test/config
|
|||
|
||||
modules/node_modules/
|
||||
docker/archive/node_modules/
|
||||
npm-tools/node_modules/
|
||||
docker/archive/package-lock.json
|
||||
|
||||
# open street map files
|
||||
|
|
@ -130,7 +129,6 @@ docker-compose.override.yml
|
|||
|
||||
# test directory is used as media directory, we don't want to commit what a user downloads.
|
||||
/test
|
||||
# Legacy local Postgres data directory from pre-SQLite docker-compose (safe to delete).
|
||||
pg_data
|
||||
|
||||
# Directories used to build images
|
||||
|
|
@ -149,8 +147,3 @@ app/cypress/videos
|
|||
|
||||
# Generated by release/release.sh before upload
|
||||
release/latest.json
|
||||
perf_results/
|
||||
scripts/api_perf_hosts.json
|
||||
|
||||
# Tile cache for scripts/build_solar_climatology.py
|
||||
/scripts/.solar_climatology_cache/
|
||||
|
|
|
|||
17
.gitpod.yml
Normal file
17
.gitpod.yml
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
# This configuration file was automatically generated by Gitpod.
|
||||
# Please adjust to your needs (see https://www.gitpod.io/docs/introduction/learn-gitpod/gitpod-yaml)
|
||||
# and commit this file to your remote git repository to share the goodness with others.
|
||||
|
||||
# Learn more from ready-to-use templates: https://www.gitpod.io/docs/introduction/getting-started/quickstart
|
||||
|
||||
tasks:
|
||||
- name: Start App
|
||||
# init runs once for each commit to the default branch
|
||||
init: |
|
||||
docker-compose build --parallel
|
||||
docker volume create --name=openstreetmap-data
|
||||
docker volume create --name=openstreetmap-rendered-tiles
|
||||
docker-compose up -d db
|
||||
docker-compose run --rm api db upgrade
|
||||
# command runs each time a user starts their workspace
|
||||
command: docker-compose up
|
||||
67
INSTALL.md
67
INSTALL.md
|
|
@ -3,10 +3,8 @@
|
|||
There are several ways to run WROLPi. Pick the one that matches your hardware:
|
||||
|
||||
* [WROLPi Portable (Live USB)](#wrolpi-portable-live-usb) — boot a full WROLPi from a USB stick on any x86 PC or laptop, no installation required.
|
||||
* [Debian 13 Install](#debian-13-install) — install WROLPi onto an x86 PC or laptop.
|
||||
* [Debian 12 Install](#debian-12-install) — install WROLPi onto an x86 PC or laptop.
|
||||
* [Raspberry Pi Install](#raspberry-pi-install) — install WROLPi onto a Raspberry Pi with an external drive.
|
||||
|
||||
After installing, follow [First Boot](#first-boot) to set up your drive.
|
||||
* [Docker](docker/README.md) — run the WROLPi containers on an existing Linux host (best for trying it out or development).
|
||||
|
||||
See [UPGRADE.md](UPGRADE.md) for upgrading an existing WROLPi.
|
||||
|
|
@ -38,7 +36,6 @@ Steps:
|
|||
minute or two; progress is shown on screen.
|
||||
5. Once the desktop loads, browse to https://wrolpi.local or the IP address of
|
||||
your WROLPi. Wi-Fi hotspot and all other features work as usual.
|
||||
6. To use a terminal remotely: `ssh user@wrolpi.local`, password `live`.
|
||||
|
||||
Notes:
|
||||
|
||||
|
|
@ -55,50 +52,30 @@ Notes:
|
|||
* **Upgrading.** See [Upgrading a WROLPi Portable USB](UPGRADE.md#upgrading-a-wrolpi-portable-usb)
|
||||
to move to a newer ISO without losing your library.
|
||||
|
||||
## Debian 13 Install
|
||||
## Debian 12 Install
|
||||
|
||||
Install WROLPi onto the internal disk of an x86 PC or laptop. This uses the same
|
||||
`WROLPi-v*-amd64.iso` as WROLPi Portable.
|
||||
Steps necessary to initialize your WROLPi after installing the Debian image from wrolpi.org
|
||||
|
||||
1. Download the latest `WROLPi-v*-amd64.iso` from [wrolpi.org](https://wrolpi.org) and flash it to a USB drive
|
||||
(see [WROLPi Portable](#wrolpi-portable-live-usb) step 2).
|
||||
2. Boot the PC from the USB drive. At the boot menu, choose **Install** or **Graphical Install**.
|
||||
3. Install Debian 13 as you would like.
|
||||
1. It is recommended to use the hostname **wrolpi**.
|
||||
2. WROLPi is installed along with Debian; there is nothing extra to select.
|
||||
4. Unplug the USB drive after the installation has completed, and reboot.
|
||||
5. Continue with [First Boot](#first-boot).
|
||||
1. Download and copy a pre-built Debian image from https://wrolpi.org onto a USB thumb-drive (USB 2 recommended).
|
||||
2. Insert the thumb-drive into the laptop, boot to the thumb-drive.
|
||||
1. Select "Start Installer".
|
||||
2. Install Debian 12 as you would like.
|
||||
1. It is recommended to use the hostname **wrolpi**.
|
||||
2. (WROLPi will be installed during the installation without your intervention.)
|
||||
3. Unplug the thumb-drive after the installation has completed.
|
||||
4. Login as the user _you_ created during installation.
|
||||
5. Initialize the WROLPi databases using the repair script: `/opt/wrolpi/repair.sh`
|
||||
6. Reboot: `reboot`
|
||||
7. Browse to https://wrolpi.local or the IP address of your WROLPi!
|
||||
|
||||
## Raspberry Pi Install
|
||||
|
||||
Install WROLPi onto a Raspberry Pi. An external drive is recommended for your library.
|
||||
Steps necessary to initialize your WROLPi after installing the Raspberry Pi image from wrolpi.org
|
||||
|
||||
1. Download the latest `WROLPi-v*-aarch64-desktop.img.xz` from [wrolpi.org](https://wrolpi.org).
|
||||
2. Flash it to an SD card using Raspberry Pi Imager.
|
||||
3. Plug in your external drive, insert the SD card, and boot the Raspberry Pi.
|
||||
4. On the first boot, Raspberry Pi OS asks you to create your own user.
|
||||
5. Continue with [First Boot](#first-boot).
|
||||
|
||||
## First Boot
|
||||
|
||||
These steps are the same for every install.
|
||||
|
||||
1. Join the WROLPi hotspot (network **WROLPi**, password **wrolpi hotspot**; it starts on every boot), or connect
|
||||
your WROLPi to your network, then browse to https://wrolpi.local (or the IP address of your WROLPi).
|
||||
2. **Choose your drive.**
|
||||
* **Raspberry Pi and Debian:** until a drive is set up, you will see the **Controller** with a *Welcome to WROLPi*
|
||||
wizard (also at http://wrolpi.local). Select the drive which will hold your library; WROLPi mounts it
|
||||
at `/media/wrolpi`, adds it to `/etc/fstab`, and runs the repair script for you. If the drive already holds a
|
||||
WROLPi library (from another WROLPi, or a backup), its configuration is used. No external drive? Choose **Run
|
||||
repair without external drive** to keep your library on the internal disk or SD card.
|
||||
* **WROLPi Portable:** nothing to do; your library lives in the persistence partition on the USB drive.
|
||||
3. **Trust the certificate.** Your browser will warn about the HTTPS certificate because it was made by your WROLPi,
|
||||
not by a public authority. Download https://wrolpi.local/ca.crt and trust it on each device you use; see
|
||||
*Help > Certificates* on your WROLPi for per-device instructions.
|
||||
4. **Wait for the first refresh.** WROLPi refreshes all your files when it first starts so it can find anything already
|
||||
on the drive. Your library looks empty, and Download and Upload are disabled, until the refresh completes.
|
||||
5. Start adding content: download a video channel, archive a web page, or add a Zim (Wikipedia) file. The *Help* page
|
||||
on your WROLPi explains each module.
|
||||
|
||||
You do not need to edit `/etc/fstab` or run `repair.sh` by hand. `sudo /opt/wrolpi/repair.sh` is still available if
|
||||
your WROLPi ever needs repairing.
|
||||
1. Download and copy a pre-built image from https://wrolpi.org onto an SD card.
|
||||
2. Boot the Raspberry Pi, login with username pi and password wrolpi.
|
||||
3. Modify fstab to mount your external drive to /media/wrolpi (modify this command to match your system).
|
||||
* `echo '/dev/sda1 /media/wrolpi auto defaults,nofail 0 0' | sudo tee -a /etc/fstab`
|
||||
4. Initialize the WROLPi databases using the repair script: `sudo /opt/wrolpi/repair.sh`
|
||||
5. Reboot `sudo reboot`
|
||||
6. Join the Hotspot or browse to https://wrolpi.local or the IP address of your WROLPi!
|
||||
|
|
|
|||
17
README.md
17
README.md
|
|
@ -1,8 +1,9 @@
|
|||
# WROLPi
|
||||
|
||||
[](https://github.com/lrnselfreliance/wrolpi/actions/workflows/backend.yml?query=branch%3Amaster)
|
||||
[](https://app.circleci.com/pipelines/github/lrnselfreliance/wrolpi?branch=release&filter=all)
|
||||
[](https://github.com/lrnselfreliance/wrolpi/blob/master/LICENSE)
|
||||
[](https://discord.gg/HrwFk7nqA2)
|
||||
[](https://gitpod.io/#https://github.com/lrnselfreliance/wrolpi)
|
||||
|
||||
**Create your own off-grid library.**
|
||||
|
||||
|
|
@ -39,8 +40,8 @@ network so that any user with a laptop/tablet/phone can connect and use the libr
|
|||
- [x] Universal search
|
||||
- [x] Food Inventory management
|
||||
- [x] One-Time pad generator, encrypter/decrypter
|
||||
- [x] Sync to a second WROLPi, and backup to a second drive
|
||||
- [x] Food storage calculator
|
||||
- [ ] Synchronizer/duplicator
|
||||
- [ ] Food storage calculator
|
||||
|
||||
## Module features matrix
|
||||
|
||||
|
|
@ -78,11 +79,13 @@ You can try out WROLPi by running the docker containers.
|
|||
6. Create volumes.
|
||||
* `docker volume create --name=openstreetmap-data`
|
||||
* `docker volume create --name=openstreetmap-rendered-tiles`
|
||||
7. Initialize the database (SQLite in the media directory).
|
||||
7. Start the database.
|
||||
* `docker-compose up -d db`
|
||||
8. Initialize the database.
|
||||
* `docker-compose run --rm api db upgrade`
|
||||
8. Start the docker containers.
|
||||
9. Start the docker containers.
|
||||
* `docker-compose up`
|
||||
9. Browse to WROLPi.
|
||||
10. Browse to WROLPi.
|
||||
* https://0.0.0.0:8443
|
||||
|
||||
More Docker documentation is available in [docker/README.md](docker/README.md)
|
||||
|
|
@ -92,7 +95,7 @@ More Docker documentation is available in [docker/README.md](docker/README.md)
|
|||
Full installation instructions are in [INSTALL.md](INSTALL.md). Pick the option that matches your hardware:
|
||||
|
||||
* **[WROLPi Portable (Live USB)](INSTALL.md#wrolpi-portable-live-usb)** — boot a complete WROLPi from a USB stick on any x86 PC or laptop. Nothing is installed to the computer; the first boot creates a persistence partition on the USB so your library, database, and configuration survive reboots.
|
||||
* **[Debian 13](INSTALL.md#debian-13-install)** — install WROLPi onto an x86 PC or laptop.
|
||||
* **[Debian 12](INSTALL.md#debian-12-install)** — install WROLPi onto an x86 PC or laptop.
|
||||
* **[Raspberry Pi](INSTALL.md#raspberry-pi-install)** — install WROLPi onto a Raspberry Pi with an external drive.
|
||||
* **[Docker](docker/README.md)** — run the WROLPi containers on an existing Linux host.
|
||||
|
||||
|
|
|
|||
10
UPGRADE.md
10
UPGRADE.md
|
|
@ -3,7 +3,7 @@
|
|||
# Table of Contents
|
||||
|
||||
* [Upgrading Docker containers](#upgrading-docker-containers)
|
||||
* [Upgrading Raspberry Pi or Debian Installation](#upgrading-raspberry-pi-or-debian-installation)
|
||||
* [Upgrading Raspberry Pi or Debian 12 Installation](#upgrading-raspberry-pi-or-debian-12-installation)
|
||||
* [Upgrading a WROLPi Portable USB](#upgrading-a-wrolpi-portable-usb)
|
||||
|
||||
## Upgrading Docker containers
|
||||
|
|
@ -14,8 +14,6 @@
|
|||
* `git pull origin master --ff`
|
||||
3. Build all docker containers
|
||||
* `docker-compose build --parallel`
|
||||
* Rebuild the VPN container without its cache, so it gets the latest qBittorrent (it faces the Internet
|
||||
through the VPN): `docker compose build --pull --no-cache vpn`
|
||||
4. Create the map volumes
|
||||
* `docker volume create --name=openstreetmap-data`
|
||||
* `docker volume create --name=openstreetmap-rendered-tiles`
|
||||
|
|
@ -26,15 +24,11 @@
|
|||
7. Start all docker containers
|
||||
* `docker-compose up -d`
|
||||
|
||||
## Upgrading Raspberry Pi or Debian Installation
|
||||
|
||||
A Debian 12 (bookworm) WROLPi stays on the final version for Debian 12; reinstall on Debian 13 to get newer versions.
|
||||
## Upgrading Raspberry Pi or Debian 12 Installation
|
||||
|
||||
1. Run the upgrade script
|
||||
* `sudo /bin/bash /opt/wrolpi/upgrade.sh`
|
||||
* (If the upgrade script does not exist, run the installation script: `sudo /bin/bash /opt/wrolpi/install.sh`)
|
||||
* The upgrade refuses to move back to an older commit of the branch you are on. To downgrade on purpose,
|
||||
run `sudo /bin/bash /opt/wrolpi/upgrade.sh -d`.
|
||||
|
||||
## Upgrading a WROLPi Portable USB
|
||||
|
||||
|
|
|
|||
|
|
@ -35,17 +35,11 @@ prepend_sys_path = .
|
|||
# directories, initial revisions must be specified with --version-path
|
||||
# version_locations = %(here)s/bar %(here)s/bat alembic/versions
|
||||
|
||||
# Revision ids ARE dates (see process_revision_directives in env.py), so filenames self-sort
|
||||
# chronologically and the alembic_version table says when a database's schema was created.
|
||||
file_template = %%(rev)s_%%(slug)s
|
||||
|
||||
# the output encoding used when revision files
|
||||
# are written from script.py.mako
|
||||
# output_encoding = utf-8
|
||||
|
||||
# Placeholder: env.py derives the real URL from the media directory (see wrolpi.db.get_db_uri);
|
||||
# `main.py db ...` overrides it explicitly.
|
||||
sqlalchemy.url = sqlite:///CHANGEME
|
||||
sqlalchemy.url = postgresql://postgres:wrolpi@localhost:5432/wrolpi
|
||||
|
||||
|
||||
[post_write_hooks]
|
||||
|
|
|
|||
|
|
@ -1,15 +1,17 @@
|
|||
import os
|
||||
from logging.config import fileConfig
|
||||
|
||||
from alembic import context
|
||||
from sqlalchemy import engine_from_config
|
||||
from sqlalchemy import pool
|
||||
|
||||
# this is the Alembic Config object, which provides
|
||||
# access to the values within the .ini file in use.
|
||||
config = context.config
|
||||
|
||||
# Configure logging only for the alembic command line. WROLPi also migrates in-process at startup
|
||||
# (db_bootstrap), where fileConfig would replace the API's handlers and disable its existing loggers.
|
||||
if config.cmd_opts is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
|
|
@ -24,41 +26,13 @@ from wrolpi.collections.models import Collection, CollectionItem # noqa: F401
|
|||
from modules.videos.models import Video, Channel # noqa: F401
|
||||
from modules.archive.models import Archive # noqa: F401
|
||||
from modules.zim.models import Zim, TagZimEntry, ZimSubscription # noqa: F401
|
||||
from modules.repos.models import Repository # noqa: F401
|
||||
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def get_url() -> str:
|
||||
"""The database URL: from the ini/CLI when overridden, otherwise derived from the media directory."""
|
||||
url = config.get_main_option('sqlalchemy.url')
|
||||
if url and not url.startswith('sqlite:///CHANGEME'):
|
||||
return url
|
||||
from wrolpi.db import get_db_uri
|
||||
return get_db_uri()
|
||||
|
||||
|
||||
def include_object(object_, name, type_, reflected, compare_to):
|
||||
"""Exclude tables Alembic must not manage from autogenerate/check.
|
||||
|
||||
The FTS5 virtual tables and their shadow tables (created by wrolpi.schema_ddl /
|
||||
wrolpi.fts) plus SQLite internals would otherwise be proposed for DROP."""
|
||||
if type_ == 'table':
|
||||
from wrolpi.fts import FTS_TABLE_PREFIXES
|
||||
if name == 'sqlite_sequence' or any(name.startswith(prefix) for prefix in FTS_TABLE_PREFIXES):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def process_revision_directives(context_, revision, directives):
|
||||
"""New revisions get date ids (e.g. 2026_07_10_1350) instead of random hashes.
|
||||
|
||||
Filenames therefore self-sort chronologically, and the `alembic_version` value in a
|
||||
database says when its schema was created. Underscores, not dashes: alembic forbids
|
||||
`-` in revision identifiers (it is reserved for relative-revision syntax like `head-1`)."""
|
||||
from datetime import datetime, timezone
|
||||
script = directives[0]
|
||||
script.rev_id = datetime.now(timezone.utc).strftime('%Y_%m_%d_%H%M')
|
||||
# other values from the config, defined by the needs of env.py,
|
||||
# can be acquired:
|
||||
# my_important_option = config.get_main_option("my_important_option")
|
||||
# ... etc.
|
||||
|
||||
|
||||
def run_migrations_offline():
|
||||
|
|
@ -73,14 +47,12 @@ def run_migrations_offline():
|
|||
script output.
|
||||
|
||||
"""
|
||||
url = config.get_main_option("sqlalchemy.url")
|
||||
context.configure(
|
||||
url=get_url(),
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
render_as_batch=True,
|
||||
include_object=include_object,
|
||||
process_revision_directives=process_revision_directives,
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
|
|
@ -94,21 +66,18 @@ def run_migrations_online():
|
|||
and associate a connection with the context.
|
||||
|
||||
"""
|
||||
from wrolpi.db import create_wrolpi_engine
|
||||
connectable = engine_from_config(
|
||||
config.get_section(config.config_ini_section),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
connectable = create_wrolpi_engine(get_url())
|
||||
|
||||
# Autocommit: each migration statement is its own transaction. A migration may call WROLPi
|
||||
# functions which write on their own connection; a migration connection holding an open read
|
||||
# transaction could not then upgrade to a writer ("database is locked").
|
||||
with connectable.connect().execution_options(isolation_level='AUTOCOMMIT') as connection:
|
||||
with connectable.connect() as connection:
|
||||
if not os.environ.get('DOCKER', '').lower().startswith('t'):
|
||||
# Set role when not in a docker container
|
||||
connection.execute("SET ROLE 'wrolpi'")
|
||||
context.configure(
|
||||
connection=connection,
|
||||
target_metadata=target_metadata,
|
||||
# SQLite's limited ALTER TABLE requires batch mode for most column changes.
|
||||
render_as_batch=True,
|
||||
include_object=include_object,
|
||||
process_revision_directives=process_revision_directives,
|
||||
connection=connection, target_metadata=target_metadata
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
|
|
|
|||
|
|
@ -5,8 +5,9 @@ Revises: ${down_revision | comma,n}
|
|||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
import os
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.orm import Session
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
|
|
@ -15,10 +16,18 @@ down_revision = ${repr(down_revision)}
|
|||
branch_labels = ${repr(branch_labels)}
|
||||
depends_on = ${repr(depends_on)}
|
||||
|
||||
DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
if not DOCKERIZED:
|
||||
session.execute('ALTER TABLE public.TABLE_NAME OWNER TO wrolpi')
|
||||
|
||||
|
||||
def downgrade():
|
||||
${downgrades if downgrades else "pass"}
|
||||
|
|
|
|||
33
alembic/versions/00f11f309c53_filegroup_censored.py
Normal file
33
alembic/versions/00f11f309c53_filegroup_censored.py
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
"""FileGroup.censored
|
||||
|
||||
Revision ID: 00f11f309c53
|
||||
Revises: 1c041aeee0fc
|
||||
Create Date: 2024-06-17 14:02:09.881477
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '00f11f309c53'
|
||||
down_revision = '1c041aeee0fc'
|
||||
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)
|
||||
|
||||
session.execute('ALTER TABLE file_group ADD COLUMN censored BOOLEAN DEFAULT FALSE')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('ALTER TABLE file_group DROP COLUMN IF EXISTS censored')
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
"""Video textsearch coalesce fix.
|
||||
|
||||
Revision ID: 0400005fe2dc
|
||||
Revises: 53f6780aa599
|
||||
Create Date: 2022-01-04 11:00:21.776124
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '0400005fe2dc'
|
||||
down_revision = '53f6780aa599'
|
||||
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)
|
||||
|
||||
# Replace the textsearch and index. The old textsearch failed if one of the columns was null.
|
||||
session.execute('DROP INDEX IF EXISTS video_textsearch_idx')
|
||||
session.execute('ALTER TABLE video DROP COLUMN IF EXISTS textsearch')
|
||||
session.execute('''
|
||||
ALTER TABLE video
|
||||
ADD COLUMN textsearch tsvector
|
||||
GENERATED ALWAYS AS (
|
||||
setweight(to_tsvector('english'::regconfig, COALESCE(title, '')), 'A') ||
|
||||
setweight(to_tsvector('english'::regconfig, COALESCE(caption, '')), 'D')
|
||||
) STORED
|
||||
''')
|
||||
session.execute('CREATE INDEX video_textsearch_idx ON video USING GIN(textsearch)')
|
||||
|
||||
|
||||
def downgrade():
|
||||
# The upgrade is backwards compatible.
|
||||
pass
|
||||
70
alembic/versions/053f17f07c4e_init_inventory_tables.py
Normal file
70
alembic/versions/053f17f07c4e_init_inventory_tables.py
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
"""Init inventory tables.
|
||||
|
||||
Revision ID: 053f17f07c4e
|
||||
Revises: f0d0086a73d1
|
||||
Create Date: 2021-09-20 16:21:00.322598
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
revision = '053f17f07c4e'
|
||||
down_revision = 'f0d0086a73d1'
|
||||
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)
|
||||
|
||||
session.execute('''
|
||||
CREATE TABLE inventories_version (
|
||||
version SERIAL PRIMARY KEY NOT NULL
|
||||
)
|
||||
''')
|
||||
|
||||
session.execute('''
|
||||
CREATE TABLE public.inventory (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
viewed_at TIMESTAMP WITHOUT TIME ZONE,
|
||||
created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
deleted_at TIMESTAMP WITHOUT TIME ZONE
|
||||
)''')
|
||||
|
||||
session.execute('''
|
||||
CREATE TABLE public.item (
|
||||
id SERIAL PRIMARY KEY,
|
||||
inventory_id INTEGER REFERENCES inventory(id) ON DELETE CASCADE,
|
||||
brand TEXT,
|
||||
name TEXT,
|
||||
count DECIMAL,
|
||||
item_size DECIMAL,
|
||||
unit TEXT,
|
||||
serving INTEGER,
|
||||
category TEXT,
|
||||
subcategory TEXT,
|
||||
expiration_date DATE,
|
||||
purchase_date DATE,
|
||||
created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
deleted_at TIMESTAMP WITHOUT TIME ZONE
|
||||
)''')
|
||||
|
||||
if not DOCKERIZED:
|
||||
session.execute('ALTER TABLE public.inventories_version OWNER TO wrolpi')
|
||||
session.execute('ALTER TABLE public.inventory OWNER TO wrolpi')
|
||||
session.execute('ALTER TABLE public.item OWNER TO wrolpi')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('DROP TABLE IF EXISTS public.inventories_version''')
|
||||
session.execute('DROP TABLE IF EXISTS public.item''')
|
||||
session.execute('DROP TABLE IF EXISTS public.inventory''')
|
||||
33
alembic/versions/13542a230c78_archive_url_index.py
Normal file
33
alembic/versions/13542a230c78_archive_url_index.py
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
"""Archive url index.
|
||||
|
||||
Revision ID: 13542a230c78
|
||||
Revises: c72d305cf11e
|
||||
Create Date: 2022-11-02 15:19:42.408462
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '13542a230c78'
|
||||
down_revision = 'c72d305cf11e'
|
||||
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)
|
||||
|
||||
session.execute('CREATE INDEX IF NOT EXISTS archive_url_idx ON archive(url)')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('DROP INDEX IF EXISTS archive_url_idx')
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
"""Lower FileGroup.primary_path
|
||||
|
||||
Revision ID: 158973fda20f
|
||||
Revises: 69e9754d1a63
|
||||
Create Date: 2025-08-16 10:54:58.874094
|
||||
|
||||
"""
|
||||
import os
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '158973fda20f'
|
||||
down_revision = '69e9754d1a63'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.execute('CREATE INDEX file_group_primary_path_lower_idx ON file_group (LOWER(primary_path))')
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.execute('DROP INDEX IF EXISTS file_group_primary_path_lower_idx')
|
||||
35
alembic/versions/170d1be52bc7_download_destination.py
Normal file
35
alembic/versions/170d1be52bc7_download_destination.py
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
"""Create Download.destination column.
|
||||
|
||||
Revision ID: 170d1be52bc7
|
||||
Revises: 9ec4c765ef8d
|
||||
Create Date: 2024-11-02 11:16:15.297850
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '170d1be52bc7'
|
||||
down_revision = '9ec4c765ef8d'
|
||||
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)
|
||||
|
||||
session.execute('ALTER TABLE download ADD COLUMN IF NOT EXISTS destination TEXT')
|
||||
session.execute('ALTER TABLE download ADD COLUMN IF NOT EXISTS tag_names TEXT[]')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('ALTER TABLE download DROP COLUMN IF EXISTS tag_names')
|
||||
session.execute('ALTER TABLE download DROP COLUMN IF EXISTS destination')
|
||||
51
alembic/versions/184329ed5137_downloader.py
Normal file
51
alembic/versions/184329ed5137_downloader.py
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
"""Downloader
|
||||
|
||||
Revision ID: 184329ed5137
|
||||
Revises: 1870bec7c81e
|
||||
Create Date: 2021-11-17 19:13:58.305140
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '184329ed5137'
|
||||
down_revision = '1870bec7c81e'
|
||||
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)
|
||||
|
||||
session.execute('''
|
||||
CREATE TABLE download (
|
||||
id SERIAL PRIMARY KEY,
|
||||
url TEXT NOT NULL,
|
||||
status TEXT DEFAULT 'new',
|
||||
next_download TIMESTAMPTZ,
|
||||
last_successful_download TIMESTAMPTZ,
|
||||
frequency INT,
|
||||
attempts INT DEFAULT 0
|
||||
)
|
||||
''')
|
||||
session.execute('ALTER TABLE video ADD COLUMN url TEXT')
|
||||
session.execute('ALTER TABLE channel ADD COLUMN source_id TEXT')
|
||||
session.execute('CREATE INDEX channel_source_id ON channel (source_id)')
|
||||
|
||||
if not DOCKERIZED:
|
||||
session.execute('ALTER TABLE public.download OWNER TO wrolpi')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
session.execute('DROP TABLE IF EXISTS download')
|
||||
session.execute('DROP INDEX IF EXISTS channel_source_id')
|
||||
session.execute('ALTER TABLE channel DROP COLUMN IF EXISTS source_id')
|
||||
session.execute('ALTER TABLE video DROP COLUMN IF EXISTS url')
|
||||
70
alembic/versions/1870bec7c81e_initialize_archive_tables.py
Normal file
70
alembic/versions/1870bec7c81e_initialize_archive_tables.py
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
"""Initialize archive tables.
|
||||
|
||||
Revision ID: 1870bec7c81e
|
||||
Revises: 053f17f07c4e
|
||||
Create Date: 2021-09-22 18:31:15.056697
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '1870bec7c81e'
|
||||
down_revision = '053f17f07c4e'
|
||||
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)
|
||||
|
||||
session.execute('''
|
||||
CREATE TABLE domains (
|
||||
id SERIAL PRIMARY KEY,
|
||||
domain TEXT NOT NULL UNIQUE,
|
||||
directory TEXT NOT NULL UNIQUE
|
||||
)''')
|
||||
|
||||
session.execute('''
|
||||
CREATE TABLE url (
|
||||
id SERIAL PRIMARY KEY,
|
||||
domain_id INTEGER REFERENCES domains(id) NOT NULL,
|
||||
url TEXT NOT NULL UNIQUE,
|
||||
latest_datetime TIMESTAMPTZ
|
||||
)''')
|
||||
|
||||
session.execute('''
|
||||
CREATE TABLE archive (
|
||||
id SERIAL PRIMARY KEY,
|
||||
url_id INTEGER REFERENCES url(id) ON DELETE CASCADE NOT NULL,
|
||||
domain_id INTEGER REFERENCES domains(id) ON DELETE CASCADE NOT NULL,
|
||||
singlefile_path TEXT,
|
||||
readability_path TEXT,
|
||||
readability_txt_path TEXT,
|
||||
readability_json_path TEXT,
|
||||
screenshot_path TEXT,
|
||||
title TEXT,
|
||||
archive_datetime TIMESTAMPTZ,
|
||||
status TEXT
|
||||
)''')
|
||||
|
||||
session.execute('ALTER TABLE url ADD COLUMN latest_id INTEGER REFERENCES archive(id) ON DELETE CASCADE')
|
||||
|
||||
if not DOCKERIZED:
|
||||
session.execute('ALTER TABLE public.domains OWNER TO wrolpi')
|
||||
session.execute('ALTER TABLE public.url OWNER TO wrolpi')
|
||||
session.execute('ALTER TABLE public.archive OWNER TO wrolpi')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('DROP TABLE IF EXISTS domains CASCADE')
|
||||
session.execute('DROP TABLE IF EXISTS url CASCADE')
|
||||
session.execute('DROP TABLE IF EXISTS archive CASCADE')
|
||||
33
alembic/versions/1a70196c05bb_download_location.py
Normal file
33
alembic/versions/1a70196c05bb_download_location.py
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
"""Download location
|
||||
|
||||
Revision ID: 1a70196c05bb
|
||||
Revises: d8fcdb7773c0
|
||||
Create Date: 2022-05-02 12:01:51.210070
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '1a70196c05bb'
|
||||
down_revision = 'd8fcdb7773c0'
|
||||
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)
|
||||
session.execute('ALTER TABLE download ADD COLUMN IF NOT EXISTS location TEXT')
|
||||
session.execute('ALTER TABLE download ADD COLUMN IF NOT EXISTS error TEXT')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
session.execute('ALTER TABLE download DROP COLUMN IF EXISTS location')
|
||||
session.execute('ALTER TABLE download DROP COLUMN IF EXISTS error')
|
||||
36
alembic/versions/1c041aeee0fc_doc_indexer.py
Normal file
36
alembic/versions/1c041aeee0fc_doc_indexer.py
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
"""Doc indexer.
|
||||
|
||||
Revision ID: 1c041aeee0fc
|
||||
Revises: d96a04eb2785
|
||||
Create Date: 2024-03-05 16:54:34.478974
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '1c041aeee0fc'
|
||||
down_revision = 'd96a04eb2785'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False
|
||||
|
||||
|
||||
def upgrade():
|
||||
# Re-index Word documents.
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
session.execute(
|
||||
"""
|
||||
UPDATE file_group
|
||||
SET indexed=false
|
||||
WHERE mimetype in
|
||||
('application/msword','application/vnd.openxmlformats-officedocument.wordprocessingml.document')
|
||||
""")
|
||||
|
||||
|
||||
def downgrade():
|
||||
pass
|
||||
137
alembic/versions/1f2325523525_download_destination_migrate.py
Normal file
137
alembic/versions/1f2325523525_download_destination_migrate.py
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
"""Create `Download.destination` and `Download.tag_names`, migrate from `Download.settings`.
|
||||
|
||||
Revision ID: 1f2325523525
|
||||
Revises: 170d1be52bc7
|
||||
Create Date: 2024-11-02 11:20:45.028865
|
||||
|
||||
"""
|
||||
import os
|
||||
from copy import copy
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy import Column, Integer, Text, String, ARRAY
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from wrolpi.common import ModelHelper
|
||||
from wrolpi.dates import TZDateTime
|
||||
from wrolpi.downloader import get_download_manager_config, DownloadStatus
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '1f2325523525'
|
||||
down_revision = '170d1be52bc7'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
class MDownload(ModelHelper, Base):
|
||||
__tablename__ = 'download'
|
||||
id = Column(Integer, primary_key=True)
|
||||
url = Column(String, nullable=False, unique=True)
|
||||
attempts = Column(Integer, default=0)
|
||||
destination = Column(Text)
|
||||
downloader = Column(Text)
|
||||
sub_downloader = Column(Text)
|
||||
error = Column(Text)
|
||||
frequency = Column(Integer)
|
||||
info_json = Column(JSONB)
|
||||
last_successful_download = Column(TZDateTime)
|
||||
location = Column(Text)
|
||||
next_download = Column(TZDateTime)
|
||||
settings = Column(JSONB)
|
||||
status = Column(String, default=DownloadStatus.new)
|
||||
tag_names = Column(ARRAY(Text))
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
for download in session.query(MDownload):
|
||||
if not download.settings:
|
||||
continue
|
||||
# Move `download.settings['destination']` to `download.destination`, if any.
|
||||
settings = copy(download.settings) if download.settings else dict()
|
||||
destination = settings.pop('destination', None)
|
||||
tag_names = settings.pop('tag_names', None)
|
||||
if isinstance(excluded_urls := settings.get('excluded_urls'), list):
|
||||
settings['excluded_urls'] = ','.join(excluded_urls)
|
||||
download.destination = destination or None
|
||||
download.tag_names = tag_names or None
|
||||
download.settings = settings
|
||||
|
||||
# This will migrate the config as-is at the time that this migration was written. This code is probably not
|
||||
# safe to reuse in the future!
|
||||
|
||||
# Read config file directly.
|
||||
try:
|
||||
config = get_download_manager_config()
|
||||
config._config.update(config.read_config_file())
|
||||
except FileNotFoundError:
|
||||
# Config does not exist, probably testing, or a new WROLPi.
|
||||
return
|
||||
|
||||
new_downloads = []
|
||||
for download in session.query(MDownload).order_by(MDownload.url):
|
||||
if download.last_successful_download and not download.frequency:
|
||||
# This once-download has completed, do not save it.
|
||||
continue
|
||||
new_download = dict(
|
||||
destination=download.destination,
|
||||
downloader=download.downloader,
|
||||
frequency=download.frequency,
|
||||
last_successful_download=download.last_successful_download,
|
||||
next_download=download.next_download,
|
||||
settings=download.settings,
|
||||
status=download.status,
|
||||
sub_downloader=download.sub_downloader,
|
||||
url=download.url,
|
||||
)
|
||||
new_downloads.append(new_download)
|
||||
|
||||
# Write directly to file, bypassing usual checks.
|
||||
config._config['downloads'] = new_downloads
|
||||
config.write_config_data(config._config, config.get_file())
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
for download in session.query(MDownload):
|
||||
if download.destination:
|
||||
settings = copy(download.settings) if download.settings else dict()
|
||||
settings['destination'] = download.destination or settings.get('destination')
|
||||
settings['tag_names'] = download.tag_names or settings.get('tag_names')
|
||||
if isinstance(excluded_urls := settings.get('excluded_urls'), str):
|
||||
settings['excluded_urls'] = excluded_urls.split(',')
|
||||
download.settings = settings
|
||||
|
||||
try:
|
||||
config = get_download_manager_config()
|
||||
config._config.update(config.read_config_file())
|
||||
except FileNotFoundError:
|
||||
# Config does not exist, probably testing, or a new WROLPi.
|
||||
return
|
||||
|
||||
new_downloads = []
|
||||
for download in session.query(MDownload).order_by(MDownload.url):
|
||||
new_download = dict(
|
||||
downloader=download.downloader,
|
||||
frequency=download.frequency,
|
||||
last_successful_download=download.last_successful_download,
|
||||
next_download=download.next_download,
|
||||
settings=download.settings,
|
||||
status=download.status,
|
||||
sub_downloader=download.sub_downloader,
|
||||
url=download.url,
|
||||
)
|
||||
new_downloads.append(new_download)
|
||||
|
||||
config._config['downloads'] = new_downloads
|
||||
config.write_config_data(config._config, config.get_file())
|
||||
|
|
@ -1,378 +0,0 @@
|
|||
"""The SQLite baseline.
|
||||
|
||||
The entire Postgres-era migration history (85 revisions) was squashed into this baseline when
|
||||
WROLPi moved its database into the media directory (SQLite). See the git history of
|
||||
alembic/versions/ for the old chain.
|
||||
|
||||
Revision ID: 2026_07_10_1350
|
||||
Revises:
|
||||
Create Date: 2026-07-10 13:50:59.070646
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
import wrolpi.dates
|
||||
import wrolpi.files.models
|
||||
import wrolpi.media_path
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2026_07_10_1350'
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('directory',
|
||||
sa.Column('path', wrolpi.media_path.MediaPathType(), nullable=False),
|
||||
sa.Column('name', sa.String(), nullable=False),
|
||||
sa.Column('idempotency', wrolpi.dates.TZDateTime(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('path')
|
||||
)
|
||||
with op.batch_alter_table('directory', schema=None) as batch_op:
|
||||
batch_op.create_index('directory_name_idx', ['name'], unique=False)
|
||||
|
||||
op.create_table('file_group',
|
||||
sa.Column('id', sa.BigInteger().with_variant(sa.Integer(), 'sqlite'), nullable=False),
|
||||
sa.Column('directory', wrolpi.media_path.MediaPathType(), nullable=False),
|
||||
sa.Column('author', sa.String(), nullable=True),
|
||||
sa.Column('censored', sa.Boolean(), nullable=True),
|
||||
sa.Column('data', wrolpi.files.models.FancyJSON(), nullable=True),
|
||||
sa.Column('download_datetime', wrolpi.dates.TZDateTime(), nullable=True),
|
||||
sa.Column('files', wrolpi.files.models.FancyJSON(), nullable=True),
|
||||
sa.Column('idempotency', wrolpi.dates.TZDateTime(), nullable=True),
|
||||
sa.Column('indexed', sa.Boolean(), nullable=True),
|
||||
sa.Column('length', sa.BigInteger(), nullable=True),
|
||||
sa.Column('mimetype', sa.String(), nullable=True),
|
||||
sa.Column('model', sa.String(), nullable=True),
|
||||
sa.Column('modification_datetime', wrolpi.dates.TZDateTime(), nullable=True),
|
||||
sa.Column('primary_path', wrolpi.media_path.MediaPathType(), nullable=False),
|
||||
sa.Column('published_datetime', wrolpi.dates.TZDateTime(), nullable=True),
|
||||
sa.Column('published_modified_datetime', wrolpi.dates.TZDateTime(), nullable=True),
|
||||
sa.Column('size', sa.BigInteger(), nullable=True),
|
||||
sa.Column('suffix', sa.String(), nullable=True),
|
||||
sa.Column('title', sa.String(), nullable=True),
|
||||
sa.Column('url', sa.String(), nullable=True),
|
||||
sa.Column('viewed', wrolpi.dates.TZDateTime(), nullable=True),
|
||||
sa.Column('effective_datetime', wrolpi.dates.TZDateTime(), nullable=True),
|
||||
sa.Column('a_text', sa.String(), nullable=True),
|
||||
sa.Column('b_text', sa.String(), nullable=True),
|
||||
sa.Column('c_text', sa.String(), nullable=True),
|
||||
sa.Column('d_text', sa.String(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('primary_path')
|
||||
)
|
||||
with op.batch_alter_table('file_group', schema=None) as batch_op:
|
||||
batch_op.create_index('file_group_author_idx', ['author'], unique=False)
|
||||
batch_op.create_index('file_group_directory_idx', ['directory'], unique=False)
|
||||
batch_op.create_index('file_group_download_datetime_idx', ['download_datetime'], unique=False)
|
||||
batch_op.create_index('file_group_effective_datetime_idx', ['effective_datetime'], unique=False)
|
||||
batch_op.create_index('file_group_length_idx', ['length'], unique=False)
|
||||
batch_op.create_index('file_group_mimetype_idx', ['mimetype'], unique=False)
|
||||
batch_op.create_index('file_group_model_idx', ['model'], unique=False)
|
||||
batch_op.create_index('file_group_modification_datetime_idx', ['modification_datetime'], unique=False)
|
||||
batch_op.create_index('file_group_published_datetime_idx', ['published_datetime'], unique=False)
|
||||
batch_op.create_index('file_group_published_modified_datetime_idx', ['published_modified_datetime'], unique=False)
|
||||
batch_op.create_index('file_group_size_ix', ['size'], unique=False)
|
||||
batch_op.create_index('file_group_url_idx', ['url'], unique=False)
|
||||
batch_op.create_index('file_group_viewed_idx', ['viewed'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_file_group_suffix'), ['suffix'], unique=False)
|
||||
|
||||
op.create_table('tag',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sa.String(), nullable=False),
|
||||
sa.Column('color', sa.String(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('name')
|
||||
)
|
||||
op.create_table('wrolpi_flag',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('refresh_complete', sa.Boolean(), nullable=True),
|
||||
sa.Column('outdated_zims', sa.Boolean(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_table('collection',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sa.String(), nullable=False),
|
||||
sa.Column('description', sa.Text(), nullable=True),
|
||||
sa.Column('kind', sa.String(), server_default='channel', nullable=False),
|
||||
sa.Column('directory', wrolpi.media_path.MediaPathType(), nullable=True),
|
||||
sa.Column('tag_id', sa.Integer(), nullable=True),
|
||||
sa.Column('file_format', sa.String(), nullable=True),
|
||||
sa.Column('created_date', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False),
|
||||
sa.Column('item_count', sa.Integer(), nullable=False),
|
||||
sa.Column('total_size', sa.BigInteger(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['tag_id'], ['tag.id'], ),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('directory', name='uq_collection_directory'),
|
||||
sa.UniqueConstraint('name', 'kind', name='uq_collection_name_kind')
|
||||
)
|
||||
with op.batch_alter_table('collection', schema=None) as batch_op:
|
||||
batch_op.create_index('idx_collection_item_count', ['item_count'], unique=False)
|
||||
batch_op.create_index('idx_collection_kind', ['kind'], unique=False)
|
||||
batch_op.create_index('idx_collection_total_size', ['total_size'], unique=False)
|
||||
|
||||
op.create_table('doc',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('size', sa.BigInteger(), nullable=True),
|
||||
sa.Column('publisher', sa.String(), nullable=True),
|
||||
sa.Column('language', sa.String(), nullable=True),
|
||||
sa.Column('page_count', sa.Integer(), nullable=True),
|
||||
sa.Column('subject', sa.String(), nullable=True),
|
||||
sa.Column('description', sa.Text(), nullable=True),
|
||||
sa.Column('file_group_id', sa.BigInteger(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['file_group_id'], ['file_group.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('file_group_id')
|
||||
)
|
||||
with op.batch_alter_table('doc', schema=None) as batch_op:
|
||||
batch_op.create_index('doc_size_idx', ['size'], unique=False)
|
||||
|
||||
op.create_table('tag_file',
|
||||
sa.Column('created_at', wrolpi.dates.TZDateTime(), nullable=True),
|
||||
sa.Column('tag_id', sa.Integer(), nullable=False),
|
||||
sa.Column('file_group_id', sa.BigInteger(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['file_group_id'], ['file_group.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['tag_id'], ['tag.id'], ),
|
||||
sa.PrimaryKeyConstraint('tag_id', 'file_group_id'),
|
||||
sa.UniqueConstraint('tag_id', 'file_group_id', name='tag_file_tag_id_file_group_id_key')
|
||||
)
|
||||
op.create_table('zim',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('path', wrolpi.media_path.MediaPathType(), nullable=False),
|
||||
sa.Column('file_group_id', sa.BigInteger(), nullable=False),
|
||||
sa.Column('auto_search', sa.Boolean(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['file_group_id'], ['file_group.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('path', name='zim_path_key')
|
||||
)
|
||||
op.create_table('archive',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('collection_id', sa.Integer(), nullable=True),
|
||||
sa.Column('file_group_id', sa.BigInteger(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['collection_id'], ['collection.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['file_group_id'], ['file_group.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('file_group_id')
|
||||
)
|
||||
with op.batch_alter_table('archive', schema=None) as batch_op:
|
||||
batch_op.create_index('idx_archive_collection_id', ['collection_id'], unique=False)
|
||||
|
||||
op.create_table('channel',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('url', sa.String(), nullable=True),
|
||||
sa.Column('generate_posters', sa.Boolean(), nullable=True),
|
||||
sa.Column('calculate_duration', sa.Boolean(), nullable=True),
|
||||
sa.Column('download_missing_data', sa.Boolean(), nullable=True),
|
||||
sa.Column('source_id', sa.String(), nullable=True),
|
||||
sa.Column('refreshed', sa.Boolean(), nullable=True),
|
||||
sa.Column('video_count', sa.Integer(), nullable=False),
|
||||
sa.Column('total_size', sa.BigInteger(), nullable=False),
|
||||
sa.Column('minimum_frequency', sa.Integer(), nullable=True),
|
||||
sa.Column('info_json', sa.JSON(), nullable=True),
|
||||
sa.Column('info_date', sa.Date(), nullable=True),
|
||||
sa.Column('collection_id', sa.Integer(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['collection_id'], ['collection.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
with op.batch_alter_table('channel', schema=None) as batch_op:
|
||||
batch_op.create_index('channel_minimum_frequency_idx', ['minimum_frequency'], unique=False)
|
||||
batch_op.create_index('channel_source_id', ['source_id'], unique=False)
|
||||
batch_op.create_index('channel_total_size_idx', ['total_size'], unique=False)
|
||||
batch_op.create_index('channel_url_key', ['url'], unique=True, postgresql_where=sa.text('url IS NOT NULL'), sqlite_where=sa.text('url IS NOT NULL'))
|
||||
batch_op.create_index('channel_video_count_idx', ['video_count'], unique=False)
|
||||
|
||||
op.create_table('collection_item',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('collection_id', sa.Integer(), nullable=False),
|
||||
sa.Column('item_kind', sa.String(), server_default='file', nullable=False),
|
||||
sa.Column('file_group_id', sa.Integer(), nullable=True),
|
||||
sa.Column('zim_id', sa.Integer(), nullable=True),
|
||||
sa.Column('zim_entry', sa.Text(), nullable=True),
|
||||
sa.Column('url', sa.Text(), nullable=True),
|
||||
sa.Column('title', sa.Text(), nullable=True),
|
||||
sa.Column('position', sa.Integer(), nullable=False),
|
||||
sa.Column('added_date', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False),
|
||||
sa.CheckConstraint("(item_kind = 'file' AND file_group_id IS NOT NULL AND zim_id IS NULL AND url IS NULL) OR (item_kind = 'zim' AND zim_id IS NOT NULL AND zim_entry IS NOT NULL AND file_group_id IS NULL AND url IS NULL) OR (item_kind = 'url' AND url IS NOT NULL AND file_group_id IS NULL AND zim_id IS NULL)", name='ck_collection_item_kind'),
|
||||
sa.ForeignKeyConstraint(['collection_id'], ['collection.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['file_group_id'], ['file_group.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['zim_id'], ['zim.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('collection_id', 'file_group_id', name='uq_collection_file_group'),
|
||||
sa.UniqueConstraint('collection_id', 'url', name='uq_collection_url'),
|
||||
sa.UniqueConstraint('collection_id', 'zim_id', 'zim_entry', name='uq_collection_zim_entry')
|
||||
)
|
||||
with op.batch_alter_table('collection_item', schema=None) as batch_op:
|
||||
batch_op.create_index('idx_collection_item_collection_id', ['collection_id'], unique=False)
|
||||
batch_op.create_index('idx_collection_item_collection_position', ['collection_id', 'position'], unique=False)
|
||||
batch_op.create_index('idx_collection_item_file_group_id', ['file_group_id'], unique=False)
|
||||
batch_op.create_index('idx_collection_item_position', ['position'], unique=False)
|
||||
|
||||
op.create_table('doc_section',
|
||||
sa.Column('id', sa.BigInteger().with_variant(sa.Integer(), 'sqlite'), nullable=False),
|
||||
sa.Column('doc_id', sa.Integer(), nullable=False),
|
||||
sa.Column('kind', sa.String(), nullable=False),
|
||||
sa.Column('ordinal', sa.Integer(), nullable=False),
|
||||
sa.Column('label', sa.String(), nullable=True),
|
||||
sa.Column('content', sa.Text(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['doc_id'], ['doc.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
with op.batch_alter_table('doc_section', schema=None) as batch_op:
|
||||
batch_op.create_index('doc_section_doc_id_idx', ['doc_id', 'ordinal'], unique=False)
|
||||
|
||||
op.create_table('download',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('url', sa.String(), nullable=False),
|
||||
sa.Column('attempts', sa.Integer(), nullable=True),
|
||||
sa.Column('destination', wrolpi.media_path.MediaPathType(), nullable=True),
|
||||
sa.Column('downloader', sa.Text(), nullable=True),
|
||||
sa.Column('sub_downloader', sa.Text(), nullable=True),
|
||||
sa.Column('error', sa.Text(), nullable=True),
|
||||
sa.Column('frequency', sa.Integer(), nullable=True),
|
||||
sa.Column('info_json', sa.JSON(), nullable=True),
|
||||
sa.Column('last_download_attempt', wrolpi.dates.TZDateTime(), nullable=True),
|
||||
sa.Column('last_successful_download', wrolpi.dates.TZDateTime(), nullable=True),
|
||||
sa.Column('location', sa.Text(), nullable=True),
|
||||
sa.Column('next_download', wrolpi.dates.TZDateTime(), nullable=True),
|
||||
sa.Column('settings', sa.JSON(), nullable=True),
|
||||
sa.Column('status', sa.String(), nullable=True),
|
||||
sa.Column('tag_names', sa.JSON(), nullable=True),
|
||||
sa.Column('collection_id', sa.Integer(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['collection_id'], ['collection.id'], ondelete='SET NULL'),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('url')
|
||||
)
|
||||
with op.batch_alter_table('download', schema=None) as batch_op:
|
||||
batch_op.create_index('idx_download_collection_id', ['collection_id'], unique=False)
|
||||
batch_op.create_index('idx_download_last_download_attempt', ['last_download_attempt'], unique=False)
|
||||
|
||||
op.create_table('tag_zim',
|
||||
sa.Column('tag_id', sa.Integer(), nullable=False),
|
||||
sa.Column('zim_id', sa.Integer(), nullable=False),
|
||||
sa.Column('zim_entry', sa.Text(), nullable=False),
|
||||
sa.Column('created_at', wrolpi.dates.TZDateTime(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['tag_id'], ['tag.id'], ),
|
||||
sa.ForeignKeyConstraint(['zim_id'], ['zim.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('tag_id', 'zim_id', 'zim_entry'),
|
||||
sa.UniqueConstraint('tag_id', 'zim_id', 'zim_entry', name='tag_zim_tag_id_zim_id_zim_entry_key')
|
||||
)
|
||||
op.create_table('video',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('source_id', sa.String(), nullable=True),
|
||||
sa.Column('view_count', sa.BigInteger(), nullable=True),
|
||||
sa.Column('ffprobe_json', sa.JSON(), nullable=True),
|
||||
sa.Column('have_comments', sa.Boolean(), nullable=True),
|
||||
sa.Column('comments_failed', sa.Boolean(), nullable=True),
|
||||
sa.Column('channel_id', sa.Integer(), nullable=True),
|
||||
sa.Column('file_group_id', sa.BigInteger(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['channel_id'], ['channel.id'], ),
|
||||
sa.ForeignKeyConstraint(['file_group_id'], ['file_group.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('file_group_id'),
|
||||
sqlite_autoincrement=True
|
||||
)
|
||||
with op.batch_alter_table('video', schema=None) as batch_op:
|
||||
batch_op.create_index('video_channel_id_idx', ['channel_id'], unique=False)
|
||||
batch_op.create_index('video_source_id_idx', ['source_id'], unique=False)
|
||||
batch_op.create_index('video_view_count_idx', ['view_count'], unique=False)
|
||||
|
||||
op.create_table('zim_subscription',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sa.Text(), nullable=False),
|
||||
sa.Column('language', sa.Text(), nullable=False),
|
||||
sa.Column('download_id', sa.Integer(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['download_id'], ['download.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('name')
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
# Triggers (channel summaries, effective_datetime) and the FTS5 full-text-search tables.
|
||||
# Shared with the test databases (wrolpi/conftest.py) so tests exercise the same schema.
|
||||
from wrolpi.schema_ddl import install_raw_ddl
|
||||
from wrolpi.fts import rebuild_fts
|
||||
|
||||
connection = op.get_bind()
|
||||
install_raw_ddl(connection)
|
||||
# Index any existing content (no-op on a fresh database).
|
||||
rebuild_fts(connection)
|
||||
|
||||
|
||||
def downgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table('zim_subscription')
|
||||
with op.batch_alter_table('video', schema=None) as batch_op:
|
||||
batch_op.drop_index('video_view_count_idx')
|
||||
batch_op.drop_index('video_source_id_idx')
|
||||
batch_op.drop_index('video_channel_id_idx')
|
||||
|
||||
op.drop_table('video')
|
||||
op.drop_table('tag_zim')
|
||||
with op.batch_alter_table('download', schema=None) as batch_op:
|
||||
batch_op.drop_index('idx_download_last_download_attempt')
|
||||
batch_op.drop_index('idx_download_collection_id')
|
||||
|
||||
op.drop_table('download')
|
||||
with op.batch_alter_table('doc_section', schema=None) as batch_op:
|
||||
batch_op.drop_index('doc_section_doc_id_idx')
|
||||
|
||||
op.drop_table('doc_section')
|
||||
with op.batch_alter_table('collection_item', schema=None) as batch_op:
|
||||
batch_op.drop_index('idx_collection_item_position')
|
||||
batch_op.drop_index('idx_collection_item_file_group_id')
|
||||
batch_op.drop_index('idx_collection_item_collection_position')
|
||||
batch_op.drop_index('idx_collection_item_collection_id')
|
||||
|
||||
op.drop_table('collection_item')
|
||||
with op.batch_alter_table('channel', schema=None) as batch_op:
|
||||
batch_op.drop_index('channel_video_count_idx')
|
||||
batch_op.drop_index('channel_url_key', postgresql_where=sa.text('url IS NOT NULL'), sqlite_where=sa.text('url IS NOT NULL'))
|
||||
batch_op.drop_index('channel_total_size_idx')
|
||||
batch_op.drop_index('channel_source_id')
|
||||
batch_op.drop_index('channel_minimum_frequency_idx')
|
||||
|
||||
op.drop_table('channel')
|
||||
with op.batch_alter_table('archive', schema=None) as batch_op:
|
||||
batch_op.drop_index('idx_archive_collection_id')
|
||||
|
||||
op.drop_table('archive')
|
||||
op.drop_table('zim')
|
||||
op.drop_table('tag_file')
|
||||
with op.batch_alter_table('doc', schema=None) as batch_op:
|
||||
batch_op.drop_index('doc_size_idx')
|
||||
|
||||
op.drop_table('doc')
|
||||
with op.batch_alter_table('collection', schema=None) as batch_op:
|
||||
batch_op.drop_index('idx_collection_total_size')
|
||||
batch_op.drop_index('idx_collection_kind')
|
||||
batch_op.drop_index('idx_collection_item_count')
|
||||
|
||||
op.drop_table('collection')
|
||||
op.drop_table('wrolpi_flag')
|
||||
op.drop_table('tag')
|
||||
with op.batch_alter_table('file_group', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_file_group_suffix'))
|
||||
batch_op.drop_index('file_group_viewed_idx')
|
||||
batch_op.drop_index('file_group_url_idx')
|
||||
batch_op.drop_index('file_group_size_ix')
|
||||
batch_op.drop_index('file_group_published_modified_datetime_idx')
|
||||
batch_op.drop_index('file_group_published_datetime_idx')
|
||||
batch_op.drop_index('file_group_modification_datetime_idx')
|
||||
batch_op.drop_index('file_group_model_idx')
|
||||
batch_op.drop_index('file_group_mimetype_idx')
|
||||
batch_op.drop_index('file_group_length_idx')
|
||||
batch_op.drop_index('file_group_effective_datetime_idx')
|
||||
batch_op.drop_index('file_group_download_datetime_idx')
|
||||
batch_op.drop_index('file_group_directory_idx')
|
||||
batch_op.drop_index('file_group_author_idx')
|
||||
|
||||
op.drop_table('file_group')
|
||||
with op.batch_alter_table('directory', schema=None) as batch_op:
|
||||
batch_op.drop_index('directory_name_idx')
|
||||
|
||||
op.drop_table('directory')
|
||||
# ### end Alembic commands ###
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
"""Covering index for browse pages.
|
||||
|
||||
The videos/files browse queries filter on mimetype and order by effective_datetime; without a
|
||||
covering index SQLite scans every file_group row (which carries the indexed texts inline), which
|
||||
takes ~18 seconds cold on a Pi. With (mimetype, effective_datetime) the filter, count, and sort
|
||||
resolve index-only.
|
||||
|
||||
Revision ID: 2026_07_14_0900
|
||||
Revises: 2026_07_10_1350
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2026_07_14_0900'
|
||||
down_revision = '2026_07_10_1350'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# IF NOT EXISTS: QA boxes may have had the index created manually before this migration.
|
||||
op.execute('CREATE INDEX IF NOT EXISTS file_group_mimetype_effective_idx '
|
||||
'ON file_group (mimetype, effective_datetime)')
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.execute('DROP INDEX IF EXISTS file_group_mimetype_effective_idx')
|
||||
|
|
@ -1,37 +0,0 @@
|
|||
"""Add file_group.stem for (directory, stem) grouping.
|
||||
|
||||
A stored stem is a cache of split_path_stem_and_suffix. Compare joins on it.
|
||||
NULL stems (and algorithm-version mismatches) are backfilled at refresh by
|
||||
ensure_file_group_stems() before any compare is allowed.
|
||||
|
||||
The unique (directory, stem) index is intentionally omitted: duplicates are
|
||||
collapsed at refresh time. A later release can add UNIQUE after a full refresh.
|
||||
|
||||
Revision ID: 2026_09_16_1200
|
||||
Revises: 2026_07_14_0900
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2026_09_16_1200'
|
||||
down_revision = '2026_07_14_0900'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.execute('ALTER TABLE file_group ADD COLUMN stem VARCHAR')
|
||||
op.execute('CREATE INDEX IF NOT EXISTS file_group_directory_stem_idx '
|
||||
'ON file_group (directory, stem)')
|
||||
op.execute('''
|
||||
CREATE TABLE IF NOT EXISTS wrolpi_kv (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
)
|
||||
''')
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.execute('DROP INDEX IF EXISTS file_group_directory_stem_idx')
|
||||
# SQLite cannot DROP COLUMN without rebuilding the table; leave stem in place.
|
||||
op.execute('DROP TABLE IF EXISTS wrolpi_kv')
|
||||
|
|
@ -1,30 +0,0 @@
|
|||
"""Unique (directory, stem) on file_group.
|
||||
|
||||
713 added the stem column and a non-unique index. This release collapses any
|
||||
remaining duplicate (directory, stem) rows (moving tags and collection
|
||||
membership onto the winner) and makes the index UNIQUE.
|
||||
|
||||
Revision ID: 2026_09_18_1200
|
||||
Revises: 2026_09_16_1200
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2026_09_18_1200'
|
||||
down_revision = '2026_09_16_1200'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
from wrolpi.files.lib import backfill_null_file_group_stems, dedupe_file_groups_by_directory_stem
|
||||
|
||||
backfill_null_file_group_stems()
|
||||
dedupe_file_groups_by_directory_stem()
|
||||
op.execute('DROP INDEX IF EXISTS file_group_directory_stem_idx')
|
||||
op.execute('CREATE UNIQUE INDEX file_group_directory_stem_idx ON file_group (directory, stem)')
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.execute('DROP INDEX IF EXISTS file_group_directory_stem_idx')
|
||||
op.execute('CREATE INDEX IF NOT EXISTS file_group_directory_stem_idx ON file_group (directory, stem)')
|
||||
|
|
@ -1,24 +0,0 @@
|
|||
"""Drop unused file_group.idempotency.
|
||||
|
||||
FileWorker no longer stamps this column (refresh diffs in SQL). directory.idempotency
|
||||
is unchanged. SQLite 3.35+ DROP COLUMN does not rebuild the table, so file_group_fts
|
||||
(external content on file_group.id) is left intact.
|
||||
|
||||
Revision ID: 2026_09_20_1200
|
||||
Revises: 2026_09_18_1200
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2026_09_20_1200'
|
||||
down_revision = '2026_09_18_1200'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.execute('ALTER TABLE file_group DROP COLUMN idempotency')
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.execute('ALTER TABLE file_group ADD COLUMN idempotency DATETIME')
|
||||
|
|
@ -1,45 +0,0 @@
|
|||
"""Maintain collection.item_count/total_size for Domain Collections with triggers.
|
||||
|
||||
Listing Domain Collections summed file_group.size through an archive join on every request,
|
||||
one random page read per archive. The new triggers keep the summary columns current
|
||||
(as the channel triggers already do for Channels); this migration installs them and
|
||||
backfills existing Domain Collections.
|
||||
|
||||
Revision ID: 2026_09_27_1200
|
||||
Revises: 2026_09_20_1200
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2026_09_27_1200'
|
||||
down_revision = '2026_09_20_1200'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
TRIGGERS = (
|
||||
'archive_insert_collection_summary',
|
||||
'archive_delete_collection_summary',
|
||||
'archive_update_collection_summary',
|
||||
'file_group_size_collection_summary',
|
||||
)
|
||||
|
||||
|
||||
def upgrade():
|
||||
from wrolpi.schema_ddl import install_raw_ddl
|
||||
|
||||
# Idempotent: only the new triggers are created.
|
||||
install_raw_ddl(op.get_bind())
|
||||
|
||||
op.execute('''
|
||||
UPDATE collection SET
|
||||
item_count = (SELECT COUNT(*) FROM archive WHERE collection_id = collection.id),
|
||||
total_size = (SELECT COALESCE(SUM(fg.size), 0) FROM archive a
|
||||
LEFT JOIN file_group fg ON a.file_group_id = fg.id
|
||||
WHERE a.collection_id = collection.id)
|
||||
WHERE kind = 'domain'
|
||||
''')
|
||||
|
||||
|
||||
def downgrade():
|
||||
for name in TRIGGERS:
|
||||
op.execute(f'DROP TRIGGER IF EXISTS {name}')
|
||||
|
|
@ -1,29 +0,0 @@
|
|||
"""Covering indexes for the Collection listing.
|
||||
|
||||
Listing Collections read every channel row (for video_count/total_size) and every download
|
||||
row of those Collections (for the minimum frequency). Both tables store yt-dlp info_json,
|
||||
so their rows are tens of KB and each sits on its own scattered page; from a cold disk cache
|
||||
that was 10+ seconds. These indexes answer both queries without touching a row.
|
||||
|
||||
Revision ID: 2026_09_28_1200
|
||||
Revises: 2026_09_27_1200
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2026_09_28_1200'
|
||||
down_revision = '2026_09_27_1200'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.execute('CREATE INDEX IF NOT EXISTS channel_collection_summary_idx'
|
||||
' ON channel (collection_id, video_count, total_size)')
|
||||
op.execute('CREATE INDEX IF NOT EXISTS download_collection_frequency_idx'
|
||||
' ON download (collection_id, frequency)')
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.execute('DROP INDEX IF EXISTS channel_collection_summary_idx')
|
||||
op.execute('DROP INDEX IF EXISTS download_collection_frequency_idx')
|
||||
|
|
@ -1,31 +0,0 @@
|
|||
"""Retag existing markdown file groups as text/markdown.
|
||||
|
||||
A refresh skips a group whose files have not changed, so markdown indexed before text/markdown
|
||||
existed would keep the type libmagic gave it (text/plain, or a programming language when the file
|
||||
holds code) and the indexer that type chose. Marking the rows unindexed lets apply_indexers
|
||||
re-index them with TextIndexer. SQLite's LIKE is case-insensitive for ASCII, so `.MD` matches.
|
||||
|
||||
Revision ID: 2026_10_05_1200
|
||||
Revises: 2026_09_28_1200
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2026_10_05_1200'
|
||||
down_revision = '2026_09_28_1200'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.execute("""
|
||||
UPDATE file_group SET mimetype = 'text/markdown', "indexed" = 0
|
||||
WHERE (primary_path LIKE '%.md' OR primary_path LIKE '%.markdown')
|
||||
AND mimetype LIKE 'text/%'
|
||||
AND mimetype != 'text/markdown'
|
||||
""")
|
||||
|
||||
|
||||
def downgrade():
|
||||
# The original types are not recorded; text/plain is what libmagic reports for most markdown.
|
||||
op.execute("""UPDATE file_group SET mimetype = 'text/plain', "indexed" = 0 WHERE mimetype = 'text/markdown'""")
|
||||
|
|
@ -1,43 +0,0 @@
|
|||
"""Add the repository table for git Repos (Collections with kind='repo').
|
||||
|
||||
Revision ID: 2026_10_06_1200
|
||||
Revises: 2026_10_05_1200
|
||||
"""
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
import wrolpi.dates
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2026_10_06_1200'
|
||||
down_revision = '2026_10_05_1200'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.create_table(
|
||||
'repository',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('url', sa.String(), nullable=False),
|
||||
sa.Column('host', sa.String(), nullable=True),
|
||||
sa.Column('owner', sa.String(), nullable=True),
|
||||
sa.Column('mode', sa.String(), nullable=False),
|
||||
sa.Column('branch', sa.String(), nullable=True),
|
||||
sa.Column('default_branch', sa.String(), nullable=True),
|
||||
sa.Column('head_sha', sa.String(), nullable=True),
|
||||
sa.Column('head_date', wrolpi.dates.TZDateTime(), nullable=True),
|
||||
sa.Column('head_message', sa.Text(), nullable=True),
|
||||
sa.Column('last_fetch', wrolpi.dates.TZDateTime(), nullable=True),
|
||||
sa.Column('size', sa.BigInteger(), nullable=True),
|
||||
sa.Column('readme_path', sa.String(), nullable=True),
|
||||
sa.Column('collection_id', sa.Integer(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['collection_id'], ['collection.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('collection_id'),
|
||||
sa.UniqueConstraint('url'),
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_table('repository')
|
||||
|
|
@ -1,39 +0,0 @@
|
|||
"""Search git Repos by name and README: repository.search_name/readme_text and repository_fts.
|
||||
|
||||
Revision ID: 2026_10_06_1300
|
||||
Revises: 2026_10_06_1200
|
||||
"""
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2026_10_06_1300'
|
||||
down_revision = '2026_10_06_1200'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
from wrolpi.schema_ddl import install_raw_ddl
|
||||
|
||||
op.add_column('repository', sa.Column('search_name', sa.String(), nullable=True))
|
||||
op.add_column('repository', sa.Column('readme_text', sa.Text(), nullable=True))
|
||||
op.execute('''
|
||||
UPDATE repository SET search_name = TRIM(
|
||||
COALESCE((SELECT name FROM collection WHERE collection.id = repository.collection_id), '')
|
||||
|| ' ' || COALESCE(owner, ''))
|
||||
''')
|
||||
|
||||
# Creates repository_fts and its triggers now that the columns exist. The README text is filled by the next
|
||||
# update of each Repo.
|
||||
install_raw_ddl(op.get_bind())
|
||||
op.execute("INSERT INTO repository_fts(repository_fts) VALUES('rebuild')")
|
||||
|
||||
|
||||
def downgrade():
|
||||
for name in ('repository_fts_ai', 'repository_fts_ad', 'repository_fts_au'):
|
||||
op.execute(f'DROP TRIGGER IF EXISTS {name}')
|
||||
op.execute('DROP TABLE IF EXISTS repository_fts')
|
||||
with op.batch_alter_table('repository') as batch_op:
|
||||
batch_op.drop_column('readme_text')
|
||||
batch_op.drop_column('search_name')
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
"""A git Repo can also download its submodules: repository.submodules.
|
||||
|
||||
Revision ID: 2026_10_06_1400
|
||||
Revises: 2026_10_06_1300
|
||||
"""
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2026_10_06_1400'
|
||||
down_revision = '2026_10_06_1300'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column('repository', sa.Column('submodules', sa.Boolean(), server_default=sa.false(), nullable=False))
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table('repository') as batch_op:
|
||||
batch_op.drop_column('submodules')
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
"""A git Repo's clone holds a random token: repository.clone_token.
|
||||
|
||||
Revision ID: 2026_10_06_1500
|
||||
Revises: 2026_10_06_1400
|
||||
"""
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2026_10_06_1500'
|
||||
down_revision = '2026_10_06_1400'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column('repository', sa.Column('clone_token', sa.String(), nullable=True))
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table('repository') as batch_op:
|
||||
batch_op.drop_column('clone_token')
|
||||
|
|
@ -1,24 +0,0 @@
|
|||
"""A FileGroup records how far the user is through it: file_group.progress and file_group.position.
|
||||
|
||||
Revision ID: 2026_10_08_1200
|
||||
Revises: 2026_10_06_1500
|
||||
"""
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2026_10_08_1200'
|
||||
down_revision = '2026_10_06_1500'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column('file_group', sa.Column('progress', sa.Float(), nullable=True))
|
||||
op.add_column('file_group', sa.Column('position', sa.JSON(), nullable=True))
|
||||
|
||||
|
||||
def downgrade():
|
||||
# Not batch_alter_table: rebuilding file_group drops its FTS triggers (see 2026_09_20_1200).
|
||||
op.execute('ALTER TABLE file_group DROP COLUMN position')
|
||||
op.execute('ALTER TABLE file_group DROP COLUMN progress')
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
"""Each database config's version, so an import can tell whether the database or the file is newer
|
||||
(see wrolpi.config_version).
|
||||
|
||||
Revision ID: 2026_10_24_1200
|
||||
Revises: 2026_10_08_1200
|
||||
"""
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2026_10_24_1200'
|
||||
down_revision = '2026_10_08_1200'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# No rows: a config's next import (without deletes) records its version.
|
||||
op.create_table(
|
||||
'config_version',
|
||||
sa.Column('name', sa.String(), primary_key=True),
|
||||
sa.Column('version', sa.Integer(), nullable=False),
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_table('config_version')
|
||||
|
|
@ -1,175 +0,0 @@
|
|||
"""Tag names have no leading or trailing whitespace.
|
||||
|
||||
A Tag whose name had whitespace is renamed. Tags whose names are the same once stripped are merged into one: it
|
||||
keeps every tagged file, Zim entry and Collection, and the first color (by Tag id) of the merged Tags. Downloads
|
||||
and the config files that name Tags are rewritten the same way, so the next import finds them in step with the
|
||||
database (an import of the old names would create the padded Tags again, or delete the stripped ones).
|
||||
|
||||
Revision ID: 2026_10_25_1200
|
||||
Revises: 2026_10_24_1200
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
|
||||
import yaml
|
||||
from alembic import op
|
||||
|
||||
from wrolpi.common import get_media_directory, write_config_data
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2026_10_25_1200'
|
||||
down_revision = '2026_10_24_1200'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# The configs which name Tags.
|
||||
CONFIG_FILES = ('tags.yaml', 'download_manager.yaml', 'channels.yaml', 'domains.yaml', 'playlists.yaml',
|
||||
'repos.yaml', 'videos_downloader.yaml', 'archives_downloader.yaml')
|
||||
|
||||
|
||||
def _strip(name):
|
||||
"""A Tag name without its whitespace; a name that would be empty is kept (it cannot be renamed)."""
|
||||
if isinstance(name, str) and name.strip():
|
||||
return name.strip()
|
||||
return name
|
||||
|
||||
|
||||
def _strip_names(names: list) -> list:
|
||||
stripped = list()
|
||||
for name in map(_strip, names):
|
||||
if name not in stripped:
|
||||
stripped.append(name)
|
||||
return stripped
|
||||
|
||||
|
||||
def _strip_nested(data):
|
||||
"""Strip the Tag names in a config's (or a Download's settings') `tag_name`, `tag_names` and
|
||||
`channel_tag_name` values, at any depth."""
|
||||
if isinstance(data, list):
|
||||
return [_strip_nested(i) for i in data]
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
result = dict()
|
||||
for key, value in data.items():
|
||||
if key == 'tag_name':
|
||||
value = _strip(value)
|
||||
elif key in ('tag_names', 'channel_tag_name') and isinstance(value, list):
|
||||
value = _strip_names(value)
|
||||
else:
|
||||
value = _strip_nested(value)
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
|
||||
def _strip_rows(rows: list, key_length: int) -> list:
|
||||
"""tags.yaml's tag_files or tag_zims, each row keyed by its first `key_length` values (the Tag name first)."""
|
||||
result, seen = list(), set()
|
||||
for row in rows:
|
||||
if isinstance(row, list) and row:
|
||||
row = [_strip(row[0]), *row[1:]]
|
||||
key = json.dumps(row[:key_length], default=str)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
result.append(row)
|
||||
return result
|
||||
|
||||
|
||||
def _strip_tags_config(config: dict, colors: dict) -> dict:
|
||||
"""`colors`: each renamed Tag's color in the database, which the file must match (an import copies the file's
|
||||
color into the database)."""
|
||||
config = dict(config)
|
||||
if isinstance(config.get('tags'), dict):
|
||||
tags = dict()
|
||||
for name, attrs in config['tags'].items():
|
||||
stripped = _strip(name)
|
||||
if stripped not in tags:
|
||||
tags[stripped] = attrs
|
||||
elif isinstance(attrs, dict) and attrs.get('color') and not (tags[stripped] or dict()).get('color'):
|
||||
# The first color of the merged Tags.
|
||||
tags[stripped] = {**(tags[stripped] or dict()), 'color': attrs['color']}
|
||||
for name in tags.keys() & colors.keys():
|
||||
tags[name] = {**(tags[name] or dict()), 'color': colors[name]}
|
||||
config['tags'] = tags
|
||||
if isinstance(config.get('tag_files'), list):
|
||||
config['tag_files'] = _strip_rows(config['tag_files'], 2)
|
||||
if isinstance(config.get('tag_zims'), list):
|
||||
config['tag_zims'] = _strip_rows(config['tag_zims'], 3)
|
||||
return config
|
||||
|
||||
|
||||
def strip_tag_names_in_configs(colors: dict):
|
||||
config_directory = get_media_directory() / 'config'
|
||||
for file_name in CONFIG_FILES:
|
||||
file = config_directory / file_name
|
||||
if not file.is_file():
|
||||
continue
|
||||
try:
|
||||
with file.open('rt') as fh:
|
||||
config = yaml.load(fh, Loader=yaml.CSafeLoader)
|
||||
except Exception as e:
|
||||
logger.error(f'Cannot strip Tag names of invalid config: {file}', exc_info=e)
|
||||
continue
|
||||
if not isinstance(config, dict):
|
||||
continue
|
||||
stripped = _strip_tags_config(config, colors) if file_name == 'tags.yaml' else config
|
||||
stripped = _strip_nested(stripped)
|
||||
if stripped != config:
|
||||
logger.warning(f'Stripping whitespace from Tag names in {file}')
|
||||
write_config_data(stripped, file, width=500 if file_name == 'tags.yaml' else 90)
|
||||
|
||||
|
||||
def strip_tag_names_in_db(connection) -> dict:
|
||||
"""Returns the color of each renamed Tag, by its new name."""
|
||||
groups, colors = dict(), dict()
|
||||
for id_, name, color in connection.exec_driver_sql('SELECT id, name, color FROM tag ORDER BY id').fetchall():
|
||||
groups.setdefault(_strip(name), list()).append((id_, name, color))
|
||||
|
||||
for stripped, tags in groups.items():
|
||||
if all(name == stripped for _, name, _ in tags):
|
||||
continue
|
||||
# Keep the Tag already named this, if any, otherwise the oldest.
|
||||
survivor_id = next((id_ for id_, name, _ in tags if name == stripped), tags[0][0])
|
||||
color = colors[stripped] = next((color for _, _, color in tags if color), None)
|
||||
for id_, name, _ in tags:
|
||||
if id_ == survivor_id:
|
||||
continue
|
||||
logger.warning(f'Merging Tag {name!r} into {stripped!r}')
|
||||
connection.exec_driver_sql(
|
||||
'INSERT OR IGNORE INTO tag_file (tag_id, file_group_id, created_at)'
|
||||
' SELECT ?, file_group_id, created_at FROM tag_file WHERE tag_id = ?', (survivor_id, id_))
|
||||
connection.exec_driver_sql(
|
||||
'INSERT OR IGNORE INTO tag_zim (tag_id, zim_id, zim_entry, created_at)'
|
||||
' SELECT ?, zim_id, zim_entry, created_at FROM tag_zim WHERE tag_id = ?', (survivor_id, id_))
|
||||
connection.exec_driver_sql('DELETE FROM tag_file WHERE tag_id = ?', (id_,))
|
||||
connection.exec_driver_sql('DELETE FROM tag_zim WHERE tag_id = ?', (id_,))
|
||||
connection.exec_driver_sql('UPDATE collection SET tag_id = ? WHERE tag_id = ?', (survivor_id, id_))
|
||||
connection.exec_driver_sql('DELETE FROM tag WHERE id = ?', (id_,))
|
||||
logger.warning(f'Renaming Tag to {stripped!r}')
|
||||
connection.exec_driver_sql('UPDATE tag SET name = ?, color = ? WHERE id = ?', (stripped, color, survivor_id))
|
||||
|
||||
# The Downloads which apply them (download_manager.yaml is stripped the same way).
|
||||
downloads = connection.exec_driver_sql(
|
||||
'SELECT id, tag_names, settings FROM download WHERE tag_names IS NOT NULL OR settings IS NOT NULL').fetchall()
|
||||
for id_, tag_names, settings in downloads:
|
||||
tag_names, settings = json.loads(tag_names) if tag_names else None, json.loads(settings) if settings else None
|
||||
new_tag_names = _strip_names(tag_names) if isinstance(tag_names, list) else tag_names
|
||||
new_settings = _strip_nested(settings)
|
||||
if new_tag_names != tag_names or new_settings != settings:
|
||||
connection.exec_driver_sql(
|
||||
'UPDATE download SET tag_names = ?, settings = ? WHERE id = ?',
|
||||
(json.dumps(new_tag_names) if new_tag_names is not None else None,
|
||||
json.dumps(new_settings) if new_settings is not None else None, id_))
|
||||
return colors
|
||||
|
||||
|
||||
def upgrade():
|
||||
colors = strip_tag_names_in_db(op.get_bind())
|
||||
strip_tag_names_in_configs(colors)
|
||||
|
||||
|
||||
def downgrade():
|
||||
# Whitespace that was stripped is not restored.
|
||||
pass
|
||||
|
|
@ -1,24 +0,0 @@
|
|||
"""A partial index of the unindexed FileGroups.
|
||||
|
||||
The modelers and indexers look up `file_group WHERE indexed != 1` (and count it for progress) on every
|
||||
refresh. SQLite cannot use an index on `indexed` for `!=`, so each lookup read every file_group row; on a
|
||||
large library from a cold disk cache that was close to a minute. This index holds only the unindexed rows.
|
||||
|
||||
Revision ID: 2026_10_30_1200
|
||||
Revises: 2026_10_25_1200
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2026_10_30_1200'
|
||||
down_revision = '2026_10_25_1200'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.execute('CREATE INDEX IF NOT EXISTS file_group_unindexed_idx ON file_group (id) WHERE "indexed" != 1')
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.execute('DROP INDEX IF EXISTS file_group_unindexed_idx')
|
||||
|
|
@ -1,31 +0,0 @@
|
|||
"""Cover a Channel's Videos with indexes: video (channel_id, file_group_id) and
|
||||
file_group (id, published_datetime, size, length).
|
||||
|
||||
A Channel's statistics find its Videos' FileGroups and sum their sizes and lengths, and a Video's neighbors are
|
||||
found by the published dates of its Channel's Videos. Reading those video and file_group rows is a scattered page
|
||||
per Video; a Channel with thousands of Videos took seconds from a cold disk cache. The video index replaces
|
||||
video_channel_id_idx, whose lookups it also serves.
|
||||
|
||||
Revision ID: 2026_12_01_1200
|
||||
Revises: 2026_10_30_1200
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2026_12_01_1200'
|
||||
down_revision = '2026_10_30_1200'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.execute('CREATE INDEX IF NOT EXISTS video_channel_file_group_idx ON video (channel_id, file_group_id)')
|
||||
op.execute('DROP INDEX IF EXISTS video_channel_id_idx')
|
||||
op.execute('CREATE INDEX IF NOT EXISTS file_group_published_size_length_idx'
|
||||
' ON file_group (id, published_datetime, size, length)')
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.execute('CREATE INDEX IF NOT EXISTS video_channel_id_idx ON video (channel_id)')
|
||||
op.execute('DROP INDEX IF EXISTS video_channel_file_group_idx')
|
||||
op.execute('DROP INDEX IF EXISTS file_group_published_size_length_idx')
|
||||
|
|
@ -1,26 +0,0 @@
|
|||
"""Add minimum_frequency and url to channel_collection_summary_idx so it covers the Channel list.
|
||||
|
||||
A channel row stores its yt-dlp info_json (up to megabytes). The Channel list read every channel row; from
|
||||
a cold disk cache that was seconds even when only the start of each row was read.
|
||||
|
||||
Revision ID: 2026_12_01_1300
|
||||
Revises: 2026_12_01_1200
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2026_12_01_1300'
|
||||
down_revision = '2026_12_01_1200'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.execute('DROP INDEX IF EXISTS channel_collection_summary_idx')
|
||||
op.execute('CREATE INDEX channel_collection_summary_idx'
|
||||
' ON channel (collection_id, video_count, total_size, minimum_frequency, url)')
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.execute('DROP INDEX IF EXISTS channel_collection_summary_idx')
|
||||
op.execute('CREATE INDEX channel_collection_summary_idx ON channel (collection_id, video_count, total_size)')
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
"""make_filegroup_directory_not_null
|
||||
|
||||
Revision ID: 26c5a62ec683
|
||||
Revises: af4527503bdf
|
||||
Create Date: 2025-12-23 20:47:11.549264
|
||||
|
||||
This migration makes the `directory` column NOT NULL after the previous migration
|
||||
has populated it for all existing FileGroups.
|
||||
"""
|
||||
import os
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '26c5a62ec683'
|
||||
down_revision = 'af4527503bdf'
|
||||
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)
|
||||
|
||||
# Safety check: ensure no NULL directory values remain
|
||||
result = session.execute(sa.text(
|
||||
"SELECT COUNT(*) FROM file_group WHERE directory IS NULL"
|
||||
))
|
||||
null_count = result.scalar()
|
||||
if null_count > 0:
|
||||
# Fill any remaining NULL values (shouldn't happen if previous migration ran)
|
||||
print(f"Warning: Found {null_count} FileGroups with NULL directory, filling from primary_path...")
|
||||
session.execute(sa.text("""
|
||||
UPDATE file_group
|
||||
SET directory = regexp_replace(primary_path, '/[^/]+$', '')
|
||||
WHERE directory IS NULL AND primary_path IS NOT NULL
|
||||
"""))
|
||||
session.commit()
|
||||
|
||||
# Make the column NOT NULL
|
||||
op.alter_column('file_group', 'directory', nullable=False)
|
||||
|
||||
# Create index on directory column for efficient directory lookups
|
||||
op.create_index('file_group_directory_idx', 'file_group', ['directory'])
|
||||
|
||||
if not DOCKERIZED:
|
||||
session.execute(sa.text('ALTER TABLE public.file_group OWNER TO wrolpi'))
|
||||
|
||||
|
||||
def downgrade():
|
||||
# Drop the index
|
||||
op.drop_index('file_group_directory_idx', 'file_group')
|
||||
# Make the column nullable again
|
||||
op.alter_column('file_group', 'directory', nullable=True)
|
||||
137
alembic/versions/2bfb3b50b178_tag_names_migration.py
Normal file
137
alembic/versions/2bfb3b50b178_tag_names_migration.py
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
"""MTag names migration
|
||||
|
||||
Revision ID: 2bfb3b50b178
|
||||
Revises: 8d0d81bc9c34
|
||||
Create Date: 2024-07-31 14:58:29.583029
|
||||
|
||||
"""
|
||||
import os
|
||||
import pathlib
|
||||
from datetime import datetime
|
||||
|
||||
import yaml
|
||||
from alembic import op
|
||||
from sqlalchemy import Column, Integer, BigInteger, ForeignKey, Text, String
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.orm.exc import NoResultFound # noqa
|
||||
|
||||
from wrolpi import dates
|
||||
from wrolpi.common import escape_file_name, get_media_directory, ModelHelper
|
||||
from wrolpi.common import get_relative_to_media_directory
|
||||
from wrolpi.dates import TZDateTime
|
||||
from wrolpi.tags import get_tags_config
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2bfb3b50b178'
|
||||
down_revision = '8d0d81bc9c34'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
class MFileGroup(ModelHelper, Base):
|
||||
__tablename__ = 'file_group'
|
||||
id: int = Column(BigInteger, primary_key=True)
|
||||
primary_path: pathlib.Path = Column(String, unique=True, nullable=False)
|
||||
|
||||
|
||||
class MTagFile(ModelHelper, Base):
|
||||
__tablename__ = 'tag_file'
|
||||
tag_id = Column(Integer, ForeignKey('tag.id', ondelete='CASCADE'), primary_key=True)
|
||||
file_group_id = Column(BigInteger, ForeignKey('file_group.id', ondelete='CASCADE'), primary_key=True)
|
||||
|
||||
|
||||
class MTag(ModelHelper, Base):
|
||||
__tablename__ = 'tag'
|
||||
id = Column(Integer, primary_key=True)
|
||||
name = Column(String, unique=True, nullable=False)
|
||||
color = Column(String)
|
||||
|
||||
|
||||
class MZim(Base):
|
||||
__tablename__ = 'zim'
|
||||
id = Column(Integer, primary_key=True)
|
||||
path: pathlib.Path = Column(String, unique=True, nullable=False)
|
||||
|
||||
|
||||
class MTagZimEntry(Base):
|
||||
__tablename__ = 'tag_zim'
|
||||
tag_id = Column(Integer, ForeignKey('tag.id', ondelete='CASCADE'), primary_key=True)
|
||||
zim_id = Column(Integer, ForeignKey('zim.id', ondelete='CASCADE'), primary_key=True)
|
||||
zim_entry: str = Column(Text, nullable=False, primary_key=True)
|
||||
created_at: datetime = Column(TZDateTime, default=dates.now)
|
||||
|
||||
|
||||
def save_tags(session: Session):
|
||||
media_directory = get_media_directory()
|
||||
|
||||
tags = dict()
|
||||
tag_rows = session.query(MTag)
|
||||
for tag in tag_rows:
|
||||
tags[tag.name] = dict(color=tag.color)
|
||||
|
||||
results = session.query(MTag, MTagFile, MFileGroup) \
|
||||
.filter(MTagFile.tag_id == MTag.id, MTagFile.file_group_id == MFileGroup.id) \
|
||||
.order_by(MFileGroup.primary_path)
|
||||
|
||||
tag_files = []
|
||||
for tag, tag_file, file_group in results:
|
||||
value = [
|
||||
tag.name,
|
||||
str(file_group.primary_path.relative_to(media_directory)),
|
||||
# Fallback to current time if not set.
|
||||
tag_file.created_at.isoformat() if tag_file.created_at else dates.now().isoformat(),
|
||||
]
|
||||
tag_files.append(value)
|
||||
|
||||
results = session.query(MTag, MZim, MTagZimEntry) \
|
||||
.filter(MTag.id == MTagZimEntry.tag_id, MZim.id == MTagZimEntry.zim_id) \
|
||||
.order_by(MTagZimEntry.zim_id, MTagZimEntry.zim_entry)
|
||||
|
||||
tag_zims = []
|
||||
for tag, zim, tag_zim_entry in results:
|
||||
zim: MZim
|
||||
tag_zim_entry: MTagZimEntry
|
||||
value = [
|
||||
tag.name,
|
||||
str(get_relative_to_media_directory(zim.path)),
|
||||
tag_zim_entry.zim_entry,
|
||||
# Fallback to current time if not set.
|
||||
tag_zim_entry.created_at.isoformat() if tag_zim_entry.created_at else dates.now().isoformat(),
|
||||
]
|
||||
tag_zims.append(value)
|
||||
|
||||
# Write to the config.
|
||||
with get_tags_config().get_file().open('wt') as fh:
|
||||
data = {
|
||||
'tag_files': tag_files,
|
||||
'tag_zims': tag_zims,
|
||||
'tags': tags,
|
||||
}
|
||||
yaml.dump(data, fh)
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
need_commit = False
|
||||
tags = session.query(MTag).all()
|
||||
for tag in tags:
|
||||
escaped_name = escape_file_name(tag.name)
|
||||
if escaped_name != tag.name:
|
||||
tag.name = escaped_name
|
||||
session.flush([tag, ])
|
||||
need_commit = True
|
||||
|
||||
if need_commit:
|
||||
session.commit()
|
||||
save_tags(session)
|
||||
|
||||
|
||||
def downgrade():
|
||||
pass
|
||||
40
alembic/versions/2fb39c1861c7_create_mapfile_table.py
Normal file
40
alembic/versions/2fb39c1861c7_create_mapfile_table.py
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
"""Create MapFile table.
|
||||
|
||||
Revision ID: 2fb39c1861c7
|
||||
Revises: 36cae041ad31
|
||||
Create Date: 2022-03-03 19:13:39.997580
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2fb39c1861c7'
|
||||
down_revision = '36cae041ad31'
|
||||
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)
|
||||
|
||||
session.execute('''CREATE TABLE map_file (
|
||||
id SERIAL PRIMARY KEY,
|
||||
path TEXT NOT NULL,
|
||||
imported BOOLEAN DEFAULT FALSE,
|
||||
size BIGINT
|
||||
)''')
|
||||
|
||||
if not DOCKERIZED:
|
||||
session.execute('ALTER TABLE public.map_file OWNER TO wrolpi')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
session.execute('DROP TABLE IF EXISTS map_file')
|
||||
42
alembic/versions/31896cc29b71_archive_contents_search.py
Normal file
42
alembic/versions/31896cc29b71_archive_contents_search.py
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
"""Archive contents search.
|
||||
|
||||
Revision ID: 31896cc29b71
|
||||
Revises: bddb5e95a91e
|
||||
Create Date: 2021-12-31 18:53:25.326674
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '31896cc29b71'
|
||||
down_revision = 'bddb5e95a91e'
|
||||
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)
|
||||
session.execute('ALTER TABLE archive ADD COLUMN contents TEXT')
|
||||
session.execute('''
|
||||
ALTER TABLE archive
|
||||
ADD COLUMN textsearch tsvector
|
||||
GENERATED ALWAYS AS (
|
||||
setweight(to_tsvector('english'::regconfig, title), 'A') ||
|
||||
setweight(to_tsvector('english'::regconfig, contents), 'D')
|
||||
) STORED
|
||||
''')
|
||||
session.execute('CREATE INDEX IF NOT EXISTS archive_textsearch_idx ON archive USING GIN(textsearch)')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
session.execute('DROP INDEX IF EXISTS archive_textsearch_idx')
|
||||
session.execute('ALTER TABLE archive DROP COLUMN IF EXISTS contents')
|
||||
session.execute('ALTER TABLE archive DROP COLUMN IF EXISTS textsearch')
|
||||
33
alembic/versions/32d96eb9122d_video_censored.py
Normal file
33
alembic/versions/32d96eb9122d_video_censored.py
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
"""Video censored
|
||||
|
||||
Revision ID: 32d96eb9122d
|
||||
Revises: 184329ed5137
|
||||
Create Date: 2021-12-23 14:03:53.677547
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '32d96eb9122d'
|
||||
down_revision = '184329ed5137'
|
||||
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)
|
||||
session.execute('ALTER TABLE video ADD COLUMN censored BOOL DEFAULT false')
|
||||
session.execute('CREATE INDEX video_censored ON video (censored)')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
session.execute('ALTER TABLE video DROP COLUMN IF EXISTS censored')
|
||||
session.execute('DROP INDEX IF EXISTS video_censored')
|
||||
49
alembic/versions/365c985893b8_ebook_creator.py
Normal file
49
alembic/versions/365c985893b8_ebook_creator.py
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
"""eBook creator.
|
||||
|
||||
Revision ID: 365c985893b8
|
||||
Revises: 5ad9efbf3570
|
||||
Create Date: 2023-10-29 16:54:28.319427
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '365c985893b8'
|
||||
down_revision = '5ad9efbf3570'
|
||||
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)
|
||||
|
||||
session.execute('''
|
||||
UPDATE file_group
|
||||
SET author=creator
|
||||
FROM ebook
|
||||
WHERE ebook.file_group_id = file_group.id
|
||||
''')
|
||||
session.execute('DROP INDEX IF EXISTS ebook_creator_idx')
|
||||
session.execute('ALTER TABLE ebook DROP COLUMN IF EXISTS creator')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('ALTER TABLE ebook ADD COLUMN IF NOT EXISTS creator TEXT')
|
||||
session.execute('''
|
||||
UPDATE ebook
|
||||
SET creator=author
|
||||
FROM file_group
|
||||
WHERE
|
||||
ebook.file_group_id = file_group.id
|
||||
AND model = 'ebook'
|
||||
''')
|
||||
session.execute('CREATE INDEX IF NOT EXISTS ebook_creator_idx ON ebook(creator)')
|
||||
53
alembic/versions/36cae041ad31_files.py
Normal file
53
alembic/versions/36cae041ad31_files.py
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
"""Files
|
||||
|
||||
Revision ID: 36cae041ad31
|
||||
Revises: b97c1313f986
|
||||
Create Date: 2022-02-01 11:05:57.605541
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '36cae041ad31'
|
||||
down_revision = 'b97c1313f986'
|
||||
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)
|
||||
|
||||
session.execute('''CREATE TABLE file (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
path TEXT NOT NULL,
|
||||
title TEXT,
|
||||
mimetype TEXT,
|
||||
size INTEGER,
|
||||
modification_datetime TIMESTAMPTZ,
|
||||
textsearch tsvector GENERATED ALWAYS AS (
|
||||
setweight(to_tsvector('english'::regconfig, title), 'A'::"char")
|
||||
) stored,
|
||||
idempotency TEXT
|
||||
)''')
|
||||
session.execute('CREATE INDEX file_path_idx ON file(path)')
|
||||
session.execute('CREATE INDEX file_mimetype_idx ON file(textsearch)')
|
||||
session.execute('CREATE INDEX file_textsearch_idx ON file(textsearch)')
|
||||
if not DOCKERIZED:
|
||||
session.execute('ALTER TABLE public.file OWNER TO wrolpi')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('DROP INDEX IF EXISTS file_textsearch_idx')
|
||||
session.execute('DROP INDEX IF EXISTS file_mimetype_idx')
|
||||
session.execute('DROP INDEX IF EXISTS file_path_idx')
|
||||
|
||||
session.execute('DROP TABLE IF EXISTS file')
|
||||
242
alembic/versions/3b6918aeca4b_file_group.py
Normal file
242
alembic/versions/3b6918aeca4b_file_group.py
Normal file
|
|
@ -0,0 +1,242 @@
|
|||
"""File group.
|
||||
|
||||
Revision ID: 3b6918aeca4b
|
||||
Revises: 930b9b7adb79
|
||||
Create Date: 2023-02-27 14:52:46.943351
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '3b6918aeca4b'
|
||||
down_revision = '930b9b7adb79'
|
||||
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)
|
||||
|
||||
session.execute('DELETE FROM video') # noqa
|
||||
session.execute('ALTER TABLE video DROP COLUMN caption_path')
|
||||
session.execute('ALTER TABLE video DROP COLUMN censored')
|
||||
session.execute('ALTER TABLE video DROP COLUMN favorite')
|
||||
session.execute('ALTER TABLE video DROP COLUMN info_json_path')
|
||||
session.execute('ALTER TABLE video DROP COLUMN modification_datetime')
|
||||
session.execute('ALTER TABLE video DROP COLUMN poster_path')
|
||||
session.execute('ALTER TABLE video DROP COLUMN size')
|
||||
session.execute('ALTER TABLE video DROP COLUMN title')
|
||||
session.execute('ALTER TABLE video DROP COLUMN validated')
|
||||
session.execute('ALTER TABLE video DROP COLUMN video_path')
|
||||
|
||||
session.execute('DELETE FROM archive') # noqa
|
||||
session.execute('ALTER TABLE archive DROP COLUMN readability_json_path')
|
||||
session.execute('ALTER TABLE archive DROP COLUMN readability_path')
|
||||
session.execute('ALTER TABLE archive DROP COLUMN readability_txt_path')
|
||||
session.execute('ALTER TABLE archive DROP COLUMN screenshot_path')
|
||||
session.execute('ALTER TABLE archive DROP COLUMN singlefile_path')
|
||||
session.execute('ALTER TABLE archive DROP COLUMN title')
|
||||
session.execute('ALTER TABLE archive DROP COLUMN validated')
|
||||
|
||||
session.execute('DELETE FROM ebook') # noqa
|
||||
session.execute('ALTER TABLE ebook DROP COLUMN cover_path')
|
||||
session.execute('ALTER TABLE ebook DROP COLUMN ebook_path')
|
||||
session.execute('ALTER TABLE ebook DROP COLUMN title')
|
||||
|
||||
session.execute('DROP TABLE IF EXISTS file')
|
||||
|
||||
session.execute('''
|
||||
CREATE TABLE file_group (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
data JSON,
|
||||
files JSON,
|
||||
idempotency TIMESTAMP WITH TIME ZONE,
|
||||
indexed BOOLEAN DEFAULT FALSE,
|
||||
mimetype TEXT NOT NULL,
|
||||
model TEXT,
|
||||
modification_datetime TIMESTAMP WITH TIME ZONE,
|
||||
primary_path TEXT NOT NULL UNIQUE,
|
||||
size BIGINT,
|
||||
title TEXT,
|
||||
a_text TEXT,
|
||||
b_text TEXT,
|
||||
c_text TEXT,
|
||||
d_text TEXT,
|
||||
textsearch tsvector GENERATED ALWAYS AS (
|
||||
setweight(to_tsvector('english'::regconfig, COALESCE(a_text, '')), 'A'::"char") ||
|
||||
setweight(to_tsvector('english'::regconfig, COALESCE(b_text, '')), 'B'::"char") ||
|
||||
setweight(to_tsvector('english'::regconfig, COALESCE(c_text, '')), 'C'::"char") ||
|
||||
setweight(to_tsvector('english'::regconfig, COALESCE(d_text, '')), 'D'::"char")
|
||||
) STORED
|
||||
)''')
|
||||
|
||||
session.execute(
|
||||
'ALTER TABLE video ADD COLUMN file_group_id BIGINT REFERENCES file_group(id) ON DELETE CASCADE NOT NULL UNIQUE')
|
||||
session.execute(
|
||||
'ALTER TABLE ebook ADD COLUMN file_group_id BIGINT REFERENCES file_group(id) ON DELETE CASCADE NOT NULL UNIQUE')
|
||||
session.execute(
|
||||
'ALTER TABLE archive ADD COLUMN file_group_id BIGINT REFERENCES file_group(id) ON DELETE CASCADE NOT NULL UNIQUE')
|
||||
|
||||
session.execute('''
|
||||
CREATE TABLE tag (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
color VARCHAR(7)
|
||||
)''')
|
||||
|
||||
session.execute('''
|
||||
CREATE TABLE tag_file (
|
||||
tag_id INTEGER REFERENCES tag(id),
|
||||
file_group_id BIGINT REFERENCES file_group(id) ON DELETE CASCADE,
|
||||
created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE (tag_id, file_group_id)
|
||||
)''')
|
||||
|
||||
session.execute('''
|
||||
INSERT INTO tag (name, color) VALUES
|
||||
('Automotive', '#353535'),
|
||||
('Clothing', '#9858C5'),
|
||||
('Comms', '#ECD71C'),
|
||||
('Cooking', '#00A04A'),
|
||||
('Electronics', '#1b731f'),
|
||||
('Entertainment', '#981473'),
|
||||
('Favorite', '#000000'),
|
||||
('Fire Safety', '#d16711'),
|
||||
('Firearms', '#6c6c6c'),
|
||||
('First Aid', '#C40405'),
|
||||
('Food Preservation', '#676816'),
|
||||
('Food', '#2F8055'),
|
||||
('Fuel', '#c47fb3'),
|
||||
('Garden', '#3E8B22'),
|
||||
('Heating', '#ff5400'),
|
||||
('Husbandry','#B58039'),
|
||||
('Hygiene', '#adadad'),
|
||||
('Knots', '#9d6a4c'),
|
||||
('Light', '#EEEEEE'),
|
||||
('Mechanical', '#7A7A7A'),
|
||||
('Medical', '#4a869c'),
|
||||
('Navigation', '#1ab3ce'),
|
||||
('Nuclear', '#0dff00'),
|
||||
('Pests', '#050068'),
|
||||
('Power', '#D837FF'),
|
||||
('Primitive', '#A18A62'),
|
||||
('Radio', '#134cbb'),
|
||||
('Schooling', '#6d752e'),
|
||||
('Security', '#333333'),
|
||||
('Shelter', '#625641'),
|
||||
('Social', '#490c73'),
|
||||
('Tools', '#f0d730'),
|
||||
('WROL', '#4700ab'),
|
||||
('Water', '#291BC2')
|
||||
''')
|
||||
|
||||
session.execute('UPDATE wrolpi_flag SET refresh_complete = false')
|
||||
|
||||
if not DOCKERIZED:
|
||||
session.execute('ALTER TABLE public.file_group OWNER TO wrolpi')
|
||||
session.execute('ALTER TABLE public.tag OWNER TO wrolpi')
|
||||
session.execute('ALTER TABLE public.tag_file OWNER TO wrolpi')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('DROP TABLE IF EXISTS tag_file')
|
||||
session.execute('DROP TABLE IF EXISTS tag')
|
||||
|
||||
session.execute('ALTER TABLE video DROP COLUMN file_group_id')
|
||||
session.execute('ALTER TABLE ebook DROP COLUMN file_group_id')
|
||||
session.execute('ALTER TABLE archive DROP COLUMN file_group_id')
|
||||
|
||||
session.execute('DROP TABLE file_group')
|
||||
|
||||
session.execute('''
|
||||
create table file
|
||||
(
|
||||
path text not null primary key,
|
||||
idempotency timestamp with time zone,
|
||||
indexed boolean default false,
|
||||
mimetype text,
|
||||
suffix text,
|
||||
model text,
|
||||
associated boolean default false,
|
||||
modification_datetime timestamp with time zone,
|
||||
size bigint,
|
||||
title text,
|
||||
a_text text,
|
||||
b_text text,
|
||||
c_text text,
|
||||
d_text text,
|
||||
textsearch tsvector generated always as ((
|
||||
((setweight(to_tsvector('english'::regconfig, COALESCE(a_text, ''::text)), 'A'::"char") ||
|
||||
setweight(to_tsvector('english'::regconfig, COALESCE(b_text, ''::text)), 'B'::"char")) ||
|
||||
setweight(to_tsvector('english'::regconfig, COALESCE(c_text, ''::text)), 'C'::"char")) ||
|
||||
setweight(to_tsvector('english'::regconfig, COALESCE(d_text, ''::text)), 'D'::"char"))) stored,
|
||||
full_stem text
|
||||
);
|
||||
|
||||
alter table file
|
||||
owner to postgres;
|
||||
|
||||
create index file_mimetype_idx
|
||||
on file (mimetype);
|
||||
|
||||
create index file_textsearch_idx
|
||||
on file using gin (textsearch);
|
||||
|
||||
create index file_modification_datetime_idx
|
||||
on file (modification_datetime);
|
||||
|
||||
create index file_size_idx
|
||||
on file (size);
|
||||
|
||||
create index file_model_idx
|
||||
on file (model);
|
||||
|
||||
create index file_idempotency_idx
|
||||
on file (idempotency);
|
||||
|
||||
create index file_suffix_idx
|
||||
on file (suffix);
|
||||
|
||||
create index file_full_stem_idx
|
||||
on file (full_stem);
|
||||
''')
|
||||
|
||||
session.execute('DELETE FROM video') # noqa
|
||||
session.execute('ALTER TABLE video ADD COLUMN caption_path TEXT REFERENCES file(path)')
|
||||
session.execute('ALTER TABLE video ADD COLUMN censored BOOLEAN DEFAULT FALSE')
|
||||
session.execute('ALTER TABLE video ADD COLUMN favorite TIMESTAMPTZ')
|
||||
session.execute('ALTER TABLE video ADD COLUMN info_json_path TEXT REFERENCES file(path)')
|
||||
session.execute('ALTER TABLE video ADD COLUMN poster_path TEXT REFERENCES file(path)')
|
||||
session.execute('ALTER TABLE video ADD COLUMN video_path TEXT REFERENCES file(path)')
|
||||
session.execute('ALTER TABLE video ADD COLUMN modification_datetime TIMESTAMPTZ')
|
||||
session.execute('ALTER TABLE video ADD COLUMN size BIGINT')
|
||||
session.execute('ALTER TABLE video ADD COLUMN title TEXT')
|
||||
session.execute('ALTER TABLE video ADD COLUMN validated BOOLEAN DEFAULT FALSE')
|
||||
|
||||
session.execute('DELETE FROM archive') # noqa
|
||||
session.execute('ALTER TABLE archive ADD COLUMN readability_json_path TEXT REFERENCES file(path)')
|
||||
session.execute('ALTER TABLE archive ADD COLUMN readability_path TEXT REFERENCES file(path)')
|
||||
session.execute('ALTER TABLE archive ADD COLUMN readability_txt_path TEXT REFERENCES file(path)')
|
||||
session.execute('ALTER TABLE archive ADD COLUMN screenshot_path TEXT REFERENCES file(path)')
|
||||
session.execute('ALTER TABLE archive ADD COLUMN singlefile_path TEXT REFERENCES file(path)')
|
||||
session.execute('ALTER TABLE archive ADD COLUMN title TEXT')
|
||||
session.execute('ALTER TABLE archive ADD COLUMN validated BOOLEAN DEFAULT FALSE')
|
||||
|
||||
session.execute('DELETE FROM ebook') # noqa
|
||||
session.execute('ALTER TABLE ebook ADD COLUMN cover_path TEXT REFERENCES file(path)')
|
||||
session.execute('ALTER TABLE ebook ADD COLUMN ebook_path TEXT REFERENCES file(path)')
|
||||
session.execute('ALTER TABLE ebook ADD COLUMN title TEXT')
|
||||
|
||||
session.execute('UPDATE wrolpi_flag SET refresh_complete = false')
|
||||
|
||||
if not DOCKERIZED:
|
||||
session.execute('ALTER TABLE public.file OWNER TO wrolpi')
|
||||
35
alembic/versions/3c33b1dae069_video_validated.py
Normal file
35
alembic/versions/3c33b1dae069_video_validated.py
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
"""Video validated.
|
||||
|
||||
Revision ID: 3c33b1dae069
|
||||
Revises: f2c6326cad29
|
||||
Create Date: 2022-01-13 16:14:23.409242
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '3c33b1dae069'
|
||||
down_revision = 'f2c6326cad29'
|
||||
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)
|
||||
session.execute('ALTER TABLE video ADD COLUMN validated BOOLEAN DEFAULT FALSE')
|
||||
session.execute('ALTER TABLE video DROP COLUMN IF EXISTS validated_poster')
|
||||
# Generating posters is slow, and may delete files.
|
||||
session.execute('ALTER TABLE channel ALTER COLUMN generate_posters SET DEFAULT false')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
session.execute('ALTER TABLE video DROP COLUMN IF EXISTS validated')
|
||||
session.execute('ALTER TABLE video ADD COLUMN validated_poster BOOLEAN DEFAULT FALSE')
|
||||
29
alembic/versions/467235201c70_download_sub_downloader.py
Normal file
29
alembic/versions/467235201c70_download_sub_downloader.py
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
"""Download.sub_downloader.
|
||||
|
||||
Revision ID: 467235201c70
|
||||
Revises: 1a70196c05bb
|
||||
Create Date: 2022-05-20 11:51:58.064020
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '467235201c70'
|
||||
down_revision = '1a70196c05bb'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False
|
||||
|
||||
|
||||
def upgrade():
|
||||
session = Session(bind=op.get_bind())
|
||||
session.execute('ALTER TABLE download ADD COLUMN IF NOT EXISTS sub_downloader TEXT')
|
||||
|
||||
|
||||
def downgrade():
|
||||
session = Session(bind=op.get_bind())
|
||||
session.execute('ALTER TABLE download DROP COLUMN IF EXISTS sub_downloader')
|
||||
32
alembic/versions/4b54ad052e2e_reindex_archives.py
Normal file
32
alembic/versions/4b54ad052e2e_reindex_archives.py
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
"""Reindex archives.
|
||||
|
||||
Revision ID: 4b54ad052e2e
|
||||
Revises: 6b0b249a4f81
|
||||
Create Date: 2023-10-20 13:28:55.517086
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '4b54ad052e2e'
|
||||
down_revision = '6b0b249a4f81'
|
||||
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)
|
||||
|
||||
# Archives must be re-indexed because of the previous revision.
|
||||
session.execute("UPDATE file_group SET indexed=false WHERE model='archive'")
|
||||
session.execute("DELETE FROM archive") # noqa
|
||||
|
||||
|
||||
def downgrade():
|
||||
pass
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
"""Drop Channel.skip_download_videos.
|
||||
|
||||
Revision ID: 4c8da5502c8a
|
||||
Revises: 8bdb48a486b9
|
||||
Create Date: 2023-09-29 14:45:42.999526
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '4c8da5502c8a'
|
||||
down_revision = '8bdb48a486b9'
|
||||
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)
|
||||
session.execute('ALTER TABLE channel DROP COLUMN IF EXISTS skip_download_videos')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
session.execute('ALTER TABLE channel ADD COLUMN IF NOT EXISTS skip_download_videos TEXT[]')
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
"""file_group.effective_date trigger
|
||||
|
||||
Revision ID: 4f03b9548f6e
|
||||
Revises: 54c19aa847da
|
||||
Create Date: 2025-08-17 10:49:35.754548
|
||||
|
||||
"""
|
||||
import os
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '4f03b9548f6e'
|
||||
down_revision = '54c19aa847da'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# Create trigger function
|
||||
op.execute("""
|
||||
CREATE OR REPLACE FUNCTION update_effective_datetime()
|
||||
RETURNS TRIGGER AS
|
||||
$$
|
||||
BEGIN
|
||||
NEW.effective_datetime = COALESCE(NEW.published_datetime, NEW.download_datetime);
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
""")
|
||||
|
||||
# Create trigger
|
||||
op.execute("""
|
||||
CREATE TRIGGER file_group_effective_datetime_trigger
|
||||
BEFORE INSERT OR UPDATE OF published_datetime, download_datetime
|
||||
ON file_group
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION update_effective_datetime();
|
||||
""")
|
||||
|
||||
|
||||
def downgrade():
|
||||
# Drop trigger
|
||||
op.execute("DROP TRIGGER IF EXISTS file_group_effective_datetime_trigger ON file_group")
|
||||
|
||||
# Drop trigger function
|
||||
op.execute("DROP FUNCTION IF EXISTS update_effective_datetime")
|
||||
39
alembic/versions/53f6780aa599_drop_urls.py
Normal file
39
alembic/versions/53f6780aa599_drop_urls.py
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
"""Drop URLs.
|
||||
|
||||
Revision ID: 53f6780aa599
|
||||
Revises: 31896cc29b71
|
||||
Create Date: 2022-01-03 12:25:51.575505
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '53f6780aa599'
|
||||
down_revision = '31896cc29b71'
|
||||
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)
|
||||
|
||||
urls = {i['id']: i['url'] for i in session.execute(text('SELECT id, url FROM url'))}
|
||||
archives = {i['id']: i['url_id'] for i in session.execute(text('SELECT id, url_id FROM archive'))}
|
||||
|
||||
session.execute(text('ALTER TABLE archive ADD COLUMN url TEXT'))
|
||||
|
||||
for archive_id, url_id in archives.items():
|
||||
session.execute(
|
||||
text('UPDATE archive SET url = :url WHERE id = :id'),
|
||||
{'url': urls[url_id], 'id': archive_id}
|
||||
)
|
||||
|
||||
session.execute(text('ALTER TABLE archive DROP COLUMN url_id'))
|
||||
session.execute(text('DROP TABLE url'))
|
||||
145
alembic/versions/54c19aa847da_channel_summary_indexes.py
Normal file
145
alembic/versions/54c19aa847da_channel_summary_indexes.py
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
"""Channel summary columns, triggers and indexes.
|
||||
|
||||
Revision ID: 54c19aa847da
|
||||
Revises: 158973fda20f
|
||||
Create Date: 2025-08-16 11:45:48.190427
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '54c19aa847da'
|
||||
down_revision = '158973fda20f'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# Add columns
|
||||
op.execute("""
|
||||
ALTER TABLE channel
|
||||
ADD COLUMN video_count INTEGER DEFAULT 0 NOT NULL,
|
||||
ADD COLUMN total_size BIGINT DEFAULT 0 NOT NULL,
|
||||
ADD COLUMN minimum_frequency INTEGER;
|
||||
""")
|
||||
|
||||
# Populate columns
|
||||
op.execute("""
|
||||
UPDATE channel
|
||||
SET video_count = (SELECT COUNT(*)
|
||||
FROM video
|
||||
WHERE channel_id = channel.id),
|
||||
total_size = (SELECT COALESCE(SUM(fg.size), 0)::BIGINT
|
||||
FROM video v
|
||||
LEFT JOIN file_group fg ON v.file_group_id = fg.id
|
||||
WHERE v.channel_id = channel.id),
|
||||
minimum_frequency = (SELECT MIN(frequency)
|
||||
FROM download
|
||||
WHERE channel_id = channel.id);
|
||||
""")
|
||||
|
||||
# Create trigger functions
|
||||
op.execute("""
|
||||
CREATE OR REPLACE FUNCTION update_channel_video_count()
|
||||
RETURNS TRIGGER AS
|
||||
$$
|
||||
BEGIN
|
||||
UPDATE channel
|
||||
SET video_count = (SELECT COUNT(*) FROM video WHERE channel_id = NEW.channel_id)
|
||||
WHERE id = NEW.channel_id;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
""")
|
||||
op.execute("""
|
||||
CREATE OR REPLACE FUNCTION update_channel_size()
|
||||
RETURNS TRIGGER AS
|
||||
$$
|
||||
BEGIN
|
||||
UPDATE channel
|
||||
SET total_size = (SELECT COALESCE(SUM(fg.size), 0)::BIGINT
|
||||
FROM video v
|
||||
LEFT JOIN file_group fg ON v.file_group_id = fg.id
|
||||
WHERE v.channel_id = NEW.id)
|
||||
WHERE id = NEW.id;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
""")
|
||||
op.execute("""
|
||||
CREATE OR REPLACE FUNCTION update_channel_minimum_frequency()
|
||||
RETURNS TRIGGER AS
|
||||
$$
|
||||
BEGIN
|
||||
UPDATE channel
|
||||
SET minimum_frequency = (SELECT MIN(frequency) FROM download WHERE channel_id = NEW.channel_id)
|
||||
WHERE id = NEW.channel_id;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
""")
|
||||
|
||||
# Create triggers
|
||||
op.execute("""
|
||||
CREATE TRIGGER video_count_trigger
|
||||
AFTER INSERT OR DELETE
|
||||
ON video
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION update_channel_video_count();
|
||||
""")
|
||||
op.execute("""
|
||||
CREATE TRIGGER video_size_trigger
|
||||
AFTER INSERT OR DELETE
|
||||
ON video
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION update_channel_size();
|
||||
""")
|
||||
op.execute("""
|
||||
CREATE TRIGGER file_group_size_trigger
|
||||
AFTER UPDATE OF size
|
||||
ON file_group
|
||||
FOR EACH ROW
|
||||
WHEN (OLD.size IS DISTINCT FROM NEW.size)
|
||||
EXECUTE FUNCTION update_channel_size();
|
||||
""")
|
||||
op.execute("""
|
||||
CREATE TRIGGER download_frequency_trigger
|
||||
AFTER INSERT OR UPDATE OF frequency OR DELETE
|
||||
ON download
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION update_channel_minimum_frequency();
|
||||
""")
|
||||
|
||||
# Create indexes
|
||||
op.execute("""
|
||||
CREATE INDEX channel_video_count_idx ON channel (video_count);
|
||||
CREATE INDEX channel_total_size_idx ON channel (total_size);
|
||||
CREATE INDEX channel_minimum_frequency_idx ON channel (minimum_frequency);
|
||||
""")
|
||||
|
||||
|
||||
def downgrade():
|
||||
# Drop triggers
|
||||
op.execute("DROP TRIGGER IF EXISTS video_count_trigger ON video;")
|
||||
op.execute("DROP TRIGGER IF EXISTS video_size_trigger ON video;")
|
||||
op.execute("DROP TRIGGER IF EXISTS file_group_size_trigger ON file_group;")
|
||||
op.execute("DROP TRIGGER IF EXISTS download_frequency_trigger ON download;")
|
||||
|
||||
# Drop trigger functions
|
||||
op.execute("DROP FUNCTION IF EXISTS update_channel_video_count;")
|
||||
op.execute("DROP FUNCTION IF EXISTS update_channel_size;")
|
||||
op.execute("DROP FUNCTION IF EXISTS update_channel_minimum_frequency;")
|
||||
|
||||
# Drop indexes
|
||||
op.execute("DROP INDEX IF EXISTS channel_minimum_frequency_idx;")
|
||||
op.execute("DROP INDEX IF EXISTS channel_total_size_idx;")
|
||||
op.execute("DROP INDEX IF EXISTS channel_video_count_idx;")
|
||||
|
||||
# Drop columns
|
||||
op.execute("""
|
||||
ALTER TABLE channel
|
||||
DROP COLUMN IF EXISTS minimum_frequency,
|
||||
DROP COLUMN IF EXISTS total_size,
|
||||
DROP COLUMN IF EXISTS video_count;
|
||||
""")
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
"""add_archive_collection_id_index
|
||||
|
||||
Revision ID: 577e414f1bc4
|
||||
Revises: f38cfe4b5cb2
|
||||
Create Date: 2025-12-07 17:25:27.809843
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '577e414f1bc4'
|
||||
down_revision = 'f38cfe4b5cb2'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# Add index on archive.collection_id to speed up GROUP BY queries
|
||||
# and per-collection lookups. This index was missing and causing
|
||||
# full table scans on the archive table (115k+ rows).
|
||||
op.create_index('idx_archive_collection_id', 'archive', ['collection_id'])
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_index('idx_archive_collection_id', table_name='archive')
|
||||
141
alembic/versions/5ad9efbf3570_filegroup_length.py
Normal file
141
alembic/versions/5ad9efbf3570_filegroup_length.py
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
"""
|
||||
Migrates Video.duration/.url/.viewed/Archive.url to FileGroup.length/.url/.viewed.
|
||||
|
||||
Revision ID: 5ad9efbf3570
|
||||
Revises: 4b54ad052e2e
|
||||
Create Date: 2023-10-24 09:25:33.818373
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '5ad9efbf3570'
|
||||
down_revision = '4b54ad052e2e'
|
||||
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)
|
||||
|
||||
session.execute('ALTER TABLE file_group ADD COLUMN length INT DEFAULT 0')
|
||||
session.execute('''
|
||||
UPDATE file_group
|
||||
SET length=video.duration
|
||||
FROM video
|
||||
WHERE file_group.id = video.file_group_id
|
||||
''')
|
||||
|
||||
# Migrate Archive.url and Video.url to FileGroup.url.
|
||||
session.execute('ALTER TABLE file_group ADD COLUMN url TEXT')
|
||||
session.execute('''
|
||||
UPDATE file_group
|
||||
SET url=archive.url
|
||||
FROM archive
|
||||
WHERE file_group.id = archive.file_group_id
|
||||
''')
|
||||
session.execute('''
|
||||
UPDATE file_group
|
||||
SET url=video.url
|
||||
FROM video
|
||||
WHERE file_group.id = video.file_group_id
|
||||
''')
|
||||
|
||||
# Migrate Archive.archive_datetime to FileGroup.download_datetime.
|
||||
session.execute('ALTER TABLE file_group ADD COLUMN download_datetime TIMESTAMP WITH TIME ZONE')
|
||||
session.execute('''
|
||||
UPDATE file_group
|
||||
SET download_datetime=archive.archive_datetime
|
||||
FROM archive
|
||||
WHERE file_group.id = archive.file_group_id
|
||||
''')
|
||||
|
||||
# Migrate Video.viewed to FileGroup.viewed.
|
||||
session.execute('ALTER TABLE file_group ADD COLUMN viewed TIMESTAMP WITH TIME ZONE')
|
||||
session.execute('''
|
||||
UPDATE file_group
|
||||
SET viewed=video.viewed
|
||||
FROM video
|
||||
WHERE file_group.id = video.file_group_id
|
||||
''')
|
||||
|
||||
session.execute('DROP INDEX IF EXISTS archive_archive_datetime_idx')
|
||||
session.execute('DROP INDEX IF EXISTS archive_url_idx')
|
||||
session.execute('DROP INDEX IF EXISTS video_url_idx')
|
||||
session.execute('DROP INDEX IF EXISTS video_viewed_idx')
|
||||
session.execute('ALTER TABLE archive DROP COLUMN IF EXISTS archive_datetime')
|
||||
session.execute('ALTER TABLE archive DROP COLUMN IF EXISTS url')
|
||||
session.execute('ALTER TABLE video DROP COLUMN IF EXISTS url')
|
||||
session.execute('ALTER TABLE video DROP COLUMN IF EXISTS viewed')
|
||||
|
||||
session.execute('CREATE INDEX file_group_download_datetime_idx ON file_group(download_datetime)')
|
||||
session.execute('CREATE INDEX file_group_length_idx ON file_group(length)')
|
||||
session.execute('CREATE INDEX file_group_url_idx ON file_group(url)')
|
||||
session.execute('CREATE INDEX file_group_viewed_idx ON file_group(viewed)')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('ALTER TABLE video ADD COLUMN IF NOT EXISTS duration INTEGER')
|
||||
session.execute('''
|
||||
UPDATE video
|
||||
SET duration=file_group.length
|
||||
FROM file_group
|
||||
WHERE file_group.id = video.file_group_id
|
||||
''')
|
||||
|
||||
session.execute('ALTER TABLE video ADD COLUMN IF NOT EXISTS url TEXT')
|
||||
session.execute('''
|
||||
UPDATE video
|
||||
SET url=file_group.url
|
||||
FROM file_group
|
||||
WHERE file_group.id = video.file_group_id
|
||||
''')
|
||||
|
||||
# Video has `viewed`, Archive does not.
|
||||
session.execute('ALTER TABLE video ADD COLUMN IF NOT EXISTS viewed TIMESTAMP WITH TIME ZONE')
|
||||
session.execute('''
|
||||
UPDATE video
|
||||
SET url=file_group.url
|
||||
FROM file_group
|
||||
WHERE file_group.id = video.file_group_id
|
||||
''')
|
||||
|
||||
session.execute('ALTER TABLE archive ADD COLUMN IF NOT EXISTS url TEXT')
|
||||
session.execute('''
|
||||
UPDATE archive
|
||||
SET url=file_group.url
|
||||
FROM file_group
|
||||
WHERE file_group.id = archive.file_group_id
|
||||
''')
|
||||
|
||||
session.execute('ALTER TABLE archive ADD COLUMN IF NOT EXISTS archive_datetime TIMESTAMP WITH TIME ZONE')
|
||||
session.execute('''
|
||||
UPDATE archive
|
||||
SET archive_datetime=file_group.download_datetime
|
||||
FROM file_group
|
||||
WHERE file_group.id = archive.file_group_id
|
||||
''')
|
||||
|
||||
session.execute('ALTER TABLE file_group DROP COLUMN IF EXISTS download_datetime')
|
||||
session.execute('ALTER TABLE file_group DROP COLUMN IF EXISTS length')
|
||||
session.execute('ALTER TABLE file_group DROP COLUMN IF EXISTS url')
|
||||
session.execute('ALTER TABLE file_group DROP COLUMN IF EXISTS viewed')
|
||||
session.execute('DROP INDEX IF EXISTS file_group_download_datetime_idx')
|
||||
session.execute('DROP INDEX IF EXISTS file_group_length_idx')
|
||||
session.execute('DROP INDEX IF EXISTS file_group_url_idx')
|
||||
session.execute('DROP INDEX IF EXISTS file_group_viewed_idx')
|
||||
|
||||
session.execute('CREATE INDEX IF NOT EXISTS archive_archive_datetime_idx ON archive(archive_datetime)')
|
||||
session.execute('CREATE INDEX IF NOT EXISTS archive_url_idx ON archive(url)')
|
||||
session.execute('CREATE INDEX IF NOT EXISTS video_duration_idx ON video(duration)')
|
||||
session.execute('CREATE INDEX IF NOT EXISTS video_url_idx ON video(url)')
|
||||
session.execute('CREATE INDEX IF NOT EXISTS video_viewed_idx ON video(viewed)')
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
"""Archive textsearch coalesce fix.
|
||||
|
||||
Revision ID: 62acddc55091
|
||||
Revises: 0400005fe2dc
|
||||
Create Date: 2022-01-04 11:11:29.100317
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '62acddc55091'
|
||||
down_revision = '0400005fe2dc'
|
||||
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)
|
||||
session.execute('DROP INDEX IF EXISTS archive_textsearch_idx')
|
||||
session.execute('ALTER TABLE archive DROP COLUMN IF EXISTS textsearch')
|
||||
session.execute('''
|
||||
ALTER TABLE archive
|
||||
ADD COLUMN textsearch tsvector
|
||||
GENERATED ALWAYS AS (
|
||||
setweight(to_tsvector('english'::regconfig, COALESCE(title, '')), 'A') ||
|
||||
setweight(to_tsvector('english'::regconfig, COALESCE(contents, '')), 'D')
|
||||
) STORED
|
||||
''')
|
||||
session.execute('CREATE INDEX archive_textsearch_idx ON archive USING GIN(textsearch)')
|
||||
|
||||
|
||||
def downgrade():
|
||||
# The upgrade is backwards compatible.
|
||||
pass
|
||||
43
alembic/versions/6489cd50c889_file_stem_and_directory.py
Normal file
43
alembic/versions/6489cd50c889_file_stem_and_directory.py
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
"""File stem and directory
|
||||
|
||||
Revision ID: 6489cd50c889
|
||||
Revises: 13542a230c78
|
||||
Create Date: 2022-12-04 15:39:55.485355
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '6489cd50c889'
|
||||
down_revision = '13542a230c78'
|
||||
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)
|
||||
|
||||
session.execute('ALTER TABLE file ADD COLUMN directory TEXT')
|
||||
session.execute('ALTER TABLE file ADD COLUMN full_stem TEXT')
|
||||
session.execute('ALTER TABLE file ADD COLUMN stem TEXT')
|
||||
session.execute('CREATE INDEX file_directory_idx ON file(directory)')
|
||||
session.execute('CREATE INDEX file_full_stem_idx ON file(full_stem)')
|
||||
session.execute('CREATE INDEX file_stem_idx ON file(stem)')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('DROP INDEX IF EXISTS file_directory_idx')
|
||||
session.execute('DROP INDEX IF EXISTS file_full_stem_idx')
|
||||
session.execute('DROP INDEX IF EXISTS file_stem_idx')
|
||||
session.execute('ALTER TABLE file DROP COLUMN IF EXISTS directory')
|
||||
session.execute('ALTER TABLE file DROP COLUMN IF EXISTS full_stem')
|
||||
session.execute('ALTER TABLE file DROP COLUMN IF EXISTS stem')
|
||||
87
alembic/versions/66407d145b76_.py
Normal file
87
alembic/versions/66407d145b76_.py
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
"""Create collection table for domain collections
|
||||
|
||||
Revision ID: 66407d145b76
|
||||
Revises: 4f03b9548f6e
|
||||
Create Date: 2025-10-26 10:57:16.462524
|
||||
|
||||
"""
|
||||
import os
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '66407d145b76'
|
||||
down_revision = '4f03b9548f6e'
|
||||
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)
|
||||
|
||||
# Step 1: Create new collection table (keeping channel table separate for now)
|
||||
op.create_table(
|
||||
'collection',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sa.String(), nullable=False),
|
||||
sa.Column('description', sa.Text(), nullable=True),
|
||||
sa.Column('kind', sa.String(), nullable=False),
|
||||
sa.Column('directory', sa.Text(), nullable=True),
|
||||
sa.Column('tag_id', sa.Integer(), nullable=True),
|
||||
sa.Column('created_date', sa.DateTime(), server_default=sa.func.now(), nullable=False),
|
||||
sa.Column('item_count', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.Column('total_size', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.ForeignKeyConstraint(['tag_id'], ['tag.id'], name='collection_tag_id_fkey'),
|
||||
sa.UniqueConstraint('directory', name='uq_collection_directory')
|
||||
)
|
||||
|
||||
# Create indexes for collection
|
||||
op.create_index('idx_collection_kind', 'collection', ['kind'], unique=False)
|
||||
op.create_index('idx_collection_item_count', 'collection', ['item_count'], unique=False)
|
||||
op.create_index('idx_collection_total_size', 'collection', ['total_size'], unique=False)
|
||||
|
||||
# Step 2: Create collection_item junction table
|
||||
op.create_table(
|
||||
'collection_item',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('collection_id', sa.Integer(), nullable=False),
|
||||
sa.Column('file_group_id', sa.Integer(), nullable=False),
|
||||
sa.Column('position', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.Column('added_date', sa.DateTime(), server_default=sa.func.now(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.ForeignKeyConstraint(['collection_id'], ['collection.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['file_group_id'], ['file_group.id'], ondelete='CASCADE'),
|
||||
sa.UniqueConstraint('collection_id', 'file_group_id', name='uq_collection_file_group')
|
||||
)
|
||||
|
||||
# Create indexes for collection_item
|
||||
op.create_index('idx_collection_item_collection_id', 'collection_item', ['collection_id'], unique=False)
|
||||
op.create_index('idx_collection_item_file_group_id', 'collection_item', ['file_group_id'], unique=False)
|
||||
op.create_index('idx_collection_item_position', 'collection_item', ['position'], unique=False)
|
||||
op.create_index('idx_collection_item_collection_position', 'collection_item', ['collection_id', 'position'], unique=False)
|
||||
|
||||
# Ensure table owner in non-docker environments
|
||||
if not DOCKERIZED:
|
||||
session.execute(sa.text('ALTER TABLE public.collection OWNER TO wrolpi'))
|
||||
session.execute(sa.text('ALTER TABLE public.collection_item OWNER TO wrolpi'))
|
||||
|
||||
|
||||
def downgrade():
|
||||
# Drop collection_item table and its indexes
|
||||
op.drop_index('idx_collection_item_collection_position', table_name='collection_item')
|
||||
op.drop_index('idx_collection_item_position', table_name='collection_item')
|
||||
op.drop_index('idx_collection_item_file_group_id', table_name='collection_item')
|
||||
op.drop_index('idx_collection_item_collection_id', table_name='collection_item')
|
||||
op.drop_table('collection_item')
|
||||
|
||||
# Drop collection table and its indexes
|
||||
op.drop_index('idx_collection_total_size', table_name='collection')
|
||||
op.drop_index('idx_collection_item_count', table_name='collection')
|
||||
op.drop_index('idx_collection_kind', table_name='collection')
|
||||
op.drop_table('collection')
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
"""FileGroup.effective_datetime
|
||||
|
||||
Revision ID: 69e9754d1a63
|
||||
Revises: f7229a67e333
|
||||
Create Date: 2025-08-16 10:28:42.661108
|
||||
|
||||
"""
|
||||
import os
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '69e9754d1a63'
|
||||
down_revision = 'f7229a67e333'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.execute('ALTER TABLE file_group ADD COLUMN IF NOT EXISTS effective_datetime TIMESTAMPTZ')
|
||||
|
||||
# Populating effective_datetime for existing rows
|
||||
op.execute("""
|
||||
UPDATE file_group
|
||||
SET effective_datetime = COALESCE(published_datetime, download_datetime)
|
||||
WHERE published_datetime IS NOT NULL
|
||||
OR download_datetime IS NOT NULL;
|
||||
""")
|
||||
|
||||
op.execute('CREATE INDEX IF NOT EXISTS file_group_effective_datetime_idx ON file_group(effective_datetime)')
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.execute('DROP INDEX IF EXISTS file_group_effective_datetime_idx')
|
||||
op.execute('ALTER TABLE file_group DROP COLUMN IF EXISTS effective_datetime')
|
||||
61
alembic/versions/6b0b249a4f81_archive_published_datetime.py
Normal file
61
alembic/versions/6b0b249a4f81_archive_published_datetime.py
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
"""Archive published_datetime
|
||||
|
||||
Revision ID: 6b0b249a4f81
|
||||
Revises: 4c8da5502c8a
|
||||
Create Date: 2023-10-20 12:54:55.879180
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '6b0b249a4f81'
|
||||
down_revision = '4c8da5502c8a'
|
||||
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)
|
||||
session.execute('ALTER TABLE file_group ADD COLUMN author TEXT')
|
||||
session.execute('ALTER TABLE file_group ADD COLUMN published_datetime TIMESTAMP WITH TIME ZONE')
|
||||
session.execute('ALTER TABLE file_group ADD COLUMN published_modified_datetime TIMESTAMP WITH TIME ZONE')
|
||||
|
||||
# Migrate Video.upload_date to FileGroup.published_datetime.
|
||||
session.execute('''
|
||||
UPDATE file_group
|
||||
SET published_datetime=upload_date
|
||||
FROM video
|
||||
WHERE file_group.id = video.file_group_id
|
||||
''')
|
||||
|
||||
session.execute('CREATE INDEX IF NOT EXISTS file_group_author_idx ON file_group(author)')
|
||||
session.execute('CREATE INDEX IF NOT EXISTS file_group_published_datetime_idx ON file_group(published_datetime)')
|
||||
session.execute('CREATE INDEX IF NOT EXISTS file_group_published_modified_datetime_idx'
|
||||
' ON file_group(published_modified_datetime)')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
# Migrate FileGroup.published_datetime to Video.upload_date.
|
||||
session.execute('''
|
||||
UPDATE video
|
||||
SET upload_date=published_datetime
|
||||
FROM file_group
|
||||
WHERE file_group.id = video.file_group_id
|
||||
''')
|
||||
|
||||
session.execute('DROP INDEX IF EXISTS file_group_author_idx')
|
||||
session.execute('DROP INDEX IF EXISTS file_group_published_datetime_idx')
|
||||
session.execute('DROP INDEX IF EXISTS file_group_published_modified_datetime_idx')
|
||||
|
||||
session.execute('ALTER TABLE file_group DROP COLUMN IF EXISTS author')
|
||||
session.execute('ALTER TABLE file_group DROP COLUMN IF EXISTS published_datetime')
|
||||
session.execute('ALTER TABLE file_group DROP COLUMN IF EXISTS published_modified_datetime')
|
||||
218
alembic/versions/70db5ba8763d_files_rework.py
Normal file
218
alembic/versions/70db5ba8763d_files_rework.py
Normal file
|
|
@ -0,0 +1,218 @@
|
|||
"""Files rework. Unifying files for Videos and Archives.
|
||||
|
||||
Revision ID: 70db5ba8763d
|
||||
Revises: aac864072193
|
||||
Create Date: 2022-07-27 20:11:30.990396
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '70db5ba8763d'
|
||||
down_revision = 'aac864072193'
|
||||
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)
|
||||
|
||||
# Recreate the file table. Use file.path as the primary key.
|
||||
session.execute('DROP TABLE IF EXISTS file')
|
||||
session.execute('''CREATE TABLE file (
|
||||
path TEXT PRIMARY KEY,
|
||||
idempotency TIMESTAMP WITH TIME ZONE,
|
||||
indexed BOOLEAN DEFAULT FALSE,
|
||||
mimetype TEXT,
|
||||
suffix TEXT,
|
||||
model TEXT,
|
||||
associated BOOLEAN DEFAULT FALSE,
|
||||
modification_datetime TIMESTAMP WITH TIME ZONE,
|
||||
size BIGINT,
|
||||
title TEXT,
|
||||
a_text TEXT,
|
||||
b_text TEXT,
|
||||
c_text TEXT,
|
||||
d_text TEXT,
|
||||
textsearch tsvector GENERATED ALWAYS AS (
|
||||
setweight(to_tsvector('english'::regconfig, COALESCE(a_text, '')), 'A'::"char") ||
|
||||
setweight(to_tsvector('english'::regconfig, COALESCE(b_text, '')), 'B'::"char") ||
|
||||
setweight(to_tsvector('english'::regconfig, COALESCE(c_text, '')), 'C'::"char") ||
|
||||
setweight(to_tsvector('english'::regconfig, COALESCE(d_text, '')), 'D'::"char")
|
||||
) STORED
|
||||
)''')
|
||||
session.execute('CREATE INDEX file_mimetype_idx ON file USING BTREE(mimetype)')
|
||||
session.execute('CREATE INDEX file_textsearch_idx ON file USING GIN(textsearch)')
|
||||
session.execute('CREATE INDEX file_modification_datetime_idx ON file USING BTREE(modification_datetime)')
|
||||
session.execute('CREATE INDEX file_size_idx ON file USING BTREE(size)')
|
||||
session.execute('CREATE INDEX file_model_idx ON file USING BTREE(model)')
|
||||
session.execute('CREATE INDEX file_idempotency_idx ON file USING BTREE(idempotency)')
|
||||
session.execute('CREATE INDEX file_suffix_idx ON file USING BTREE(suffix)')
|
||||
|
||||
# Videos are fundamentally different, replace the video table.
|
||||
session.execute('DROP TABLE IF EXISTS video')
|
||||
session.execute('''
|
||||
CREATE TABLE video (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
title TEXT,
|
||||
source_id TEXT,
|
||||
channel_id INTEGER REFERENCES channel(id),
|
||||
upload_date TIMESTAMPTZ,
|
||||
duration INTEGER,
|
||||
favorite TIMESTAMPTZ,
|
||||
size BIGINT,
|
||||
viewed TIMESTAMPTZ,
|
||||
view_count INTEGER,
|
||||
url TEXT,
|
||||
censored BOOLEAN DEFAULT FALSE,
|
||||
validated BOOLEAN DEFAULT FALSE,
|
||||
modification_datetime TIMESTAMPTZ,
|
||||
video_path TEXT REFERENCES file(path),
|
||||
info_json_path TEXT REFERENCES file(path),
|
||||
poster_path TEXT REFERENCES file(path),
|
||||
caption_path TEXT REFERENCES file(path)
|
||||
)''')
|
||||
session.execute('''
|
||||
CREATE INDEX video_caption_path_idx ON video(caption_path);
|
||||
CREATE INDEX video_info_json_path_idx ON video(info_json_path);
|
||||
CREATE INDEX video_poster_path_idx ON video(poster_path);
|
||||
CREATE INDEX video_video_path_idx ON video(video_path);
|
||||
CREATE INDEX video_url_idx ON video(url);
|
||||
CREATE INDEX video_channel_id_idx ON video(channel_id);
|
||||
''')
|
||||
|
||||
session.execute('ALTER TABLE channel DROP COLUMN IF EXISTS idempotency')
|
||||
|
||||
session.execute('DELETE FROM archive') # noqa
|
||||
session.execute('DELETE FROM domains') # noqa
|
||||
session.execute('DROP TABLE IF EXISTS archive')
|
||||
session.execute('DROP TABLE IF EXISTS domains')
|
||||
session.execute('''
|
||||
CREATE TABLE domains (
|
||||
id SERIAL PRIMARY KEY,
|
||||
domain TEXT NOT NULL,
|
||||
directory TEXT
|
||||
)''')
|
||||
session.execute('''
|
||||
CREATE TABLE archive (
|
||||
id SERIAL PRIMARY KEY,
|
||||
domain_id INTEGER REFERENCES domains(id),
|
||||
title TEXT,
|
||||
archive_datetime timestamptz,
|
||||
url TEXT,
|
||||
validated BOOLEAN DEFAULT FALSE,
|
||||
singlefile_path TEXT REFERENCES file(path),
|
||||
readability_path TEXT REFERENCES file(path),
|
||||
readability_json_path TEXT REFERENCES file(path),
|
||||
readability_txt_path TEXT REFERENCES file(path),
|
||||
screenshot_path TEXT REFERENCES file(path)
|
||||
)''')
|
||||
session.execute('''
|
||||
CREATE INDEX archive_singlefile_path ON archive(singlefile_path);
|
||||
CREATE INDEX archive_readability_path ON archive(readability_path);
|
||||
CREATE INDEX archive_readability_json_path ON archive(readability_json_path);
|
||||
CREATE INDEX archive_readability_txt_path ON archive(readability_txt_path);
|
||||
CREATE INDEX archive_screenshot_path ON archive(screenshot_path);
|
||||
''')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('''
|
||||
DROP INDEX IF EXISTS archive_singlefile_path;
|
||||
DROP INDEX IF EXISTS archive_readability_path;
|
||||
DROP INDEX IF EXISTS archive_readability_json_path;
|
||||
DROP INDEX IF EXISTS archive_readability_txt_path;
|
||||
DROP INDEX IF EXISTS archive_screenshot_path;
|
||||
''')
|
||||
|
||||
session.execute('DELETE FROM archive') # noqa
|
||||
session.execute('''
|
||||
ALTER TABLE archive DROP COLUMN IF EXISTS singlefile_path;
|
||||
ALTER TABLE archive DROP COLUMN IF EXISTS readability_path;
|
||||
ALTER TABLE archive DROP COLUMN IF EXISTS readability_json_path;
|
||||
ALTER TABLE archive DROP COLUMN IF EXISTS readability_txt_path;
|
||||
ALTER TABLE archive DROP COLUMN IF EXISTS screenshot_path;
|
||||
ALTER TABLE archive DROP COLUMN IF EXISTS associated;
|
||||
''')
|
||||
session.execute('''
|
||||
ALTER TABLE archive ADD COLUMN IF NOT EXISTS singlefile_path TEXT;
|
||||
ALTER TABLE archive ADD COLUMN IF NOT EXISTS readability_path TEXT;
|
||||
ALTER TABLE archive ADD COLUMN IF NOT EXISTS readability_json_path TEXT;
|
||||
ALTER TABLE archive ADD COLUMN IF NOT EXISTS readability_txt_path TEXT;
|
||||
ALTER TABLE archive ADD COLUMN IF NOT EXISTS screenshot_path TEXT;
|
||||
ALTER TABLE archive ADD COLUMN IF NOT EXISTS contents TEXT;
|
||||
ALTER TABLE archive ADD COLUMN IF NOT EXISTS status TEXT;
|
||||
''')
|
||||
session.execute('ALTER TABLE archive ALTER COLUMN domain_id SET NOT NULL')
|
||||
|
||||
session.execute('ALTER TABLE channel ADD COLUMN IF NOT EXISTS idempotency TEXT')
|
||||
|
||||
session.execute('DELETE FROM video') # noqa
|
||||
session.execute('''
|
||||
ALTER TABLE video DROP COLUMN IF EXISTS caption_path;
|
||||
ALTER TABLE video DROP COLUMN IF EXISTS info_json_path;
|
||||
ALTER TABLE video DROP COLUMN IF EXISTS poster_path;
|
||||
ALTER TABLE video DROP COLUMN IF EXISTS video_path;
|
||||
ALTER TABLE video DROP COLUMN IF EXISTS video_path;
|
||||
''')
|
||||
session.execute('''
|
||||
ALTER TABLE video ADD COLUMN IF NOT EXISTS idempotency TEXT;
|
||||
ALTER TABLE video ADD COLUMN IF NOT EXISTS caption_path TEXT;
|
||||
ALTER TABLE video ADD COLUMN IF NOT EXISTS description_path TEXT;
|
||||
ALTER TABLE video ADD COLUMN IF NOT EXISTS info_json_path TEXT;
|
||||
ALTER TABLE video ADD COLUMN IF NOT EXISTS poster_path TEXT;
|
||||
ALTER TABLE video ADD COLUMN IF NOT EXISTS video_path TEXT;
|
||||
ALTER TABLE video ADD COLUMN IF NOT EXISTS caption TEXT;
|
||||
''')
|
||||
session.execute('''
|
||||
DROP INDEX IF EXISTS video_caption_path_idx;
|
||||
DROP INDEX IF EXISTS video_info_json_path_idx;
|
||||
DROP INDEX IF EXISTS video_poster_path_idx;
|
||||
DROP INDEX IF EXISTS video_video_path_idx;
|
||||
DROP INDEX IF EXISTS video_url_idx;
|
||||
DROP INDEX IF EXISTS video_channel_id_idx;
|
||||
''')
|
||||
session.execute('''
|
||||
ALTER TABLE video
|
||||
ADD COLUMN textsearch tsvector
|
||||
GENERATED ALWAYS AS (
|
||||
setweight(to_tsvector('english'::regconfig, title), 'A') ||
|
||||
setweight(to_tsvector('english'::regconfig, caption), 'D')
|
||||
) STORED
|
||||
''')
|
||||
session.execute('CREATE INDEX IF NOT EXISTS video_textsearch_idx ON video USING GIN(textsearch)')
|
||||
|
||||
session.execute('DROP INDEX IF EXISTS file_mimetype_idx')
|
||||
session.execute('DROP INDEX IF EXISTS file_textsearch_idx')
|
||||
session.execute('DROP INDEX IF EXISTS file_modification_datetime_idx')
|
||||
session.execute('DROP INDEX IF EXISTS file_size_idx')
|
||||
session.execute('DROP INDEX IF EXISTS file_model_idx')
|
||||
session.execute('DROP INDEX IF EXISTS file_idempotency_idx')
|
||||
session.execute('DROP INDEX IF EXISTS file_suffix_idx')
|
||||
|
||||
# Restore the old file table.
|
||||
session.execute('DROP TABLE IF EXISTS file')
|
||||
session.execute('''CREATE TABLE file (
|
||||
id SERIAL PRIMARY KEY,
|
||||
path TEXT,
|
||||
title TEXT,
|
||||
mimetype TEXT,
|
||||
size BIGINT,
|
||||
modification_datetime TIMESTAMP WITH TIME ZONE,
|
||||
idempotency TEXT DEFAULT NULL,
|
||||
textsearch tsvector GENERATED ALWAYS AS (
|
||||
setweight(to_tsvector('english'::regconfig, title), 'A'::"char")
|
||||
) STORED
|
||||
)''')
|
||||
session.execute('CREATE UNIQUE INDEX file_path_idx ON file USING BTREE(path)')
|
||||
session.execute('CREATE INDEX file_mimetype_idx ON file USING BTREE(mimetype)')
|
||||
session.execute('CREATE INDEX file_textsearch_idx ON file USING GIN(textsearch)')
|
||||
66
alembic/versions/717f36a4da94_ebook.py
Normal file
66
alembic/versions/717f36a4da94_ebook.py
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
"""Ebook
|
||||
|
||||
Revision ID: 717f36a4da94
|
||||
Revises: d0bbe45e56c3
|
||||
Create Date: 2022-12-09 15:32:32.228539
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '717f36a4da94'
|
||||
down_revision = 'd0bbe45e56c3'
|
||||
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)
|
||||
|
||||
session.execute('''
|
||||
DROP INDEX IF EXISTS ebook_title_idx;
|
||||
DROP INDEX IF EXISTS ebook_size_idx;
|
||||
DROP INDEX IF EXISTS ebook_creator_idx;
|
||||
DROP INDEX IF EXISTS ebook_ebook_path_idx;
|
||||
DROP INDEX IF EXISTS ebook_cover_path_idx;
|
||||
DROP TABLE IF EXISTS ebook;
|
||||
''')
|
||||
|
||||
session.execute('''
|
||||
CREATE TABLE ebook (
|
||||
id SERIAL PRIMARY KEY,
|
||||
size INTEGER,
|
||||
title TEXT,
|
||||
creator TEXT,
|
||||
ebook_path TEXT REFERENCES file(path) ON DELETE CASCADE,
|
||||
cover_path TEXT REFERENCES file(path) ON DELETE CASCADE
|
||||
)''')
|
||||
|
||||
if not DOCKERIZED:
|
||||
session.execute('ALTER TABLE public.ebook OWNER TO wrolpi')
|
||||
|
||||
session.execute('CREATE INDEX ebook_title_idx ON ebook(title)')
|
||||
session.execute('CREATE INDEX ebook_size_idx ON ebook(size)')
|
||||
session.execute('CREATE INDEX ebook_creator_idx ON ebook(creator)')
|
||||
session.execute('CREATE INDEX ebook_ebook_path_idx ON ebook(ebook_path)')
|
||||
session.execute('CREATE INDEX ebook_cover_path_idx ON ebook(cover_path)')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('''
|
||||
DROP INDEX IF EXISTS ebook_title_idx;
|
||||
DROP INDEX IF EXISTS ebook_size_idx;
|
||||
DROP INDEX IF EXISTS ebook_creator_idx;
|
||||
DROP INDEX IF EXISTS ebook_ebook_path_idx;
|
||||
DROP INDEX IF EXISTS ebook_cover_path_idx;
|
||||
DROP TABLE IF EXISTS ebook;
|
||||
''')
|
||||
67
alembic/versions/751aecf46b88_zim.py
Normal file
67
alembic/versions/751aecf46b88_zim.py
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
"""Zim
|
||||
|
||||
Revision ID: 751aecf46b88
|
||||
Revises: 75d34a2b442d
|
||||
Create Date: 2023-06-04 19:48:41.305111
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '751aecf46b88'
|
||||
down_revision = '75d34a2b442d'
|
||||
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)
|
||||
|
||||
session.execute('''
|
||||
CREATE TABLE zim (
|
||||
id SERIAL PRIMARY KEY,
|
||||
path TEXT NOT NULL UNIQUE,
|
||||
file_group_id BIGINT REFERENCES file_group(id) ON DELETE CASCADE NOT NULL
|
||||
)''')
|
||||
|
||||
session.execute('''
|
||||
CREATE TABLE tag_zim (
|
||||
tag_id INTEGER REFERENCES tag(id),
|
||||
zim_id INTEGER REFERENCES zim(id) ON DELETE CASCADE,
|
||||
zim_entry TEXT NOT NULL,
|
||||
created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE (tag_id, zim_id, zim_entry)
|
||||
)''')
|
||||
|
||||
session.execute('''
|
||||
CREATE TABLE zim_subscription (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
language TEXT NOT NULL,
|
||||
download_id INTEGER NOT NULL REFERENCES download(id) ON DELETE CASCADE
|
||||
)
|
||||
''')
|
||||
|
||||
# We want to index all Zim files using `zim_modeler`
|
||||
session.execute("UPDATE file_group SET indexed=false WHERE primary_path ILIKE '%.zim'")
|
||||
|
||||
if not DOCKERIZED:
|
||||
session.execute('ALTER TABLE public.zim OWNER TO wrolpi')
|
||||
session.execute('ALTER TABLE public.tag_zim OWNER TO wrolpi')
|
||||
session.execute('ALTER TABLE public.zim_subscription OWNER TO wrolpi')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('DROP TABLE IF EXISTS zim_subscription')
|
||||
session.execute('DROP TABLE IF EXISTS tag_zim')
|
||||
session.execute('DROP TABLE IF EXISTS zim')
|
||||
session.execute("UPDATE file_group SET indexed=false WHERE primary_path ILIKE '%.zim'")
|
||||
33
alembic/versions/75d34a2b442d_archive_datetime_index.py
Normal file
33
alembic/versions/75d34a2b442d_archive_datetime_index.py
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
"""Archive datetime index.
|
||||
|
||||
Revision ID: 75d34a2b442d
|
||||
Revises: f9928a3b6bc5
|
||||
Create Date: 2023-05-15 13:09:47.661940
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '75d34a2b442d'
|
||||
down_revision = 'f9928a3b6bc5'
|
||||
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)
|
||||
|
||||
session.execute('CREATE INDEX archive_datetime_idx ON archive(archive_datetime)')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('DROP INDEX IF EXISTS archive_datetime_idx')
|
||||
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'))
|
||||
31
alembic/versions/84b6993a6091_drop_channel_next_download.py
Normal file
31
alembic/versions/84b6993a6091_drop_channel_next_download.py
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
"""Drop channel next_download
|
||||
|
||||
Revision ID: 84b6993a6091
|
||||
Revises: 8df411232c17
|
||||
Create Date: 2021-12-27 16:42:32.099796
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '84b6993a6091'
|
||||
down_revision = '8df411232c17'
|
||||
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)
|
||||
session.execute('ALTER TABLE channel DROP COLUMN IF EXISTS next_download')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
session.execute('ALTER TABLE channel ADD COLUMN IF NOT EXISTS next_download DATE')
|
||||
35
alembic/versions/8bdb48a486b9_video_ffprobe_json.py
Normal file
35
alembic/versions/8bdb48a486b9_video_ffprobe_json.py
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
"""Video ffprobe json.
|
||||
|
||||
Revision ID: 8bdb48a486b9
|
||||
Revises: bf704baa185d
|
||||
Create Date: 2023-07-24 10:59:17.426100
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '8bdb48a486b9'
|
||||
down_revision = 'bf704baa185d'
|
||||
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)
|
||||
|
||||
session.execute('ALTER TABLE video ADD COLUMN ffprobe_json JSON')
|
||||
# Re-index all videos so the ffprobe data is fetched.
|
||||
session.execute("UPDATE file_group SET indexed=false WHERE mimetype like 'video/%'")
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('ALTER TABLE video DROP COLUMN IF EXISTS ffprobe_json')
|
||||
148
alembic/versions/8d0d81bc9c34_channel_channel_downloads.py
Normal file
148
alembic/versions/8d0d81bc9c34_channel_channel_downloads.py
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
"""Channel.downloads / Download.channel
|
||||
|
||||
Revision ID: 8d0d81bc9c34
|
||||
Revises: 00f11f309c53
|
||||
Create Date: 2024-06-25 22:13:23.885687
|
||||
|
||||
"""
|
||||
import os
|
||||
import pathlib
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy import Column, Integer, String, Boolean, JSON, Date, Text, ForeignKey
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import Session, deferred, relationship
|
||||
from sqlalchemy.orm.collections import InstrumentedList
|
||||
|
||||
from wrolpi.common import ModelHelper
|
||||
from wrolpi.dates import TZDateTime
|
||||
from wrolpi.downloader import DownloadStatus
|
||||
from wrolpi.media_path import MediaPathType
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '8d0d81bc9c34'
|
||||
down_revision = '00f11f309c53'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
# The `Channel` model at the time of this migration.
|
||||
class MChannel(ModelHelper, Base):
|
||||
__tablename__ = 'channel'
|
||||
id = Column(Integer, primary_key=True)
|
||||
name = Column(String)
|
||||
url = Column(String, unique=True)
|
||||
directory: pathlib.Path = Column(MediaPathType)
|
||||
generate_posters = Column(Boolean, default=False)
|
||||
calculate_duration = Column(Boolean, default=True)
|
||||
source_id = Column(String)
|
||||
refreshed = Column(Boolean, default=False)
|
||||
|
||||
info_json = deferred(Column(JSON))
|
||||
info_date = Column(Date)
|
||||
|
||||
downloads: InstrumentedList = relationship('MDownload', primaryjoin='MDownload.channel_id==MChannel.id')
|
||||
|
||||
@staticmethod
|
||||
def get_by_url(url: str, session: Session = None):
|
||||
if not url:
|
||||
raise RuntimeError('Must provide URL to get Channel')
|
||||
channel = session.query(MChannel).filter_by(url=url).one_or_none()
|
||||
return channel
|
||||
|
||||
def get_rss_url(self) -> str | None:
|
||||
if self.url and self.source_id and 'youtube.com' in self.url:
|
||||
return f'https://www.youtube.com/feeds/videos.xml?channel_id={self.source_id}'
|
||||
|
||||
|
||||
# The `Download` model at the time of this migration.
|
||||
class MDownload(ModelHelper, Base):
|
||||
__tablename__ = 'download'
|
||||
id = Column(Integer, primary_key=True)
|
||||
url = Column(String, nullable=False, unique=True)
|
||||
|
||||
attempts = Column(Integer, default=0)
|
||||
downloader = Column(Text)
|
||||
sub_downloader = Column(Text)
|
||||
error = Column(Text)
|
||||
frequency = Column(Integer)
|
||||
info_json = Column(JSONB)
|
||||
last_successful_download = Column(TZDateTime)
|
||||
location = Column(Text)
|
||||
next_download = Column(TZDateTime)
|
||||
settings = Column(JSONB)
|
||||
status = Column(String, default=DownloadStatus.new)
|
||||
|
||||
channel_id = Column(Integer, ForeignKey('channel.id'))
|
||||
channel = relationship('MChannel', primaryjoin='MDownload.channel_id==MChannel.id', back_populates='downloads')
|
||||
|
||||
|
||||
def _link_channel_and_downloads(session: Session):
|
||||
"""Associate each Download with its Channel via `Download.channel_id`.
|
||||
|
||||
This is a frozen copy of the linking logic as it existed when this migration was written. It deliberately does
|
||||
NOT import `modules.videos.lib.link_channel_and_downloads`; that function has since been rewritten for the
|
||||
Collections feature and now relies on `Download.collection_id` / `Download.destination`, neither of which exists at
|
||||
this point in the migration chain. A migration must remain frozen against the schema it targets.
|
||||
"""
|
||||
downloads = list(session.query(MDownload).all())
|
||||
downloads_by_url = {i.url: i for i in downloads}
|
||||
downloads_by_destination = {i.settings['destination']: i
|
||||
for i in downloads if 'destination' in (i.settings or dict())}
|
||||
channels = session.query(MChannel).all()
|
||||
|
||||
need_commit = False
|
||||
for channel in channels:
|
||||
directory = str(channel.directory)
|
||||
download = downloads_by_destination.get(directory) or downloads_by_url.get(channel.url)
|
||||
if download and not download.channel_id:
|
||||
download.channel_id = channel.id
|
||||
need_commit = True
|
||||
|
||||
# Get any Downloads for a Channel's RSS feed.
|
||||
rss_url = channel.get_rss_url()
|
||||
download = downloads_by_url.get(rss_url) if rss_url else None
|
||||
if download and not download.channel_id:
|
||||
download.channel_id = channel.id
|
||||
need_commit = True
|
||||
|
||||
# Associate any Download which shares a Channel's URL.
|
||||
for download in downloads:
|
||||
if download.url and not download.channel_id:
|
||||
channel = MChannel.get_by_url(download.url, session)
|
||||
if channel:
|
||||
download.channel_id = channel.id
|
||||
need_commit = True
|
||||
|
||||
if need_commit:
|
||||
session.commit()
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('ALTER TABLE download ADD CONSTRAINT download_url_unique UNIQUE (url)')
|
||||
session.execute('ALTER TABLE download ADD COLUMN channel_id INTEGER REFERENCES channel(id)')
|
||||
|
||||
_link_channel_and_downloads(session)
|
||||
|
||||
session.execute('ALTER TABLE channel DROP COLUMN IF EXISTS match_regex')
|
||||
session.execute('ALTER TABLE channel DROP COLUMN IF EXISTS download_frequency')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('DROP TABLE IF EXISTS channel_download')
|
||||
session.execute('ALTER TABLE download DROP COLUMN IF EXISTS channel_id')
|
||||
session.execute('ALTER TABLE channel DROP COLUMN IF EXISTS channel_id')
|
||||
session.execute('ALTER TABLE channel ADD COLUMN IF NOT EXISTS match_regex TEXT')
|
||||
session.execute('ALTER TABLE channel ADD COLUMN IF NOT EXISTS download_frequency INTEGER')
|
||||
session.execute('ALTER TABLE download DROP CONSTRAINT IF EXISTS download_url_unique')
|
||||
37
alembic/versions/8df411232c17_video_indexes.py
Normal file
37
alembic/versions/8df411232c17_video_indexes.py
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
"""Video indexes
|
||||
|
||||
Revision ID: 8df411232c17
|
||||
Revises: 32d96eb9122d
|
||||
Create Date: 2021-12-24 14:42:02.365100
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '8df411232c17'
|
||||
down_revision = '32d96eb9122d'
|
||||
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)
|
||||
session.execute('CREATE INDEX video_favorite ON video (favorite)')
|
||||
session.execute('CREATE INDEX video_view_count ON video (view_count)')
|
||||
session.execute('CREATE INDEX video_validated_poster ON video (validated_poster)')
|
||||
session.execute('CREATE INDEX video_upload_date ON video (upload_date)')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
session.execute('DROP INDEX IF EXISTS video_favorite')
|
||||
session.execute('DROP INDEX IF EXISTS video_view_count')
|
||||
session.execute('DROP INDEX IF EXISTS video_validated_poster')
|
||||
session.execute('DROP INDEX IF EXISTS video_upload_date')
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
"""Remove file directory and stem.
|
||||
|
||||
Revision ID: 90ac16f9140a
|
||||
Revises: 717f36a4da94
|
||||
Create Date: 2022-12-16 09:58:32.238873
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '90ac16f9140a'
|
||||
down_revision = '717f36a4da94'
|
||||
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)
|
||||
|
||||
session.execute('DROP INDEX IF EXISTS file_directory_idx')
|
||||
session.execute('DROP INDEX IF EXISTS file_stem_idx')
|
||||
session.execute('ALTER TABLE file DROP COLUMN IF EXISTS directory')
|
||||
session.execute('ALTER TABLE file DROP COLUMN IF EXISTS stem')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('ALTER TABLE file ADD COLUMN directory TEXT')
|
||||
session.execute('ALTER TABLE file ADD COLUMN stem TEXT')
|
||||
session.execute('CREATE INDEX file_directory_idx ON file(directory)')
|
||||
session.execute('CREATE INDEX file_stem_idx ON file(stem)')
|
||||
39
alembic/versions/930b9b7adb79_wrolpi_flags.py
Normal file
39
alembic/versions/930b9b7adb79_wrolpi_flags.py
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
"""WROLPi flags
|
||||
|
||||
Revision ID: 930b9b7adb79
|
||||
Revises: 90ac16f9140a
|
||||
Create Date: 2022-12-20 21:02:28.975897
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '930b9b7adb79'
|
||||
down_revision = '90ac16f9140a'
|
||||
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)
|
||||
|
||||
session.execute('''CREATE TABLE wrolpi_flag(
|
||||
id SERIAL PRIMARY KEY,
|
||||
refresh_complete BOOLEAN DEFAULT FALSE
|
||||
)''')
|
||||
|
||||
if not DOCKERIZED:
|
||||
session.execute('ALTER TABLE public.wrolpi_flag OWNER TO wrolpi')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('DROP TABLE IF EXISTS wrolpi_flag')
|
||||
40
alembic/versions/9ec4c765ef8d_remove_inventories_version.py
Normal file
40
alembic/versions/9ec4c765ef8d_remove_inventories_version.py
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
"""Remove inventories version.
|
||||
|
||||
Revision ID: 9ec4c765ef8d
|
||||
Revises: d4e446637f18
|
||||
Create Date: 2024-09-24 16:01:41.716017
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '9ec4c765ef8d'
|
||||
down_revision = 'd4e446637f18'
|
||||
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)
|
||||
|
||||
session.execute('DROP TABLE IF EXISTS inventories_version')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('''
|
||||
CREATE TABLE inventories_version (
|
||||
version SERIAL PRIMARY KEY NOT NULL
|
||||
)
|
||||
''')
|
||||
|
||||
if not DOCKERIZED:
|
||||
session.execute('ALTER TABLE public.inventories_version OWNER TO wrolpi')
|
||||
48
alembic/versions/a1b2c3d4e5f6_add_collection_file_format.py
Normal file
48
alembic/versions/a1b2c3d4e5f6_add_collection_file_format.py
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
"""add_collection_file_format
|
||||
|
||||
Revision ID: a1b2c3d4e5f6
|
||||
Revises: 76add63ed225
|
||||
Create Date: 2026-01-23
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'a1b2c3d4e5f6'
|
||||
down_revision = '76add63ed225'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# Add file_format column to collection table
|
||||
# This stores the file_name_format used when files were last organized
|
||||
op.add_column('collection', sa.Column('file_format', sa.String(), nullable=True))
|
||||
|
||||
# Set default values from current configs so existing collections don't need reorganization
|
||||
from modules.archive.lib import get_archive_downloader_config
|
||||
from modules.videos.lib import get_videos_downloader_config
|
||||
|
||||
connection = op.get_bind()
|
||||
|
||||
# Update domain collections with archive config's file_name_format
|
||||
archive_config = get_archive_downloader_config()
|
||||
if archive_config.file_name_format:
|
||||
connection.execute(
|
||||
sa.text("UPDATE collection SET file_format = :format WHERE kind = 'domain'"),
|
||||
{'format': archive_config.file_name_format}
|
||||
)
|
||||
|
||||
# Update channel collections with video config's file_name_format
|
||||
video_config = get_videos_downloader_config()
|
||||
if video_config.file_name_format:
|
||||
connection.execute(
|
||||
sa.text("UPDATE collection SET file_format = :format WHERE kind = 'channel'"),
|
||||
{'format': video_config.file_name_format}
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_column('collection', 'file_format')
|
||||
29
alembic/versions/a2b3c4d5e6f7_drop_map_file_table.py
Normal file
29
alembic/versions/a2b3c4d5e6f7_drop_map_file_table.py
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
"""Drop map_file table.
|
||||
|
||||
PMTiles files are now scanned directly from disk; the map_file table is no longer needed.
|
||||
|
||||
Revision ID: a2b3c4d5e6f7
|
||||
Revises: e7f8a9b0c1d2
|
||||
Create Date: 2026-03-29
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'a2b3c4d5e6f7'
|
||||
down_revision = 'e7f8a9b0c1d2'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.drop_table('map_file')
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.execute('''CREATE TABLE map_file (
|
||||
id SERIAL PRIMARY KEY,
|
||||
path TEXT NOT NULL,
|
||||
imported BOOLEAN DEFAULT FALSE,
|
||||
size BIGINT
|
||||
)''')
|
||||
58
alembic/versions/a7b1c2d3e4f5_collection_item_polymorphic.py
Normal file
58
alembic/versions/a7b1c2d3e4f5_collection_item_polymorphic.py
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
"""Make collection_item polymorphic: file | zim | url items.
|
||||
|
||||
CollectionItem previously only referenced a FileGroup. Playlists (kind='playlist') also need to
|
||||
order Zim articles (zim_id + zim_entry, mirroring TagZimEntry) and arbitrary URLs (a link the WROLPi
|
||||
browser can open, e.g. a map location). This adds item_kind plus the zim/url/title columns, relaxes
|
||||
file_group_id to nullable, and adds per-kind unique constraints and a CHECK that exactly one kind's
|
||||
columns are populated. Existing rows default to item_kind='file'.
|
||||
|
||||
Revision ID: a7b1c2d3e4f5
|
||||
Revises: e6f7a8b9c0d1
|
||||
Create Date: 2026-06-08
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = 'a7b1c2d3e4f5'
|
||||
down_revision = 'e6f7a8b9c0d1'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
CHECK_SQL = (
|
||||
"(item_kind = 'file' AND file_group_id IS NOT NULL AND zim_id IS NULL AND url IS NULL)"
|
||||
" OR (item_kind = 'zim' AND zim_id IS NOT NULL AND zim_entry IS NOT NULL"
|
||||
" AND file_group_id IS NULL AND url IS NULL)"
|
||||
" OR (item_kind = 'url' AND url IS NOT NULL AND file_group_id IS NULL AND zim_id IS NULL)"
|
||||
)
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column('collection_item',
|
||||
sa.Column('item_kind', sa.String(), nullable=False, server_default='file'))
|
||||
op.add_column('collection_item', sa.Column('zim_id', sa.Integer(), nullable=True))
|
||||
op.add_column('collection_item', sa.Column('zim_entry', sa.Text(), nullable=True))
|
||||
op.add_column('collection_item', sa.Column('url', sa.Text(), nullable=True))
|
||||
op.add_column('collection_item', sa.Column('title', sa.Text(), nullable=True))
|
||||
# `file` is no longer the only kind, so a row need not have a FileGroup.
|
||||
op.alter_column('collection_item', 'file_group_id', existing_type=sa.Integer(), nullable=True)
|
||||
op.create_foreign_key('collection_item_zim_id_fkey', 'collection_item', 'zim',
|
||||
['zim_id'], ['id'], ondelete='CASCADE')
|
||||
op.create_unique_constraint('uq_collection_zim_entry', 'collection_item',
|
||||
['collection_id', 'zim_id', 'zim_entry'])
|
||||
op.create_unique_constraint('uq_collection_url', 'collection_item', ['collection_id', 'url'])
|
||||
op.create_check_constraint('ck_collection_item_kind', 'collection_item', CHECK_SQL)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_constraint('ck_collection_item_kind', 'collection_item', type_='check')
|
||||
op.drop_constraint('uq_collection_url', 'collection_item', type_='unique')
|
||||
op.drop_constraint('uq_collection_zim_entry', 'collection_item', type_='unique')
|
||||
op.drop_constraint('collection_item_zim_id_fkey', 'collection_item', type_='foreignkey')
|
||||
# Restore NOT NULL (valid only if no non-file rows remain).
|
||||
op.alter_column('collection_item', 'file_group_id', existing_type=sa.Integer(), nullable=False)
|
||||
op.drop_column('collection_item', 'title')
|
||||
op.drop_column('collection_item', 'url')
|
||||
op.drop_column('collection_item', 'zim_entry')
|
||||
op.drop_column('collection_item', 'zim_id')
|
||||
op.drop_column('collection_item', 'item_kind')
|
||||
30
alembic/versions/aac864072193_increase_file_size_column.py
Normal file
30
alembic/versions/aac864072193_increase_file_size_column.py
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
"""Increase file size column.
|
||||
|
||||
Revision ID: aac864072193
|
||||
Revises: 467235201c70
|
||||
Create Date: 2022-06-22 17:34:33.635528
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'aac864072193'
|
||||
down_revision = '467235201c70'
|
||||
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)
|
||||
|
||||
session.execute('ALTER TABLE file ALTER COLUMN size TYPE bigint')
|
||||
|
||||
|
||||
def downgrade():
|
||||
pass
|
||||
95
alembic/versions/add_unique_collection_name_kind.py
Normal file
95
alembic/versions/add_unique_collection_name_kind.py
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
"""Add unique constraint on collection (name, kind)
|
||||
|
||||
This migration:
|
||||
1. Removes duplicate collections (keeping the one with most items/archives)
|
||||
2. Adds a unique constraint on (name, kind) to prevent future duplicates
|
||||
|
||||
Revision ID: add_unique_collection_name_kind
|
||||
Revises: migrate_download_to_collection
|
||||
Create Date: 2025-11-27
|
||||
"""
|
||||
import os
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'add_unique_collection_name_kind'
|
||||
down_revision = 'migrate_download_to_collection'
|
||||
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)
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("Add Unique Constraint on Collection (name, kind)")
|
||||
print("=" * 60 + "\n")
|
||||
|
||||
# Step 1: Find and remove duplicate collections
|
||||
print("Step 1: Finding duplicate collections...")
|
||||
|
||||
# Find duplicates - keep the one with the lowest id (first created)
|
||||
duplicates = session.execute(text("""
|
||||
SELECT name, kind, array_agg(id ORDER BY id) as ids
|
||||
FROM collection
|
||||
GROUP BY name, kind
|
||||
HAVING COUNT(*) > 1
|
||||
""")).fetchall()
|
||||
|
||||
if duplicates:
|
||||
print(f"Found {len(duplicates)} sets of duplicate collections")
|
||||
for name, kind, ids in duplicates:
|
||||
keep_id = ids[0] # Keep the first one (lowest id)
|
||||
remove_ids = ids[1:] # Remove the rest
|
||||
print(f" - '{name}' ({kind}): keeping id={keep_id}, removing ids={remove_ids}")
|
||||
|
||||
# Move any archives from duplicate collections to the one we're keeping
|
||||
for remove_id in remove_ids:
|
||||
session.execute(text("""
|
||||
UPDATE archive SET collection_id = :keep_id
|
||||
WHERE collection_id = :remove_id
|
||||
"""), {'keep_id': keep_id, 'remove_id': remove_id})
|
||||
|
||||
# Move any downloads from duplicate collections
|
||||
session.execute(text("""
|
||||
UPDATE download SET collection_id = :keep_id
|
||||
WHERE collection_id = :remove_id
|
||||
"""), {'keep_id': keep_id, 'remove_id': remove_id})
|
||||
|
||||
# Move any collection items
|
||||
session.execute(text("""
|
||||
UPDATE collection_item SET collection_id = :keep_id
|
||||
WHERE collection_id = :remove_id
|
||||
"""), {'keep_id': keep_id, 'remove_id': remove_id})
|
||||
|
||||
# Delete the duplicate collection
|
||||
session.execute(text("""
|
||||
DELETE FROM collection WHERE id = :remove_id
|
||||
"""), {'remove_id': remove_id})
|
||||
|
||||
session.commit()
|
||||
print("Duplicates removed\n")
|
||||
else:
|
||||
print("No duplicate collections found\n")
|
||||
|
||||
# Step 2: Add unique constraint
|
||||
print("Step 2: Adding unique constraint on (name, kind)...")
|
||||
op.create_unique_constraint('uq_collection_name_kind', 'collection', ['name', 'kind'])
|
||||
print("Done\n")
|
||||
|
||||
print("=" * 60)
|
||||
print("Migration Complete")
|
||||
print("=" * 60 + "\n")
|
||||
|
||||
if not DOCKERIZED:
|
||||
session.execute(text('ALTER TABLE public.collection OWNER TO wrolpi'))
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_constraint('uq_collection_name_kind', 'collection', type_='unique')
|
||||
192
alembic/versions/af4527503bdf_add_filegroup_directory_column.py
Normal file
192
alembic/versions/af4527503bdf_add_filegroup_directory_column.py
Normal file
|
|
@ -0,0 +1,192 @@
|
|||
"""add_filegroup_directory_column
|
||||
|
||||
Revision ID: af4527503bdf
|
||||
Revises: 577e414f1bc4
|
||||
Create Date: 2025-12-23 19:35:18.776018
|
||||
|
||||
This migration:
|
||||
1. Adds `directory` column to file_group (stores parent directory of primary_path)
|
||||
2. Converts paths in `files` JSON from absolute to relative (filename only)
|
||||
3. Converts paths in `data` JSON from absolute to relative (filename only)
|
||||
|
||||
After this migration:
|
||||
- directory: /media/wrolpi/videos/channel1 (absolute)
|
||||
- primary_path: /media/wrolpi/videos/channel1/video.mp4 (absolute, unchanged for now)
|
||||
- files: [{path: "video.mp4", ...}] (relative filenames)
|
||||
- data: {poster_path: "video.jpg", ...} (relative filenames)
|
||||
|
||||
Processing is done in batches to handle large databases (hundreds of thousands of FileGroups)
|
||||
on memory-constrained devices like Raspberry Pi.
|
||||
"""
|
||||
import os
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
import wrolpi.media_path
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'af4527503bdf'
|
||||
down_revision = '577e414f1bc4'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False
|
||||
|
||||
# Batch size for processing - balances memory usage vs. migration speed
|
||||
BATCH_SIZE = 1000
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
# Add the directory column (nullable initially)
|
||||
# Index is created in the next migration (26c5a62ec683) AFTER data is populated for efficiency.
|
||||
op.add_column('file_group', sa.Column('directory', wrolpi.media_path.MediaPathType(), nullable=True))
|
||||
|
||||
# Phase 1: Populate directory from existing primary_path (batched)
|
||||
# Uses regexp_replace to remove the filename (everything after the last /).
|
||||
print("Phase 1: Populating directory column...")
|
||||
total_updated = 0
|
||||
while True:
|
||||
result = session.execute(sa.text("""
|
||||
UPDATE file_group
|
||||
SET directory = regexp_replace(primary_path, '/[^/]+$', '')
|
||||
WHERE id IN (
|
||||
SELECT id FROM file_group
|
||||
WHERE directory IS NULL
|
||||
AND primary_path IS NOT NULL
|
||||
LIMIT :batch_size
|
||||
)
|
||||
"""), {'batch_size': BATCH_SIZE})
|
||||
session.commit()
|
||||
if result.rowcount == 0:
|
||||
break
|
||||
total_updated += result.rowcount
|
||||
print(f" Processed {total_updated} directories...")
|
||||
print(f"Phase 1 complete: {total_updated} directories populated.")
|
||||
|
||||
# Phase 2: Convert files JSON paths from absolute to relative (batched)
|
||||
# Only processes rows where at least one path is still absolute (starts with /)
|
||||
print("Phase 2: Converting files JSON to relative paths...")
|
||||
total_updated = 0
|
||||
while True:
|
||||
result = session.execute(sa.text("""
|
||||
UPDATE file_group
|
||||
SET files = (
|
||||
SELECT jsonb_agg(
|
||||
jsonb_set(
|
||||
elem,
|
||||
'{path}',
|
||||
to_jsonb(regexp_replace(elem->>'path', '.+/', ''))
|
||||
)
|
||||
)
|
||||
FROM jsonb_array_elements(files::jsonb) AS elem
|
||||
)
|
||||
WHERE id IN (
|
||||
SELECT id FROM file_group
|
||||
WHERE files IS NOT NULL
|
||||
AND jsonb_array_length(files::jsonb) > 0
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM jsonb_array_elements(files::jsonb) AS elem
|
||||
WHERE elem->>'path' LIKE '/%'
|
||||
)
|
||||
LIMIT :batch_size
|
||||
)
|
||||
"""), {'batch_size': BATCH_SIZE})
|
||||
session.commit()
|
||||
if result.rowcount == 0:
|
||||
break
|
||||
total_updated += result.rowcount
|
||||
print(f" Converted {total_updated} files arrays...")
|
||||
print(f"Phase 2 complete: {total_updated} files arrays converted.")
|
||||
|
||||
# Phase 3: Convert data JSON paths from absolute to relative (batched)
|
||||
# Handle known path fields: video_path, info_json_path, poster_path, ebook_path, cover_path, screenshot_path
|
||||
# Only processes rows where data contains at least one absolute path
|
||||
print("Phase 3: Converting data JSON to relative paths...")
|
||||
total_updated = 0
|
||||
while True:
|
||||
result = session.execute(sa.text("""
|
||||
UPDATE file_group
|
||||
SET data = (
|
||||
SELECT COALESCE(
|
||||
jsonb_object_agg(
|
||||
key,
|
||||
CASE
|
||||
-- Handle path fields that are strings starting with /
|
||||
-- Use ::jsonb cast instead of to_jsonb() since value::text already has JSON quotes
|
||||
WHEN key IN ('video_path', 'info_json_path', 'poster_path', 'ebook_path', 'cover_path', 'screenshot_path',
|
||||
'readability_json_path', 'readability_path', 'readability_txt_path', 'singlefile_path')
|
||||
AND jsonb_typeof(value) = 'string'
|
||||
AND value::text LIKE '"/%%'
|
||||
THEN regexp_replace(value::text, '^".+/', '"')::jsonb
|
||||
|
||||
-- Handle caption_paths which is an array of strings
|
||||
WHEN key = 'caption_paths' AND jsonb_typeof(value) = 'array'
|
||||
THEN (
|
||||
SELECT jsonb_agg(
|
||||
CASE
|
||||
WHEN jsonb_typeof(elem) = 'string' AND elem::text LIKE '"/%%'
|
||||
THEN regexp_replace(elem::text, '^".+/', '"')::jsonb
|
||||
ELSE elem
|
||||
END
|
||||
)
|
||||
FROM jsonb_array_elements(value) AS elem
|
||||
)
|
||||
|
||||
-- Keep other values unchanged
|
||||
ELSE value
|
||||
END
|
||||
),
|
||||
'{}'::jsonb
|
||||
)
|
||||
FROM jsonb_each(data::jsonb)
|
||||
)
|
||||
WHERE id IN (
|
||||
SELECT id FROM file_group
|
||||
WHERE data IS NOT NULL
|
||||
AND data::text != 'null'
|
||||
AND data::text != '{}'
|
||||
AND (
|
||||
-- Check if any known path field contains an absolute path
|
||||
data->>'video_path' LIKE '/%'
|
||||
OR data->>'info_json_path' LIKE '/%'
|
||||
OR data->>'poster_path' LIKE '/%'
|
||||
OR data->>'ebook_path' LIKE '/%'
|
||||
OR data->>'cover_path' LIKE '/%'
|
||||
OR data->>'screenshot_path' LIKE '/%'
|
||||
OR data->>'readability_json_path' LIKE '/%'
|
||||
OR data->>'readability_path' LIKE '/%'
|
||||
OR data->>'readability_txt_path' LIKE '/%'
|
||||
OR data->>'singlefile_path' LIKE '/%'
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM jsonb_array_elements_text(
|
||||
CASE WHEN data->>'caption_paths' IS NOT NULL THEN (data->'caption_paths')::jsonb ELSE '[]'::jsonb END
|
||||
) AS elem
|
||||
WHERE elem LIKE '/%'
|
||||
)
|
||||
)
|
||||
LIMIT :batch_size
|
||||
)
|
||||
"""), {'batch_size': BATCH_SIZE})
|
||||
session.commit()
|
||||
if result.rowcount == 0:
|
||||
break
|
||||
total_updated += result.rowcount
|
||||
print(f" Converted {total_updated} data objects...")
|
||||
print(f"Phase 3 complete: {total_updated} data objects converted.")
|
||||
|
||||
print("Migration complete!")
|
||||
|
||||
if not DOCKERIZED:
|
||||
session.execute(sa.text('ALTER TABLE public.file_group OWNER TO wrolpi'))
|
||||
|
||||
|
||||
def downgrade():
|
||||
# Note: Downgrade does not restore absolute paths in files/data columns.
|
||||
# This would require knowing the original directory for each record.
|
||||
# Index is dropped in the previous downgrade (26c5a62ec683).
|
||||
op.drop_column('file_group', 'directory')
|
||||
189
alembic/versions/b2b9700f5048_fix_corrupted_media_paths.py
Normal file
189
alembic/versions/b2b9700f5048_fix_corrupted_media_paths.py
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
"""Fix media paths incorrectly resolved against /opt/wrolpi.
|
||||
|
||||
MediaPathType.process_bind_param() was calling .absolute() on relative paths,
|
||||
which resolves against the current working directory (cwd) instead of the
|
||||
media directory. In production, cwd is /opt/wrolpi, so paths like
|
||||
'archive/spiegel.de' became '/opt/wrolpi/archive/spiegel.de' instead of
|
||||
'/media/wrolpi/archive/spiegel.de'.
|
||||
|
||||
This migration fixes any corrupted paths in the database and saves the
|
||||
corrected paths to config files.
|
||||
|
||||
Revision ID: b2b9700f5048
|
||||
Revises: a1b2c3d4e5f6
|
||||
Create Date: 2026-01-27
|
||||
"""
|
||||
import os
|
||||
import pathlib
|
||||
|
||||
import yaml
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'b2b9700f5048'
|
||||
down_revision = 'a1b2c3d4e5f6'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def get_relative_path(absolute_path: str, media_directory: str) -> str:
|
||||
"""Convert absolute path to relative path under media directory."""
|
||||
if absolute_path and absolute_path.startswith(media_directory):
|
||||
return absolute_path[len(media_directory):].lstrip('/')
|
||||
return absolute_path
|
||||
|
||||
|
||||
def save_config_file(config: dict, file_path: pathlib.Path, width: int = 120):
|
||||
"""Write config dict to YAML file."""
|
||||
file_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with file_path.open('wt') as fh:
|
||||
yaml.dump(config, fh, width=width, sort_keys=True)
|
||||
fh.flush()
|
||||
os.fsync(fh.fileno())
|
||||
|
||||
|
||||
def upgrade():
|
||||
connection = op.get_bind()
|
||||
|
||||
# Fix collection.directory
|
||||
result = connection.execute(sa.text("""
|
||||
UPDATE collection
|
||||
SET directory = REPLACE(directory, '/opt/wrolpi/', '/media/wrolpi/')
|
||||
WHERE directory LIKE '/opt/wrolpi/%'
|
||||
"""))
|
||||
if result.rowcount:
|
||||
print(f"Fixed {result.rowcount} collection directory paths")
|
||||
|
||||
# Fix file_group.directory
|
||||
result = connection.execute(sa.text("""
|
||||
UPDATE file_group
|
||||
SET directory = REPLACE(directory, '/opt/wrolpi/', '/media/wrolpi/')
|
||||
WHERE directory LIKE '/opt/wrolpi/%'
|
||||
"""))
|
||||
if result.rowcount:
|
||||
print(f"Fixed {result.rowcount} file_group directory paths")
|
||||
|
||||
# Fix file_group.primary_path
|
||||
result = connection.execute(sa.text("""
|
||||
UPDATE file_group
|
||||
SET primary_path = REPLACE(primary_path, '/opt/wrolpi/', '/media/wrolpi/')
|
||||
WHERE primary_path LIKE '/opt/wrolpi/%'
|
||||
"""))
|
||||
if result.rowcount:
|
||||
print(f"Fixed {result.rowcount} file_group primary_path paths")
|
||||
|
||||
# Fix download.destination
|
||||
result = connection.execute(sa.text("""
|
||||
UPDATE download
|
||||
SET destination = REPLACE(destination, '/opt/wrolpi/', '/media/wrolpi/')
|
||||
WHERE destination LIKE '/opt/wrolpi/%'
|
||||
"""))
|
||||
if result.rowcount:
|
||||
print(f"Fixed {result.rowcount} download destination paths")
|
||||
|
||||
# Save corrected paths to config files directly (bypass config framework which needs SharedContext)
|
||||
try:
|
||||
from wrolpi.common import get_media_directory
|
||||
media_dir = str(get_media_directory())
|
||||
config_dir = get_media_directory() / 'config'
|
||||
|
||||
# Save domains config
|
||||
domains_result = connection.execute(sa.text("""
|
||||
SELECT id, name, kind, description, directory, file_format
|
||||
FROM collection
|
||||
WHERE kind = 'domain'
|
||||
ORDER BY name
|
||||
"""))
|
||||
domains_collections = []
|
||||
for row in domains_result:
|
||||
collection_config = {'name': row[1], 'kind': row[2]}
|
||||
if row[3]: # description
|
||||
collection_config['description'] = row[3]
|
||||
if row[4]: # directory
|
||||
collection_config['directory'] = get_relative_path(row[4], media_dir + '/')
|
||||
if row[5]: # file_format
|
||||
collection_config['file_format'] = row[5]
|
||||
# Get tag name if exists
|
||||
tag_result = connection.execute(sa.text("""
|
||||
SELECT t.name FROM tag t
|
||||
JOIN collection c ON c.tag_id = t.id
|
||||
WHERE c.id = :id
|
||||
"""), {'id': row[0]}).first()
|
||||
collection_config['tag_name'] = tag_result[0] if tag_result else None
|
||||
domains_collections.append(collection_config)
|
||||
|
||||
# Read existing config to preserve version
|
||||
domains_file = config_dir / 'domains.yaml'
|
||||
version = 0
|
||||
if domains_file.exists():
|
||||
with domains_file.open() as f:
|
||||
existing = yaml.safe_load(f) or {}
|
||||
version = existing.get('version', 0)
|
||||
|
||||
domains_config = {'version': version + 1, 'collections': domains_collections}
|
||||
save_config_file(domains_config, domains_file)
|
||||
print(f"Saved domains config with {len(domains_collections)} collections")
|
||||
|
||||
# Save channels config
|
||||
# Columns: 0=id, 1=name, 2=kind, 3=description, 4=directory, 5=file_format,
|
||||
# 6=url, 7=source_id, 8=generate_posters, 9=calculate_duration, 10=download_missing_data
|
||||
channels_result = connection.execute(sa.text("""
|
||||
SELECT c.id, c.name, c.kind, c.description, c.directory, c.file_format,
|
||||
ch.url, ch.source_id, ch.generate_posters, ch.calculate_duration,
|
||||
ch.download_missing_data
|
||||
FROM collection c
|
||||
JOIN channel ch ON ch.collection_id = c.id
|
||||
WHERE c.kind = 'channel'
|
||||
ORDER BY c.name
|
||||
"""))
|
||||
channels_list = []
|
||||
for row in channels_result:
|
||||
channel_config = {'name': row[1]}
|
||||
if row[4]: # directory
|
||||
channel_config['directory'] = get_relative_path(row[4], media_dir + '/')
|
||||
if row[6]: # url
|
||||
channel_config['url'] = row[6]
|
||||
if row[7]: # source_id
|
||||
channel_config['source_id'] = row[7]
|
||||
channel_config['generate_posters'] = row[8]
|
||||
channel_config['calculate_duration'] = row[9]
|
||||
channel_config['download_missing_data'] = row[10]
|
||||
if row[5]: # file_format
|
||||
channel_config['file_format'] = row[5]
|
||||
# Get tag name if exists
|
||||
tag_result = connection.execute(sa.text("""
|
||||
SELECT t.name FROM tag t
|
||||
JOIN collection c ON c.tag_id = t.id
|
||||
WHERE c.id = :id
|
||||
"""), {'id': row[0]}).first()
|
||||
channel_config['tag_name'] = tag_result[0] if tag_result else None
|
||||
# Get downloads for this channel's collection
|
||||
downloads_result = connection.execute(sa.text("""
|
||||
SELECT url, frequency FROM download
|
||||
WHERE collection_id = :collection_id
|
||||
"""), {'collection_id': row[0]})
|
||||
downloads = [{'url': d[0], 'frequency': d[1]} for d in downloads_result]
|
||||
if downloads:
|
||||
channel_config['downloads'] = downloads
|
||||
channels_list.append(channel_config)
|
||||
|
||||
# Read existing config to preserve version
|
||||
channels_file = config_dir / 'channels.yaml'
|
||||
version = 0
|
||||
if channels_file.exists():
|
||||
with channels_file.open() as f:
|
||||
existing = yaml.safe_load(f) or {}
|
||||
version = existing.get('version', 0)
|
||||
|
||||
channels_config = {'version': version + 1, 'channels': channels_list}
|
||||
save_config_file(channels_config, channels_file)
|
||||
print(f"Saved channels config with {len(channels_list)} channels")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Warning: Could not save configs: {e}")
|
||||
|
||||
|
||||
def downgrade():
|
||||
# Data fix, no meaningful downgrade
|
||||
pass
|
||||
74
alembic/versions/b2e4f6a8c1d3_drop_inventory_tables.py
Normal file
74
alembic/versions/b2e4f6a8c1d3_drop_inventory_tables.py
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
"""Drop inventory tables (inventory is now config-only).
|
||||
|
||||
The inventory system no longer uses the database; each inventory is a YAML file at config/inventory/<slug>.yaml.
|
||||
Legacy data is migrated to those files on startup (see modules/inventory/migrate.py) before these tables are dropped.
|
||||
|
||||
Revision ID: b2e4f6a8c1d3
|
||||
Revises: a7b1c2d3e4f5
|
||||
Create Date: 2026-06-13 00:00:00.000000
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
revision = 'b2e4f6a8c1d3'
|
||||
down_revision = 'a7b1c2d3e4f5'
|
||||
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)
|
||||
|
||||
# `item` first due to its foreign key to `inventory`.
|
||||
session.execute('DROP TABLE IF EXISTS public.item')
|
||||
session.execute('DROP TABLE IF EXISTS public.inventory')
|
||||
session.execute('DROP TABLE IF EXISTS public.inventories_version')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('''
|
||||
CREATE TABLE inventories_version (
|
||||
version SERIAL PRIMARY KEY NOT NULL
|
||||
)
|
||||
''')
|
||||
|
||||
session.execute('''
|
||||
CREATE TABLE public.inventory (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
viewed_at TIMESTAMP WITHOUT TIME ZONE,
|
||||
created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
deleted_at TIMESTAMP WITHOUT TIME ZONE
|
||||
)''')
|
||||
|
||||
session.execute('''
|
||||
CREATE TABLE public.item (
|
||||
id SERIAL PRIMARY KEY,
|
||||
inventory_id INTEGER REFERENCES inventory(id) ON DELETE CASCADE,
|
||||
brand TEXT,
|
||||
name TEXT,
|
||||
count DECIMAL,
|
||||
item_size DECIMAL,
|
||||
unit TEXT,
|
||||
serving INTEGER,
|
||||
category TEXT,
|
||||
subcategory TEXT,
|
||||
expiration_date DATE,
|
||||
purchase_date DATE,
|
||||
created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
deleted_at TIMESTAMP WITHOUT TIME ZONE
|
||||
)''')
|
||||
|
||||
if not DOCKERIZED:
|
||||
session.execute('ALTER TABLE public.inventories_version OWNER TO wrolpi')
|
||||
session.execute('ALTER TABLE public.inventory OWNER TO wrolpi')
|
||||
session.execute('ALTER TABLE public.item OWNER TO wrolpi')
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
"""Create map_subscription table.
|
||||
|
||||
Revision ID: b3c4d5e6f7a8
|
||||
Revises: a2b3c4d5e6f7
|
||||
Create Date: 2026-03-29
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
revision = 'b3c4d5e6f7a8'
|
||||
down_revision = 'a2b3c4d5e6f7'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.execute('''CREATE TABLE map_subscription (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name TEXT UNIQUE NOT NULL,
|
||||
region TEXT NOT NULL,
|
||||
download_id INTEGER NOT NULL REFERENCES download(id) ON DELETE CASCADE
|
||||
)''')
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.execute('DROP TABLE IF EXISTS map_subscription')
|
||||
|
|
@ -0,0 +1,73 @@
|
|||
"""Remove duplicate Channel fields delegated to Collection
|
||||
|
||||
This migration removes fields from Channel that now delegate to Collection:
|
||||
- name (now property: channel.name → collection.name)
|
||||
- directory (now property: channel.directory → collection.directory)
|
||||
- tag_id (now property: channel.tag_id → collection.tag_id)
|
||||
|
||||
These fields were already synced to Collection in previous migration.
|
||||
|
||||
Revision ID: b43f70f369d0
|
||||
Revises: ba98bd360b7a
|
||||
Create Date: 2025-11-19 21:48:58.488850
|
||||
|
||||
"""
|
||||
import os
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'b43f70f369d0'
|
||||
down_revision = 'ba98bd360b7a'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False
|
||||
|
||||
|
||||
def upgrade():
|
||||
print("\n" + "="*60)
|
||||
print("Removing Duplicate Fields from Channel")
|
||||
print("="*60 + "\n")
|
||||
|
||||
# Step 1: Drop foreign key constraint on tag_id
|
||||
print("Step 1: Dropping tag_id foreign key constraint...")
|
||||
op.drop_constraint('channel_tag_id_fkey', 'channel', type_='foreignkey')
|
||||
print("✓ Dropped foreign key constraint\n")
|
||||
|
||||
# Step 2: Drop columns (data already in Collection)
|
||||
print("Step 2: Dropping duplicate columns...")
|
||||
op.drop_column('channel', 'name')
|
||||
print(" ✓ Dropped channel.name")
|
||||
op.drop_column('channel', 'directory')
|
||||
print(" ✓ Dropped channel.directory")
|
||||
op.drop_column('channel', 'tag_id')
|
||||
print(" ✓ Dropped channel.tag_id\n")
|
||||
|
||||
print("="*60)
|
||||
print("✓ Channel Cleanup Complete")
|
||||
print(" Channels now delegate name/directory/tag to Collection")
|
||||
print("="*60 + "\n")
|
||||
|
||||
|
||||
def downgrade():
|
||||
# Re-add the columns
|
||||
op.add_column('channel', sa.Column('name', sa.String(), nullable=True))
|
||||
op.add_column('channel', sa.Column('directory', sa.String(), nullable=True))
|
||||
op.add_column('channel', sa.Column('tag_id', sa.Integer(), nullable=True))
|
||||
|
||||
# Re-add foreign key
|
||||
op.create_foreign_key('channel_tag_id_fkey', 'channel', 'tag', ['tag_id'], ['id'], ondelete='CASCADE')
|
||||
|
||||
# Restore data from Collection
|
||||
bind = op.get_bind()
|
||||
bind.execute(text("""
|
||||
UPDATE channel
|
||||
SET name = collection.name,
|
||||
directory = collection.directory,
|
||||
tag_id = collection.tag_id
|
||||
FROM collection
|
||||
WHERE channel.collection_id = collection.id
|
||||
"""))
|
||||
34
alembic/versions/b97c1313f986_video_modification_datetime.py
Normal file
34
alembic/versions/b97c1313f986_video_modification_datetime.py
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
"""Video modification_datetime
|
||||
|
||||
Revision ID: b97c1313f986
|
||||
Revises: 3c33b1dae069
|
||||
Create Date: 2022-01-25 08:00:26.944183
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'b97c1313f986'
|
||||
down_revision = '3c33b1dae069'
|
||||
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)
|
||||
session.execute('ALTER TABLE video ADD COLUMN modification_datetime TIMESTAMPTZ')
|
||||
session.execute('CREATE INDEX video_modification_datetime_idx ON video USING BRIN(modification_datetime)')
|
||||
session.execute('UPDATE video SET validated=false') # get modification time for every video duration validation.
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
session.execute('DROP INDEX IF EXISTS video_modification_datetime_idx')
|
||||
session.execute('ALTER TABLE video DROP COLUMN IF EXISTS modification_datetime')
|
||||
|
|
@ -0,0 +1,130 @@
|
|||
"""Add collection_id to Channel model
|
||||
|
||||
This migration:
|
||||
1. Adds collection_id column to channel table
|
||||
2. Creates Collection records for existing Channels
|
||||
3. Links Channels to their Collections
|
||||
4. Adds foreign key constraint
|
||||
|
||||
Revision ID: ba98bd360b7a
|
||||
Revises: migrate_domains_to_collections
|
||||
Create Date: 2025-11-19 21:10:56.472836
|
||||
|
||||
"""
|
||||
import os
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'ba98bd360b7a'
|
||||
down_revision = 'migrate_domains_to_collections'
|
||||
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)
|
||||
|
||||
print("\n" + "="*60)
|
||||
print("Channel → Collection Migration")
|
||||
print("="*60 + "\n")
|
||||
|
||||
# Step 1: Add collection_id column to channel table (nullable initially)
|
||||
print("Step 1: Adding collection_id column to channel table...")
|
||||
op.add_column('channel', sa.Column('collection_id', sa.Integer(), nullable=True))
|
||||
print("✓ Added collection_id column\n")
|
||||
|
||||
# Step 2: Create Collection records for each Channel
|
||||
print("Step 2: Creating Collection records for existing Channels...")
|
||||
|
||||
# Fetch all channels
|
||||
result = session.execute(text("""
|
||||
SELECT id, name, directory, tag_id
|
||||
FROM channel
|
||||
ORDER BY name
|
||||
"""))
|
||||
|
||||
channels = []
|
||||
for row in result:
|
||||
channels.append({
|
||||
'id': row[0],
|
||||
'name': row[1],
|
||||
'directory': row[2],
|
||||
'tag_id': row[3],
|
||||
})
|
||||
|
||||
print(f"Found {len(channels)} Channel records to migrate")
|
||||
|
||||
if channels:
|
||||
for channel in channels:
|
||||
channel_id = channel['id']
|
||||
channel_name = channel['name']
|
||||
|
||||
print(f" Processing Channel {channel_id}: {channel_name}")
|
||||
|
||||
# Check if Collection already exists (using raw SQL to avoid ORM model mismatch)
|
||||
existing = session.execute(text("""
|
||||
SELECT id FROM collection
|
||||
WHERE name = :name AND kind = 'channel'
|
||||
LIMIT 1
|
||||
"""), {'name': channel_name}).first()
|
||||
|
||||
if existing:
|
||||
print(f" Collection already exists (id={existing[0]})")
|
||||
collection_id = existing[0]
|
||||
else:
|
||||
# Create Collection using raw SQL
|
||||
result = session.execute(text("""
|
||||
INSERT INTO collection (name, kind, directory, tag_id)
|
||||
VALUES (:name, 'channel', :directory, :tag_id)
|
||||
RETURNING id
|
||||
"""), {
|
||||
'name': channel_name,
|
||||
'directory': channel['directory'],
|
||||
'tag_id': channel['tag_id'],
|
||||
})
|
||||
collection_id = result.first()[0]
|
||||
print(f" Created Collection id={collection_id}")
|
||||
|
||||
# Link Channel to Collection
|
||||
session.execute(
|
||||
text("UPDATE channel SET collection_id = :collection_id WHERE id = :channel_id"),
|
||||
{'collection_id': collection_id, 'channel_id': channel_id}
|
||||
)
|
||||
|
||||
session.commit()
|
||||
print(f"✓ Created Collections and linked Channels\n")
|
||||
else:
|
||||
print("No channels to migrate\n")
|
||||
|
||||
# Step 3: Add foreign key constraint
|
||||
print("Step 3: Adding foreign key constraint...")
|
||||
op.create_foreign_key(
|
||||
'fk_channel_collection_id',
|
||||
'channel',
|
||||
'collection',
|
||||
['collection_id'],
|
||||
['id'],
|
||||
ondelete='CASCADE'
|
||||
)
|
||||
print("✓ Added foreign key constraint\n")
|
||||
|
||||
print("="*60)
|
||||
print("✓ Channel → Collection Migration Complete")
|
||||
print("="*60 + "\n")
|
||||
|
||||
if not DOCKERIZED:
|
||||
session.execute(text('ALTER TABLE public.channel OWNER TO wrolpi'))
|
||||
|
||||
|
||||
def downgrade():
|
||||
# Remove foreign key constraint
|
||||
op.drop_constraint('fk_channel_collection_id', 'channel', type_='foreignkey')
|
||||
|
||||
# Drop collection_id column
|
||||
op.drop_column('channel', 'collection_id')
|
||||
48
alembic/versions/bddb5e95a91e_video_textsearch_index.py
Normal file
48
alembic/versions/bddb5e95a91e_video_textsearch_index.py
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
"""Video textsearch index
|
||||
|
||||
Revision ID: bddb5e95a91e
|
||||
Revises: db0a1560d923
|
||||
Create Date: 2021-12-31 18:12:00.407694
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'bddb5e95a91e'
|
||||
down_revision = 'db0a1560d923'
|
||||
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)
|
||||
session.execute('DROP INDEX IF EXISTS video_textsearch_idx')
|
||||
session.execute('ALTER TABLE video DROP COLUMN IF EXISTS textsearch')
|
||||
session.execute('''
|
||||
ALTER TABLE video
|
||||
ADD COLUMN textsearch tsvector
|
||||
GENERATED ALWAYS AS (
|
||||
setweight(to_tsvector('english'::regconfig, title), 'A') ||
|
||||
setweight(to_tsvector('english'::regconfig, caption), 'D')
|
||||
) STORED
|
||||
''')
|
||||
session.execute('CREATE INDEX IF NOT EXISTS video_textsearch_idx ON video USING GIN(textsearch)')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
session.execute('DROP INDEX IF EXISTS video_textsearch_idx')
|
||||
session.execute("""
|
||||
ALTER TABLE video
|
||||
ADD COLUMN IF NOT EXISTS textsearch tsvector
|
||||
GENERATED ALWAYS AS (to_tsvector('english'::regconfig,
|
||||
((COALESCE(title, ''::text) || ' '::text) ||
|
||||
COALESCE(caption, ''::text)))) STORED
|
||||
""")
|
||||
33
alembic/versions/bf704baa185d_zim_flag.py
Normal file
33
alembic/versions/bf704baa185d_zim_flag.py
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
"""Zim flag
|
||||
|
||||
Revision ID: bf704baa185d
|
||||
Revises: 751aecf46b88
|
||||
Create Date: 2023-07-01 20:00:35.601752
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'bf704baa185d'
|
||||
down_revision = '751aecf46b88'
|
||||
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)
|
||||
|
||||
session.execute('ALTER TABLE wrolpi_flag ADD COLUMN outdated_zims BOOLEAN DEFAULT FALSE')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('ALTER TABLE wrolpi_flag DROP COLUMN outdated_zims')
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
"""download_last_download_attempt
|
||||
|
||||
Add the `last_download_attempt` column to the `download` table. This records the last time a Download was
|
||||
dispatched (whether the attempt succeeds or fails) and is used to enforce per-domain and global daily download
|
||||
limits. An index supports the "attempted since local midnight" count query.
|
||||
|
||||
Revision ID: c3d5f7a9b1e2
|
||||
Revises: b2e4f6a8c1d3
|
||||
Create Date: 2026-06-28
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'c3d5f7a9b1e2'
|
||||
down_revision = 'b2e4f6a8c1d3'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column('download', sa.Column('last_download_attempt', sa.DateTime(timezone=True), nullable=True))
|
||||
op.create_index('idx_download_last_download_attempt', 'download', ['last_download_attempt'])
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_index('idx_download_last_download_attempt', table_name='download')
|
||||
op.drop_column('download', 'last_download_attempt')
|
||||
28
alembic/versions/c4d5e6f7a8b9_drop_map_subscription_table.py
Normal file
28
alembic/versions/c4d5e6f7a8b9_drop_map_subscription_table.py
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
"""Drop map_subscription table.
|
||||
|
||||
Map subscriptions are now managed via settings.regions on a single Download record.
|
||||
|
||||
Revision ID: c4d5e6f7a8b9
|
||||
Revises: b3c4d5e6f7a8
|
||||
Create Date: 2026-03-31
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
revision = 'c4d5e6f7a8b9'
|
||||
down_revision = 'b3c4d5e6f7a8'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.execute('DROP TABLE IF EXISTS map_subscription')
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.execute('''CREATE TABLE map_subscription (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name TEXT UNIQUE NOT NULL,
|
||||
region TEXT NOT NULL,
|
||||
download_id INTEGER NOT NULL REFERENCES download(id) ON DELETE CASCADE
|
||||
)''')
|
||||
29
alembic/versions/c72d305cf11e_download_settings.py
Normal file
29
alembic/versions/c72d305cf11e_download_settings.py
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
"""Download settings
|
||||
|
||||
Revision ID: c72d305cf11e
|
||||
Revises: d2eace02f5b9
|
||||
Create Date: 2022-10-14 13:00:30.333384
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'c72d305cf11e'
|
||||
down_revision = 'd2eace02f5b9'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('ALTER TABLE download ADD COLUMN settings JSONB')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('ALTER TABLE download DROP COLUMN IF EXISTS settings')
|
||||
59
alembic/versions/c9561bda3cf0_file_group_indexes.py
Normal file
59
alembic/versions/c9561bda3cf0_file_group_indexes.py
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
"""file_group indexes
|
||||
|
||||
Revision ID: c9561bda3cf0
|
||||
Revises: 3b6918aeca4b
|
||||
Create Date: 2023-03-25 20:45:00.470336
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'c9561bda3cf0'
|
||||
down_revision = '3b6918aeca4b'
|
||||
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)
|
||||
|
||||
session.execute('CREATE INDEX file_group_mimetype_idx ON file_group(mimetype)')
|
||||
session.execute('CREATE INDEX file_group_model_idx ON file_group(model)')
|
||||
session.execute('CREATE INDEX file_group_modification_datetime_idx ON file_group(modification_datetime)')
|
||||
session.execute('CREATE INDEX file_group_size_ix ON file_group(size)')
|
||||
session.execute('CREATE INDEX file_group_textsearch_idx ON file_group USING GIN(textsearch)')
|
||||
|
||||
session.execute('CREATE INDEX archive_domain_id_idx ON archive(domain_id)')
|
||||
|
||||
session.execute('CREATE INDEX domains_domain_idx ON domains(domain)')
|
||||
|
||||
session.execute('CREATE INDEX video_source_id_idx ON video(source_id)')
|
||||
session.execute('CREATE INDEX video_upload_date_idx ON video(upload_date)')
|
||||
session.execute('CREATE INDEX video_view_count_idx ON video(view_count)')
|
||||
session.execute('CREATE INDEX video_viewed_idx ON video(viewed)')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('DROP INDEX IF EXISTS file_group_full_stem_idx')
|
||||
session.execute('DROP INDEX IF EXISTS file_group_mimetype_idx')
|
||||
session.execute('DROP INDEX IF EXISTS file_group_model_idx')
|
||||
session.execute('DROP INDEX IF EXISTS file_group_modification_datetime_idx')
|
||||
session.execute('DROP INDEX IF EXISTS file_group_size_ix')
|
||||
|
||||
session.execute('DROP INDEX IF EXISTS archive_domain_id_idx')
|
||||
|
||||
session.execute('DROP INDEX IF EXISTS domains_domain_idx')
|
||||
|
||||
session.execute('DROP INDEX IF EXISTS video_source_id_idx')
|
||||
session.execute('DROP INDEX IF EXISTS video_upload_date_idx')
|
||||
session.execute('DROP INDEX IF EXISTS video_view_count_idx')
|
||||
session.execute('DROP INDEX IF EXISTS video_viewed_idx')
|
||||
30
alembic/versions/d0bbe45e56c3_reindex_pdfs.py
Normal file
30
alembic/versions/d0bbe45e56c3_reindex_pdfs.py
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
"""Reindex pdfs
|
||||
|
||||
Revision ID: d0bbe45e56c3
|
||||
Revises: dbf05c8e8dcc
|
||||
Create Date: 2022-12-09 12:27:18.908533
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'd0bbe45e56c3'
|
||||
down_revision = 'dbf05c8e8dcc'
|
||||
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)
|
||||
|
||||
session.execute("UPDATE file SET indexed=false WHERE mimetype = 'application/pdf'")
|
||||
|
||||
|
||||
def downgrade():
|
||||
pass
|
||||
58
alembic/versions/d2eace02f5b9_file_path_on_cascade.py
Normal file
58
alembic/versions/d2eace02f5b9_file_path_on_cascade.py
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
"""file.path on cascade
|
||||
|
||||
Revision ID: d2eace02f5b9
|
||||
Revises: 70db5ba8763d
|
||||
Create Date: 2022-09-28 15:14:43.306819
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'd2eace02f5b9'
|
||||
down_revision = '70db5ba8763d'
|
||||
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)
|
||||
|
||||
session.execute('''
|
||||
ALTER TABLE video DROP CONSTRAINT video_caption_path_fkey;
|
||||
ALTER TABLE video DROP CONSTRAINT video_info_json_path_fkey;
|
||||
ALTER TABLE video DROP CONSTRAINT video_poster_path_fkey;
|
||||
ALTER TABLE video DROP CONSTRAINT video_video_path_fkey;
|
||||
ALTER TABLE video ADD FOREIGN KEY (caption_path) REFERENCES file ON DELETE CASCADE;
|
||||
ALTER TABLE video ADD FOREIGN KEY (info_json_path) REFERENCES file ON DELETE CASCADE;
|
||||
ALTER TABLE video ADD FOREIGN KEY (poster_path) REFERENCES file ON DELETE CASCADE;
|
||||
ALTER TABLE video ADD FOREIGN KEY (video_path) REFERENCES file ON DELETE CASCADE;
|
||||
''')
|
||||
|
||||
session.execute('''
|
||||
ALTER TABLE archive DROP CONSTRAINT archive_readability_json_path_fkey;
|
||||
ALTER TABLE archive DROP CONSTRAINT archive_readability_path_fkey;
|
||||
ALTER TABLE archive DROP CONSTRAINT archive_readability_txt_path_fkey;
|
||||
ALTER TABLE archive DROP CONSTRAINT archive_screenshot_path_fkey;
|
||||
ALTER TABLE archive DROP CONSTRAINT archive_singlefile_path_fkey;
|
||||
ALTER TABLE archive ADD FOREIGN KEY (readability_json_path) REFERENCES file ON DELETE CASCADE;
|
||||
ALTER TABLE archive ADD FOREIGN KEY (readability_path) REFERENCES file ON DELETE CASCADE;
|
||||
ALTER TABLE archive ADD FOREIGN KEY (readability_txt_path) REFERENCES file ON DELETE CASCADE;
|
||||
ALTER TABLE archive ADD FOREIGN KEY (screenshot_path) REFERENCES file ON DELETE CASCADE;
|
||||
ALTER TABLE archive ADD FOREIGN KEY (singlefile_path) REFERENCES file ON DELETE CASCADE;
|
||||
''')
|
||||
|
||||
if not DOCKERIZED:
|
||||
session.execute('ALTER TABLE public.file OWNER TO wrolpi')
|
||||
session.execute('ALTER TABLE public.video OWNER TO wrolpi')
|
||||
session.execute('ALTER TABLE public.domains OWNER TO wrolpi')
|
||||
session.execute('ALTER TABLE public.archive OWNER TO wrolpi')
|
||||
|
||||
|
||||
def downgrade():
|
||||
pass
|
||||
29
alembic/versions/d371333159ab_video_view_count_bigint.py
Normal file
29
alembic/versions/d371333159ab_video_view_count_bigint.py
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
"""Video view_count bigint.
|
||||
|
||||
Revision ID: d371333159ab
|
||||
Revises: b2b9700f5048
|
||||
Create Date: 2026-02-08
|
||||
|
||||
This migration changes the view_count column from INTEGER to BIGINT
|
||||
to accommodate YouTube videos with view counts exceeding 2,147,483,647.
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'd371333159ab'
|
||||
down_revision = 'b2b9700f5048'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.alter_column('video', 'view_count',
|
||||
existing_type=sa.Integer(),
|
||||
type_=sa.BigInteger())
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.alter_column('video', 'view_count',
|
||||
existing_type=sa.BigInteger(),
|
||||
type_=sa.Integer())
|
||||
33
alembic/versions/d4e446637f18_channel_tag.py
Normal file
33
alembic/versions/d4e446637f18_channel_tag.py
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
"""Channel tag
|
||||
|
||||
Revision ID: d4e446637f18
|
||||
Revises: 2bfb3b50b178
|
||||
Create Date: 2024-08-03 17:49:17.133086
|
||||
|
||||
"""
|
||||
import os
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'd4e446637f18'
|
||||
down_revision = '2bfb3b50b178'
|
||||
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)
|
||||
|
||||
session.execute('ALTER TABLE channel ADD COLUMN IF NOT EXISTS tag_id INTEGER REFERENCES tag(id)')
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
session.execute('ALTER TABLE channel DROP COLUMN IF EXISTS tag_id')
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue