class Migration(migrations.Migration):

    dependencies = [(
        "reporting",
        "0105_ocpcostsummary_ocpcostsummarybynode_ocpcostsummarybyproject_ocppodsummary_ocppodsummarybyproject_ocp",
    )]

    operations = [
        migrations.CreateModel(
            name="OCPAWSCostSummary",
            fields=[
                ("id", models.IntegerField(primary_key=True, serialize=False)),
                ("usage_start", models.DateField()),
                ("usage_end", models.DateField()),
                ("cluster_id", models.CharField(max_length=50, null=True)),
                ("cluster_alias", models.CharField(max_length=256, null=True)),
                ("unblended_cost",
                 models.DecimalField(decimal_places=9,
                                     max_digits=24,
                                     null=True)),
                ("markup_cost",
                 models.DecimalField(decimal_places=9,
                                     max_digits=24,
                                     null=True)),
                ("currency_code", models.CharField(max_length=10)),
            ],
            options={
                "db_table": "reporting_ocpaws_cost_summary",
                "managed": False
            },
        ),
        migrations.CreateModel(
            name="OCPAWSComputeSummary",
            fields=[
                ("id", models.IntegerField(primary_key=True, serialize=False)),
                ("usage_start", models.DateField()),
                ("usage_end", models.DateField()),
                ("cluster_id", models.CharField(max_length=50, null=True)),
                ("cluster_alias", models.CharField(max_length=256, null=True)),
                ("instance_type", models.CharField(max_length=50, null=True)),
                ("resource_id", models.CharField(max_length=253, null=True)),
                ("usage_amount",
                 models.DecimalField(decimal_places=9,
                                     max_digits=24,
                                     null=True)),
                ("unit", models.CharField(max_length=63, null=True)),
                ("unblended_cost",
                 models.DecimalField(decimal_places=9,
                                     max_digits=24,
                                     null=True)),
                ("markup_cost",
                 models.DecimalField(decimal_places=9,
                                     max_digits=24,
                                     null=True)),
                ("currency_code", models.CharField(max_length=10)),
            ],
            options={
                "db_table": "reporting_ocpaws_compute_summary",
                "managed": False
            },
        ),
        migrations.CreateModel(
            name="OCPAWSCostSummaryByAccount",
            fields=[
                ("id", models.IntegerField(primary_key=True, serialize=False)),
                ("usage_start", models.DateField()),
                ("usage_end", models.DateField()),
                ("cluster_id", models.CharField(max_length=50, null=True)),
                ("cluster_alias", models.CharField(max_length=256, null=True)),
                ("usage_account_id", models.CharField(max_length=50)),
                ("unblended_cost",
                 models.DecimalField(decimal_places=9,
                                     max_digits=24,
                                     null=True)),
                ("markup_cost",
                 models.DecimalField(decimal_places=9,
                                     max_digits=24,
                                     null=True)),
                ("currency_code", models.CharField(max_length=10)),
            ],
            options={
                "db_table": "reporting_ocpaws_cost_summary_by_account",
                "managed": False
            },
        ),
        migrations.CreateModel(
            name="OCPAWSCostSummaryByService",
            fields=[
                ("id", models.IntegerField(primary_key=True, serialize=False)),
                ("usage_start", models.DateField()),
                ("usage_end", models.DateField()),
                ("cluster_id", models.CharField(max_length=50, null=True)),
                ("cluster_alias", models.CharField(max_length=256, null=True)),
                ("product_code", models.CharField(max_length=50)),
                ("product_family", models.CharField(max_length=150,
                                                    null=True)),
                ("unblended_cost",
                 models.DecimalField(decimal_places=9,
                                     max_digits=24,
                                     null=True)),
                ("markup_cost",
                 models.DecimalField(decimal_places=9,
                                     max_digits=24,
                                     null=True)),
                ("currency_code", models.CharField(max_length=10)),
            ],
            options={
                "db_table": "reporting_ocpaws_cost_summary_by_account",
                "managed": False
            },
        ),
        migrations.CreateModel(
            name="OCPAWSCostSummaryByRegion",
            fields=[
                ("id", models.IntegerField(primary_key=True, serialize=False)),
                ("usage_start", models.DateField()),
                ("usage_end", models.DateField()),
                ("region", models.CharField(max_length=50, null=True)),
                ("availability_zone", models.CharField(max_length=50,
                                                       null=True)),
                ("unblended_cost",
                 models.DecimalField(decimal_places=9,
                                     max_digits=24,
                                     null=True)),
                ("markup_cost",
                 models.DecimalField(decimal_places=9,
                                     max_digits=24,
                                     null=True)),
                ("currency_code", models.CharField(max_length=10)),
            ],
            options={
                "db_table": "reporting_ocpaws_cost_summary_by_region",
                "managed": False
            },
        ),
        migrations.CreateModel(
            name="OCPAWSDatabaseSummary",
            fields=[
                ("id", models.IntegerField(primary_key=True, serialize=False)),
                ("usage_start", models.DateField()),
                ("usage_end", models.DateField()),
                ("cluster_id", models.CharField(max_length=50, null=True)),
                ("cluster_alias", models.CharField(max_length=256, null=True)),
                ("product_code", models.CharField(max_length=50)),
                ("usage_amount",
                 models.DecimalField(decimal_places=9,
                                     max_digits=24,
                                     null=True)),
                ("unit", models.CharField(max_length=63, null=True)),
                ("unblended_cost",
                 models.DecimalField(decimal_places=9,
                                     max_digits=24,
                                     null=True)),
                ("markup_cost",
                 models.DecimalField(decimal_places=9,
                                     max_digits=24,
                                     null=True)),
                ("currency_code", models.CharField(max_length=10)),
            ],
            options={
                "db_table": "reporting_ocpaws_database_summary",
                "managed": False
            },
        ),
        migrations.CreateModel(
            name="OCPAWSNetworkSummary",
            fields=[
                ("id", models.IntegerField(primary_key=True, serialize=False)),
                ("usage_start", models.DateField()),
                ("usage_end", models.DateField()),
                ("cluster_id", models.CharField(max_length=50, null=True)),
                ("cluster_alias", models.CharField(max_length=256, null=True)),
                ("product_code", models.CharField(max_length=50)),
                ("usage_amount",
                 models.DecimalField(decimal_places=9,
                                     max_digits=24,
                                     null=True)),
                ("unit", models.CharField(max_length=63, null=True)),
                ("unblended_cost",
                 models.DecimalField(decimal_places=9,
                                     max_digits=24,
                                     null=True)),
                ("markup_cost",
                 models.DecimalField(decimal_places=9,
                                     max_digits=24,
                                     null=True)),
                ("currency_code", models.CharField(max_length=10)),
            ],
            options={
                "db_table": "reporting_ocpaws_network_summary",
                "managed": False
            },
        ),
        migrations.CreateModel(
            name="OCPAWSStorageSummary",
            fields=[
                ("id", models.IntegerField(primary_key=True, serialize=False)),
                ("usage_start", models.DateField()),
                ("usage_end", models.DateField()),
                ("cluster_id", models.CharField(max_length=50, null=True)),
                ("cluster_alias", models.CharField(max_length=256, null=True)),
                ("product_family", models.CharField(max_length=150,
                                                    null=True)),
                ("usage_amount",
                 models.DecimalField(decimal_places=9,
                                     max_digits=24,
                                     null=True)),
                ("unit", models.CharField(max_length=63, null=True)),
                ("unblended_cost",
                 models.DecimalField(decimal_places=9,
                                     max_digits=24,
                                     null=True)),
                ("markup_cost",
                 models.DecimalField(decimal_places=9,
                                     max_digits=24,
                                     null=True)),
                ("currency_code", models.CharField(max_length=10)),
            ],
            options={
                "db_table": "reporting_ocpaws_storage_summary",
                "managed": False
            },
        ),
        migrations.RunSQL("""
            DROP MATERIALIZED VIEW IF EXISTS reporting_ocpaws_cost_summary
            ;

            CREATE MATERIALIZED VIEW reporting_ocpaws_cost_summary AS(
                SELECT row_number() OVER(ORDER BY usage_start, cluster_id, cluster_alias) as id,
                    usage_start as usage_start,
                    usage_start as usage_end,
                    cluster_id,
                    cluster_alias,
                    sum(unblended_cost) as unblended_cost,
                    sum(markup_cost) as markup_cost,
                    max(currency_code) as currency_code
                FROM reporting_ocpawscostlineitem_daily_summary
                -- Get data for this month or last month
                WHERE usage_start >= DATE_TRUNC('month', NOW() - '1 month'::interval)::date
                GROUP BY usage_start, cluster_id, cluster_alias
            )
            WITH DATA
            ;

            CREATE UNIQUE INDEX ocpaws_cost_summary
            ON reporting_ocpaws_cost_summary (usage_start, cluster_id, cluster_alias)
            ;

            DROP MATERIALIZED VIEW IF EXISTS reporting_ocpaws_cost_summary_by_account
            ;

            CREATE MATERIALIZED VIEW reporting_ocpaws_cost_summary_by_account AS(
                SELECT row_number() OVER(ORDER BY usage_start, cluster_id, cluster_alias, usage_account_id, account_alias_id) as id,
                    usage_start as usage_start,
                    usage_start as usage_end,
                    cluster_id,
                    cluster_alias,
                    usage_account_id,
                    account_alias_id,
                    sum(unblended_cost) as unblended_cost,
                    sum(markup_cost) as markup_cost,
                    max(currency_code) as currency_code
                FROM reporting_ocpawscostlineitem_daily_summary
                -- Get data for this month or last month
                WHERE usage_start >= DATE_TRUNC('month', NOW() - '1 month'::interval)::date
                GROUP BY usage_start, cluster_id, cluster_alias, usage_account_id, account_alias_id
            )
            WITH DATA
            ;

            CREATE UNIQUE INDEX ocpaws_cost_summary_account
            ON reporting_ocpaws_cost_summary_by_account (usage_start, cluster_id, cluster_alias, usage_account_id, account_alias_id)
            ;

            DROP MATERIALIZED VIEW IF EXISTS reporting_ocpaws_cost_summary_by_service
            ;

            CREATE MATERIALIZED VIEW reporting_ocpaws_cost_summary_by_service AS(
                SELECT row_number() OVER(ORDER BY usage_start, cluster_id, cluster_alias, product_code, product_family) as id,
                    usage_start as usage_start,
                    usage_start as usage_end,
                    cluster_id,
                    cluster_alias,
                    product_code,
                    product_family,
                    sum(unblended_cost) as unblended_cost,
                    sum(markup_cost) as markup_cost,
                    max(currency_code) as currency_code
                FROM reporting_ocpawscostlineitem_daily_summary
                -- Get data for this month or last month
                WHERE usage_start >= DATE_TRUNC('month', NOW() - '1 month'::interval)::date
                GROUP BY usage_start, cluster_id, cluster_alias, product_code, product_family
            )
            WITH DATA
            ;

            CREATE UNIQUE INDEX ocpaws_cost_summary_service
            ON reporting_ocpaws_cost_summary_by_service (usage_start, cluster_id, cluster_alias, product_code, product_family)
            ;

            DROP MATERIALIZED VIEW IF EXISTS reporting_ocpaws_cost_summary_by_region
            ;

            CREATE MATERIALIZED VIEW reporting_ocpaws_cost_summary_by_region AS(
                SELECT row_number() OVER(ORDER BY usage_start, cluster_id, cluster_alias, region, availability_zone) as id,
                    usage_start as usage_start,
                    usage_start as usage_end,
                    cluster_id,
                    cluster_alias,
                    region,
                    availability_zone,
                    sum(unblended_cost) as unblended_cost,
                    sum(markup_cost) as markup_cost,
                    max(currency_code) as currency_code
                FROM reporting_ocpawscostlineitem_daily_summary
                -- Get data for this month or last month
                WHERE usage_start >= DATE_TRUNC('month', NOW() - '1 month'::interval)::date
                GROUP BY usage_start, cluster_id, cluster_alias, region, availability_zone
            )
            WITH DATA
            ;

            CREATE UNIQUE INDEX ocpaws_cost_summary_region
            ON reporting_ocpaws_cost_summary_by_region (usage_start, cluster_id, cluster_alias, region, availability_zone)
            ;

            DROP MATERIALIZED VIEW IF EXISTS reporting_ocpaws_compute_summary
            ;

            CREATE MATERIALIZED VIEW reporting_ocpaws_compute_summary AS(
                SELECT ROW_NUMBER() OVER(ORDER BY usage_start, cluster_id, cluster_alias, instance_type, resource_id) AS id,
                    usage_start,
                    usage_start as usage_end,
                    cluster_id,
                    cluster_alias,
                    instance_type,
                    resource_id,
                    sum(usage_amount) as usage_amount,
                    max(unit) as unit,
                    sum(unblended_cost) as unblended_cost,
                    sum(markup_cost) as markup_cost,
                    max(currency_code) as currency_code
                FROM reporting_ocpawscostlineitem_daily_summary
                WHERE usage_start >= DATE_TRUNC('month', NOW() - '1 month'::interval)::date
                    AND instance_type IS NOT NULL
                GROUP BY usage_start, cluster_id, cluster_alias, instance_type, resource_id
            )
            WITH DATA
            ;

            CREATE UNIQUE INDEX ocpaws_compute_summary
                ON reporting_ocpaws_compute_summary (usage_start, cluster_id, cluster_alias, instance_type, resource_id)
            ;

            DROP MATERIALIZED VIEW IF EXISTS reporting_ocpaws_storage_summary
            ;

            CREATE MATERIALIZED VIEW reporting_ocpaws_storage_summary AS(
                SELECT row_number() OVER(ORDER BY usage_start, cluster_id, cluster_alias, product_family) as id,
                    usage_start as usage_start,
                    usage_start as usage_end,
                    cluster_id,
                    cluster_alias,
                    product_family,
                    sum(usage_amount) as usage_amount,
                    max(unit) as unit,
                    sum(unblended_cost) as unblended_cost,
                    sum(markup_cost) as markup_cost,
                    max(currency_code) as currency_code
                FROM reporting_ocpawscostlineitem_daily_summary
                -- Get data for this month or last month
                WHERE product_family LIKE '%Storage%'
                    AND unit = 'GB-Mo'
                    AND usage_start >= DATE_TRUNC('month', NOW() - '1 month'::interval)::date
                GROUP BY usage_start, cluster_id, cluster_alias, product_family
            )
            WITH DATA
            ;

            CREATE UNIQUE INDEX ocpaws_storage_summary
            ON reporting_ocpaws_storage_summary (usage_start, cluster_id, cluster_alias, product_family)
            ;

            DROP MATERIALIZED VIEW IF EXISTS reporting_ocpaws_network_summary
            ;

            CREATE MATERIALIZED VIEW reporting_ocpaws_network_summary AS(
                SELECT row_number() OVER(ORDER BY usage_start, cluster_id, cluster_alias, product_code) as id,
                    usage_start as usage_start,
                    usage_start as usage_end,
                    cluster_id,
                    cluster_alias,
                    product_code,
                    sum(usage_amount) as usage_amount,
                    max(unit) as unit,
                    sum(unblended_cost) as unblended_cost,
                    sum(markup_cost) as markup_cost,
                    max(currency_code) as currency_code
                FROM reporting_ocpawscostlineitem_daily_summary
                -- Get data for this month or last month
                WHERE product_code IN ('AmazonVPC','AmazonCloudFront','AmazonRoute53','AmazonAPIGateway')
                    AND usage_start >= DATE_TRUNC('month', NOW() - '1 month'::interval)::date
                GROUP BY usage_start, cluster_id, cluster_alias, product_code
            )
            WITH DATA
            ;

            CREATE UNIQUE INDEX ocpaws_network_summary
            ON reporting_ocpaws_network_summary (usage_start, cluster_id, cluster_alias, product_code)
            ;

            DROP MATERIALIZED VIEW IF EXISTS reporting_ocpaws_database_summary
            ;

            CREATE MATERIALIZED VIEW reporting_ocpaws_database_summary AS(
                SELECT row_number() OVER(ORDER BY usage_start, cluster_id, cluster_alias, product_code) as id,
                    usage_start as usage_start,
                    usage_start as usage_end,
                    cluster_id,
                    cluster_alias,
                    product_code,
                    sum(usage_amount) as usage_amount,
                    max(unit) as unit,
                    sum(unblended_cost) as unblended_cost,
                    sum(markup_cost) as markup_cost,
                    max(currency_code) as currency_code
                FROM reporting_ocpawscostlineitem_daily_summary
                -- Get data for this month or last month
                WHERE product_code IN ('AmazonRDS','AmazonDynamoDB','AmazonElastiCache','AmazonNeptune','AmazonRedshift','AmazonDocumentDB')
                    AND usage_start >= DATE_TRUNC('month', NOW() - '1 month'::interval)::date
                GROUP BY usage_start, cluster_id, cluster_alias, product_code
            )
            WITH DATA
            ;

            CREATE UNIQUE INDEX ocpaws_database_summary
            ON reporting_ocpaws_database_summary (usage_start, cluster_id, cluster_alias, product_code)
            ;
            """),
    ]
Example #2
0
class Migration(migrations.Migration):

    dependencies = [
        ('db', '0002_db_migration_prep'),
    ]

    operations = [
        migrations.RunPython(create_vocabularies),
        migrations.RunSQL('delete from screen_funding_supports;'),
        migrations.RunSQL('''
            insert into screen_funding_supports (id,screen_id,funding_support) (
              select nextval('screen_funding_supports_id_seq'), screen.screen_id, value
              from screen
              join screen_funding_support_link fsl on(screen.screen_id=fsl.screen_id)
              join funding_support fs on(fsl.funding_support_id=fs.funding_support_id) 
              order by screen.screen_id,value
              );
        '''.strip()),
        # TODO: 20180920 - no longer needed (JAS)
        #         migrations.RunSQL('delete from user_facility_usage_role;'),
        #         migrations.RunSQL('''
        #             insert into user_facility_usage_role (id,screensaver_user_id,facility_usage_role) (
        #               select nextval('user_facility_usage_role_id_seq'), su.screensaver_user_id, facility_usage_role
        #               from screening_room_user su
        #               join screening_room_user_facility_usage_role roles on(su.screensaver_user_id=roles.screening_room_user_id)
        #               order by su.screensaver_user_id,roles.facility_usage_role
        #               );
        #         '''.strip()),
        # Transfer the cell_line vocab from the "screen_cell_line" table to the
        # "screen_cell_lines" vocab table
        migrations.RunSQL('delete from screen_cell_lines;'),
        migrations.RunSQL('''
            insert into screen_cell_lines (id,screen_id,cell_line) (
              select nextval('screen_cell_lines_id_seq'), screen.screen_id, value
              from screen
              join screen_cell_line scl on(screen.screen_id=scl.screen_id)
              join cell_line cl on(scl.cell_line_id=cl.cell_line_id) 
              order by screen.screen_id,value
              );
        '''.strip()),
        # Transfer the transfection_agent vocab from the transfection_agent
        # table to the screen.transfection_agent field
        migrations.RunSQL('''
            update screen set transfection_agent_text = value 
            from transfection_agent ta 
            where ta.transfection_agent_id=screen.transfection_agent_id;
        '''.strip()),

        # Lab affiliation migration prep: data migration in 0007
        migrations.RenameField(
            model_name='labaffiliation',
            old_name='affiliation_category',
            new_name='category',
        ),
        migrations.RenameField(
            model_name='labaffiliation',
            old_name='affiliation_name',
            new_name='name',
        ),

        # Removed: 20180920 - per JAS no longer needed
        # migrations.RunPython(update_facility_usage_roles),
    ]
Example #3
0
class Migration(migrations.Migration):

    dependencies = [
        ('base', '0008_auto_20160209_1659'),
    ]

    operations = [
        migrations.RunSQL("""CREATE OR REPLACE FUNCTION update_changed_column()
        RETURNS TRIGGER AS $$
        BEGIN
            -- Si on ne fournit pas de nouvelle date
            IF (NEW.changed IS NULL) OR (NEW.changed = OLD.changed) THEN
                NEW.changed := now();
                RETURN NEW;
            END IF;
            -- Condition ci-dessous pour si jamais le record a été modifié entre
            -- le début et la fin de (ou pendant) l'exécution du script de synchronisation
            IF (OLD.changed > NEW.changed) THEN
                NEW.changed := OLD.changed;
            END IF;
            RETURN NEW;
        END;
        $$ language 'plpgsql';"""),
        migrations.RunSQL(create_trigger_for_changed_field('person'), ),
        migrations.RunSQL(create_trigger_for_changed_field('tutor'), ),
        migrations.RunSQL(create_trigger_for_changed_field('student'), ),
        migrations.RunSQL(create_trigger_for_changed_field('organization'), ),
        migrations.RunSQL(create_trigger_for_changed_field('structure'), ),
        migrations.RunSQL(
            create_trigger_for_changed_field('programmemanager'), ),
        migrations.RunSQL(create_trigger_for_changed_field('academicyear'), ),
        migrations.RunSQL(
            create_trigger_for_changed_field('academiccalendar'), ),
        migrations.RunSQL(create_trigger_for_changed_field('offer'), ),
        migrations.RunSQL(create_trigger_for_changed_field('offeryear'), ),
        migrations.RunSQL(
            create_trigger_for_changed_field('offerenrollment'), ),
        migrations.RunSQL(
            create_trigger_for_changed_field('offeryearcalendar'), ),
        migrations.RunSQL(create_trigger_for_changed_field('learningunit'), ),
        migrations.RunSQL(create_trigger_for_changed_field('attribution'), ),
        migrations.RunSQL(
            create_trigger_for_changed_field('learningunityear'), ),
        migrations.RunSQL(
            create_trigger_for_changed_field('learningunitenrollment'), ),
        migrations.RunSQL(create_trigger_for_changed_field('sessionexam'), ),
        migrations.RunSQL(create_trigger_for_changed_field('examenrollment'), )
    ]
