# Generated by Django 2.2.13 on 2021-03-23 16:22

from django.db import migrations, models

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.code AS station_code,
    mst.label AS station,
    mst.id AS station_id,
    n.id AS network_id,
    n.code AS network_code,
    n.label AS network_label,
    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_network n ON mst.network_id = n.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;"""


class Migration(migrations.Migration):

    dependencies = [
        ('measurements', '0016_parametermapping_source_parameter_uom'),
    ]

    operations = [
        migrations.AddField(
            model_name='station',
            name='description',
            field=models.TextField(blank=True, null=True),
        ),
        migrations.RunSQL(sql_drop_view),
        migrations.RunSQL(sql_create_view),
        migrations.RunSQL(sql_grant),
    ]
