DO $$ 
DECLARE 
	my_cursor CURSOR FOR SELECT "Id","Title" FROM public."Customers" WHERE "Status"=1;
	quota_cursor CURSOR FOR SELECT "Id","CustomerId" FROM public."UserQuotas" WHERE "CustomerId" IS NOT NULL;
	customerId INT;
	quotaId BIGINT;
	oldQuotaId BIGINT;
	count INT;
BEGIN
	IF EXISTS (SELECT "Id" FROM public."Versions" WHERE "Build">=1765) THEN
		RETURN;
	END IF;
		  
		  
	SELECT COUNT(*) INTO count FROM public."Customers";
	IF(count = 1) THEN
		SELECT "Id" INTO customerId FROM public."Customers" LIMIT 1;
		UPDATE public."UserQuotas" SET "CustomerId" = customerId;
		RAISE NOTICE 'One customer update';
		RETURN;
	END IF;
		  
	OPEN my_cursor;    
	LOOP
		FETCH my_cursor INTO customerId;
		EXIT WHEN NOT FOUND;

		INSERT INTO public."UserQuotas"("Name","Size","CustomerId","IsDefault")
		SELECT uq."Name",uq."Size",customerId,uq."IsDefault" 
		FROM public."UserQuotas" uq WHERE uq."CustomerId" IS NULL 
		AND NOT EXISTS( SELECT "Id" FROM public."UserQuotas" 
					   WHERE "CustomerId" = customerId 
					   AND uq."Name" = "Name"
					   AND uq."Size" = "Size" LIMIT 1);
	END LOOP;
	CLOSE my_cursor;
	
	OPEN quota_cursor;
	LOOP
		FETCH quota_cursor INTO quotaId, customerId;
		EXIT WHEN NOT FOUND;
		
		RAISE NOTICE 'quotaId:% customerId:%',quotaId ,customerId;
		
		SELECT uq."Id" INTO oldQuotaId
		FROM public."UserQuotas" uq 
		JOIN public."UserQuotas" uqn ON uq."Name"=uqn."Name" AND uq."Size"=uqn."Size"
		WHERE uqn."Id" = quotaId;
		
		RAISE NOTICE 'oldQuotaId:% quotaId:% customerId:%', oldQuotaId,quotaId ,customerId;
		
		UPDATE public."UserMetrics" as um
			SET "QuotaId" = quotaId
		FROM public."Users" u 
		WHERE um."QuotaId" = oldQuotaId AND u."CustomerId" = customerId AND u."Id" = um."UserId";
	END LOOP;
	CLOSE quota_cursor;
END $$
