# Generated by Django 2.2.13 on 2022-01-31 11:19

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ("models", "8085_relational_data_model_handle_dates"),
    ]

    operations = [
        migrations.AddField(
            model_name="node",
            name="alias",
            field=models.TextField(blank=True, null=True),
        ),
        migrations.AddConstraint(
            model_name="node",
            constraint=models.UniqueConstraint(fields=("alias", "graph"), name="unique_alias_graph"),
        ),
        migrations.RunSQL(
            """
            /*
            The following SQL sets a default alias for each node. 
            If the slugified node name is unique to the graph, the alias is the slugified node name. 
            However if the slugified node name occurs more than once in a graph, the first occurance of the name is the slugified node name.
            Each following occurance is the slugified node name with the ordinal ranking appended to it. 
            For example, if there are three nodes named language within a graph, the aliases would be language, language_n1, and language_n2. 
            If another graph were to have four nodes named language, those nodes would be language, language_n1, language_n2, language_n3
            */

            WITH alias_table AS (
                SELECT name,
                    nodeid,
                    CASE
                        
                        -- if __arches_slugify(name) occurs just once per graph, use __arches_slugify(name)
                        WHEN (
                            ROW_NUMBER() OVER (
                                PARTITION BY __arches_slugify(name), graphid
                                ORDER BY __arches_slugify(name)
                            ) - 1
                        ) = 0 THEN __arches_slugify(name) 
                        
                        -- if __arches_slugify(name) occurs more than once per graph, concat the ordinal to the end of __arches_slugify(name)
                        WHEN (
                            ROW_NUMBER() OVER (
                                PARTITION BY __arches_slugify(name), graphid
                                ORDER BY __arches_slugify(name)
                            ) - 1
                        ) > 0 THEN (
                            __arches_slugify(name) || '_n' || ROW_NUMBER() OVER (
                                PARTITION BY __arches_slugify(name), graphid
                                ORDER BY __arches_slugify(name)
                            ) -1
                        )
                    END as alias
                FROM nodes
            )
            UPDATE nodes
            SET alias = alias_table.alias
            FROM alias_table
            WHERE nodes.nodeid = alias_table.nodeid;
            """,
            """SELECT 1=1;""",
        ),
    ]
