# Generated by Django 3.0.4 on 2020-03-24 04:44

from django.db import migrations, connection


def dictfetchall(cursor):
    "Return all rows from a cursor as a dict"
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]


def rename_media_url(apps, schema_editor):
    old_path = 'media/django_gii_blog/'
    new_path = 'media/gii_django_blog/'

    update_text_raw = []
    update_text = []
    update_short_text_raw = []
    update_short_text = []
    with connection.cursor() as cursor:
        cursor.execute('select * from "gii_django_blog_post"')

        for row in dictfetchall(cursor):
            if old_path in row['text_raw']:
                update_text_raw.append((row['text_raw'].replace(old_path, new_path), row['id']))

            if old_path in row['text']:
                update_text.append((row['text'].replace(old_path, new_path), row['id']))

            if old_path in row['short_text_raw']:
                update_short_text_raw.append((row['short_text_raw'].replace(old_path, new_path), row['id']))

            if old_path in row['short_text']:
                update_short_text.append((row['short_text'].replace(old_path, new_path), row['id']))

    if update_text_raw:
        with connection.cursor() as cursor:
            cursor.executemany(
                'update "gii_django_blog_post" set "text_raw" = %s where "id" = %s',
                update_text_raw
            )
    if update_text:
        with connection.cursor() as cursor:
            cursor.executemany(
                'update "gii_django_blog_post" set "text" = %s where "id" = %s',
                update_text
            )
    if update_short_text_raw:
        with connection.cursor() as cursor:
            cursor.executemany(
                'update "gii_django_blog_post" set "short_text_raw" = %s where "id" = %s',
                update_short_text_raw
            )
    if update_short_text:
        with connection.cursor() as cursor:
            cursor.executemany(
                'update "gii_django_blog_post" set "short_text" = %s where "id" = %s',
                update_short_text
            )


class Migration(migrations.Migration):

    dependencies = [
        ('gii_django_blog', '0011_auto_20200324_0710'),
    ]

    operations = [
        migrations.RunPython(rename_media_url, migrations.RunPython.noop)
    ]