class Migration(migrations.Migration):
    dependencies = [
        ('rtb', '0164_merge_20170328_1423'),
    ]

    operations = [
        migrations.RunSQL("""
            DROP VIEW view_rule_type_usual;
        """),
        migrations.RunSQL("""
            DROP VIEW view_rule_type_tracker;
        """),
        migrations.RunSQL("""
            CREATE VIEW view_rule_type_tracker AS SELECT
  data_grid.campaign_id,
  data_grid.placement_id,
  coalesce(data_grid.imps,0) as impressions,
  coalesce(data_grid.conversions,0) as conversions,
  coalesce(data_grid.clicks,0) as clicks,
  coalesce(data_grid.spent,0) as spent,
  CASE coalesce(data_grid.conversions,0) WHEN 0 THEN (0)::double precision
    ELSE ((coalesce(data_grid.spent,0))::double precision / (coalesce(data_grid.conversions,0))::double precision)
  END AS cpa,
  CASE coalesce(data_grid.imps,0) WHEN 0 THEN 0.0 ELSE ((coalesce(data_grid.conversions,0))::double precision / (coalesce(data_grid.imps,0))) END AS cvr,
  case coalesce(data_grid.clicks,0) when 0 then 0 else (coalesce(data_grid.spent,0)) / (coalesce(data_grid.clicks,0)) end as cpc,
  case coalesce(data_grid.imps,0) when 0 then 0 else (coalesce(data_grid.clicks,0) / (coalesce(data_grid.imps,0))) end as ctr,
  kmeansecomm.good as predictionecomm,
  kmeansleadgen.good as predictionleadgen
FROM ui_usual_placements_grid_data_all_tracker as data_grid
LEFT JOIN ( SELECT ml_placements_clusters_kmeans.placement_id,
            ml_placements_clusters_kmeans.good
           FROM ml_placements_clusters_kmeans
          WHERE ((ml_placements_clusters_kmeans.day = 7) AND (ml_placements_clusters_kmeans.test_number = 2) and ml_placements_clusters_kmeans.adv_type='ecommerceAd')) kmeansecomm ON ((data_grid.placement_id = kmeansecomm.placement_id))
LEFT JOIN ( SELECT ml_placements_clusters_kmeans.placement_id,
            ml_placements_clusters_kmeans.good
           FROM ml_placements_clusters_kmeans
          WHERE ((ml_placements_clusters_kmeans.day = 7) AND (ml_placements_clusters_kmeans.test_number = 2) and ml_placements_clusters_kmeans.adv_type='leadGenerationAd')) kmeansleadgen ON ((data_grid.placement_id = kmeansleadgen.placement_id));
        """),
        migrations.RunSQL("""
        CREATE VIEW view_rule_type_report AS SELECT
  data_grid.campaign_id,
  data_grid.placement_id,
  coalesce(data_grid.imps,0) as impressions,
  coalesce(data_grid.conversions,0) as conversions,
  coalesce(data_grid.clicks,0) as clicks,
  coalesce(data_grid.spent,0) as spent,
  CASE coalesce(data_grid.conversions,0) WHEN 0 THEN (0)::double precision
    ELSE ((coalesce(data_grid.spent,0))::double precision / (coalesce(data_grid.conversions,0))::double precision)
  END AS cpa,
  CASE coalesce(data_grid.imps,0) WHEN 0 THEN 0.0 ELSE ((coalesce(data_grid.conversions,0))::double precision / (coalesce(data_grid.imps,0))) END AS cvr,
  case coalesce(data_grid.clicks,0) when 0 then 0 else (coalesce(data_grid.spent,0)) / (coalesce(data_grid.clicks,0)) end as cpc,
  case coalesce(data_grid.imps,0) when 0 then 0 else (coalesce(data_grid.clicks,0) / (coalesce(data_grid.imps,0))) end as ctr,
  kmeansecomm.good as predictionecomm,
  kmeansleadgen.good as predictionleadgen
FROM ui_usual_placements_grid_data_all as data_grid
LEFT JOIN ( SELECT ml_placements_clusters_kmeans.placement_id,
            ml_placements_clusters_kmeans.good
           FROM ml_placements_clusters_kmeans
          WHERE ((ml_placements_clusters_kmeans.day = 7) AND (ml_placements_clusters_kmeans.test_number = 2) and ml_placements_clusters_kmeans.adv_type='ecommerceAd')) kmeansecomm ON ((data_grid.placement_id = kmeansecomm.placement_id))
LEFT JOIN ( SELECT ml_placements_clusters_kmeans.placement_id,
            ml_placements_clusters_kmeans.good
           FROM ml_placements_clusters_kmeans
          WHERE ((ml_placements_clusters_kmeans.day = 7) AND (ml_placements_clusters_kmeans.test_number = 2) and ml_placements_clusters_kmeans.adv_type='leadGenerationAd')) kmeansleadgen ON ((data_grid.placement_id = kmeansleadgen.placement_id));
        """),
        migrations.RunSQL("""
        CREATE VIEW view_rule_unsuspend_type_report AS SELECT
  unsus.campaign_id,
  unsus.placement_id,
  coalesce(data_grid.imps,0)-coalesce(unsus.imps,0) as impressions,
  coalesce(data_grid.conversions,0)-coalesce(unsus.conversions,0) as conversions,
  coalesce(data_grid.clicks,0)-coalesce(unsus.clicks,0) as clicks,
  coalesce(data_grid.spent,0)-coalesce(unsus.spent,0) as spent,
  CASE coalesce(data_grid.conversions-unsus.conversions,0) WHEN 0 THEN (0)::double precision
    ELSE ((coalesce(data_grid.spent,0)-coalesce(unsus.spent,0))::double precision / (coalesce(data_grid.conversions,0)-coalesce(unsus.conversions,0))::double precision)
  END AS cpa,
  CASE coalesce(data_grid.imps,0)-coalesce(unsus.imps, 0) WHEN 0 THEN 0.0 ELSE ((coalesce(data_grid.conversions,0)-coalesce(unsus.conversions,0))::double precision / (coalesce(data_grid.imps,0)-coalesce(unsus.imps,0))::double precision) END AS cvr,
  case coalesce(data_grid.clicks,0)-coalesce(unsus.clicks,0) when 0 then 0 else (coalesce(data_grid.spent,0)-coalesce(unsus.spent,0)) / (coalesce(data_grid.clicks,0)-coalesce(unsus.clicks,0)) end as cpc,
  case coalesce(data_grid.imps,0)-coalesce(unsus.imps,0) when 0 then 0 else (coalesce(data_grid.clicks,0)-coalesce(unsus.clicks,0))::float / (coalesce(data_grid.imps,0)-coalesce(unsus.imps,0)) end as ctr,
  kmeansecomm.good as predictionecomm,
  kmeansleadgen.good as predictionleadgen
FROM placement_state_unsuspend as unsus
LEFT JOIN ui_usual_placements_grid_data_all as data_grid ON data_grid.placement_id = unsus.placement_id AND data_grid.campaign_id = unsus.campaign_id
LEFT JOIN ( SELECT ml_placements_clusters_kmeans.placement_id,
            ml_placements_clusters_kmeans.good
           FROM ml_placements_clusters_kmeans
          WHERE ((ml_placements_clusters_kmeans.day = 7) AND (ml_placements_clusters_kmeans.test_number = 2) and ml_placements_clusters_kmeans.adv_type='ecommerceAd')) kmeansecomm ON ((unsus.placement_id = kmeansecomm.placement_id))
LEFT JOIN ( SELECT ml_placements_clusters_kmeans.placement_id,
            ml_placements_clusters_kmeans.good
           FROM ml_placements_clusters_kmeans
          WHERE ((ml_placements_clusters_kmeans.day = 7) AND (ml_placements_clusters_kmeans.test_number = 2) and ml_placements_clusters_kmeans.adv_type='leadGenerationAd')) kmeansleadgen ON ((unsus.placement_id = kmeansleadgen.placement_id));
        """),
        migrations.RunSQL("""
        CREATE VIEW view_rule_unsuspend_type_tracker AS SELECT
  unsus.campaign_id,
  unsus.placement_id,
  coalesce(data_grid.imps,0)-coalesce(unsus.imps,0) as impressions,
  coalesce(data_grid.conversions,0)-coalesce(unsus.conversions,0) as conversions,
  coalesce(data_grid.clicks,0)-coalesce(unsus.clicks,0) as clicks,
  coalesce(data_grid.spent,0)-coalesce(unsus.spent,0) as spent,
  CASE coalesce(data_grid.conversions-unsus.conversions,0) WHEN 0 THEN (0)::double precision
    ELSE ((coalesce(data_grid.spent,0)-coalesce(unsus.spent,0))::double precision / (coalesce(data_grid.conversions,0)-coalesce(unsus.conversions,0))::double precision)
  END AS cpa,
  CASE coalesce(data_grid.imps,0)-coalesce(unsus.imps, 0) WHEN 0 THEN 0.0 ELSE ((coalesce(data_grid.conversions,0)-coalesce(unsus.conversions,0))::double precision / (coalesce(data_grid.imps,0)-coalesce(unsus.imps,0))::double precision) END AS cvr,
  case coalesce(data_grid.clicks,0)-coalesce(unsus.clicks,0) when 0 then 0 else (coalesce(data_grid.spent,0)-coalesce(unsus.spent,0)) / (coalesce(data_grid.clicks,0)-coalesce(unsus.clicks,0)) end as cpc,
  case coalesce(data_grid.imps,0)-coalesce(unsus.imps,0) when 0 then 0 else (coalesce(data_grid.clicks,0)-coalesce(unsus.clicks,0))::float / (coalesce(data_grid.imps,0)-coalesce(unsus.imps,0)) end as ctr,
  kmeansecomm.good as predictionecomm,
  kmeansleadgen.good as predictionleadgen
FROM placement_state_unsuspend as unsus
LEFT JOIN ui_usual_placements_grid_data_all_tracker as data_grid ON data_grid.placement_id = unsus.placement_id AND data_grid.campaign_id = unsus.campaign_id
LEFT JOIN ( SELECT ml_placements_clusters_kmeans.placement_id,
            ml_placements_clusters_kmeans.good
           FROM ml_placements_clusters_kmeans
          WHERE ((ml_placements_clusters_kmeans.day = 7) AND (ml_placements_clusters_kmeans.test_number = 2) and ml_placements_clusters_kmeans.adv_type='ecommerceAd')) kmeansecomm ON ((unsus.placement_id = kmeansecomm.placement_id))
LEFT JOIN ( SELECT ml_placements_clusters_kmeans.placement_id,
            ml_placements_clusters_kmeans.good
           FROM ml_placements_clusters_kmeans
          WHERE ((ml_placements_clusters_kmeans.day = 7) AND (ml_placements_clusters_kmeans.test_number = 2) and ml_placements_clusters_kmeans.adv_type='leadGenerationAd')) kmeansleadgen ON ((unsus.placement_id = kmeansleadgen.placement_id));
        """)
    ]
Example #5
0
class Migration(migrations.Migration):

    dependencies = [("reporting", "0150_presto_bulk_pk_delete")]

    operations = [
        migrations.RunSQL("""
create view reporting_ocpusagelineitem_daily_summary_presto as
select cluster_id,
       cluster_alias,
       data_source,
       namespace,
       node,
       resource_id,
       usage_start,
       usage_end,
       pod_labels::json,
       pod_usage_cpu_core_hours::text,
       pod_request_cpu_core_hours::text,
       pod_limit_cpu_core_hours::text,
       pod_usage_memory_gigabyte_hours::text,
       pod_request_memory_gigabyte_hours::text,
       pod_limit_memory_gigabyte_hours::text,
       node_capacity_cpu_cores::text,
       node_capacity_cpu_core_hours::text,
       node_capacity_memory_gigabytes::text,
       node_capacity_memory_gigabyte_hours::text,
       cluster_capacity_cpu_core_hours::text,
       cluster_capacity_memory_gigabyte_hours::text,
       persistentvolumeclaim,
       persistentvolume,
       storageclass,
       volume_labels::json,
       persistentvolumeclaim_capacity_gigabyte::text,
       persistentvolumeclaim_capacity_gigabyte_months::text,
       volume_request_storage_gigabyte_months::text,
       persistentvolumeclaim_usage_gigabyte_months::text,
       infrastructure_raw_cost::text,
       infrastructure_project_raw_cost::text,
       infrastructure_usage_cost::json,
       infrastructure_markup_cost::text,
       infrastructure_project_markup_cost::text,
       infrastructure_monthly_cost::text,
       supplementary_usage_cost::json,
       supplementary_monthly_cost::text,
       monthly_cost_type,
       source_uuid,
       report_period_id,
       uuid
from reporting_ocpusagelineitem_daily_summary;
"""),
        migrations.RunSQL("""
create rule ins_reporting_ocpusagelineitem_daily_summary_presto as
    on insert to reporting_ocpusagelineitem_daily_summary_presto
    do instead
       insert into reporting_ocpusagelineitem_daily_summary (
           cluster_id,
           cluster_alias,
           data_source,
           namespace,
           node,
           resource_id,
           usage_start,
           usage_end,
           pod_labels,
           pod_usage_cpu_core_hours,
           pod_request_cpu_core_hours,
           pod_limit_cpu_core_hours,
           pod_usage_memory_gigabyte_hours,
           pod_request_memory_gigabyte_hours,
           pod_limit_memory_gigabyte_hours,
           node_capacity_cpu_cores,
           node_capacity_cpu_core_hours,
           node_capacity_memory_gigabytes,
           node_capacity_memory_gigabyte_hours,
           cluster_capacity_cpu_core_hours,
           cluster_capacity_memory_gigabyte_hours,
           persistentvolumeclaim,
           persistentvolume,
           storageclass,
           volume_labels,
           persistentvolumeclaim_capacity_gigabyte,
           persistentvolumeclaim_capacity_gigabyte_months,
           volume_request_storage_gigabyte_months,
           persistentvolumeclaim_usage_gigabyte_months,
           infrastructure_raw_cost,
           infrastructure_project_raw_cost,
           infrastructure_usage_cost,
           infrastructure_markup_cost,
           infrastructure_project_markup_cost,
           infrastructure_monthly_cost,
           supplementary_usage_cost,
           supplementary_monthly_cost,
           monthly_cost_type,
           source_uuid,
           report_period_id,
           uuid
       )
       values (
           NEW.cluster_id,
           NEW.cluster_alias,
           NEW.data_source,
           NEW.namespace,
           NEW.node,
           NEW.resource_id,
           NEW.usage_start,
           NEW.usage_end,
           NEW.pod_labels::jsonb,
           NEW.pod_usage_cpu_core_hours::numeric(73,9),
           NEW.pod_request_cpu_core_hours::numeric(73,9),
           NEW.pod_limit_cpu_core_hours::numeric(73,9),
           NEW.pod_usage_memory_gigabyte_hours::numeric(73,9),
           NEW.pod_request_memory_gigabyte_hours::numeric(73,9),
           NEW.pod_limit_memory_gigabyte_hours::numeric(73,9),
           NEW.node_capacity_cpu_cores::numeric(73,9),
           NEW.node_capacity_cpu_core_hours::numeric(73,9),
           NEW.node_capacity_memory_gigabytes::numeric(73,9),
           NEW.node_capacity_memory_gigabyte_hours::numeric(73,9),
           NEW.cluster_capacity_cpu_core_hours::numeric(73,9),
           NEW.cluster_capacity_memory_gigabyte_hours::numeric(73,9),
           NEW.persistentvolumeclaim,
           NEW.persistentvolume,
           NEW.storageclass,
           NEW.volume_labels::jsonb,
           NEW.persistentvolumeclaim_capacity_gigabyte::numeric(73,9),
           NEW.persistentvolumeclaim_capacity_gigabyte_months::numeric(73,9),
           NEW.volume_request_storage_gigabyte_months::numeric(73,9),
           NEW.persistentvolumeclaim_usage_gigabyte_months::numeric(73,9),
           NEW.infrastructure_raw_cost::numeric(33,15),
           NEW.infrastructure_project_raw_cost::numeric(33,15),
           NEW.infrastructure_usage_cost::jsonb,
           NEW.infrastructure_markup_cost::numeric(33,15),
           NEW.infrastructure_project_markup_cost::numeric(33,15),
           NEW.infrastructure_monthly_cost::numeric(33,15),
           NEW.supplementary_usage_cost::jsonb,
           NEW.supplementary_monthly_cost::numeric(33,15),
           NEW.monthly_cost_type,
           NEW.source_uuid,
           NEW.report_period_id,
           NEW.uuid
       );
comment on view reporting_ocpusagelineitem_daily_summary_presto is 'Interface to reporting_ocpusagelineitem_daily_summary table for Presto';
"""),
    ]
class Migration(migrations.Migration):
    """
    Add the SQL function update_skeleton_summaries() to update all entries in
    the catmaid_skeleton_summary table.
    """

    dependencies = [
        ('catmaid', '0039_make_more_constraints_deferrable'),
    ]

    operations = [
        migrations.RunSQL(
            """
            -- Cable length, nodes, creation info, edition info
            CREATE OR REPLACE FUNCTION update_skeleton_summaries()
            RETURNS void AS
            $$
                WITH node_data AS (
                    SELECT creation.skeleton_id, creation.project_id,
                        creation.user_id, creation.creation_time,edit.editor_id,
                        edit.edition_time, counter.nodes, len.cable_length
                    FROM
                    (
                      SELECT *, row_number() OVER(PARTITION BY skeleton_id ORDER BY edition_time DESC) AS rn
                      FROM treenode
                    ) edit
                    JOIN
                    (
                      SELECT *, row_number() OVER(PARTITION BY skeleton_id ORDER BY creation_time ASC) AS rn
                      FROM treenode
                    ) creation
                    ON edit.skeleton_id = creation.skeleton_id
                    JOIN
                    (
                      SELECT skeleton_id, COUNT(*) AS nodes FROM treenode GROUP BY skeleton_id
                    ) counter
                    ON creation.skeleton_id = counter.skeleton_id
                    JOIN
                    (
                      SELECT t1.skeleton_id, SUM(
                        ST_3DLength(ST_MakeLine(ARRAY[
                            ST_MakePoint(t1.location_x, t1.location_y, t1.location_z),
                            ST_MakePoint(t2.location_x, t2.location_y, t2.location_z)
                        ]::geometry[]))
                      ) AS cable_length
                      FROM treenode t1
                      JOIN treenode t2
                      ON (t1.parent_id = t2.id)
                        OR (t1.id = t2.id AND t1.parent_id IS NULL)
                      GROUP BY t1.skeleton_id
                    ) len
                    ON creation.skeleton_id = len.skeleton_id
                    LEFT JOIN catmaid_skeleton_summary summary
                    ON summary.skeleton_id =  len.skeleton_id
                    WHERE edit.rn = 1 AND creation.rn = 1
                    AND summary IS NULL
                )
                INSERT INTO catmaid_skeleton_summary (skeleton_id,
                    project_id, last_summary_update, original_creation_time,
                    last_edition_time, num_nodes, cable_length)
                (
                    SELECT d.skeleton_id, d.project_id, now(), d.creation_time,
                        d.edition_time, d.nodes, d.cable_length
                    FROM node_data d
                )
                ON CONFLICT (skeleton_id) DO UPDATE
                SET last_summary_update = EXCLUDED.last_summary_update,
                    original_creation_time = EXCLUDED.original_creation_time,
                    last_edition_time = EXCLUDED.last_edition_time,
                    num_nodes = EXCLUDED.num_nodes,
                    cable_length = EXCLUDED.cable_length;
            $$ LANGUAGE sql;
        """, """
            DROP FUNCTION update_skeleton_summaries();
        """)
    ]
Example #7
0
class Migration(migrations.Migration):

  dependencies = [
    ('input', '0005_new_data_model'),
  ]

  operations = [
    migrations.RunSQL(
      '''
      insert into operationplan
        (type, id, lastmodified, source, reference, status, quantity,
		 startdate, enddate, criticality, item_id, location_id, supplier_id,
		 name)
      select
         'PO', id, lastmodified, source, reference, status, quantity,
		 startdate, enddate, criticality, item_id, location_id, supplier_id,
         'Purchase ' || item_id || ' @ ' || location_id || '  from ' || supplier_id
      from purchase_order
      ''',
      '''
      insert into purchase_order
        (id, lastmodified, source, reference, status, quantity, startdate,
		 enddate, criticality, item_id, location_id, supplier_id)
      select
         id, lastmodified, source, reference, status, quantity, startdate,
		 enddate, criticality, item_id, location_id, supplier_id
      from operationplan
      where type = 'PO'
      '''
    ),
    migrations.RunSQL(
      '''
      insert into operationplan
        (type, id, lastmodified, source, reference, status, quantity, startdate,
		 enddate, criticality, item_id, origin_id, destination_id, name)
      select
         'DO', id, lastmodified, source, reference, status, quantity, startdate,
		 enddate, criticality, item_id, origin_id, destination_id,
		 'Ship ' || item_id || ' from ' || origin_id || ' to ' || destination_id
      from distribution_order
      ''',
      '''
      insert into distribution_order
        (id, lastmodified, source, reference, status, quantity, startdate, enddate,
		 criticality, item_id, origin_id, destination_id)
      select
       id, lastmodified, source, reference, status, quantity, startdate, enddate,
	   criticality, item_id, origin_id, destination_id from operationplan
      where type = 'DO'
      '''
    ),
    migrations.RunSQL(
      "update operationplan set type = 'MO' where type is null or type = ''",
      "delete from operationplan where type <> 'MO'"
    ),
    migrations.RemoveField(
      model_name='distributionorder',
      name='destination',
    ),
    migrations.RemoveField(
      model_name='distributionorder',
      name='item',
    ),
    migrations.RemoveField(
      model_name='distributionorder',
      name='origin',
    ),
    migrations.RemoveField(
      model_name='purchaseorder',
      name='item',
    ),
    migrations.RemoveField(
      model_name='purchaseorder',
      name='location',
    ),
    migrations.RemoveField(
      model_name='purchaseorder',
      name='supplier',
    ),
    migrations.CreateModel(
      name='DeliveryOrder',
      fields=[
      ],
      options={
        'verbose_name': 'customer shipment',
        'proxy': True,
        'verbose_name_plural': 'customer shipments',
      },
      bases=('input.operationplan',),
    ),
    migrations.CreateModel(
      name='ManufacturingOrder',
      fields=[
      ],
      options={
        'verbose_name': 'manufacturing order',
        'proxy': True,
        'verbose_name_plural': 'manufacturing orders',
      },
      bases=('input.operationplan',),
    ),
    migrations.DeleteModel(
      name='DistributionOrder',
    ),
    migrations.DeleteModel(
      name='PurchaseOrder',
    ),
    migrations.CreateModel(
      name='DistributionOrder',
      fields=[],
      options={
        'verbose_name': 'distribution order',
        'proxy': True,
        'verbose_name_plural': 'distribution orders',
      },
      bases=('input.operationplan',),
    ),
    migrations.CreateModel(
      name='PurchaseOrder',
      fields=[],
      options={
        'verbose_name': 'purchase order',
        'proxy': True,
        'verbose_name_plural': 'purchase orders',
      },
      bases=('input.operationplan',),
    ),
    migrations.AddField(
      model_name='operation',
      name='effective_end',
      field=models.DateTimeField(blank=True, null=True, verbose_name='effective end', help_text='Validity end date'),
    ),
    migrations.AddField(
      model_name='operation',
      name='effective_start',
      field=models.DateTimeField(blank=True, null=True, verbose_name='effective start', help_text='Validity start date'),
    ),
    migrations.AddField(
      model_name='operation',
      name='item',
      field=models.ForeignKey(related_name='operations', verbose_name='item', to='input.Item', blank=True, null=True),
    ),
    migrations.AddField(
      model_name='operation',
      name='priority',
      field=models.IntegerField(blank=True, default=1, null=True, verbose_name='priority', help_text='Priority among all alternates'),
    ),
    migrations.RunSQL(
      '''
      update operation
        set item_id = buffer.item_id
      from buffer
      where buffer.producing_id = operation.name
      ''',
      '''
      update buffer
      set producing_id = operation.name
      from operation
      where buffer.item_id = operation.item_id
        and buffer.location_id = operation.location_id
      '''
      ),
    migrations.RemoveField(
      model_name='buffer',
      name='producing',
    ),
    # A buffer is recognized by an item and location, and they automatically
    # get assigned a name.
#     migrations.RunSQL(
#       '''
#       TODO update buffer name
#       ''',
#       migrations.RunSQL.noop
#     ),

  ]
