# Generated by Django 2.2.3 on 2021-03-17 16:35

from django.db import migrations, models
import django.db.models.deletion

sql_create_view = """
create or replace view measurements_grafana_view as
 SELECT mm."timestamp",
    mm.value,
    ml.label AS location,
    ml.id AS location_id,
    mst.label AS station,
    mst.id AS station_id,
    st_x(ml.geo) AS longitude,
    st_y(ml.geo) AS latitude,
    mp.code AS parameter,
    mp.id AS parameter_id,
    ms.height,
    ms.id AS serie_id
   FROM measurements_measure mm
     LEFT JOIN measurements_serie ms ON mm.serie_id = ms.id
     LEFT JOIN measurements_station mst ON ms.station_id = mst.id
     LEFT JOIN measurements_location ml ON ms.location_id = ml.id
     LEFT JOIN measurements_parameter mp ON ms.parameter_id = mp.id;
"""

sql_drop_view = """drop view if exists measurements_grafana_view;"""

sql_grant = """grant select on measurements_grafana_view to public;"""

sql_update = """
    update measurements_serie
        set location_id=mst.location_id
        from measurements_station mst
        where measurements_serie.station_id = mst.id;
"""


class Migration(migrations.Migration):

    dependencies = [
        ('measurements', '0009_location_elevation'),
    ]

    operations = [
        migrations.RunSQL(sql_drop_view),
        migrations.AddField(
            model_name='serie',
            name='location',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='measurements.Location'),
        ),
        migrations.RunSQL(sql_update),
        migrations.RunSQL(sql_create_view),
        migrations.RunSQL(sql_grant),
    ]
