using Microsoft.EntityFrameworkCore.Migrations;
using System;
#nullable disable
namespace gehGassi.Persistence.Migrations
{
///
public partial class tv_SubscriptionsWithNamesEx : Migration
{
///
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn(
name: "GracePeriodInDays",
table: "Subscriptions",
type: "int",
nullable: false,
defaultValue: 0);
var viewName = "tv_SubscriptionsWithNames";
var sql = @"CREATE FUNCTION tv_SubscriptionsWithNames(@language nvarchar(2), @fallback nvarchar(2)) RETURNS TABLE AS RETURN
SELECT S.*,
Isnull(JSON_VALUE(S.NameLocalized, '$.' + @language), JSON_VALUE(S.NameLocalized, '$.' + @fallback)) AS Name,
Isnull(JSON_VALUE(S.DescriptionLocalized, '$.' + @language), JSON_VALUE(S.DescriptionLocalized, '$.' + @fallback)) AS Description,
(SELECT COUNT(Id) FROM AppUserSubscriptions WHERE SubscriptionId = S.Id) AS SubscriptionCountTotal,
(SELECT COUNT(Id) FROM AppUserSubscriptions WHERE SubscriptionId = S.Id AND IsValid = 1) AS SubscriptionCountActive,
(SELECT COUNT(Id) FROM AppUserSubscriptions WHERE SubscriptionId = S.Id AND IsValid = 0) AS SubscriptionCountInactive
FROM Subscriptions S";
migrationBuilder.Sql($"IF(exists (SELECT 1 FROM sys.objects WHERE Name = '{viewName}')) BEGIN DROP FUNCTION [dbo].[{viewName}] END {Environment.NewLine} GO");
migrationBuilder.Sql($"{sql} {Environment.NewLine} GO");
}
///
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "GracePeriodInDays",
table: "Subscriptions");
var viewName = "tv_SubscriptionsWithNames";
var sql = @"CREATE FUNCTION tv_SubscriptionsWithNames(@language nvarchar(2), @fallback nvarchar(2)) RETURNS TABLE AS RETURN
SELECT S.*,
Isnull(JSON_VALUE(S.NameLocalized, '$.' + @language), JSON_VALUE(S.NameLocalized, '$.' + @fallback)) AS Name,
Isnull(JSON_VALUE(S.DescriptionLocalized, '$.' + @language), JSON_VALUE(S.DescriptionLocalized, '$.' + @fallback)) AS Description,
(SELECT COUNT(Id) FROM AppUserSubscriptions WHERE SubscriptionId = S.Id) AS SubscriptionCountTotal,
(SELECT COUNT(Id) FROM AppUserSubscriptions WHERE SubscriptionId = S.Id AND IsValid = 1) AS SubscriptionCountActive,
(SELECT COUNT(Id) FROM AppUserSubscriptions WHERE SubscriptionId = S.Id AND IsValid = 0) AS SubscriptionCountInactive
FROM Subscriptions S";
migrationBuilder.Sql($"IF(exists (SELECT 1 FROM sys.objects WHERE Name = '{viewName}')) BEGIN DROP FUNCTION [dbo].[{viewName}] END {Environment.NewLine} GO");
migrationBuilder.Sql($"{sql} {Environment.NewLine} GO");
}
}
}