class Migration(migrations.Migration):

    ops = [
        (
            """
            DROP INDEX IF EXISTS campusonline_student_cardid_idx;
            """,
            """
            CREATE INDEX campusonline_student_cardid_idx ON "public"."campusonline_student" ("cardid");
            """,
        ),
        (
            """
            DROP INDEX IF EXISTS campusonline_student_matriculation_idx;
            """,
            """
            CREATE INDEX campusonline_student_matriculation_idx ON "public"."campusonline_student" ("matriculation");
            """,
        ),
        (
            """
            DROP INDEX IF EXISTS campusonline_student_id_idx;
            """,
            """
            CREATE INDEX campusonline_student_id_idx ON "public"."campusonline_student" ("id");
            """,
        ),
        (
            """
            DROP MATERIALIZED VIEW IF EXISTS "public"."campusonline_student";
            """,
            """
            CREATE MATERIALIZED VIEW "public"."campusonline_student" AS SELECT
                stud_nr::integer AS id,
                stud_mnr AS matriculation,
                stud_famnam AS last_name,
                stud_vorname AS first_name,
                stud_akadgrad AS title,
                stud_mifare AS cardid
            FROM "campusonline"."stud"
            WITH DATA;
            """,
        ),
        (
            """
            DROP FOREIGN TABLE IF EXISTS "campusonline"."stud";
            """,
            """
            CREATE FOREIGN TABLE "campusonline"."stud" (
                STUD_NR numeric,
                STUD_MNR varchar,
                STUD_FAMNAM varchar,
                STUD_VORNAME varchar,
                STUD_AKADGRAD varchar,
                STUD_SEX varchar,
                STUD_MIFARE varchar
            )
            SERVER sqlalchemy OPTIONS (
                tablename 'STUD_V',
                db_url '{}'
            );
            """.format(settings.MULTICORN.get("campusonline")),
        ),
        (
            """
            CREATE FOREIGN TABLE "campusonline"."stud" (
                STUD_NR numeric,
                STUD_MNR varchar,
                STUD_FAMNAM varchar,
                STUD_VORNAME varchar,
                STUD_AKADGRAD varchar,
                STUD_SEX varchar,
                STUD_MIFARE varchar,
                STUD_BENUTZERNAME varchar
            )
            SERVER sqlalchemy OPTIONS (
                tablename 'STUD_V',
                db_url '{}'
            );
            """.format(settings.MULTICORN.get("campusonline")),
            """
            DROP FOREIGN TABLE IF EXISTS "campusonline"."stud";
            """,
        ),
        (
            """
            CREATE MATERIALIZED VIEW "public"."campusonline_student" AS SELECT
                stud_nr::integer AS id,
                stud_mnr AS matriculation,
                stud_famnam AS last_name,
                stud_vorname AS first_name,
                stud_akadgrad AS title,
                stud_mifare AS cardid,
                stud_benutzername as username
            FROM "campusonline"."stud"
            WITH DATA;
            """,
            """
            DROP MATERIALIZED VIEW IF EXISTS "public"."campusonline_student";
            """,
        ),
        (
            """
            CREATE INDEX campusonline_student_id_idx ON "public"."campusonline_student" ("id");
            """,
            """
            DROP INDEX IF EXISTS campusonline_student_id_idx;
            """,
        ),
        (
            """
            CREATE INDEX campusonline_student_matriculation_idx ON "public"."campusonline_student" ("matriculation");
            """,
            """
            DROP INDEX IF EXISTS campusonline_student_matriculation_idx;
            """,
        ),
        (
            """
            CREATE INDEX campusonline_student_cardid_idx ON "public"."campusonline_student" ("cardid");
            """,
            """
            DROP INDEX IF EXISTS campusonline_student_cardid_idx;
            """,
        ),
        (
            """
            CREATE INDEX campusonline_student_username_idx ON "public"."campusonline_student" ("username");
            """,
            """
            DROP INDEX IF EXISTS campusonline_student_username_idx;
            """,
        ),
    ]

    dependencies = [("campusonline", "0045_course_group_term_filterd")]

    operations = [
        migrations.RunSQL(
            [forward for forward, reverse in ops],
            [reverse for forward, reverse in reversed(ops)],
        )
    ]
class Migration(migrations.Migration):

    dependencies = [
        ('custom_attributes',
         '0002_issuecustomattributesvalues_taskcustomattributesvalues_userstorycustomattributesvalues'
         ),
    ]

    operations = [
        # Function: Remove a key in a json field
        migrations.RunSQL(
            """
            CREATE OR REPLACE FUNCTION "json_object_delete_keys"("json" json, VARIADIC "keys_to_delete" text[])
                               RETURNS json
                              LANGUAGE sql
                             IMMUTABLE
                                STRICT
                                    AS $function$
                       SELECT COALESCE ((SELECT ('{' || string_agg(to_json("key") || ':' || "value", ',') || '}')
                                           FROM json_each("json")
                                          WHERE "key" <> ALL ("keys_to_delete")),
                                        '{}')::json $function$;
            """,
            reverse_sql=
            """DROP FUNCTION IF EXISTS "json_object_delete_keys"("json" json, VARIADIC "keys_to_delete" text[])
                                           CASCADE;"""),

        # Function: Romeve a key in the json field of *_custom_attributes_values.values
        migrations.RunSQL(
            """
            CREATE OR REPLACE FUNCTION "clean_key_in_custom_attributes_values"()
                               RETURNS trigger
                                    AS $clean_key_in_custom_attributes_values$
                               DECLARE
                                       key text;
                                       tablename text;
                                 BEGIN
                                       key := OLD.id::text;
                                       tablename := TG_ARGV[0]::text;

                                     EXECUTE 'UPDATE ' || quote_ident(tablename) || '
                                                 SET attributes_values = json_object_delete_keys(attributes_values, ' ||
                                                                                                 quote_literal(key) || ')';

                                       RETURN NULL;
                                   END; $clean_key_in_custom_attributes_values$
                              LANGUAGE plpgsql;

            """,
            reverse_sql=
            """DROP FUNCTION IF EXISTS "clean_key_in_custom_attributes_values"()
                                           CASCADE;"""),

        # Trigger: Clean userstorycustomattributes values before remove a userstorycustomattribute
        migrations.RunSQL(
            """
            CREATE TRIGGER "update_userstorycustomvalues_after_remove_userstorycustomattribute"
           AFTER DELETE ON custom_attributes_userstorycustomattribute
              FOR EACH ROW
         EXECUTE PROCEDURE clean_key_in_custom_attributes_values('custom_attributes_userstorycustomattributesvalues');
            """,
            reverse_sql=
            """DROP TRIGGER IF EXISTS "update_userstorycustomvalues_after_remove_userstorycustomattribute"
                                               ON custom_attributes_userstorycustomattribute
                                          CASCADE;"""),

        # Trigger: Clean taskcustomattributes values before remove a taskcustomattribute
        migrations.RunSQL(
            """
            CREATE TRIGGER "update_taskcustomvalues_after_remove_taskcustomattribute"
           AFTER DELETE ON custom_attributes_taskcustomattribute
              FOR EACH ROW
         EXECUTE PROCEDURE clean_key_in_custom_attributes_values('custom_attributes_taskcustomattributesvalues');
            """,
            reverse_sql=
            """DROP TRIGGER IF EXISTS "update_taskcustomvalues_after_remove_taskcustomattribute"
                                               ON custom_attributes_taskcustomattribute
                                          CASCADE;"""),

        # Trigger: Clean issuecustomattributes values before remove a issuecustomattribute
        migrations.RunSQL(
            """
            CREATE TRIGGER "update_issuecustomvalues_after_remove_issuecustomattribute"
           AFTER DELETE ON custom_attributes_issuecustomattribute
              FOR EACH ROW
         EXECUTE PROCEDURE clean_key_in_custom_attributes_values('custom_attributes_issuecustomattributesvalues');
            """,
            reverse_sql=
            """DROP TRIGGER IF EXISTS "update_issuecustomvalues_after_remove_issuecustomattribute"
                                               ON custom_attributes_issuecustomattribute
                                          CASCADE;""")
    ]
Example #10
0
class Migration(migrations.Migration):

    dependencies = [
        ('nv', '0001_initial'),
    ]

    operations = [
        inform('Please, wait a bit...'),
        migrations.RunSQL(
            """
            CREATE PROCEDURAL LANGUAGE 'plpython3u' HANDLER plpython_call_handler;

            CREATE OR REPLACE FUNCTION create_customers() RETURNS boolean AS
            $$
                import plpy
                from itertools import product

                names = ['Mary', 'Jane', 'Peter', 'Saya', 'Max']
                surnames = ['Red', 'Green', 'Black', 'Blue', 'White']
                values_string = str(tuple(product(names, surnames)))[1:-1]
                try:
                    for i in range(2000000 // 25): # divide by number of values pairs
                        plpy.execute("INSERT INTO nv_customer(first_name, last_name) VALUES {}".format(values_string))
                except plpy.SPIError:
                    return False
                return True
            $$
            LANGUAGE 'plpython3u' VOLATILE;
            SELECT create_customers();
            """,
            reverse_sql='',
        ),
        inform('Customers created, creating emails and phones...'),
        migrations.RunSQL(
            """
            CREATE OR REPLACE FUNCTION create_emails_and_phones() RETURNS boolean AS
            $$
                import plpy
                from random import randint

                cursor = plpy.cursor("SELECT id from nv_customer")
                try:
                    while True:
                        rows = list(cursor.fetch(1000))
                        if not rows:
                            break

                        customer_ids = [row['id'] for row in rows + rows[:randint(2, 30)]]

                        plpy.execute("INSERT INTO nv_phone(number, customer_id) VALUES {}".format(str(tuple(
                            (
                                '+{}{}000000'.format(customer_id, i % 13)[:10],
                                customer_id,
                            ) for i, customer_id in enumerate(customer_ids)
                        ))[1:-1]))

                        plpy.execute("INSERT INTO nv_email(address, customer_id) VALUES {}".format(str(tuple(
                            (
                                '{}{}@example.com'.format(customer_id, i % 13)[-31:],
                                customer_id,
                            ) for i, customer_id in enumerate(customer_ids)
                        ))[1:-1]))
                except plpy.SPIError:
                    return False
                return True
            $$
            LANGUAGE 'plpython3u' VOLATILE;
            SELECT create_emails_and_phones();
            """,
            reverse_sql='',
        ),
    ]
Example #11
0
class Migration(migrations.Migration):

    dependencies = [
        ('mooring', '0089_uniqueseqid'),
    ]

    operations = [
        migrations.RunSQL(
            sql="""CREATE OR REPLACE VIEW mooring_mooringsiteclass_pricehistory_v AS
                SELECT DISTINCT classes.campsite_class_id AS id,
                classes.date_start,
                classes.date_end,
                r.id AS rate_id,
                r.adult,
                r.concession,
                r.child,
                classes.details,
                classes.reason_id,
                r.infant,
                r.mooring
                FROM mooring_rate r
                INNER JOIN (
                    SELECT distinct cc.id AS campsite_class_id,
                    cr.rate_id AS campsite_rate_id,
                    cr.date_start AS date_start,
                    cr.date_end AS date_end,
                    cr.details AS details,
                    cr.reason_id AS reason_id
                    FROM mooring_mooringsite cs,
                    mooring_mooringsiteclass cc,
                    mooring_mooringsiterate cr
                    WHERE cs.mooringsite_class_id = cc.id AND
                    cr.campsite_id = cs.id AND
                    cr.update_level = 1
                ) classes ON r.id = classes.campsite_rate_id;""",
        ),
        migrations.RunSQL(
            sql="""CREATE OR REPLACE VIEW mooring_mooringarea_pricehistory_v AS
                SELECT camps.mooringarea_id AS id, 
                cr.date_start,
                cr.date_end,
                r.id AS rate_id,
                r.adult,
                r.concession,
                r.child,
                cr.details,
                cr.reason_id,
                r.infant,
                r.mooring,
                cr.booking_period_id,
                cr.id as price_id
                FROM mooring_mooringsiterate cr
                INNER JOIN mooring_rate r ON r.id = cr.rate_id
                INNER JOIN (
                    SELECT cg.id AS mooringarea_id,
                    cs.name AS name,
                    cs.id AS campsite_id
                    FROM mooring_mooringsite cs,
                    mooring_mooringarea cg
                    WHERE cs.mooringarea_id = cg.id AND
                    cg.id = cs.mooringarea_id AND
                    cg.price_level = 0
                ) camps ON cr.campsite_id = camps.campsite_id;""",
        ),
    ]
Example #12
0
class Migration(migrations.Migration):

    dependencies = [
        ('lexicon', '0011_glottocodes'),
    ]

    operations = [
        migrations.CreateModel(
            name='CognateClassList',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False,
                                        auto_created=True, primary_key=True)),
                ('name', models.CharField(
                    max_length=128,
                    validators=[
                        ielex.lexicon.validators.suitable_for_url,
                        ielex.lexicon.validators.standard_reserved_names])),
                ('description', models.TextField(null=True, blank=True)),
                ('modified', models.DateTimeField(auto_now=True)),
            ],
            options={
                'ordering': ['name'],
            },
        ),
        migrations.CreateModel(
            name='CognateClassListOrder',
            fields=[
                ('id', models.AutoField(
                    verbose_name='ID', serialize=False,
                    auto_created=True, primary_key=True)),
                ('order', models.FloatField()),
            ],
            options={
                'ordering': ['order'],
            },
        ),
        migrations.AddField(
            model_name='cognateclass',
            name='root_language',
            field=models.TextField(blank=True),
        ),
        migrations.AddField(
            model_name='cognateclasslistorder',
            name='cognateclass',
            field=models.ForeignKey(to='lexicon.CognateClass'),
        ),
        migrations.AddField(
            model_name='cognateclasslistorder',
            name='cognateclass_list',
            field=models.ForeignKey(to='lexicon.CognateClassList'),
        ),
        migrations.AddField(
            model_name='cognateclasslist',
            name='cognateclasses',
            field=models.ManyToManyField(
                to='lexicon.CognateClass',
                through='lexicon.CognateClassListOrder'),
        ),
        migrations.AlterUniqueTogether(
            name='cognateclasslistorder',
            unique_together=set(
                [('cognateclass_list', 'cognateclass'),
                 ('cognateclass_list', 'order')]),
        ),
        migrations.RunSQL(
            "INSERT INTO lexicon_cognateclasslist (name,description,modified) "
            "VALUES ('all','autogenerated by migration.',now());",
            "DELETE FROM lexicon_cognateclasslist;"),
    ]
class Migration(migrations.Migration):

    dependencies = [
        ("djstripe", "0011_auto_20170808_0628"),
    ]

    operations = [
        # Step 1: Remove the `customer` field on StripeSource (SQL noop)
        # We have to do this first because we can't add a customer field on
        # the child model without Django freaking out.
        # We could create it with a different name then rename it... but:
        # https://code.djangoproject.com/ticket/28573
        migrations.RunSQL("",
                          state_operations=[
                              migrations.RemoveField(model_name="stripesource",
                                                     name="customer")
                          ]),

        # Step 2: Create a `customer` field on Card.
        migrations.AddField(
            model_name="card",
            name="customer",
            field=models.ForeignKey(
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name="sources",
                to="djstripe.Customer"),
        ),

        # Step 3: Backfill `card.customer` using data from the parent source model.
        migrations.RunSQL("""
            UPDATE djstripe_card AS dc
            SET customer_id = dss.customer_id
            FROM djstripe_stripesource AS dss
            WHERE dc.stripesource_ptr_id = dss.id
        """),

        # Step 4: Drop NULL on `card.customer`
        migrations.AlterField(
            model_name="card",
            name="customer",
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                related_name="sources",
                to="djstripe.Customer"),
        ),

        # Step 5: Add a PaymentMethod model
        migrations.CreateModel(
            name="PaymentMethod",
            fields=[
                ("id",
                 models.CharField(max_length=255,
                                  primary_key=True,
                                  serialize=False)),
                ("type", models.CharField(db_index=True, max_length=12)),
            ],
        ),

        # Step 6: Backfill the PaymentMethod model, using data from the Card table
        # The neat thing: We don"t have to worry about handling non-card data because
        # until now, it was not supported in djstripe.
        migrations.RunSQL("""
            INSERT INTO djstripe_paymentmethod (id, type)
                SELECT stripe_id, 'card'
                FROM djstripe_stripesource
        """),

        # Step 7: Rename `charge.source` and `customer.default_source` to `_old` prefix
        migrations.RenameField(
            model_name="charge",
            old_name="source",
            new_name="source_old",
        ),
        migrations.RenameField(
            model_name="customer",
            old_name="default_source",
            new_name="default_source_old",
        ),

        # Step 8: Add `charge.source` and `customer.default_source` fields
        # They will be ForeignKeys to the PaymentMethod model
        migrations.AddField(
            model_name="charge",
            name="source",
            field=djstripe.fields.PaymentMethodForeignKey(
                help_text="The source used for this charge.",
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="charges",
                to="djstripe.PaymentMethod"),
        ),
        migrations.AddField(
            model_name="customer",
            name="default_source",
            field=djstripe.fields.PaymentMethodForeignKey(
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="customers",
                to="djstripe.PaymentMethod"),
        ),

        # Step 9: Backfill `charge.source` and `customer.default_source`
        # The values are the stripe IDs of the sources.
        migrations.RunSQL("""
            UPDATE djstripe_charge AS dch
            SET source_id = dss.stripe_id
            FROM djstripe_stripesource AS dss
            WHERE dch.source_old_id = dss.id
        """),
        migrations.RunSQL("""
            UPDATE djstripe_customer AS dcu
            SET default_source_id = dss.stripe_id
            FROM djstripe_stripesource AS dss
            WHERE dcu.default_source_old_id = dss.id
        """),

        # Step 10: Drop the `_old` fields.
        migrations.RemoveField(
            model_name="charge",
            name="source_old",
        ),
        migrations.RemoveField(
            model_name="customer",
            name="default_source_old",
        ),

        # Now we are ready to unpolymorphize the Card model
        # Okay, so altering model bases does not quite work in django migrations.
        # https://groups.google.com/forum/#!topic/django-developers/Z43FvzPP3HA
        # Step 11: Delete the Card model from the state, without deleting it from the db.
        migrations.RunSQL(
            "", state_operations=[migrations.DeleteModel(name="Card")]),

        # Step 12: Recover the Card model without its bases (again, SQL noop)
        migrations.RunSQL(
            "",
            state_operations=[
                migrations.CreateModel(
                    name="Card",
                    fields=[
                        ("stripesource_ptr",
                         models.OneToOneField(
                             auto_created=True,
                             on_delete=django.db.models.deletion.CASCADE,
                             parent_link=True,
                             primary_key=True,
                             serialize=False,
                             to="djstripe.StripeSource")),
                        ("address_city",
                         djstripe.fields.StripeTextField(
                             help_text="Billing address city.", null=True)),
                        ("address_country",
                         djstripe.fields.StripeTextField(
                             help_text="Billing address country.", null=True)),
                        ("address_line1",
                         djstripe.fields.StripeTextField(
                             help_text="Billing address (Line 1).",
                             null=True)),
                        ("address_line1_check",
                         djstripe.fields.StripeCharField(
                             choices=[("fail", "Fail"), ("pass", "Pass"),
                                      ("unavailable", "Unavailable"),
                                      ("unchecked", "Unchecked")],
                             help_text=
                             "If ``address_line1`` was provided, results of the check.",
                             max_length=11,
                             null=True)),
                        ("address_line2",
                         djstripe.fields.StripeTextField(
                             help_text="Billing address (Line 2).",
                             null=True)),
                        ("address_state",
                         djstripe.fields.StripeTextField(
                             help_text="Billing address state.", null=True)),
                        ("address_zip",
                         djstripe.fields.StripeTextField(
                             help_text="Billing address zip code.",
                             null=True)),
                        ("address_zip_check",
                         djstripe.fields.StripeCharField(
                             choices=[("fail", "Fail"), ("pass", "Pass"),
                                      ("unavailable", "Unavailable"),
                                      ("unchecked", "Unchecked")],
                             help_text=
                             "If ``address_zip`` was provided, results of the check.",
                             max_length=11,
                             null=True)),
                        ("brand",
                         djstripe.fields.StripeCharField(
                             choices=[
                                 ("American Express", "American Express"),
                                 ("Diners Club", "Diners Club"),
                                 ("Discover", "Discover"), ("JCB", "JCB"),
                                 ("MasterCard", "MasterCard"),
                                 ("Unknown", "Unknown"), ("Visa", "Visa")
                             ],
                             help_text="Card brand.",
                             max_length=16)),
                        ("country",
                         djstripe.fields.StripeCharField(
                             help_text=
                             "Two-letter ISO code representing the country of the card.",
                             max_length=2)),
                        ("cvc_check",
                         djstripe.fields.StripeCharField(
                             choices=[("fail", "Fail"), ("pass", "Pass"),
                                      ("unavailable", "Unavailable"),
                                      ("unchecked", "Unchecked")],
                             help_text=
                             "If a CVC was provided, results of the check.",
                             max_length=11,
                             null=True)),
                        ("dynamic_last4",
                         djstripe.fields.StripeCharField(
                             help_text=
                             "(For tokenized numbers only.) The last four digits of the device account number.",
                             max_length=4,
                             null=True)),
                        ("exp_month",
                         djstripe.fields.StripeIntegerField(
                             help_text="Card expiration month.")),
                        ("exp_year",
                         djstripe.fields.StripeIntegerField(
                             help_text="Card expiration year.")),
                        ("fingerprint",
                         djstripe.fields.StripeTextField(
                             help_text=
                             "Uniquely identifies this particular card number.",
                             null=True)),
                        ("funding",
                         djstripe.fields.StripeCharField(
                             choices=[("credit", "Credit"), ("debit", "Debit"),
                                      ("prepaid",
                                       "Prepaid"), ("unknown", "Unknown")],
                             help_text="Card funding type.",
                             max_length=7)),
                        ("last4",
                         djstripe.fields.StripeCharField(
                             help_text="Last four digits of Card number.",
                             max_length=4)),
                        ("name",
                         djstripe.fields.StripeTextField(
                             help_text="Cardholder name.", null=True)),
                        ("tokenization_method",
                         djstripe.fields.StripeCharField(
                             choices=[("android_pay", "Android Pay"),
                                      ("apple_pay", "Apple Pay")],
                             help_text=
                             "If the card number is tokenized, this is the method that was used.",
                             max_length=11,
                             null=True)),
                        ("customer",
                         models.ForeignKey(
                             on_delete=django.db.models.deletion.CASCADE,
                             related_name="sources",
                             to="djstripe.Customer")),
                    ],
                    options={
                        "abstract": False,
                    },
                ),
            ]),

        # Step 13: Recover common StripeObject fields previously on StripeSource
        migrations.AddField(
            model_name="card",
            name="created",
            field=models.DateTimeField(auto_now_add=True,
                                       default=django.utils.timezone.now),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name="card",
            name="description",
            field=djstripe.fields.StripeTextField(
                blank=True,
                help_text="A description of this object.",
                null=True),
        ),
        migrations.AddField(
            model_name="card",
            name="livemode",
            field=djstripe.fields.StripeNullBooleanField(
                default=None,
                help_text=
                "Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation."
            ),
        ),
        migrations.AddField(
            model_name="card",
            name="metadata",
            field=djstripe.fields.StripeJSONField(
                blank=True,
                help_text=
                "A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.",
                null=True),
        ),
        migrations.AddField(
            model_name="card",
            name="modified",
            field=models.DateTimeField(auto_now=True),
        ),
        migrations.AddField(
            model_name="card",
            name="stripe_id",
            field=djstripe.fields.StripeIdField(default="", max_length=255),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name="card",
            name="stripe_timestamp",
            field=djstripe.fields.StripeDateTimeField(
                help_text="The datetime this object was created in stripe.",
                null=True),
        ),

        # Step 14: Backfill common fields from djstripe_stripesource table
        migrations.RunSQL("""
            UPDATE djstripe_card AS dc
            SET
               created = dss.created,
               description = dss.description,
               livemode = dss.livemode,
               metadata = dss.metadata,
               modified = dss.modified,
               stripe_id = dss.stripe_id,
               stripe_timestamp = dss.stripe_timestamp
            FROM djstripe_stripesource AS dss
            WHERE dc.stripesource_ptr_id = dss.id
        """),

        # Step 15: Rename stripesource_ptr_id to id and turn it into an Auto field
        migrations.RenameField(
            model_name="card",
            old_name="stripesource_ptr",
            new_name="id",
        ),
        migrations.AlterField(
            model_name="card",
            name="id",
            field=models.AutoField(auto_created=True,
                                   primary_key=True,
                                   serialize=False,
                                   verbose_name="ID"),
        ),

        # Step 16: Delete old ctype field
        migrations.RemoveField(
            model_name="stripesource",
            name="polymorphic_ctype",
        ),

        # Step 17: Actually delete the parent djstripe_stripesource table
        migrations.DeleteModel(name="StripeSource", ),

        # Step 18: Add UNIQUE constraint on stripe_id now that it's backfilled
        # this must be done last because of triggers
        migrations.AlterField(
            model_name="card",
            name="stripe_id",
            field=djstripe.fields.StripeIdField(default="",
                                                max_length=255,
                                                unique=True),
        ),
    ]
