# Copyright (C) 2016 Linaro Limited
#
# Author: Stevan Radaković <stevan.radakovic@linaro.org>
#
# SPDX-License-Identifier: GPL-2.0-or-later

# Generated by Django 1.9.4 on 2016-04-05 15:43
from django.db import migrations, models

from lava_results_app.models import QueryMaterializedView


def remove_views(apps, schema_editor):
    # Remove materialized views for all queries of content type TestCase.
    Query = apps.get_model("lava_results_app", "Query")
    db_alias = schema_editor.connection.alias
    for query in Query.objects.using(db_alias).all():
        if query.content_type.model == "testcase":
            QueryMaterializedView.drop(query.id)


def noop(apps, schema_editor):
    pass


class Migration(migrations.Migration):
    dependencies = [("lava_results_app", "0007_auto_20160225_1256")]

    operations = [
        migrations.RunPython(remove_views, noop),
        migrations.RunSQL(
            sql=r"""CREATE OR REPLACE FUNCTION chartonumeric(convertvalue character varying)
  RETURNS numeric AS
    $BODY$
        SELECT CASE WHEN trim($1) SIMILAR TO '[0-9]+\.[0-9]+'
        THEN CAST(trim($1) AS numeric)
        ELSE NULL END;
    $BODY$
LANGUAGE 'sql' IMMUTABLE STRICT;""",
            reverse_sql="DROP FUNCTION chartonumeric(convertvalue character varying)",
        ),
        migrations.RunSQL(
            sql="ALTER TABLE lava_results_app_testcase ALTER COLUMN measurement SET DATA TYPE numeric using chartonumeric(measurement)",
            reverse_sql="ALTER TABLE lava_results_app_testcase ALTER COLUMN measurement SET DATA TYPE character varying(512)",
            state_operations=[
                migrations.AlterField(
                    model_name="testcase",
                    name="measurement",
                    field=models.DecimalField(
                        blank=True,
                        decimal_places=10,
                        help_text="Arbitrary value that was measured as a part of this test.",
                        max_digits=30,
                        null=True,
                        verbose_name="Measurement",
                    ),
                )
            ],
        ),
        migrations.RunPython(noop, remove_views),
    ]