class Migration(migrations.Migration):

    dependencies = [
        ('share', '0038_trust_system_user'),
    ]

    operations = [
        migrations.CreateModel(
            name='SubjectVersion',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('action', models.TextField(max_length=10)),
                ('name', models.TextField()),
                ('is_deleted', models.BooleanField(default=False)),
                ('uri', share.models.fields.ShareURLField(blank=True,
                                                          null=True)),
                ('date_created',
                 models.DateTimeField(
                     auto_now_add=True,
                     help_text='The date of ingress to SHARE.')),
                ('date_modified',
                 models.DateTimeField(
                     auto_now=True,
                     db_index=True,
                     help_text='The date this record was modified by SHARE.')),
            ],
            options={
                'ordering': ('-date_modified', ),
                'abstract': False,
                'db_table': None,
                'base_manager_name': 'objects',
            },
        ),
        migrations.CreateModel(
            name='SubjectTaxonomy',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('source',
                 models.OneToOneField(
                     on_delete=django.db.models.deletion.CASCADE,
                     to='share.Source')),
                ('is_deleted', models.BooleanField(default=False)),
                ('date_created', models.DateTimeField(auto_now_add=True)),
                ('date_modified', models.DateTimeField(auto_now=True)),
            ],
            options={'verbose_name_plural': 'Subject Taxonomies'},
        ),
        migrations.AddField(
            model_name='subject',
            name='central_synonym',
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=db.deletion.DatabaseOnDelete(clause='CASCADE'),
                related_name='custom_synonyms',
                to='share.Subject'),
        ),
        migrations.AddField(
            model_name='subject',
            name='date_created',
            field=models.DateTimeField(
                auto_now_add=True,
                default=django.utils.timezone.now,
                help_text='The date of ingress to SHARE.'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='subject',
            name='date_modified',
            field=models.DateTimeField(
                auto_now=True,
                db_index=True,
                help_text='The date this record was modified by SHARE.'),
        ),
        migrations.AddField(
            model_name='subject',
            name='extra',
            field=models.OneToOneField(
                null=True,
                on_delete=db.deletion.DatabaseOnDelete(clause='CASCADE'),
                to='share.ExtraData'),
        ),
        migrations.AddField(
            model_name='subject',
            name='extra_version',
            field=models.OneToOneField(
                db_index=False,
                editable=False,
                null=True,
                on_delete=db.deletion.DatabaseOnDelete(clause='CASCADE'),
                related_name='+',
                to='share.ExtraDataVersion'),
        ),
        migrations.AddField(
            model_name='subject',
            name='is_deleted',
            field=models.BooleanField(default=False),
        ),
        migrations.AddField(
            model_name='subject',
            name='same_as',
            field=models.ForeignKey(
                null=True,
                on_delete=db.deletion.DatabaseOnDelete(clause='CASCADE'),
                related_name='+',
                to='share.Subject'),
        ),
        migrations.AddField(
            model_name='subject',
            name='sources',
            field=share.models.fields.TypedManyToManyField(
                editable=False,
                related_name='source_subject',
                to=settings.AUTH_USER_MODEL),
        ),
        migrations.AddField(
            model_name='subject',
            name='uri',
            field=share.models.fields.ShareURLField(blank=True,
                                                    null=True,
                                                    unique=True),
        ),
        migrations.AddField(
            model_name='throughsubjects',
            name='is_deleted',
            field=models.BooleanField(default=False),
        ),
        migrations.AddField(
            model_name='throughsubjectsversion',
            name='is_deleted',
            field=models.BooleanField(default=False),
        ),
        migrations.AlterField(
            model_name='subject',
            name='id',
            field=models.AutoField(primary_key=True, serialize=False),
        ),
        migrations.AlterField(
            model_name='subject',
            name='name',
            field=models.TextField(),
        ),
        migrations.AlterField(
            model_name='subject',
            name='parent',
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=db.deletion.DatabaseOnDelete(clause='CASCADE'),
                related_name='children',
                to='share.Subject'),
        ),
        migrations.AlterField(
            model_name='throughsubjects',
            name='subject',
            field=models.ForeignKey(
                on_delete=db.deletion.DatabaseOnDelete(clause='CASCADE'),
                related_name='work_relations',
                to='share.Subject'),
        ),
        migrations.AlterField(
            model_name='throughsubjectsversion',
            name='subject',
            field=models.ForeignKey(
                db_index=False,
                on_delete=db.deletion.DatabaseOnDelete(clause='CASCADE'),
                related_name='+',
                to='share.Subject'),
        ),
        migrations.AddField(
            model_name='subjectversion',
            name='central_synonym',
            field=models.ForeignKey(
                blank=True,
                db_index=False,
                null=True,
                on_delete=db.deletion.DatabaseOnDelete(clause='CASCADE'),
                related_name='+',
                to='share.Subject'),
        ),
        migrations.AddField(
            model_name='subjectversion',
            name='central_synonym_version',
            field=models.ForeignKey(
                blank=True,
                db_index=False,
                editable=False,
                null=True,
                on_delete=db.deletion.DatabaseOnDelete(clause='CASCADE'),
                related_name='+',
                to='share.SubjectVersion'),
        ),
        migrations.AddField(
            model_name='subjectversion',
            name='change',
            field=models.OneToOneField(
                editable=False,
                on_delete=db.deletion.DatabaseOnDelete(clause='CASCADE'),
                related_name='affected_subjectversion',
                to='share.Change'),
        ),
        migrations.AddField(
            model_name='subjectversion',
            name='extra',
            field=models.ForeignKey(
                null=True,
                on_delete=db.deletion.DatabaseOnDelete(clause='CASCADE'),
                to='share.ExtraData'),
        ),
        migrations.AddField(
            model_name='subjectversion',
            name='extra_version',
            field=models.ForeignKey(
                db_index=False,
                editable=False,
                null=True,
                on_delete=db.deletion.DatabaseOnDelete(clause='CASCADE'),
                related_name='+',
                to='share.ExtraDataVersion'),
        ),
        migrations.AddField(
            model_name='subjectversion',
            name='parent',
            field=models.ForeignKey(
                blank=True,
                db_index=False,
                null=True,
                on_delete=db.deletion.DatabaseOnDelete(clause='CASCADE'),
                related_name='+',
                to='share.Subject'),
        ),
        migrations.AddField(
            model_name='subjectversion',
            name='parent_version',
            field=models.ForeignKey(
                blank=True,
                db_index=False,
                editable=False,
                null=True,
                on_delete=db.deletion.DatabaseOnDelete(clause='CASCADE'),
                related_name='+',
                to='share.SubjectVersion'),
        ),
        migrations.AddField(
            model_name='subjectversion',
            name='persistent_id',
            field=models.ForeignKey(
                db_column='persistent_id',
                on_delete=db.deletion.DatabaseOnDelete(clause='CASCADE'),
                related_name='versions',
                to='share.Subject'),
        ),
        migrations.AddField(
            model_name='subjectversion',
            name='same_as',
            field=models.ForeignKey(
                null=True,
                on_delete=db.deletion.DatabaseOnDelete(clause='CASCADE'),
                related_name='+',
                to='share.Subject'),
        ),
        migrations.AddField(
            model_name='subjectversion',
            name='same_as_version',
            field=models.ForeignKey(
                db_index=False,
                editable=False,
                null=True,
                on_delete=db.deletion.DatabaseOnDelete(clause='CASCADE'),
                related_name='+',
                to='share.SubjectVersion'),
        ),
        migrations.AddField(
            model_name='subjectversion',
            name='taxonomy',
            field=models.ForeignKey(
                db_index=False,
                editable=False,
                on_delete=django.db.models.deletion.CASCADE,
                related_name='+',
                to='share.SubjectTaxonomy'),
        ),
        migrations.AddField(
            model_name='abstractcreativework',
            name='subject_versions',
            field=share.models.fields.TypedManyToManyField(
                editable=False,
                related_name='_abstractcreativework_subject_versions_+',
                through='share.ThroughSubjects',
                to='share.SubjectVersion'),
        ),
        migrations.AddField(
            model_name='abstractcreativeworkversion',
            name='subject_versions',
            field=share.models.fields.TypedManyToManyField(
                editable=False,
                related_name='_abstractcreativeworkversion_subject_versions_+',
                through='share.ThroughSubjects',
                to='share.SubjectVersion'),
        ),
        migrations.AddField(
            model_name='subject',
            name='central_synonym_version',
            field=models.ForeignKey(
                blank=True,
                db_index=False,
                editable=False,
                null=True,
                on_delete=db.deletion.DatabaseOnDelete(clause='CASCADE'),
                related_name='+',
                to='share.SubjectVersion'),
        ),
        migrations.AddField(
            model_name='subject',
            name='parent_version',
            field=models.ForeignKey(
                blank=True,
                db_index=False,
                editable=False,
                null=True,
                on_delete=db.deletion.DatabaseOnDelete(clause='CASCADE'),
                related_name='+',
                to='share.SubjectVersion'),
        ),
        migrations.AddField(
            model_name='subject',
            name='same_as_version',
            field=models.ForeignKey(
                db_index=False,
                editable=False,
                null=True,
                on_delete=db.deletion.DatabaseOnDelete(clause='CASCADE'),
                related_name='+',
                to='share.SubjectVersion'),
        ),

        # Temporarily null fields
        migrations.AddField(
            model_name='subject',
            name='change',
            field=models.OneToOneField(
                null=True,
                editable=False,
                on_delete=db.deletion.DatabaseOnDelete(clause='CASCADE'),
                related_name='affected_subject',
                to='share.Change'),
        ),
        migrations.AddField(
            model_name='subject',
            name='taxonomy',
            field=models.ForeignKey(
                null=True,
                editable=False,
                on_delete=django.db.models.deletion.CASCADE,
                to='share.SubjectTaxonomy'),
        ),
        migrations.AddField(
            model_name='subject',
            name='version',
            field=models.OneToOneField(
                null=True,
                editable=False,
                on_delete=db.deletion.DatabaseOnDelete(clause='CASCADE'),
                related_name='share_subject_version',
                to='share.SubjectVersion'),
        ),
        migrations.AddField(
            model_name='throughsubjects',
            name='subject_version',
            field=models.ForeignKey(
                db_index=False,
                null=True,
                editable=False,
                on_delete=db.deletion.DatabaseOnDelete(clause='CASCADE'),
                related_name='+',
                to='share.SubjectVersion'),
        ),
        migrations.AddField(
            model_name='throughsubjectsversion',
            name='subject_version',
            field=models.ForeignKey(
                db_index=False,
                null=True,
                editable=False,
                on_delete=db.deletion.DatabaseOnDelete(clause='CASCADE'),
                related_name='+',
                to='share.SubjectVersion'),
        ),

        # Update triggers
        migrations.RunSQL(
            sql=
            'CREATE OR REPLACE FUNCTION before_share_subject_change() RETURNS trigger AS $$\n        DECLARE\n            vid INTEGER;\n        BEGIN\n            INSERT INTO share_subjectversion(persistent_id, action, central_synonym_id, central_synonym_version_id, change_id, date_created, date_modified, extra_id, extra_version_id, is_deleted, name, parent_id, parent_version_id, same_as_id, same_as_version_id, taxonomy_id, uri) VALUES (NEW.id, TG_OP, NEW.central_synonym_id, NEW.central_synonym_version_id, NEW.change_id, NEW.date_created, NEW.date_modified, NEW.extra_id, NEW.extra_version_id, NEW.is_deleted, NEW.name, NEW.parent_id, NEW.parent_version_id, NEW.same_as_id, NEW.same_as_version_id, NEW.taxonomy_id, NEW.uri) RETURNING (id) INTO vid;\n            NEW.version_id = vid;\n            RETURN NEW;\n        END;\n        $$ LANGUAGE plpgsql;',
            reverse_sql='DROP FUNCTION before_share_subject_change();',
        ),
        migrations.RunSQL(
            sql=
            'DROP TRIGGER IF EXISTS share_subject_change ON share_subject;\n\n        CREATE TRIGGER share_subject_change\n        BEFORE INSERT OR UPDATE ON share_subject\n        FOR EACH ROW\n        EXECUTE PROCEDURE before_share_subject_change();',
            reverse_sql='DROP TRIGGER share_subject_change',
        ),
        migrations.RunSQL(
            sql=
            'CREATE OR REPLACE FUNCTION before_share_throughsubjects_change() RETURNS trigger AS $$\n        DECLARE\n            vid INTEGER;\n        BEGIN\n            INSERT INTO share_throughsubjectsversion(persistent_id, action, change_id, creative_work_id, creative_work_version_id, date_created, date_modified, extra_id, extra_version_id, is_deleted, same_as_id, same_as_version_id, subject_id, subject_version_id) VALUES (NEW.id, TG_OP, NEW.change_id, NEW.creative_work_id, NEW.creative_work_version_id, NEW.date_created, NEW.date_modified, NEW.extra_id, NEW.extra_version_id, NEW.is_deleted, NEW.same_as_id, NEW.same_as_version_id, NEW.subject_id, NEW.subject_version_id) RETURNING (id) INTO vid;\n            NEW.version_id = vid;\n            RETURN NEW;\n        END;\n        $$ LANGUAGE plpgsql;',
            reverse_sql='DROP FUNCTION before_share_throughsubjects_change();',
        ),
        migrations.RunSQL(
            sql=
            'DROP TRIGGER IF EXISTS share_throughsubjects_change ON share_throughsubjects;\n\n        CREATE TRIGGER share_throughsubjects_change\n        BEFORE INSERT OR UPDATE ON share_throughsubjects\n        FOR EACH ROW\n        EXECUTE PROCEDURE before_share_throughsubjects_change();',
            reverse_sql='DROP TRIGGER share_throughsubjects_change',
        ),
    ]
Example #15
0
class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ("people", "0001_creer_modeles"),
    ]

    operations = [
        migrations.CreateModel(
            name="Subscription",
            fields=[
                (
                    "id",
                    models.AutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                (
                    "created",
                    models.DateTimeField(
                        default=django.utils.timezone.now,
                        editable=False,
                        verbose_name="date de création",
                    ),
                ),
                (
                    "modified",
                    models.DateTimeField(auto_now=True,
                                         verbose_name="dernière modification"),
                ),
                (
                    "day_of_month",
                    models.PositiveSmallIntegerField(
                        blank=True,
                        editable=False,
                        null=True,
                        verbose_name="Jour du mois",
                    ),
                ),
                (
                    "price",
                    models.IntegerField(
                        editable=False,
                        verbose_name="prix en centimes d'euros"),
                ),
                ("type", models.CharField(max_length=255,
                                          verbose_name="Type")),
                (
                    "mode",
                    models.CharField(max_length=70,
                                     verbose_name="Mode de paiement"),
                ),
                (
                    "status",
                    models.IntegerField(
                        choices=[
                            (
                                0,
                                "Souscription en attente de confirmation par SystemPay",
                            ),
                            (1, "Souscription active"),
                            (
                                2,
                                "Souscription abandonnée avant complétion par la personne",
                            ),
                            (3, "Souscription refusée côté FI"),
                            (4, "Souscription refusée côté banque"),
                            (5, "Souscription terminée"),
                        ],
                        default=0,
                        verbose_name="status",
                    ),
                ),
                ("meta", models.JSONField(blank=True, default=dict)),
                (
                    "end_date",
                    models.DateField(blank=True,
                                     null=True,
                                     verbose_name="Fin de l'abonnement"),
                ),
                (
                    "person",
                    models.ForeignKey(
                        null=True,
                        on_delete=django.db.models.deletion.SET_NULL,
                        related_name="subscriptions",
                        to="people.person",
                    ),
                ),
            ],
            options={
                "verbose_name": "Paiement récurrent",
                "verbose_name_plural": "Paiements récurrents",
            },
        ),
        migrations.CreateModel(
            name="Payment",
            fields=[
                (
                    "id",
                    models.AutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                (
                    "created",
                    models.DateTimeField(
                        default=django.utils.timezone.now,
                        editable=False,
                        verbose_name="date de création",
                    ),
                ),
                (
                    "modified",
                    models.DateTimeField(auto_now=True,
                                         verbose_name="dernière modification"),
                ),
                (
                    "coordinates",
                    django.contrib.gis.db.models.fields.PointField(
                        blank=True,
                        geography=True,
                        null=True,
                        srid=4326,
                        verbose_name="coordonnées",
                    ),
                ),
                (
                    "coordinates_type",
                    models.PositiveSmallIntegerField(
                        choices=[
                            (0, "Coordonnées manuelles"),
                            (10, "Coordonnées automatiques précises"),
                            (
                                20,
                                "Coordonnées automatiques approximatives (niveau rue)",
                            ),
                            (
                                25,
                                "Coordonnées automatique approximatives (arrondissement)",
                            ),
                            (30,
                             "Coordonnées automatiques approximatives (ville)"
                             ),
                            (50,
                             "Coordonnées automatiques (qualité inconnue)"),
                            (254, "Pas de position géographique"),
                            (255, "Coordonnées introuvables"),
                        ],
                        editable=False,
                        help_text=
                        "Comment les coordonnées ci-dessus ont-elle été acquises",
                        null=True,
                        verbose_name="type de coordonnées",
                    ),
                ),
                (
                    "location_name",
                    models.CharField(blank=True,
                                     max_length=255,
                                     verbose_name="nom du lieu"),
                ),
                (
                    "location_address1",
                    models.CharField(blank=True,
                                     max_length=100,
                                     verbose_name="adresse (1ère ligne)"),
                ),
                (
                    "location_address2",
                    models.CharField(blank=True,
                                     max_length=100,
                                     verbose_name="adresse (2ème ligne)"),
                ),
                (
                    "location_citycode",
                    models.CharField(blank=True,
                                     max_length=20,
                                     verbose_name="code INSEE"),
                ),
                (
                    "location_city",
                    models.CharField(blank=True,
                                     max_length=100,
                                     verbose_name="ville"),
                ),
                (
                    "location_zip",
                    models.CharField(blank=True,
                                     max_length=20,
                                     verbose_name="code postal"),
                ),
                (
                    "location_state",
                    models.CharField(blank=True,
                                     max_length=40,
                                     verbose_name="état"),
                ),
                (
                    "location_country",
                    django_countries.fields.CountryField(blank=True,
                                                         default="FR",
                                                         max_length=2,
                                                         verbose_name="pays"),
                ),
                ("email",
                 models.EmailField(max_length=255, verbose_name="email")),
                ("first_name",
                 models.CharField(max_length=255, verbose_name="prénom")),
                (
                    "last_name",
                    models.CharField(max_length=255,
                                     verbose_name="nom de famille"),
                ),
                (
                    "phone_number",
                    phonenumber_field.modelfields.PhoneNumberField(
                        max_length=128,
                        null=True,
                        region=None,
                        verbose_name="numéro de téléphone",
                    ),
                ),
                (
                    "type",
                    models.CharField(choices=[],
                                     max_length=255,
                                     verbose_name="type"),
                ),
                (
                    "mode",
                    models.CharField(max_length=70,
                                     verbose_name="Mode de paiement"),
                ),
                ("price",
                 agir.payments.model_fields.AmountField(verbose_name="Prix")),
                (
                    "status",
                    models.IntegerField(
                        choices=[
                            (0, "Paiement en attente"),
                            (1, "Paiement terminé"),
                            (2, "Paiement abandonné en cours"),
                            (3, "Paiement annulé avant encaissement"),
                            (4, "Paiement refusé par votre banque"),
                            (-1, "Paiement remboursé"),
                        ],
                        default=0,
                        verbose_name="status",
                    ),
                ),
                ("meta", models.JSONField(blank=True, default=dict)),
                (
                    "events",
                    models.JSONField(blank=True,
                                     default=list,
                                     verbose_name="Événements de paiement"),
                ),
                (
                    "person",
                    models.ForeignKey(
                        null=True,
                        on_delete=django.db.models.deletion.SET_NULL,
                        related_name="payments",
                        to="people.person",
                    ),
                ),
                (
                    "subscription",
                    models.ForeignKey(
                        blank=True,
                        null=True,
                        on_delete=django.db.models.deletion.PROTECT,
                        related_name="payments",
                        to="payments.subscription",
                    ),
                ),
            ],
            options={
                "verbose_name": "Paiement",
                "verbose_name_plural": "Paiements",
                "ordering": ("-created", ),
                "get_latest_by": "created",
            },
        ),
        migrations.RunSQL(
            "CREATE INDEX systempay_id ON payments_payment (mod(id, 900000))",
            reverse_sql="DROP INDEX systempay_id;",
        ),
    ]
def _rename_index(old_name, new_name):
    return migrations.RunSQL(
        sql='ALTER INDEX {} RENAME TO {}'.format(old_name, new_name),
        reverse_sql='ALTER INDEX {} RENAME TO {}'.format(new_name, old_name),
    )
Example #17
0
class Migration(migrations.Migration):

    dependencies = [
        ('share', '0002_create_share_user'),
        ('share', '0023_auto_20160809_0132'),
    ]

    operations = [
        migrations.RunSQL(
            sql='CREATE OR REPLACE FUNCTION before_share_extradata_change() RETURNS trigger AS $$\n        DECLARE\n            vid INTEGER;\n        BEGIN\n            INSERT INTO share_extradataversion(persistent_id, action, change_id, data, date_created, date_modified, same_as_id, same_as_version_id, uuid) VALUES (NEW.id, TG_OP, NEW.change_id, NEW.data, NEW.date_created, NEW.date_modified, NEW.same_as_id, NEW.same_as_version_id, NEW.uuid) RETURNING (id) INTO vid;\n            NEW.version_id = vid;\n            RETURN NEW;\n        END;\n        $$ LANGUAGE plpgsql;',
            reverse_sql='DROP FUNCTION before_share_extradata_change();',
        ),
        migrations.RunSQL(
            sql='DROP TRIGGER IF EXISTS share_extradata_change ON share_extradata;\n\n        CREATE TRIGGER share_extradata_change\n        BEFORE INSERT OR UPDATE ON share_extradata\n        FOR EACH ROW\n        EXECUTE PROCEDURE before_share_extradata_change();',
            reverse_sql='DROP TRIGGER share_extradata_change',
        ),
        migrations.RunSQL(
            sql='CREATE OR REPLACE FUNCTION before_share_venue_change() RETURNS trigger AS $$\n        DECLARE\n            vid INTEGER;\n        BEGIN\n            INSERT INTO share_venueversion(persistent_id, action, change_id, community_identifier, date_created, date_modified, extra_id, extra_version_id, location, name, same_as_id, same_as_version_id, uuid, venue_type) VALUES (NEW.id, TG_OP, NEW.change_id, NEW.community_identifier, NEW.date_created, NEW.date_modified, NEW.extra_id, NEW.extra_version_id, NEW.location, NEW.name, NEW.same_as_id, NEW.same_as_version_id, NEW.uuid, NEW.venue_type) RETURNING (id) INTO vid;\n            NEW.version_id = vid;\n            RETURN NEW;\n        END;\n        $$ LANGUAGE plpgsql;',
            reverse_sql='DROP FUNCTION before_share_venue_change();',
        ),
        migrations.RunSQL(
            sql='DROP TRIGGER IF EXISTS share_venue_change ON share_venue;\n\n        CREATE TRIGGER share_venue_change\n        BEFORE INSERT OR UPDATE ON share_venue\n        FOR EACH ROW\n        EXECUTE PROCEDURE before_share_venue_change();',
            reverse_sql='DROP TRIGGER share_venue_change',
        ),
        migrations.RunSQL(
            sql='CREATE OR REPLACE FUNCTION before_share_award_change() RETURNS trigger AS $$\n        DECLARE\n            vid INTEGER;\n        BEGIN\n            INSERT INTO share_awardversion(persistent_id, action, award, change_id, date_created, date_modified, description, extra_id, extra_version_id, same_as_id, same_as_version_id, url, uuid) VALUES (NEW.id, TG_OP, NEW.award, NEW.change_id, NEW.date_created, NEW.date_modified, NEW.description, NEW.extra_id, NEW.extra_version_id, NEW.same_as_id, NEW.same_as_version_id, NEW.url, NEW.uuid) RETURNING (id) INTO vid;\n            NEW.version_id = vid;\n            RETURN NEW;\n        END;\n        $$ LANGUAGE plpgsql;',
            reverse_sql='DROP FUNCTION before_share_award_change();',
        ),
        migrations.RunSQL(
            sql='DROP TRIGGER IF EXISTS share_award_change ON share_award;\n\n        CREATE TRIGGER share_award_change\n        BEFORE INSERT OR UPDATE ON share_award\n        FOR EACH ROW\n        EXECUTE PROCEDURE before_share_award_change();',
            reverse_sql='DROP TRIGGER share_award_change',
        ),
        migrations.RunSQL(
            sql='CREATE OR REPLACE FUNCTION before_share_tag_change() RETURNS trigger AS $$\n        DECLARE\n            vid INTEGER;\n        BEGIN\n            INSERT INTO share_tagversion(persistent_id, action, change_id, date_created, date_modified, extra_id, extra_version_id, name, same_as_id, same_as_version_id, uuid) VALUES (NEW.id, TG_OP, NEW.change_id, NEW.date_created, NEW.date_modified, NEW.extra_id, NEW.extra_version_id, NEW.name, NEW.same_as_id, NEW.same_as_version_id, NEW.uuid) RETURNING (id) INTO vid;\n            NEW.version_id = vid;\n            RETURN NEW;\n        END;\n        $$ LANGUAGE plpgsql;',
            reverse_sql='DROP FUNCTION before_share_tag_change();',
        ),
        migrations.RunSQL(
            sql='DROP TRIGGER IF EXISTS share_tag_change ON share_tag;\n\n        CREATE TRIGGER share_tag_change\n        BEFORE INSERT OR UPDATE ON share_tag\n        FOR EACH ROW\n        EXECUTE PROCEDURE before_share_tag_change();',
            reverse_sql='DROP TRIGGER share_tag_change',
        ),
        migrations.RunSQL(
            sql='CREATE OR REPLACE FUNCTION before_share_link_change() RETURNS trigger AS $$\n        DECLARE\n            vid INTEGER;\n        BEGIN\n            INSERT INTO share_linkversion(persistent_id, action, change_id, date_created, date_modified, extra_id, extra_version_id, same_as_id, same_as_version_id, type, url, uuid) VALUES (NEW.id, TG_OP, NEW.change_id, NEW.date_created, NEW.date_modified, NEW.extra_id, NEW.extra_version_id, NEW.same_as_id, NEW.same_as_version_id, NEW.type, NEW.url, NEW.uuid) RETURNING (id) INTO vid;\n            NEW.version_id = vid;\n            RETURN NEW;\n        END;\n        $$ LANGUAGE plpgsql;',
            reverse_sql='DROP FUNCTION before_share_link_change();',
        ),
        migrations.RunSQL(
            sql='DROP TRIGGER IF EXISTS share_link_change ON share_link;\n\n        CREATE TRIGGER share_link_change\n        BEFORE INSERT OR UPDATE ON share_link\n        FOR EACH ROW\n        EXECUTE PROCEDURE before_share_link_change();',
            reverse_sql='DROP TRIGGER share_link_change',
        ),
        migrations.RunSQL(
            sql='CREATE OR REPLACE FUNCTION before_share_throughlinks_change() RETURNS trigger AS $$\n        DECLARE\n            vid INTEGER;\n        BEGIN\n            INSERT INTO share_throughlinksversion(persistent_id, action, change_id, creative_work_id, creative_work_version_id, date_created, date_modified, extra_id, extra_version_id, link_id, link_version_id, same_as_id, same_as_version_id, uuid) VALUES (NEW.id, TG_OP, NEW.change_id, NEW.creative_work_id, NEW.creative_work_version_id, NEW.date_created, NEW.date_modified, NEW.extra_id, NEW.extra_version_id, NEW.link_id, NEW.link_version_id, NEW.same_as_id, NEW.same_as_version_id, NEW.uuid) RETURNING (id) INTO vid;\n            NEW.version_id = vid;\n            RETURN NEW;\n        END;\n        $$ LANGUAGE plpgsql;',
            reverse_sql='DROP FUNCTION before_share_throughlinks_change();',
        ),
        migrations.RunSQL(
            sql='DROP TRIGGER IF EXISTS share_throughlinks_change ON share_throughlinks;\n\n        CREATE TRIGGER share_throughlinks_change\n        BEFORE INSERT OR UPDATE ON share_throughlinks\n        FOR EACH ROW\n        EXECUTE PROCEDURE before_share_throughlinks_change();',
            reverse_sql='DROP TRIGGER share_throughlinks_change',
        ),
        migrations.RunSQL(
            sql='CREATE OR REPLACE FUNCTION before_share_throughvenues_change() RETURNS trigger AS $$\n        DECLARE\n            vid INTEGER;\n        BEGIN\n            INSERT INTO share_throughvenuesversion(persistent_id, action, change_id, creative_work_id, creative_work_version_id, date_created, date_modified, extra_id, extra_version_id, same_as_id, same_as_version_id, uuid, venue_id, venue_version_id) VALUES (NEW.id, TG_OP, NEW.change_id, NEW.creative_work_id, NEW.creative_work_version_id, NEW.date_created, NEW.date_modified, NEW.extra_id, NEW.extra_version_id, NEW.same_as_id, NEW.same_as_version_id, NEW.uuid, NEW.venue_id, NEW.venue_version_id) RETURNING (id) INTO vid;\n            NEW.version_id = vid;\n            RETURN NEW;\n        END;\n        $$ LANGUAGE plpgsql;',
            reverse_sql='DROP FUNCTION before_share_throughvenues_change();',
        ),
        migrations.RunSQL(
            sql='DROP TRIGGER IF EXISTS share_throughvenues_change ON share_throughvenues;\n\n        CREATE TRIGGER share_throughvenues_change\n        BEFORE INSERT OR UPDATE ON share_throughvenues\n        FOR EACH ROW\n        EXECUTE PROCEDURE before_share_throughvenues_change();',
            reverse_sql='DROP TRIGGER share_throughvenues_change',
        ),
        migrations.RunSQL(
            sql='CREATE OR REPLACE FUNCTION before_share_throughawards_change() RETURNS trigger AS $$\n        DECLARE\n            vid INTEGER;\n        BEGIN\n            INSERT INTO share_throughawardsversion(persistent_id, action, award_id, award_version_id, change_id, creative_work_id, creative_work_version_id, date_created, date_modified, extra_id, extra_version_id, same_as_id, same_as_version_id, uuid) VALUES (NEW.id, TG_OP, NEW.award_id, NEW.award_version_id, NEW.change_id, NEW.creative_work_id, NEW.creative_work_version_id, NEW.date_created, NEW.date_modified, NEW.extra_id, NEW.extra_version_id, NEW.same_as_id, NEW.same_as_version_id, NEW.uuid) RETURNING (id) INTO vid;\n            NEW.version_id = vid;\n            RETURN NEW;\n        END;\n        $$ LANGUAGE plpgsql;',
            reverse_sql='DROP FUNCTION before_share_throughawards_change();',
        ),
        migrations.RunSQL(
            sql='DROP TRIGGER IF EXISTS share_throughawards_change ON share_throughawards;\n\n        CREATE TRIGGER share_throughawards_change\n        BEFORE INSERT OR UPDATE ON share_throughawards\n        FOR EACH ROW\n        EXECUTE PROCEDURE before_share_throughawards_change();',
            reverse_sql='DROP TRIGGER share_throughawards_change',
        ),
        migrations.RunSQL(
            sql='CREATE OR REPLACE FUNCTION before_share_throughtags_change() RETURNS trigger AS $$\n        DECLARE\n            vid INTEGER;\n        BEGIN\n            INSERT INTO share_throughtagsversion(persistent_id, action, change_id, creative_work_id, creative_work_version_id, date_created, date_modified, extra_id, extra_version_id, same_as_id, same_as_version_id, tag_id, tag_version_id, uuid) VALUES (NEW.id, TG_OP, NEW.change_id, NEW.creative_work_id, NEW.creative_work_version_id, NEW.date_created, NEW.date_modified, NEW.extra_id, NEW.extra_version_id, NEW.same_as_id, NEW.same_as_version_id, NEW.tag_id, NEW.tag_version_id, NEW.uuid) RETURNING (id) INTO vid;\n            NEW.version_id = vid;\n            RETURN NEW;\n        END;\n        $$ LANGUAGE plpgsql;',
            reverse_sql='DROP FUNCTION before_share_throughtags_change();',
        ),
        migrations.RunSQL(
            sql='DROP TRIGGER IF EXISTS share_throughtags_change ON share_throughtags;\n\n        CREATE TRIGGER share_throughtags_change\n        BEFORE INSERT OR UPDATE ON share_throughtags\n        FOR EACH ROW\n        EXECUTE PROCEDURE before_share_throughtags_change();',
            reverse_sql='DROP TRIGGER share_throughtags_change',
        ),
        migrations.RunSQL(
            sql='CREATE OR REPLACE FUNCTION before_share_throughawardentities_change() RETURNS trigger AS $$\n        DECLARE\n            vid INTEGER;\n        BEGIN\n            INSERT INTO share_throughawardentitiesversion(persistent_id, action, award_id, award_version_id, change_id, date_created, date_modified, entity_id, entity_version_id, extra_id, extra_version_id, same_as_id, same_as_version_id, uuid) VALUES (NEW.id, TG_OP, NEW.award_id, NEW.award_version_id, NEW.change_id, NEW.date_created, NEW.date_modified, NEW.entity_id, NEW.entity_version_id, NEW.extra_id, NEW.extra_version_id, NEW.same_as_id, NEW.same_as_version_id, NEW.uuid) RETURNING (id) INTO vid;\n            NEW.version_id = vid;\n            RETURN NEW;\n        END;\n        $$ LANGUAGE plpgsql;',
            reverse_sql='DROP FUNCTION before_share_throughawardentities_change();',
        ),
        migrations.RunSQL(
            sql='DROP TRIGGER IF EXISTS share_throughawardentities_change ON share_throughawardentities;\n\n        CREATE TRIGGER share_throughawardentities_change\n        BEFORE INSERT OR UPDATE ON share_throughawardentities\n        FOR EACH ROW\n        EXECUTE PROCEDURE before_share_throughawardentities_change();',
            reverse_sql='DROP TRIGGER share_throughawardentities_change',
        ),
        migrations.RunSQL(
            sql='CREATE OR REPLACE FUNCTION before_share_email_change() RETURNS trigger AS $$\n        DECLARE\n            vid INTEGER;\n        BEGIN\n            INSERT INTO share_emailversion(persistent_id, action, change_id, date_created, date_modified, email, extra_id, extra_version_id, is_primary, same_as_id, same_as_version_id, uuid) VALUES (NEW.id, TG_OP, NEW.change_id, NEW.date_created, NEW.date_modified, NEW.email, NEW.extra_id, NEW.extra_version_id, NEW.is_primary, NEW.same_as_id, NEW.same_as_version_id, NEW.uuid) RETURNING (id) INTO vid;\n            NEW.version_id = vid;\n            RETURN NEW;\n        END;\n        $$ LANGUAGE plpgsql;',
            reverse_sql='DROP FUNCTION before_share_email_change();',
        ),
        migrations.RunSQL(
            sql='DROP TRIGGER IF EXISTS share_email_change ON share_email;\n\n        CREATE TRIGGER share_email_change\n        BEFORE INSERT OR UPDATE ON share_email\n        FOR EACH ROW\n        EXECUTE PROCEDURE before_share_email_change();',
            reverse_sql='DROP TRIGGER share_email_change',
        ),
        migrations.RunSQL(
            sql='CREATE OR REPLACE FUNCTION before_share_identifier_change() RETURNS trigger AS $$\n        DECLARE\n            vid INTEGER;\n        BEGIN\n            INSERT INTO share_identifierversion(persistent_id, action, base_url, change_id, date_created, date_modified, extra_id, extra_version_id, same_as_id, same_as_version_id, url, uuid) VALUES (NEW.id, TG_OP, NEW.base_url, NEW.change_id, NEW.date_created, NEW.date_modified, NEW.extra_id, NEW.extra_version_id, NEW.same_as_id, NEW.same_as_version_id, NEW.url, NEW.uuid) RETURNING (id) INTO vid;\n            NEW.version_id = vid;\n            RETURN NEW;\n        END;\n        $$ LANGUAGE plpgsql;',
            reverse_sql='DROP FUNCTION before_share_identifier_change();',
        ),
        migrations.RunSQL(
            sql='DROP TRIGGER IF EXISTS share_identifier_change ON share_identifier;\n\n        CREATE TRIGGER share_identifier_change\n        BEFORE INSERT OR UPDATE ON share_identifier\n        FOR EACH ROW\n        EXECUTE PROCEDURE before_share_identifier_change();',
            reverse_sql='DROP TRIGGER share_identifier_change',
        ),
        migrations.RunSQL(
            sql='CREATE OR REPLACE FUNCTION before_share_person_change() RETURNS trigger AS $$\n        DECLARE\n            vid INTEGER;\n        BEGIN\n            INSERT INTO share_personversion(persistent_id, action, additional_name, change_id, date_created, date_modified, extra_id, extra_version_id, family_name, given_name, location, same_as_id, same_as_version_id, suffix, url, uuid) VALUES (NEW.id, TG_OP, NEW.additional_name, NEW.change_id, NEW.date_created, NEW.date_modified, NEW.extra_id, NEW.extra_version_id, NEW.family_name, NEW.given_name, NEW.location, NEW.same_as_id, NEW.same_as_version_id, NEW.suffix, NEW.url, NEW.uuid) RETURNING (id) INTO vid;\n            NEW.version_id = vid;\n            RETURN NEW;\n        END;\n        $$ LANGUAGE plpgsql;',
            reverse_sql='DROP FUNCTION before_share_person_change();',
        ),
        migrations.RunSQL(
            sql='DROP TRIGGER IF EXISTS share_person_change ON share_person;\n\n        CREATE TRIGGER share_person_change\n        BEFORE INSERT OR UPDATE ON share_person\n        FOR EACH ROW\n        EXECUTE PROCEDURE before_share_person_change();',
            reverse_sql='DROP TRIGGER share_person_change',
        ),
        migrations.RunSQL(
            sql='CREATE OR REPLACE FUNCTION before_share_throughidentifiers_change() RETURNS trigger AS $$\n        DECLARE\n            vid INTEGER;\n        BEGIN\n            INSERT INTO share_throughidentifiersversion(persistent_id, action, change_id, date_created, date_modified, extra_id, extra_version_id, identifier_id, identifier_version_id, person_id, person_version_id, same_as_id, same_as_version_id, uuid) VALUES (NEW.id, TG_OP, NEW.change_id, NEW.date_created, NEW.date_modified, NEW.extra_id, NEW.extra_version_id, NEW.identifier_id, NEW.identifier_version_id, NEW.person_id, NEW.person_version_id, NEW.same_as_id, NEW.same_as_version_id, NEW.uuid) RETURNING (id) INTO vid;\n            NEW.version_id = vid;\n            RETURN NEW;\n        END;\n        $$ LANGUAGE plpgsql;',
            reverse_sql='DROP FUNCTION before_share_throughidentifiers_change();',
        ),
        migrations.RunSQL(
            sql='DROP TRIGGER IF EXISTS share_throughidentifiers_change ON share_throughidentifiers;\n\n        CREATE TRIGGER share_throughidentifiers_change\n        BEFORE INSERT OR UPDATE ON share_throughidentifiers\n        FOR EACH ROW\n        EXECUTE PROCEDURE before_share_throughidentifiers_change();',
            reverse_sql='DROP TRIGGER share_throughidentifiers_change',
        ),
        migrations.RunSQL(
            sql='CREATE OR REPLACE FUNCTION before_share_personemail_change() RETURNS trigger AS $$\n        DECLARE\n            vid INTEGER;\n        BEGIN\n            INSERT INTO share_personemailversion(persistent_id, action, change_id, date_created, date_modified, email_id, email_version_id, extra_id, extra_version_id, person_id, person_version_id, same_as_id, same_as_version_id, uuid) VALUES (NEW.id, TG_OP, NEW.change_id, NEW.date_created, NEW.date_modified, NEW.email_id, NEW.email_version_id, NEW.extra_id, NEW.extra_version_id, NEW.person_id, NEW.person_version_id, NEW.same_as_id, NEW.same_as_version_id, NEW.uuid) RETURNING (id) INTO vid;\n            NEW.version_id = vid;\n            RETURN NEW;\n        END;\n        $$ LANGUAGE plpgsql;',
            reverse_sql='DROP FUNCTION before_share_personemail_change();',
        ),
        migrations.RunSQL(
            sql='DROP TRIGGER IF EXISTS share_personemail_change ON share_personemail;\n\n        CREATE TRIGGER share_personemail_change\n        BEFORE INSERT OR UPDATE ON share_personemail\n        FOR EACH ROW\n        EXECUTE PROCEDURE before_share_personemail_change();',
            reverse_sql='DROP TRIGGER share_personemail_change',
        ),
        migrations.RunSQL(
            sql='CREATE OR REPLACE FUNCTION before_share_affiliation_change() RETURNS trigger AS $$\n        DECLARE\n            vid INTEGER;\n        BEGIN\n            INSERT INTO share_affiliationversion(persistent_id, action, change_id, date_created, date_modified, entity_id, entity_version_id, extra_id, extra_version_id, person_id, person_version_id, same_as_id, same_as_version_id, uuid) VALUES (NEW.id, TG_OP, NEW.change_id, NEW.date_created, NEW.date_modified, NEW.entity_id, NEW.entity_version_id, NEW.extra_id, NEW.extra_version_id, NEW.person_id, NEW.person_version_id, NEW.same_as_id, NEW.same_as_version_id, NEW.uuid) RETURNING (id) INTO vid;\n            NEW.version_id = vid;\n            RETURN NEW;\n        END;\n        $$ LANGUAGE plpgsql;',
            reverse_sql='DROP FUNCTION before_share_affiliation_change();',
        ),
        migrations.RunSQL(
            sql='DROP TRIGGER IF EXISTS share_affiliation_change ON share_affiliation;\n\n        CREATE TRIGGER share_affiliation_change\n        BEFORE INSERT OR UPDATE ON share_affiliation\n        FOR EACH ROW\n        EXECUTE PROCEDURE before_share_affiliation_change();',
            reverse_sql='DROP TRIGGER share_affiliation_change',
        ),
        migrations.RunSQL(
            sql='CREATE OR REPLACE FUNCTION before_share_contributor_change() RETURNS trigger AS $$\n        DECLARE\n            vid INTEGER;\n        BEGIN\n            INSERT INTO share_contributorversion(persistent_id, action, change_id, cited_name, creative_work_id, creative_work_version_id, date_created, date_modified, extra_id, extra_version_id, order_cited, person_id, person_version_id, same_as_id, same_as_version_id, uuid) VALUES (NEW.id, TG_OP, NEW.change_id, NEW.cited_name, NEW.creative_work_id, NEW.creative_work_version_id, NEW.date_created, NEW.date_modified, NEW.extra_id, NEW.extra_version_id, NEW.order_cited, NEW.person_id, NEW.person_version_id, NEW.same_as_id, NEW.same_as_version_id, NEW.uuid) RETURNING (id) INTO vid;\n            NEW.version_id = vid;\n            RETURN NEW;\n        END;\n        $$ LANGUAGE plpgsql;',
            reverse_sql='DROP FUNCTION before_share_contributor_change();',
        ),
        migrations.RunSQL(
            sql='DROP TRIGGER IF EXISTS share_contributor_change ON share_contributor;\n\n        CREATE TRIGGER share_contributor_change\n        BEFORE INSERT OR UPDATE ON share_contributor\n        FOR EACH ROW\n        EXECUTE PROCEDURE before_share_contributor_change();',
            reverse_sql='DROP TRIGGER share_contributor_change',
        ),
        migrations.RunSQL(
            sql='CREATE OR REPLACE FUNCTION before_share_entity_change() RETURNS trigger AS $$\n        DECLARE\n            vid INTEGER;\n        BEGIN\n            INSERT INTO share_entityversion(persistent_id, action, change_id, community_identifier, date_created, date_modified, extra_id, extra_version_id, funder_region, isni, location, name, ringgold, same_as_id, same_as_version_id, type, url, uuid) VALUES (NEW.id, TG_OP, NEW.change_id, NEW.community_identifier, NEW.date_created, NEW.date_modified, NEW.extra_id, NEW.extra_version_id, NEW.funder_region, NEW.isni, NEW.location, NEW.name, NEW.ringgold, NEW.same_as_id, NEW.same_as_version_id, NEW.type, NEW.url, NEW.uuid) RETURNING (id) INTO vid;\n            NEW.version_id = vid;\n            RETURN NEW;\n        END;\n        $$ LANGUAGE plpgsql;',
            reverse_sql='DROP FUNCTION before_share_entity_change();',
        ),
        migrations.RunSQL(
            sql='DROP TRIGGER IF EXISTS share_entity_change ON share_entity;\n\n        CREATE TRIGGER share_entity_change\n        BEFORE INSERT OR UPDATE ON share_entity\n        FOR EACH ROW\n        EXECUTE PROCEDURE before_share_entity_change();',
            reverse_sql='DROP TRIGGER share_entity_change',
        ),
        migrations.RunSQL(
            sql='CREATE OR REPLACE FUNCTION before_share_abstractcreativework_change() RETURNS trigger AS $$\n        DECLARE\n            vid INTEGER;\n        BEGIN\n            INSERT INTO share_abstractcreativeworkversion(persistent_id, action, change_id, date_created, date_modified, date_published, date_updated, description, extra_id, extra_version_id, free_to_read_date, free_to_read_type, language, rights, same_as_id, same_as_version_id, subject_id, subject_version_id, title, type, uuid) VALUES (NEW.id, TG_OP, NEW.change_id, NEW.date_created, NEW.date_modified, NEW.date_published, NEW.date_updated, NEW.description, NEW.extra_id, NEW.extra_version_id, NEW.free_to_read_date, NEW.free_to_read_type, NEW.language, NEW.rights, NEW.same_as_id, NEW.same_as_version_id, NEW.subject_id, NEW.subject_version_id, NEW.title, NEW.type, NEW.uuid) RETURNING (id) INTO vid;\n            NEW.version_id = vid;\n            RETURN NEW;\n        END;\n        $$ LANGUAGE plpgsql;',
            reverse_sql='DROP FUNCTION before_share_abstractcreativework_change();',
        ),
        migrations.RunSQL(
            sql='DROP TRIGGER IF EXISTS share_abstractcreativework_change ON share_abstractcreativework;\n\n        CREATE TRIGGER share_abstractcreativework_change\n        BEFORE INSERT OR UPDATE ON share_abstractcreativework\n        FOR EACH ROW\n        EXECUTE PROCEDURE before_share_abstractcreativework_change();',
            reverse_sql='DROP TRIGGER share_abstractcreativework_change',
        ),
        migrations.RunSQL(
            sql='CREATE OR REPLACE FUNCTION before_share_association_change() RETURNS trigger AS $$\n        DECLARE\n            vid INTEGER;\n        BEGIN\n            INSERT INTO share_associationversion(persistent_id, action, change_id, creative_work_id, creative_work_version_id, date_created, date_modified, entity_id, entity_version_id, extra_id, extra_version_id, same_as_id, same_as_version_id, uuid) VALUES (NEW.id, TG_OP, NEW.change_id, NEW.creative_work_id, NEW.creative_work_version_id, NEW.date_created, NEW.date_modified, NEW.entity_id, NEW.entity_version_id, NEW.extra_id, NEW.extra_version_id, NEW.same_as_id, NEW.same_as_version_id, NEW.uuid) RETURNING (id) INTO vid;\n            NEW.version_id = vid;\n            RETURN NEW;\n        END;\n        $$ LANGUAGE plpgsql;',
            reverse_sql='DROP FUNCTION before_share_association_change();',
        ),
        migrations.RunSQL(
            sql='DROP TRIGGER IF EXISTS share_association_change ON share_association;\n\n        CREATE TRIGGER share_association_change\n        BEFORE INSERT OR UPDATE ON share_association\n        FOR EACH ROW\n        EXECUTE PROCEDURE before_share_association_change();',
            reverse_sql='DROP TRIGGER share_association_change',
        ),
    ]
Example #18
0
class Migration(migrations.Migration):

    dependencies = [
        ('app', '0010_util_funcs'),
    ]

    operations = [
        migrations.RenameField('EntityToWorkRel', 'from_model', 'from_entity'),
        migrations.RenameField('EntityToWorkRel', 'to_model', 'to_work'),
        migrations.RenameField('EntityToWorkRel', 'comments', 'commentary'),
        migrations.RenameField('EntityToEntityRel', 'from_model',
                               'from_entity'),
        migrations.RenameField('EntityToEntityRel', 'to_model', 'to_entity'),
        migrations.RenameField('EntityToEntityRel', 'comment', 'commentary'),
        migrations.RenameField('WorkToWorkRel', 'from_model', 'from_work'),
        migrations.RenameField('WorkToWorkRel', 'to_model', 'to_work'),
        migrations.RenameField('WorkToWorkRel', 'comments', 'commentary'),
        migrations.RenameField('Work', 'comments', 'commentary'),
        migrations.RenameField('Entity', 'comments', 'commentary'),
        migrations.RenameField(
            model_name='historicalentitytoentityrel',
            old_name='from_model',
            new_name='from_entity',
        ),
        migrations.RenameField(
            model_name='historicalentitytoentityrel',
            old_name='to_model',
            new_name='to_entity',
        ),
        migrations.RenameField(
            model_name='historicalworktoworkrel',
            old_name='from_model',
            new_name='from_work',
        ),
        migrations.RenameField(
            model_name='historicalworktoworkrel',
            old_name='to_model',
            new_name='to_work',
        ),
        migrations.RemoveField(
            model_name='historicalentitytoworkrel',
            name='from_model',
        ),
        migrations.RemoveField(
            model_name='historicalentitytoworkrel',
            name='to_model',
        ),
        migrations.AddField(
            model_name='historicalentitytoworkrel',
            name='from_entity',
            field=models.ForeignKey(
                blank=True,
                db_column='from_entity',
                db_constraint=False,
                null=True,
                on_delete=django.db.models.deletion.DO_NOTHING,
                related_name='+',
                to='app.Entity'),
        ),
        migrations.AddField(
            model_name='historicalentitytoworkrel',
            name='to_work',
            field=models.ForeignKey(
                blank=True,
                db_column='to_work',
                db_constraint=False,
                null=True,
                on_delete=django.db.models.deletion.DO_NOTHING,
                related_name='+',
                to='app.Work'),
        ),
        migrations.AlterField(
            model_name='entitytoworkrel',
            name='from_entity',
            field=models.ForeignKey(
                db_column='from_entity',
                on_delete=django.db.models.deletion.CASCADE,
                to='app.Entity'),
        ),
        migrations.AlterField(
            model_name='entitytoworkrel',
            name='to_work',
            field=models.ForeignKey(
                db_column='to_work',
                on_delete=django.db.models.deletion.CASCADE,
                to='app.Work'),
        ),
        migrations.RunSQL("ALTER TABLE idioma RENAME COLUMN idioma_id TO id"),
        migrations.RunSQL(
            "ALTER TABLE idioma RENAME COLUMN nom_idioma TO nom"),
        migrations.RunSQL("ALTER TABLE tema RENAME COLUMN tema_id TO id"),
        migrations.RunSQL("ALTER TABLE tema RENAME COLUMN nom_tema TO nom"),
        migrations.RunSQL(
            "ALTER TABLE genero_musical RENAME COLUMN gen_mus_id TO id"),
        migrations.RunSQL(
            "ALTER TABLE genero_musical RENAME COLUMN nom_gen_mus TO nom"),
        migrations.RunSQL(
            "ALTER TABLE genero_musical RENAME COLUMN coment_gen_mus TO coment"
        ),
        migrations.RunSQL("ALTER TABLE album RENAME COLUMN album_id TO id"),
        migrations.RunSQL("ALTER TABLE album RENAME COLUMN nom_album TO nom"),
        migrations.RunSQL("ALTER TABLE serie RENAME COLUMN serie_id TO id"),
        migrations.RunSQL("ALTER TABLE serie RENAME COLUMN nom_serie TO nom"),
        migrations.RunSQL(
            "ALTER TABLE serie RENAME COLUMN coment_serie TO coment"),
        migrations.RunSQL(
            "ALTER TABLE familia_instrumento RENAME COLUMN familia_instr_id TO id"
        ),
        migrations.RunSQL(
            "ALTER TABLE familia_instrumento RENAME COLUMN nom_familia_instr TO nom"
        ),
        migrations.RunSQL(
            "ALTER TABLE instrumento RENAME COLUMN instrumento_id TO id"),
        migrations.RunSQL(
            "ALTER TABLE instrumento RENAME COLUMN nom_inst TO nom"),
        migrations.RunSQL(
            "ALTER TABLE instrumento RENAME COLUMN instrumento_comentario TO coment"
        ),
        migrations.RunSQL(
            "ALTER TABLE archivo RENAME COLUMN archivo_id TO id"),
        migrations.RunSQL(
            "ALTER TABLE cobertura RENAME COLUMN cobertura_id TO id"),
        migrations.RunSQL(
            "ALTER TABLE cobertura_licencia RENAME COLUMN cobertura_lic_id TO id"
        ),
        migrations.RunSQL(
            "ALTER TABLE composicion RENAME COLUMN composicion_id TO id"),
        migrations.RunSQL(
            "ALTER TABLE composicion RENAME COLUMN nom_tit TO nom"),
        migrations.RunSQL(
            "ALTER TABLE archivo RENAME COLUMN nom_archivo TO nom"),
    ]
Example #19
0
class Migration(migrations.Migration):

    initial = True

    dependencies = [("accounts", "0001_initial")]

    operations = [
        migrations.RunSQL("""
                CREATE EXTENSION IF NOT EXISTS citext WITH SCHEMA public;
            """),
        migrations.CreateModel(
            name="Education",
            fields=[
                (
                    "id",
                    models.UUIDField(
                        default=ulid2.generate_ulid_as_uuid,
                        primary_key=True,
                        serialize=False,
                    ),
                ),
                (
                    "school",
                    models.CharField(blank=True, max_length=255, null=True),
                ),  # noqa
                (
                    "course",
                    models.CharField(blank=True, max_length=255, null=True),
                ),  # noqa
                (
                    "from_date",
                    models.CharField(blank=True, max_length=255, null=True),
                ),  # noqa
                (
                    "to_date",
                    models.CharField(blank=True, max_length=255, null=True),
                ),  # noqa
                ("index", models.IntegerField()),
            ],
            options={"db_table": "education"},
        ),
        migrations.CreateModel(
            name="Experience",
            fields=[
                (
                    "id",
                    models.UUIDField(
                        default=ulid2.generate_ulid_as_uuid,
                        primary_key=True,
                        serialize=False,
                    ),
                ),
                ("position", models.TextField(blank=True, null=True)),
                (
                    "company_name",
                    models.CharField(blank=True, max_length=255, null=True),
                ),
                (
                    "from_date",
                    models.CharField(blank=True, max_length=255, null=True),
                ),  # noqa
                (
                    "to_date",
                    models.CharField(blank=True, max_length=255, null=True),
                ),  # noqa
                ("index", models.IntegerField()),
            ],
            options={"db_table": "experiences"},
        ),
        migrations.CreateModel(
            name="Resumes",
            fields=[
                (
                    "id",
                    models.UUIDField(
                        default=ulid2.generate_ulid_as_uuid,
                        primary_key=True,
                        serialize=False,
                    ),
                ),
                ("title", django.contrib.postgres.fields.citext.CITextField()),
                ("description", models.TextField(blank=True, null=True)),
                ("inserted_at", models.DateTimeField(auto_now_add=True)),
                ("updated_at", models.DateTimeField(auto_now=True)),
                (
                    "user",
                    models.ForeignKey(
                        db_constraint=False,
                        db_index=False,
                        on_delete=django.db.models.deletion.DO_NOTHING,
                        to="accounts.User",
                    ),
                ),
            ],
            options={"db_table": "resumes"},
        ),
        migrations.CreateModel(
            name="Skill",
            fields=[
                (
                    "id",
                    models.UUIDField(
                        default=ulid2.generate_ulid_as_uuid,
                        primary_key=True,
                        serialize=False,
                    ),
                ),
                ("description", models.TextField(blank=True, null=True)),
                ("index", models.IntegerField()),
                (
                    "resume",
                    models.ForeignKey(
                        db_constraint=False,
                        db_index=False,
                        on_delete=django.db.models.deletion.DO_NOTHING,
                        to="resumes.Resumes",
                    ),
                ),
            ],
            options={"db_table": "skills"},
        ),
        migrations.CreateModel(
            name="SupplementarySkill",
            fields=[
                (
                    "id",
                    models.UUIDField(
                        default=ulid2.generate_ulid_as_uuid,
                        primary_key=True,
                        serialize=False,
                    ),
                ),
                (
                    "description",
                    django.contrib.postgres.fields.citext.CITextField(),
                ),  # noqa
                (
                    "level",
                    models.CharField(blank=True, max_length=255, null=True),
                ),  # noqa
                ("inserted_at", models.DateTimeField(auto_now_add=True)),
                ("updated_at", models.DateTimeField(auto_now=True)),
                (
                    "owner",
                    models.ForeignKey(
                        db_constraint=False,
                        db_index=False,
                        on_delete=django.db.models.deletion.DO_NOTHING,
                        to="resumes.Resumes",
                    ),
                ),
            ],
            options={"db_table": "supplementary_skills"},
        ),
        migrations.CreateModel(
            name="SpokenLanguage",
            fields=[
                (
                    "id",
                    models.UUIDField(
                        default=ulid2.generate_ulid_as_uuid,
                        primary_key=True,
                        serialize=False,
                    ),
                ),
                (
                    "description",
                    django.contrib.postgres.fields.citext.CITextField(),
                ),  # noqa
                (
                    "level",
                    models.CharField(blank=True, max_length=255, null=True),
                ),  # noqa
                ("inserted_at", models.DateTimeField(auto_now_add=True)),
                ("updated_at", models.DateTimeField(auto_now=True)),
                (
                    "owner",
                    models.ForeignKey(
                        db_constraint=False,
                        db_index=False,
                        on_delete=django.db.models.deletion.DO_NOTHING,
                        to="resumes.Resumes",
                    ),
                ),
            ],
            options={"db_table": "spoken_languages"},
        ),
        migrations.CreateModel(
            name="SkillAchievement",
            fields=[
                (
                    "id",
                    models.UUIDField(
                        default=ulid2.generate_ulid_as_uuid,
                        primary_key=True,
                        serialize=False,
                    ),
                ),
                ("text", models.TextField()),
                (
                    "owner",
                    models.ForeignKey(
                        db_constraint=False,
                        db_index=False,
                        on_delete=django.db.models.deletion.DO_NOTHING,
                        to="resumes.Skill",
                    ),
                ),
            ],
            options={"db_table": "skills_achievements"},
        ),
        migrations.CreateModel(
            name="ResumeHobby",
            fields=[
                (
                    "id",
                    models.UUIDField(
                        default=ulid2.generate_ulid_as_uuid,
                        primary_key=True,
                        serialize=False,
                    ),
                ),
                ("text", models.TextField()),
                (
                    "owner",
                    models.ForeignKey(
                        db_constraint=False,
                        db_index=False,
                        on_delete=django.db.models.deletion.DO_NOTHING,
                        to="resumes.Resumes",
                    ),
                ),
            ],
            options={"db_table": "resumes_hobbies"},
        ),
        migrations.CreateModel(
            name="PersonalInfo",
            fields=[
                (
                    "id",
                    models.UUIDField(
                        default=ulid2.generate_ulid_as_uuid,
                        primary_key=True,
                        serialize=False,
                    ),
                ),
                (
                    "first_name",
                    models.CharField(blank=True, max_length=255, null=True),
                ),  # noqa
                (
                    "last_name",
                    models.CharField(blank=True, max_length=255, null=True),
                ),  # noqa
                (
                    "profession",
                    models.CharField(blank=True, max_length=255, null=True),
                ),  # noqa
                ("address", models.TextField(blank=True, null=True)),
                (
                    "email",
                    models.EmailField(blank=True, max_length=254, null=True),
                ),  # noqa
                (
                    "phone",
                    models.CharField(blank=True, max_length=255, null=True),
                ),  # noqa
                (
                    "photo",
                    models.CharField(blank=True, max_length=255, null=True),
                ),  # noqa
                (
                    "date_of_birth",
                    models.CharField(blank=True, max_length=255, null=True),
                ),
                (
                    "resume",
                    models.ForeignKey(
                        db_constraint=False,
                        db_index=False,
                        on_delete=django.db.models.deletion.DO_NOTHING,
                        to="resumes.Resumes",
                    ),
                ),
            ],
            options={"db_table": "personal_info"},
        ),
        migrations.CreateModel(
            name="ExperienceAchievement",
            fields=[
                (
                    "id",
                    models.UUIDField(
                        default=ulid2.generate_ulid_as_uuid,
                        primary_key=True,
                        serialize=False,
                    ),
                ),
                ("text", models.TextField()),
                (
                    "owner",
                    models.ForeignKey(
                        db_constraint=False,
                        db_index=False,
                        on_delete=django.db.models.deletion.DO_NOTHING,
                        to="resumes.Experience",
                    ),
                ),
            ],
            options={"db_table": "experiences_achievements"},
        ),
        migrations.AddField(
            model_name="experience",
            name="resume",
            field=models.ForeignKey(
                db_constraint=False,
                db_index=False,
                on_delete=django.db.models.deletion.DO_NOTHING,
                to="resumes.Resumes",
            ),
        ),
        migrations.CreateModel(
            name="EducationAchievement",
            fields=[
                (
                    "id",
                    models.UUIDField(
                        default=ulid2.generate_ulid_as_uuid,
                        primary_key=True,
                        serialize=False,
                    ),
                ),
                ("text", models.TextField()),
                (
                    "owner",
                    models.ForeignKey(
                        db_constraint=False,
                        db_index=False,
                        on_delete=django.db.models.deletion.DO_NOTHING,
                        to="resumes.Education",
                    ),
                ),
            ],
            options={"db_table": "education_achievements"},
        ),
        migrations.AddField(
            model_name="education",
            name="resume",
            field=models.ForeignKey(
                db_constraint=False,
                db_index=False,
                on_delete=django.db.models.deletion.DO_NOTHING,
                to="resumes.Resumes",
            ),
        ),
        migrations.AddIndex(
            model_name="skill",
            index=models.Index(fields=["resume"],
                               name="skills_resumes_id_index"),  # noqa
        ),
        migrations.AddIndex(
            model_name="resumes",
            index=models.Index(fields=["user"], name="resumes_user_id_index"),
        ),
        migrations.AddIndex(
            model_name="resumehobby",
            index=models.Index(fields=["owner"],
                               name="resumes_hobbies_owner_id_index"),  # noqa
        ),
        migrations.AddIndex(
            model_name="personalinfo",
            index=models.Index(fields=["resume"],
                               name="personal_info_resume_id_index"),  # noqa
        ),
        migrations.AddIndex(
            model_name="experience",
            index=models.Index(fields=["resume"],
                               name="experiences_resume_id_index"),  # noqa
        ),
        migrations.AddIndex(
            model_name="education",
            index=models.Index(fields=["resume"],
                               name="education_resume_id_index"),  # noqa
        ),
        migrations.RunSQL(f"""
                CREATE UNIQUE INDEX resumes_user_id_title_index
                ON resumes(user_id, title);

                CREATE INDEX education_achievements_owner_id_index
                ON education_achievements(owner_id);

                CREATE INDEX experiences_achievements_owner_id_index
                ON experiences_achievements(owner_id);

                CREATE INDEX skills_achievements_owner_id_index
                ON skills_achievements(owner_id);

                CREATE UNIQUE INDEX spoken_languages_owner_id_index
                ON spoken_languages(owner_id);

                CREATE UNIQUE INDEX spoken_languages_description_owner_id_index
                ON spoken_languages(description, owner_id);

                CREATE UNIQUE INDEX
                supplementary_skills_description_owner_id_index
                ON supplementary_skills(description, owner_id);

                {add_fkey("resumes", "user_id", "users", "id")}

                {add_fkey("education", "resume_id", "resumes", "id")}

                {add_fkey(
                    "education_achievements", "owner_id", "education", "id"
                )}

                {add_fkey("experiences", "resume_id", "resumes", "id")}

                {add_fkey(
                    "experiences_achievements", "owner_id", "experiences", "id"
                )}

                {add_fkey("personal_info", "resume_id", "resumes", "id")}

                {add_fkey("resumes_hobbies", "owner_id", "resumes", "id")}

                {add_fkey("skills", "resume_id", "resumes", "id")}

                {add_fkey("skills_achievements", "owner_id", "skills", "id")}

                {add_fkey("spoken_languages", "owner_id", "resumes", "id")}

                {add_fkey("supplementary_skills", "owner_id", "resumes")}

                {create_index("supplementary_skills", "owner_id")}
            """),
    ]
class Migration(migrations.Migration):

    dependencies = [
        ('wagtailsearch', '0005_create_indexentry'),
    ]

    if connection.vendor == 'postgresql':
        import django.contrib.postgres.indexes
        import django.contrib.postgres.search

        operations = [
            migrations.AddField(
                model_name='indexentry',
                name='autocomplete',
                field=django.contrib.postgres.search.SearchVectorField(),
            ),
            migrations.AddField(
                model_name='indexentry',
                name='title',
                field=django.contrib.postgres.search.SearchVectorField(),
            ),
            migrations.AddField(
                model_name='indexentry',
                name='body',
                field=django.contrib.postgres.search.SearchVectorField(),
            ),
            migrations.AddIndex(
                model_name='indexentry',
                index=django.contrib.postgres.indexes.GinIndex(fields=['autocomplete'], name='wagtailsear_autocom_476c89_gin'),
            ),
            migrations.AddIndex(
                model_name='indexentry',
                index=django.contrib.postgres.indexes.GinIndex(fields=['title'], name='wagtailsear_title_9caae0_gin'),
            ),
            migrations.AddIndex(
                model_name='indexentry',
                index=django.contrib.postgres.indexes.GinIndex(fields=['body'], name='wagtailsear_body_90c85d_gin'),
            )
        ]

    elif connection.vendor == 'sqlite':
        from wagtail.search.backends.database.sqlite.utils import fts5_available

        operations = [
            migrations.AddField(
                model_name='indexentry',
                name='autocomplete',
                field=models.TextField(null=True),
            ),
            migrations.AddField(
                model_name='indexentry',
                name='body',
                field=models.TextField(null=True),
            ),
            migrations.AddField(
                model_name='indexentry',
                name='title',
                field=models.TextField(),
            ),
        ]

        if fts5_available():
            operations.append(
                migrations.SeparateDatabaseAndState(state_operations=[
                    migrations.CreateModel(
                        name='sqliteftsindexentry',
                        fields=[
                            ('index_entry', models.OneToOneField(primary_key=True, serialize=False, to='wagtailsearch.indexentry', on_delete=models.CASCADE, db_column='rowid')),
                            ('title', models.TextField()),
                            ('body', models.TextField(null=True)),
                            ('autocomplete', models.TextField(null=True)),
                        ],
                        options={'db_table': '%s_fts' % IndexEntry._meta.db_table},
                    ),
                ], database_operations=[
                    migrations.RunSQL(sql=('CREATE VIRTUAL TABLE %s_fts USING fts5(autocomplete, body, title)' % IndexEntry._meta.db_table), reverse_sql=('DROP TABLE IF EXISTS %s_fts' % IndexEntry._meta.db_table)),
                    migrations.RunSQL(sql=('CREATE TRIGGER insert_wagtailsearch_indexentry_fts AFTER INSERT ON %s BEGIN INSERT INTO %s_fts(title, body, autocomplete, rowid) VALUES (NEW.title, NEW.body, NEW.autocomplete, NEW.id); END' % (IndexEntry._meta.db_table, IndexEntry._meta.db_table)), reverse_sql=('DROP TRIGGER IF EXISTS insert_wagtailsearch_indexentry_fts')),
                    migrations.RunSQL(sql=('CREATE TRIGGER update_wagtailsearch_indexentry_fts AFTER UPDATE ON %s BEGIN UPDATE %s_fts SET title=NEW.title, body=NEW.body, autocomplete=NEW.autocomplete WHERE rowid=NEW.id; END' % (IndexEntry._meta.db_table, IndexEntry._meta.db_table)), reverse_sql=('DROP TRIGGER IF EXISTS update_wagtailsearch_indexentry_fts')),
                    migrations.RunSQL(sql=('CREATE TRIGGER delete_wagtailsearch_indexentry_fts AFTER DELETE ON %s BEGIN DELETE FROM %s_fts WHERE rowid=OLD.id; END' % (IndexEntry._meta.db_table, IndexEntry._meta.db_table)), reverse_sql=('DROP TRIGGER IF EXISTS delete_wagtailsearch_indexentry_fts'))
                ])
            )

    elif connection.vendor == 'mysql':
        operations = [
            migrations.AddField(
                model_name='indexentry',
                name='autocomplete',
                field=models.TextField(null=True),
            ),
            migrations.AddField(
                model_name='indexentry',
                name='body',
                field=models.TextField(null=True),
            ),
            migrations.AddField(
                model_name='indexentry',
                name='title',
                field=models.TextField(default=''),
                preserve_default=False,
            ),
        ]

        # Create FULLTEXT indexes
        # We need to add these indexes manually because Django imposes an artificial limitation
        # that forces to specify the max length of the TextFields that get referenced by the
        # FULLTEXT index. If we do it manually, it works, because Django can't check that we are
        # defining a new index.
        operations.append(
            migrations.RunSQL(
                sql="""
                ALTER TABLE wagtailsearch_indexentry
                    ADD FULLTEXT INDEX `fulltext_body` (`body`)
                """,
                reverse_sql="""
                ALTER TABLE wagtailsearch_indexentry
                    DROP INDEX `fulltext_body`
                """
            )
        )

        # We create two separate FULLTEXT indexes for the 'body' and 'title' columns, so that we are able to handle them separately afterwards.
        # We handle them separately, for example, when we do scoring: there, we multiply the 'title' score by the value of the 'title_norm' column. This can't be done if we index 'title' and 'body' in the same index, because MySQL doesn't allow to search on subparts of a defined index (we need to search all the columns of the index at the same time).
        operations.append(
            migrations.RunSQL(
                sql="""
                ALTER TABLE wagtailsearch_indexentry
                    ADD FULLTEXT INDEX `fulltext_title` (`title`)
                """,
                reverse_sql="""
                ALTER TABLE wagtailsearch_indexentry
                    DROP INDEX `fulltext_title`
                """
            )
        )

        # We also need to create a joint index on 'title' and 'body', to be able to query both at the same time. If we don't have this, some queries may return wrong results. For example, if we match 'A AND (NOT B)' against 'A, B', it returns false, but if we do (match 'A AND (NOT B)' against 'A') or (match 'A AND (NOT B)' against 'B'), the first one would return True, and the whole expression would be True (wrong result). That's the same as saying that testing subsets does not neccessarily produce the same result as testing the whole set.
        operations.append(
            migrations.RunSQL(
                sql="""
                ALTER TABLE wagtailsearch_indexentry
                    ADD FULLTEXT INDEX `fulltext_title_body` (`title`, `body`)
                """,
                reverse_sql="""
                ALTER TABLE wagtailsearch_indexentry
                    DROP INDEX `fulltext_title_body`
                """
            )
        )

        # We use an ngram parser for autocomplete, so that it matches partial search queries.
        # The index on body and title doesn't match partial queries by default.
        # Note that this is not supported on MariaDB. See https://jira.mariadb.org/browse/MDEV-10267
        if connection.mysql_is_mariadb:
            operations.append(
                migrations.RunSQL(
                    sql="""
                    ALTER TABLE wagtailsearch_indexentry
                        ADD FULLTEXT INDEX `fulltext_autocomplete` (`autocomplete`)
                    """,
                    reverse_sql="""
                    ALTER TABLE wagtailsearch_indexentry
                        DROP INDEX `fulltext_autocomplete`
                    """
                )
            )
        else:
            operations.append(
                migrations.RunSQL(
                    sql="""
                    ALTER TABLE wagtailsearch_indexentry
                        ADD FULLTEXT INDEX `fulltext_autocomplete` (`autocomplete`)
                        WITH PARSER ngram
                    """,
                    reverse_sql="""
                    ALTER TABLE wagtailsearch_indexentry
                        DROP INDEX `fulltext_autocomplete`
                    """
                )
            )
Example #21
0
def migrate_table_name():
    tables = connection.introspection.table_names()
    return [
        migrations.RunSQL(get_migration_sql(table_name))
        for table_name in tables if table_name.startswith('core_')
    ]
class Migration(migrations.Migration):
    dependencies = [
        ('data', '0020_auto_20170712_1817'),
    ]

    operations = [
        migrations.RunSQL("""
            ALTER TABLE variant DROP COLUMN fts_document CASCADE;
            ALTER TABLE variant DROP COLUMN fts_standard CASCADE;
            DROP FUNCTION variant_fts_standard(v variant) CASCADE;
            DROP FUNCTION variant_fts_synonyms(v variant) CASCADE;
            DROP FUNCTION variant_fts_document(v variant) CASCADE;
            DROP FUNCTION variant_fts_trigger() CASCADE;

            ALTER TABLE variant ADD COLUMN fts_document TSVECTOR;
            ALTER TABLE variant ADD COLUMN fts_standard TSVECTOR;

            CREATE FUNCTION variant_fts_standard(v variant) RETURNS tsvector AS $$
                DECLARE
                    fts_standard TEXT;
                BEGIN
                    SELECT concat_ws(' ',
                        v."Source",
                        v."URL_ENIGMA",
                        v."Condition_ID_type_ENIGMA",
                        v."Condition_ID_value_ENIGMA",
                        v."Condition_category_ENIGMA",
                        v."Clinical_significance_ENIGMA",
                        v."Date_last_evaluated_ENIGMA",
                        v."Assertion_method_ENIGMA",
                        v."Assertion_method_citation_ENIGMA",
                        v."Clinical_significance_citations_ENIGMA",
                        v."Comment_on_clinical_significance_ENIGMA",
                        v."Collection_method_ENIGMA",
                        v."Allele_origin_ENIGMA",
                        v."ClinVarAccession_ENIGMA",
                        v."Clinical_Significance_ClinVar",
                        v."Date_Last_Updated_ClinVar",
                        v."Submitter_ClinVar",
                        v."SCV_ClinVar",
                        v."Allele_Origin_ClinVar",
                        v."Method_ClinVar",
                        v."Functional_analysis_result_LOVD",
                        v."Functional_analysis_technique_LOVD",
                        v."Variant_frequency_LOVD",
                        v."Variant_haplotype_LOVD",
                        v."Minor_allele_frequency_percent_ESP",
                        v."EUR_Allele_frequency_1000_Genomes",
                        v."AFR_Allele_frequency_1000_Genomes",
                        v."AMR_Allele_frequency_1000_Genomes",
                        v."EAS_Allele_frequency_1000_Genomes",
                        v."Allele_frequency_1000_Genomes",
                        v."SAS_Allele_frequency_1000_Genomes",
                        v."Allele_frequency_ExAC",
                        v."Patient_nationality_BIC",
                        v."Clinical_importance_BIC",
                        v."Clinical_classification_BIC",
                        v."Literature_citation_BIC",
                        v."Number_of_family_member_carrying_mutation_BIC",
                        v."Germline_or_Somatic_BIC",
                        v."Ethnicity_BIC",
                        v."Mutation_type_BIC",
                        v."IARC_class_exLOVD",
                        v."Sum_family_LR_exLOVD",
                        v."Combined_prior_probablility_exLOVD",
                        v."Literature_source_exLOVD",
                        v."Co_occurrence_LR_exLOVD",
                        v."Posterior_probability_exLOVD",
                        v."Missense_analysis_prior_probability_exLOVD",
                        v."Segregation_LR_exLOVD",
                        v."Gene_Symbol",
                        v."Polyphen_Prediction",
                        v."Polyphen_Score",
                        v."Sift_Prediction",
                        v."Sift_Score",
                        v."Reference_Sequence",
                        v."HGVS_cDNA",
                        v."BIC_Nomenclature",
                        v."HGVS_Protein",
                        v."HGVS_RNA",
                        v."Protein_Change",
                        v."Allele_Frequency",
                        v."Max_Allele_Frequency",
                        v."Genomic_Coordinate_hg38",
                        v."Source_URL",
                        v."Discordant",
                        v."Pathogenicity_expert",
                        v."Pathogenicity_all")
            INTO fts_standard;
                    RETURN to_tsvector('pg_catalog.simple', fts_standard);
            END;
            $$ LANGUAGE plpgsql;

            CREATE FUNCTION variant_fts_synonyms(v variant) RETURNS tsvector AS $$
                DECLARE
                    fts_synonyms TEXT;
                BEGIN
                    SELECT concat_ws(' ',
                        v."Genomic_Coordinate_hg37",
                        v."Genomic_Coordinate_hg36",
                        v."Synonyms")
                    INTO
                        fts_synonyms;
                    RETURN to_tsvector('pg_catalog.simple', fts_synonyms);
                END;
                $$ LANGUAGE plpgsql;

            CREATE FUNCTION variant_fts_document(v variant) RETURNS tsvector AS $$
                BEGIN
                    RETURN variant_fts_standard(v) || variant_fts_synonyms(v);
                END;
                $$ LANGUAGE plpgsql;

            CREATE FUNCTION variant_fts_trigger() RETURNS TRIGGER AS $$
            BEGIN
            NEW.fts_standard=variant_fts_standard(NEW);
            NEW.fts_document=variant_fts_document(NEW);
            RETURN NEW;
            END;
            $$ LANGUAGE plpgsql;

            CREATE TRIGGER variant_fts_update_trigger BEFORE UPDATE ON variant FOR EACH ROW EXECUTE PROCEDURE variant_fts_trigger();
            CREATE TRIGGER variant_fts_insert_trigger BEFORE INSERT ON variant FOR EACH ROW EXECUTE PROCEDURE variant_fts_trigger();

            CREATE INDEX variant_fts_document_index ON variant USING gin(fts_document);
            CREATE INDEX variant_fts_standard_index ON variant USING gin(fts_standard);

            """),
        migrations.RunSQL("""
                DROP MATERIALIZED VIEW IF EXISTS currentvariant;
                CREATE MATERIALIZED VIEW currentvariant AS (
                    SELECT * FROM "variant" WHERE (
                        "id" IN ( SELECT DISTINCT ON ("Genomic_Coordinate_hg38") "id" FROM "variant" ORDER BY "Genomic_Coordinate_hg38" ASC, "Data_Release_id" DESC )
                    )
                );
                """),
    ]
Example #23
0
class Migration(migrations.Migration):

    dependencies = [("contacts", "0085_indexes")]

    operations = [migrations.RunSQL(SQL)]
Example #24
0
class Migration(migrations.Migration):

    dependencies = [
        ('cards', '0001_initial'),
        ('games', '0001_initial'),
    ]

    operations = [
        migrations.RunSQL(CREATE_TABLE_TIME_DIMENSION,
                          DROP_TABLE_TIME_DIMENSION),
        migrations.RunSQL(CREATE_ENSURE_TIME_DIMENSION_CREATED_FUNCTION,
                          DROP_ENSURE_TIME_DIMENSION_CREATED_FUNCTION),
        migrations.RunSQL(CREATE_TABLE_DECK_SUMMARY_STATS,
                          DROP_TABLE_DECK_SUMMARY_STATS),
        migrations.RunSQL(CREATE_IS_ELIGABLE_FOR_STATS_FUNCTION,
                          DROP_IS_ELIGABLE_FOR_STATS_FUNCTION),
        migrations.RunSQL(CREATE_TO_DECK_SUMMARY_STATS_ROW_FUNCTION,
                          DROP_TO_DECK_SUMMARY_STATS_ROW_FUNCTION),
        migrations.RunSQL(CREATE_APPLY_DECK_SUMMARY_STATS_DELTA_FUNCTION,
                          DROP_APPLY_DECK_SUMMARY_STATS_DELTA_FUNCTION),
        migrations.RunSQL(CREATE_MAINT_DECK_SUMMARY_STATS_FUNCTION,
                          DROP_MAINT_DECK_SUMMARY_STATS_FUNCTION),
        migrations.RunSQL(CREATE_DECK_SUMMARY_STATS_TRIGGER,
                          DROP_DECK_SUMMARY_STATS_TRIGGER),
        migrations.RunSQL(CREATE_INDEX_ON_DECK_SUMMARY_STATS_DECK_ID,
                          DROP_INDEX_ON_DECK_SUMMARY_STATS_DECK_ID),
        migrations.RunSQL(CREATE_PRETTY_DECK_LIST_STRING_FUNC,
                          DROP_PRETTY_DECK_LIST_STRING_FUNC),
        migrations.RunSQL(CREATE_DECK_DIGEST_FUNC, DROP_DECK_DIGEST_FUNC),
        migrations.RunSQL(CREATE_GET_OR_CREATE_DECK_FUNC,
                          DROP_GET_OR_CREATE_DECK_FUNC),
        migrations.RunSQL(CREATE_TABLE_HEAD_TO_HEAD_ARCHETYPE_STATS,
                          DROP_TABLE_HEAD_TO_HEAD_ARCHETYPE_STATS),
        migrations.RunSQL(CREATE_FUNC_ELIGABLE_FOR_ARCHETYPE_STATS,
                          DROP_FUNC_ELIGABLE_FOR_ARCHETYPE_STATS),
        migrations.RunSQL(CREATE_FUNC_TO_HEAD_TO_HEAD_ARCHETYPE_STATS_ROW,
                          DROP_FUNC_TO_HEAD_TO_HEAD_ARCHETYPE_STATS_ROW),
        migrations.RunSQL(CREATE_FUNC_APPLY_ARCHETYPE_STATS_DELTA,
                          DROP_FUNC_APPLY_ARCHETYPE_STATS_DELTA),
        migrations.RunSQL(CREATE_FUNC_MAINT_HEAD_TO_HEAD_ARCHETYPE_STATS,
                          DROP_FUNC_MAINT_HEAD_TO_HEAD_ARCHETYPE_STATS),
        migrations.RunSQL(CREATE_ARCHETYPE_STATS_TRIGGER_ON_GAMEREPLAY_TABLE,
                          DROP_ARCHETYPE_STATS_TRIGGER_ON_GAMEREPLAY_TABLE),
        migrations.AlterField(
            model_name='deck',
            name='digest',
            field=models.CharField(max_length=32, unique=True),
        ),
        migrations.RunSQL(DROP_IDX_CARDS_DECK_DIGEST_914F4A6C, None),
        migrations.RunSQL(DROP_IDX_CARDS_INCLUDE_DBE7A8F6, None),
    ]
Example #25
0
class Migration(migrations.Migration):

    dependencies = [
        ('thesaurus', '0007_dynamic_fields'),
    ]

    operations = [
        migrations.AddField(
            model_name='facet',
            name='graph_enabled',
            field=models.NullBooleanField(default=True),
        ),
        migrations.AddField(
            model_name='facet',
            name='graph_limit',
            field=models.IntegerField(blank=True, default=50, null=True),
        ),
        migrations.AddField(
            model_name='facet',
            name='style_color',
            field=models.CharField(blank=True, default='black', max_length=20),
        ),
        migrations.AddField(
            model_name='facet',
            name='style_color_background',
            field=models.CharField(blank=True,
                                   default='lightgray',
                                   max_length=20),
        ),
        migrations.RunSQL(
            "UPDATE thesaurus_facet SET style_color_background='#f9ebdd' WHERE facet='person_ss'"
        ),
        migrations.RunSQL(
            "UPDATE thesaurus_facet SET style_color_background='#eaf9d5' WHERE facet='organization_ss'"
        ),
        migrations.RunSQL(
            "UPDATE thesaurus_facet SET style_color_background='#e3ebf9' WHERE facet='location_ss'"
        ),
        migrations.RunSQL(
            "UPDATE thesaurus_facet SET style_color_background='lightblue' WHERE facet='hashtag_ss'"
        ),
        migrations.RunSQL(
            "UPDATE thesaurus_facet SET style_color_background='orange' WHERE facet='author_ss'"
        ),
        migrations.RunSQL(
            "UPDATE thesaurus_facet SET style_color_background='cyan' WHERE facet='email_ss'"
        ),
        migrations.RunSQL(
            "UPDATE thesaurus_facet SET graph_enabled=0 WHERE facet='content_type_ss'"
        ),
        migrations.RunSQL(
            "UPDATE thesaurus_facet SET graph_enabled=0 WHERE facet='content_type_group_ss'"
        ),
        migrations.RunSQL(
            "UPDATE thesaurus_facet SET graph_enabled=0 WHERE facet='language_s'"
        ),
        migrations.RunSQL(
            "UPDATE thesaurus_facet SET graph_enabled=0 WHERE facet='money_ss'"
        ),
        migrations.RunSQL(
            "UPDATE thesaurus_facet SET graph_enabled=0 WHERE facet='hashtag_ss'"
        ),
    ]
class Migration(migrations.Migration):

    dependencies = [
        ('main', '0064_rename_role'),
        ('accounts', '0003_auto_20151125_0840'),
    ]

    operations = [
        migrations.CreateModel(
            name='Provider',
            fields=[
                ('id',
                 models.AutoField(verbose_name='ID',
                                  serialize=False,
                                  auto_created=True,
                                  primary_key=True)),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('modified', models.DateTimeField(auto_now=True)),
                ('description',
                 galaxy.main.fields.TruncatingCharField(default=b'',
                                                        max_length=255,
                                                        blank=True)),
                ('active', models.BooleanField(default=True, db_index=True)),
                ('name',
                 models.CharField(unique=True, max_length=512, db_index=True)),
                ('original_name', models.CharField(max_length=512)),
            ],
            options={
                'ordering': ('name', ),
            },
            bases=(models.Model, galaxy.main.mixins.DirtyMixin),
        ),
        migrations.CreateModel(
            name='ProviderNamespace',
            fields=[
                ('id',
                 models.AutoField(verbose_name='ID',
                                  serialize=False,
                                  auto_created=True,
                                  primary_key=True)),
                ('description',
                 galaxy.main.fields.TruncatingCharField(default=b'',
                                                        max_length=255,
                                                        blank=True)),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('modified', models.DateTimeField(auto_now=True)),
                ('active', models.BooleanField(default=True, db_index=True)),
                ('name', models.CharField(max_length=256,
                                          verbose_name=b'Name')),
                ('display_name',
                 models.CharField(verbose_name=b'Display Name',
                                  max_length=256,
                                  null=True,
                                  editable=False,
                                  blank=True)),
                ('avatar_url',
                 models.CharField(verbose_name=b'Avatar URL',
                                  max_length=256,
                                  null=True,
                                  editable=False,
                                  blank=True)),
                ('location',
                 models.CharField(verbose_name=b'Location',
                                  max_length=256,
                                  null=True,
                                  editable=False,
                                  blank=True)),
                ('company',
                 models.CharField(verbose_name=b'Company Name',
                                  max_length=256,
                                  null=True,
                                  editable=False,
                                  blank=True)),
                ('email',
                 models.CharField(verbose_name=b'Email Address',
                                  max_length=256,
                                  null=True,
                                  editable=False,
                                  blank=True)),
                ('html_url',
                 models.CharField(verbose_name=b'Web Site URL',
                                  max_length=256,
                                  null=True,
                                  editable=False,
                                  blank=True)),
                ('followers',
                 models.IntegerField(null=True,
                                     editable=False,
                                     verbose_name="Followers")),
                ('namespace',
                 models.ForeignKey(related_name='namespaces',
                                   editable=False,
                                   to='main.Namespace',
                                   null=True,
                                   on_delete=models.CASCADE,
                                   verbose_name=b'Namespace')),
                ('provider',
                 models.ForeignKey(related_name='provider',
                                   verbose_name=b'Provider',
                                   on_delete=models.CASCADE,
                                   to='main.Provider',
                                   null=True)),
            ],
            options={
                'ordering': (
                    'provider',
                    'name',
                ),
                'unique_together': {('provider', 'name'),
                                    ('namespace', 'provider', 'name')},
            },
            bases=(models.Model, galaxy.main.mixins.DirtyMixin),
        ),
        migrations.RunSQL(sql=COPY_NAMESPACE_DATA,
                          reverse_sql=migrations.RunSQL.noop),
        migrations.DeleteModel(name='Namespace', ),
        migrations.CreateModel(
            name='Namespace',
            fields=[
                ('id',
                 models.AutoField(verbose_name='ID',
                                  serialize=False,
                                  auto_created=True,
                                  primary_key=True)),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('modified', models.DateTimeField(auto_now=True)),
                ('description',
                 galaxy.main.fields.TruncatingCharField(default=b'',
                                                        max_length=255,
                                                        blank=True)),
                ('active', models.BooleanField(default=True, db_index=True)),
                ('name',
                 models.CharField(unique=True, max_length=512, db_index=True)),
                ('original_name', models.CharField(max_length=512)),
                ('avatar_url',
                 models.CharField(max_length=256,
                                  null=True,
                                  verbose_name=b'Avatar URL',
                                  blank=True)),
                ('location',
                 models.CharField(max_length=256,
                                  null=True,
                                  verbose_name=b'Location',
                                  blank=True)),
                ('company',
                 models.CharField(max_length=256,
                                  null=True,
                                  verbose_name=b'Company Name',
                                  blank=True)),
                ('email',
                 models.CharField(max_length=256,
                                  null=True,
                                  verbose_name=b'Email Address',
                                  blank=True)),
                ('html_url',
                 models.CharField(max_length=256,
                                  null=True,
                                  verbose_name=b'Web Site URL',
                                  blank=True)),
                ('owners',
                 models.ManyToManyField(related_name='namespaces',
                                        to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'ordering': ('name', ),
            },
            bases=(models.Model, galaxy.main.mixins.DirtyMixin),
        ),
        migrations.RunSQL(sql=(
            ADD_GITHUB_PROVIDER,
            ADD_REPO_GITHUB_USERS,
            ADD_ROLE_NAMESPACE,
            NAMESPACE_FROM_PROVIDER_NAMESPACE,
            SET_PROVIDER_NAMESPACE_FK,
            ADD_NAMESPACE_OWNERS,
            ADD_MISSING_OWNERS,
        )),
    ]
class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('catmaid', '0021_recreate_history_view_after_auth_user_update'),
    ]

    operations = [
        migrations.CreateModel(
            name='Sampler',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('creation_time',
                 models.DateTimeField(default=django.utils.timezone.now)),
                ('edition_time',
                 models.DateTimeField(default=django.utils.timezone.now)),
                ('interval_length', models.FloatField()),
                ('review_required', models.BooleanField(default=True)),
                ('project',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='catmaid.Project')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='SamplerConnectorState',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('name', models.TextField()),
                ('description', models.TextField()),
            ],
        ),
        migrations.CreateModel(
            name='SamplerDomain',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('creation_time',
                 models.DateTimeField(default=django.utils.timezone.now)),
                ('edition_time',
                 models.DateTimeField(default=django.utils.timezone.now)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='SamplerDomainEnd',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('domain',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='catmaid.SamplerDomain')),
                ('end_node',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='catmaid.Treenode')),
            ],
        ),
        migrations.CreateModel(
            name='SamplerDomainType',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('name', models.TextField()),
                ('description', models.TextField()),
            ],
        ),
        migrations.CreateModel(
            name='SamplerInterval',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('creation_time',
                 models.DateTimeField(default=django.utils.timezone.now)),
                ('edition_time',
                 models.DateTimeField(default=django.utils.timezone.now)),
                ('domain',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='catmaid.SamplerDomain')),
                ('end_node',
                 models.ForeignKey(
                     on_delete=django.db.models.deletion.CASCADE,
                     related_name='sampler_interval_end_node_set',
                     to='catmaid.Treenode')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='SamplerIntervalState',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('name', models.TextField()),
                ('description', models.TextField()),
            ],
        ),
        migrations.CreateModel(
            name='SamplerState',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('name', models.TextField()),
                ('description', models.TextField()),
            ],
        ),
        migrations.CreateModel(
            name='SamplerConnector',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('creation_time',
                 models.DateTimeField(default=django.utils.timezone.now)),
                ('edition_time',
                 models.DateTimeField(default=django.utils.timezone.now)),
                ('connector',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='catmaid.Connector')),
                ('connector_state',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='catmaid.SamplerConnectorState')),
                ('interval',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='catmaid.SamplerInterval')),
                ('project',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='catmaid.Project')),
                ('user',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.AddField(
            model_name='samplerinterval',
            name='interval_state',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='catmaid.SamplerIntervalState'),
        ),
        migrations.AddField(
            model_name='samplerinterval',
            name='project',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='catmaid.Project'),
        ),
        migrations.AddField(
            model_name='samplerinterval',
            name='start_node',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                related_name='sampler_interval_start_node_set',
                to='catmaid.Treenode'),
        ),
        migrations.AddField(
            model_name='samplerinterval',
            name='user',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to=settings.AUTH_USER_MODEL),
        ),
        migrations.AddField(
            model_name='samplerdomain',
            name='domain_type',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='catmaid.SamplerDomainType'),
        ),
        migrations.AddField(
            model_name='samplerdomain',
            name='parent_interval',
            field=models.ForeignKey(
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                to='catmaid.SamplerInterval'),
        ),
        migrations.AddField(
            model_name='samplerdomain',
            name='project',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='catmaid.Project'),
        ),
        migrations.AddField(
            model_name='samplerdomain',
            name='sampler',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='catmaid.Sampler'),
        ),
        migrations.AddField(
            model_name='samplerdomain',
            name='start_node',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='catmaid.Treenode'),
        ),
        migrations.AddField(
            model_name='samplerdomain',
            name='user',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to=settings.AUTH_USER_MODEL),
        ),
        migrations.AddField(
            model_name='sampler',
            name='sampler_state',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='catmaid.SamplerState'),
        ),
        migrations.AddField(
            model_name='sampler',
            name='skeleton',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='catmaid.ClassInstance'),
        ),
        migrations.AddField(
            model_name='sampler',
            name='user',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to=settings.AUTH_USER_MODEL),
        ),
        # Add history tables for sampler relations
        migrations.RunSQL(
            """
            SELECT create_history_table('catmaid_sampler'::regclass);
            SELECT create_history_table('catmaid_samplerdomain'::regclass);
            SELECT create_history_table('catmaid_samplerdomainend'::regclass);
            SELECT create_history_table('catmaid_samplerdomaintype'::regclass);
            SELECT create_history_table('catmaid_samplerinterval'::regclass);
            SELECT create_history_table('catmaid_samplerintervalstate'::regclass);
            SELECT create_history_table('catmaid_samplerstate'::regclass);
            SELECT create_history_table('catmaid_samplerconnector'::regclass);
            SELECT create_history_table('catmaid_samplerconnectorstate'::regclass);
        """, """
            SELECT disable_history_tracking_for_table('catmaid_sampler'::regclass,
                    get_history_table_name('catmaid_sampler'::regclass));
            SELECT drop_history_table('catmaid_sampler'::regclass);

            SELECT disable_history_tracking_for_table('catmaid_samplerdomain'::regclass,
                    get_history_table_name('catmaid_samplerdomain'::regclass));
            SELECT drop_history_table('catmaid_samplerdomain'::regclass);

            SELECT disable_history_tracking_for_table('catmaid_samplerdomainend'::regclass,
                    get_history_table_name('catmaid_samplerdomainend'::regclass));
            SELECT drop_history_table('catmaid_samplerdomainend'::regclass);

            SELECT disable_history_tracking_for_table('catmaid_samplerdomaintype'::regclass,
                    get_history_table_name('catmaid_samplerdomaintype'::regclass));
            SELECT drop_history_table('catmaid_samplerdomaintype'::regclass);

            SELECT disable_history_tracking_for_table('catmaid_samplerinterval'::regclass,
                    get_history_table_name('catmaid_samplerinterval'::regclass));
            SELECT drop_history_table('catmaid_samplerinterval'::regclass);

            SELECT disable_history_tracking_for_table('catmaid_samplerintervalstate'::regclass,
                    get_history_table_name('catmaid_samplerintervalstate'::regclass));
            SELECT drop_history_table('catmaid_samplerintervalstate'::regclass);

            SELECT disable_history_tracking_for_table('catmaid_samplerstate'::regclass,
                    get_history_table_name('catmaid_samplerstate'::regclass));
            SELECT drop_history_table('catmaid_samplerstate'::regclass);

            SELECT disable_history_tracking_for_table('catmaid_samplerconnector'::regclass,
                    get_history_table_name('catmaid_samplerconnector'::regclass));
            SELECT drop_history_table('catmaid_samplerconnector'::regclass);

            SELECT disable_history_tracking_for_table('catmaid_samplerconnectorstate'::regclass,
                    get_history_table_name('catmaid_samplerconnectorstate'::regclass));
            SELECT drop_history_table('catmaid_samplerconnectorstate'::regclass);
        """)
    ]
class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('submissions', '0001_initial'),
        ('references', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='AppropriationAccountBalances',
            fields=[
                ('data_source',
                 models.CharField(
                     choices=[('USA', 'USAspending'),
                              ('DBR', 'DATA Act Broker')],
                     help_text=
                     'The source of this entry, either Data Broker (DBR) or USASpending (USA)',
                     max_length=3,
                     null=True)),
                ('appropriation_account_balances_id',
                 models.AutoField(primary_key=True, serialize=False)),
                ('budget_authority_unobligated_balance_brought_forward_fyb',
                 models.DecimalField(blank=True,
                                     decimal_places=2,
                                     max_digits=21,
                                     null=True)),
                ('adjustments_to_unobligated_balance_brought_forward_cpe',
                 models.DecimalField(decimal_places=2, max_digits=21)),
                ('budget_authority_appropriated_amount_cpe',
                 models.DecimalField(decimal_places=2, max_digits=21)),
                ('borrowing_authority_amount_total_cpe',
                 models.DecimalField(blank=True,
                                     decimal_places=2,
                                     max_digits=21,
                                     null=True)),
                ('contract_authority_amount_total_cpe',
                 models.DecimalField(blank=True,
                                     decimal_places=2,
                                     max_digits=21,
                                     null=True)),
                ('spending_authority_from_offsetting_collections_amount_cpe',
                 models.DecimalField(blank=True,
                                     decimal_places=2,
                                     max_digits=21,
                                     null=True)),
                ('other_budgetary_resources_amount_cpe',
                 models.DecimalField(blank=True,
                                     decimal_places=2,
                                     max_digits=21,
                                     null=True)),
                ('budget_authority_available_amount_total_cpe',
                 models.DecimalField(decimal_places=2, max_digits=21)),
                ('gross_outlay_amount_by_tas_cpe',
                 models.DecimalField(decimal_places=2, max_digits=21)),
                ('deobligations_recoveries_refunds_by_tas_cpe',
                 models.DecimalField(decimal_places=2, max_digits=21)),
                ('unobligated_balance_cpe',
                 models.DecimalField(decimal_places=2, max_digits=21)),
                ('status_of_budgetary_resources_total_cpe',
                 models.DecimalField(decimal_places=2, max_digits=21)),
                ('obligations_incurred_total_by_tas_cpe',
                 models.DecimalField(decimal_places=2, max_digits=21)),
                ('drv_appropriation_availability_period_start_date',
                 models.DateField(blank=True, null=True)),
                ('drv_appropriation_availability_period_end_date',
                 models.DateField(blank=True, null=True)),
                ('drv_appropriation_account_expired_status',
                 models.TextField(blank=True, null=True)),
                ('drv_obligations_unpaid_amount',
                 models.DecimalField(blank=True,
                                     decimal_places=2,
                                     max_digits=21,
                                     null=True)),
                ('drv_other_obligated_amount',
                 models.DecimalField(blank=True,
                                     decimal_places=2,
                                     max_digits=21,
                                     null=True)),
                ('reporting_period_start',
                 models.DateField(blank=True, null=True)),
                ('reporting_period_end', models.DateField(blank=True,
                                                          null=True)),
                ('last_modified_date', models.DateField(blank=True,
                                                        null=True)),
                ('certified_date', models.DateField(blank=True, null=True)),
                ('create_date',
                 models.DateTimeField(auto_now_add=True, null=True)),
                ('update_date', models.DateTimeField(auto_now=True,
                                                     null=True)),
                ('final_of_fy',
                 models.BooleanField(db_index=True, default=False)),
                ('submission',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='submissions.SubmissionAttributes')),
            ],
            options={
                'db_table': 'appropriation_account_balances',
                'managed': True,
            },
        ),
        migrations.CreateModel(
            name='AppropriationAccountBalancesQuarterly',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('data_source',
                 models.CharField(
                     choices=[('USA', 'USAspending'),
                              ('DBR', 'DATA Act Broker')],
                     help_text=
                     'The source of this entry, either Data Broker (DBR) or USASpending (USA)',
                     max_length=3,
                     null=True)),
                ('budget_authority_unobligated_balance_brought_forward_fyb',
                 models.DecimalField(blank=True,
                                     decimal_places=2,
                                     max_digits=21,
                                     null=True)),
                ('adjustments_to_unobligated_balance_brought_forward_cpe',
                 models.DecimalField(decimal_places=2, max_digits=21)),
                ('budget_authority_appropriated_amount_cpe',
                 models.DecimalField(decimal_places=2, max_digits=21)),
                ('borrowing_authority_amount_total_cpe',
                 models.DecimalField(blank=True,
                                     decimal_places=2,
                                     max_digits=21,
                                     null=True)),
                ('contract_authority_amount_total_cpe',
                 models.DecimalField(blank=True,
                                     decimal_places=2,
                                     max_digits=21,
                                     null=True)),
                ('spending_authority_from_offsetting_collections_amount_cpe',
                 models.DecimalField(blank=True,
                                     decimal_places=2,
                                     max_digits=21,
                                     null=True)),
                ('other_budgetary_resources_amount_cpe',
                 models.DecimalField(blank=True,
                                     decimal_places=2,
                                     max_digits=21,
                                     null=True)),
                ('budget_authority_available_amount_total_cpe',
                 models.DecimalField(decimal_places=2, max_digits=21)),
                ('gross_outlay_amount_by_tas_cpe',
                 models.DecimalField(decimal_places=2, max_digits=21)),
                ('deobligations_recoveries_refunds_by_tas_cpe',
                 models.DecimalField(decimal_places=2, max_digits=21)),
                ('unobligated_balance_cpe',
                 models.DecimalField(decimal_places=2, max_digits=21)),
                ('status_of_budgetary_resources_total_cpe',
                 models.DecimalField(decimal_places=2, max_digits=21)),
                ('obligations_incurred_total_by_tas_cpe',
                 models.DecimalField(decimal_places=2, max_digits=21)),
                ('create_date',
                 models.DateTimeField(auto_now_add=True, null=True)),
                ('update_date', models.DateTimeField(auto_now=True,
                                                     null=True)),
                ('submission',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='submissions.SubmissionAttributes')),
            ],
            options={
                'db_table': 'appropriation_account_balances_quarterly',
                'managed': True,
            },
        ),
        migrations.CreateModel(
            name='BudgetAuthority',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('agency_identifier', models.TextField(db_index=True)),
                ('fr_entity_code', models.TextField(db_index=True, null=True)),
                ('year', models.IntegerField()),
                ('amount', models.BigIntegerField(null=True)),
            ],
            options={
                'db_table': 'budget_authority',
            },
        ),
        migrations.CreateModel(
            name='FederalAccount',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('agency_identifier', models.TextField(db_index=True)),
                ('main_account_code', models.TextField(db_index=True)),
                ('account_title', models.TextField()),
                ('federal_account_code', models.TextField(null=True)),
            ],
            options={
                'db_table': 'federal_account',
                'managed': True,
            },
        ),
        migrations.CreateModel(
            name='TreasuryAppropriationAccount',
            fields=[
                ('data_source',
                 models.CharField(
                     choices=[('USA', 'USAspending'),
                              ('DBR', 'DATA Act Broker')],
                     help_text=
                     'The source of this entry, either Data Broker (DBR) or USASpending (USA)',
                     max_length=3,
                     null=True)),
                ('treasury_account_identifier',
                 models.AutoField(primary_key=True, serialize=False)),
                ('tas_rendering_label', models.TextField(blank=True,
                                                         null=True)),
                ('allocation_transfer_agency_id',
                 models.TextField(blank=True, null=True)),
                ('agency_id', models.TextField()),
                ('beginning_period_of_availability',
                 models.TextField(blank=True, null=True)),
                ('ending_period_of_availability',
                 models.TextField(blank=True, null=True)),
                ('availability_type_code',
                 models.TextField(blank=True, null=True)),
                ('availability_type_code_description',
                 models.TextField(blank=True, null=True)),
                ('main_account_code', models.TextField()),
                ('sub_account_code', models.TextField()),
                ('account_title', models.TextField(blank=True, null=True)),
                ('reporting_agency_id', models.TextField(blank=True,
                                                         null=True)),
                ('reporting_agency_name',
                 models.TextField(blank=True, null=True)),
                ('budget_bureau_code', models.TextField(blank=True,
                                                        null=True)),
                ('budget_bureau_name', models.TextField(blank=True,
                                                        null=True)),
                ('fr_entity_code', models.TextField(blank=True, null=True)),
                ('fr_entity_description',
                 models.TextField(blank=True, null=True)),
                ('budget_function_code', models.TextField(blank=True,
                                                          null=True)),
                ('budget_function_title',
                 models.TextField(blank=True, null=True)),
                ('budget_subfunction_code',
                 models.TextField(blank=True, null=True)),
                ('budget_subfunction_title',
                 models.TextField(blank=True, null=True)),
                ('drv_appropriation_availability_period_start_date',
                 models.DateField(blank=True, null=True)),
                ('drv_appropriation_availability_period_end_date',
                 models.DateField(blank=True, null=True)),
                ('drv_appropriation_account_expired_status',
                 models.TextField(blank=True, null=True)),
                ('create_date',
                 models.DateTimeField(auto_now_add=True, null=True)),
                ('update_date', models.DateTimeField(auto_now=True,
                                                     null=True)),
                ('awarding_toptier_agency',
                 models.ForeignKey(
                     help_text=
                     'The toptier agency object associated with the ATA',
                     null=True,
                     on_delete=django.db.models.deletion.DO_NOTHING,
                     related_name='tas_ata',
                     to='references.ToptierAgency')),
                ('federal_account',
                 models.ForeignKey(
                     null=True,
                     on_delete=django.db.models.deletion.DO_NOTHING,
                     to='accounts.FederalAccount')),
                ('funding_toptier_agency',
                 models.ForeignKey(
                     help_text=
                     'The toptier agency object associated with the AID',
                     null=True,
                     on_delete=django.db.models.deletion.DO_NOTHING,
                     related_name='tas_aid',
                     to='references.ToptierAgency')),
            ],
            options={
                'db_table': 'treasury_appropriation_account',
                'managed': True,
            },
        ),
        migrations.AlterUniqueTogether(
            name='federalaccount',
            unique_together=set([('agency_identifier', 'main_account_code')]),
        ),
        migrations.AlterUniqueTogether(
            name='budgetauthority',
            unique_together=set([('agency_identifier', 'fr_entity_code',
                                  'year')]),
        ),
        migrations.AddField(
            model_name='appropriationaccountbalancesquarterly',
            name='treasury_account_identifier',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='accounts.TreasuryAppropriationAccount'),
        ),
        migrations.AddField(
            model_name='appropriationaccountbalances',
            name='treasury_account_identifier',
            field=models.ForeignKey(
                db_column='treasury_account_identifier',
                on_delete=django.db.models.deletion.CASCADE,
                related_name='account_balances',
                to='accounts.TreasuryAppropriationAccount'),
        ),
        migrations.RunSQL(FY_PG_FUNCTION_DEF),
        migrations.RunSQL(AppropriationAccountBalances.FINAL_OF_FY_SQL),
    ]
Example #29
0
class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('userstories', '0012_auto_20160614_1201'),
        ('projects', '0049_auto_20160629_1443'),
        ('history', '0012_auto_20160629_1036'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Epic',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('tags',
                 django.contrib.postgres.fields.ArrayField(
                     base_field=models.TextField(),
                     blank=True,
                     default=list,
                     null=True,
                     size=None,
                     verbose_name='tags')),
                ('version',
                 models.IntegerField(default=1, verbose_name='version')),
                ('is_blocked',
                 models.BooleanField(default=False,
                                     verbose_name='is blocked')),
                ('blocked_note',
                 models.TextField(blank=True,
                                  default='',
                                  verbose_name='blocked note')),
                ('ref',
                 models.BigIntegerField(blank=True,
                                        db_index=True,
                                        default=None,
                                        null=True,
                                        verbose_name='ref')),
                ('epics_order',
                 models.IntegerField(default=10000,
                                     verbose_name='epics order')),
                ('created_date',
                 models.DateTimeField(default=django.utils.timezone.now,
                                      verbose_name='created date')),
                ('modified_date',
                 models.DateTimeField(verbose_name='modified date')),
                ('subject', models.TextField(verbose_name='subject')),
                ('description',
                 models.TextField(blank=True, verbose_name='description')),
                ('client_requirement',
                 models.BooleanField(default=False,
                                     verbose_name='is client requirement')),
                ('team_requirement',
                 models.BooleanField(default=False,
                                     verbose_name='is team requirement')),
                ('assigned_to',
                 models.ForeignKey(blank=True,
                                   default=None,
                                   null=True,
                                   on_delete=django.db.models.deletion.CASCADE,
                                   related_name='epics_assigned_to_me',
                                   to=settings.AUTH_USER_MODEL,
                                   verbose_name='assigned to')),
                ('owner',
                 models.ForeignKey(
                     blank=True,
                     null=True,
                     on_delete=django.db.models.deletion.SET_NULL,
                     related_name='owned_epics',
                     to=settings.AUTH_USER_MODEL,
                     verbose_name='owner')),
                ('project',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   related_name='epics',
                                   to='projects.Project',
                                   verbose_name='project')),
                ('status',
                 models.ForeignKey(
                     blank=True,
                     null=True,
                     on_delete=django.db.models.deletion.SET_NULL,
                     related_name='epics',
                     to='projects.EpicStatus',
                     verbose_name='status')),
            ],
            options={
                'ordering': ['project', 'epics_order', 'ref'],
                'verbose_name_plural': 'epics',
                'verbose_name': 'epic',
            },
            bases=(taiga.projects.notifications.mixins.WatchedModelMixin,
                   models.Model),
        ),
        migrations.CreateModel(
            name='RelatedUserStory',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('order',
                 models.IntegerField(default=10000, verbose_name='order')),
                ('epic',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='epics.Epic')),
                ('user_story',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='userstories.UserStory')),
            ],
            options={
                'ordering': ['user_story', 'order', 'id'],
                'verbose_name_plural': 'related user stories',
                'verbose_name': 'related user story',
            },
        ),
        migrations.AddField(
            model_name='epic',
            name='user_stories',
            field=models.ManyToManyField(related_name='epics',
                                         through='epics.RelatedUserStory',
                                         to='userstories.UserStory',
                                         verbose_name='user stories'),
        ),
        # Execute trigger after epic update
        migrations.RunSQL("""
            DROP TRIGGER IF EXISTS update_project_tags_colors_on_epic_update ON epics_epic;
            CREATE TRIGGER update_project_tags_colors_on_epic_update
            AFTER UPDATE ON epics_epic
            FOR EACH ROW EXECUTE PROCEDURE update_project_tags_colors();
            """),
        # Execute trigger after epic insert
        migrations.RunSQL("""
            DROP TRIGGER IF EXISTS update_project_tags_colors_on_epic_insert ON epics_epic;
            CREATE TRIGGER update_project_tags_colors_on_epic_insert
            AFTER INSERT ON epics_epic
            FOR EACH ROW EXECUTE PROCEDURE update_project_tags_colors();
            """),
    ]
Example #30
0
class Migration(migrations.Migration):

    dependencies = [("flows", "0151_auto_20180418_1807")]

    operations = [migrations.RunSQL(SQL, "")]