ModuleQueries.xml 38 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
<?xml version="1.0" encoding="utf-8"?>
<queries>
  <query key="CreateAccessRightsType">
    <mssql><![CDATA[-- Параметры:
-- {0} - Имя опреации.
-- {1} - Sid опреации.
-- {2} - GUID типа сущности.
-- {3} - Набор операций типа прав.
-- {4} - Маска разрешенных операций.
-- {5} - Область типа прав: экземпляр, тип или оба.
-- {6} - Описание.
-- {7} - Признак того, является ли тип прав переопределением базового.
if (select top 1 1 from Sungero_Core_AccessRightTyp where lower(EntityTypeGuid) = '{2}' and Sid = '{1}') is null
  begin
    declare @AccessRightTypTableName varchar(30) = 'Sungero_Core_AccessRightTyp'
    declare @NewId int
    exec Sungero_System_GetNewId @AccessRightTypTableName, @NewId output
    insert into [dbo].[Sungero_Core_AccessRightTyp] ([Id], [Name], [EntityTypeGuid], [OperationSet],
                                                                                             [GrantedMask], [AccessRightsTypeArea], [Description], [Sid],
                                                                                             [IsOverride], [Discriminator], [Status])
    values (@NewId, N'{0}', N'{2}', {3}, {4}, N'{5}', N'{6}', N'{1}', {7}, N'34D8054F-43C0-4C6A-A1A6-7EE427D65DC8', 'Active')
  end
else
  begin
    update Sungero_Core_AccessRightTyp
    set [Name] = N'{0}',
          [OperationSet] = {3},
          [GrantedMask] = {4},
          [AccessRightsTypeArea] = N'{5}',
          [Description] = N'{6}',
          [IsOverride] = {7}
    where lower(EntityTypeGuid) = '{2}' and Sid = '{1}'
end]]></mssql>
    <postgres><![CDATA[-- Параметры:
-- {0} - Имя опреации.
-- {1} - Sid опреации.
-- {2} - GUID типа сущности.
-- {3} - Набор операций типа прав.
-- {4} - Маска разрешенных операций.
-- {5} - Область типа прав: экземпляр, тип или оба.
-- {6} - Описание.
-- {7} - Признак того, является ли тип прав переопределением базового.
DO $$
DECLARE newId int;
BEGIN
  IF NOT EXISTS(SELECT 1 FROM Sungero_Core_AccessRightTyp WHERE EntityTypeGuid = uuid('{2}') AND Sid = '{1}')
  THEN
    SELECT INTO newId public.sungero_system_getnewid('Sungero_Core_AccessRightTyp');
    INSERT INTO Sungero_Core_AccessRightTyp(Discriminator, Id, Name, EntityTypeGuid, OperationSet, GrantedMask, AccessRightsTypeArea, Description, Sid, IsOverride, Status)
    VALUES (uuid('34D8054F-43C0-4C6A-A1A6-7EE427D65DC8'), newId, '{0}', '{2}', '{3}', '{4}', '{5}', '{6}', '{1}', '{7}', 'Active');
  ELSE
    UPDATE Sungero_Core_AccessRightTyp
    SET Name = '{0}',
          OperationSet = '{3}',
          GrantedMask = '{4}',
          AccessRightsTypeArea = '{5}',
          Description = '{6}',
          IsOverride = '{7}'
    WHERE EntityTypeGuid = uuid('{2}')
      AND Sid = '{1}';
  END IF;
END$$;]]></postgres>
  </query>
  <query key="CreateParametersTable">
    <mssql><![CDATA[-- Создать таблицу параметров.
if not exists(select 1 from sys.objects where object_id = OBJECT_ID(N'[dbo].[Sungero_Docflow_Params]') and type in (N'U'))
create table [Sungero_Docflow_Params]
(
                [Key] varchar(50),
                [Value] varchar(max)

constraint PK_Key primary key clustered ([Key])
                with (PAD_INDEX  = off, STATISTICS_NORECOMPUTE  = off, IGNORE_DUP_KEY = off, ALLOW_ROW_LOCKS  = on, ALLOW_PAGE_LOCKS  = on) on [primary]
) on [primary]


if not exists(select 1 from [dbo].[Sungero_Docflow_Params] where [Key] = 'LastNotificationOfAssignment')
  insert [Sungero_Docflow_Params] ([Key],Value)
  values ('LastNotificationOfAssignment', convert(varchar, getutcdate(), 127) + '+0')]]></mssql>
    <postgres><![CDATA[DO $$
BEGIN
  CREATE TABLE IF NOT EXISTS Sungero_Docflow_Params
  (
    Key citext NOT NULL CHECK (char_length(Key::text) <= 50),
    Value citext,
    PRIMARY KEY (Key)
  );

  IF NOT EXISTS(SELECT 1 FROM Sungero_Docflow_Params WHERE Key = 'LastNotificationOfAssignment')
  THEN
    INSERT INTO Sungero_Docflow_Params(Key, Value) VALUES ('LastNotificationOfAssignment', to_char(CURRENT_TIMESTAMP, 'YYYY-MM-DD"T"HH24:MI:SS.MSOF'));
  END IF;
END$$]]></postgres>
  </query>
  <query key="CreateSungeroDocregisterCurrentNumbersTable">
    <mssql><![CDATA[-- Создать табличку очередных номеров журналов регистрации, если её нет.
if not exists (select * from sys.objects where object_id = OBJECT_ID(N'[dbo].[Sungero_DocRegister_CurrentNumbers]') and type in (N'U'))
begin
  create table [dbo].[Sungero_DocRegister_CurrentNumbers]
  (
    [DocRegisterId] [int] NOT NULL,
    [CurrentNumber] [int] NOT NULL,
    [Month] [int] NOT NULL,
    [Year] [int] NOT NULL,
    [LeadDocument] [int] NOT NULL,
    [Quarter] [int] NOT NULL,
    [Department] [int] NOT NULL,
    [BUnit] [int] NOT NULL,
    [Day] [int] NOT NULL
  )
end]]></mssql>
    <postgres><![CDATA[-- Создать табличку очередных номеров журналов регистрации, если её нет.
CREATE TABLE IF NOT EXISTS Sungero_DocRegister_CurrentNumbers
  (
    DocRegisterId int not null,
    CurrentNumber int not null,
    Month int not null,
    Year int not null,
    LeadDocument int not null,
    Quarter int not null,
    Department int not null,
    BUnit int not null,
    Day int not null
  );]]></postgres>
  </query>
  <query key="DropProcedureSungeroDocRegisterGetNextNumber">
    <mssql><![CDATA[-- Удалить ХП для получение очередных номеров
if exists (select name from sys.objects where object_id = OBJECT_ID(N'[dbo].[Sungero_DocRegister_GetNextNumber]') and type in (N'P'))
  drop procedure [dbo].[Sungero_DocRegister_GetNextNumber]]]></mssql>
    <postgres><![CDATA[-- Удалить ХП для получение очередных номеров
DROP FUNCTION IF EXISTS Sungero_DocRegister_GetNextNumber();]]></postgres>
  </query>
  <query key="CreateProcedureSungeroDocRegisterGetNextNumber">
    <mssql><![CDATA[-- Создать ХП для получения очередных номеров
create procedure [dbo].[Sungero_DocRegister_GetNextNumber]
  @basevalue int,
  @docregid int,
  @newmonth int,
  @newyear int,
  @leaddoc int,
  @newquarter int,
  @newdep int,
  @newbusinessunit int,
  @newday int,
  @result int OUTPUT
as
begin
  if not exists(select * 
                from [dbo].[Sungero_DocRegister_CurrentNumbers]
                where [DocRegisterId] = @docregid and [Month] = @newmonth and [Year] = @newyear 
                  and [LeadDocument] = @leaddoc and [Quarter] = @newquarter and [Department] = @newdep and [BUnit] = @newbusinessunit and [Day] = @newday)
    begin
      insert
        [dbo].[Sungero_DocRegister_CurrentNumbers]([DocRegisterId], [CurrentNumber], [Month], [Year], [LeadDocument], [Quarter], [Department], [BUnit], [Day])
      values
        (@docregid, @basevalue, @newmonth, @newyear, @leaddoc, @newquarter, @newdep, @newbusinessunit, @newday)
      set @result = @basevalue
    end
  else
    update
      [dbo].[Sungero_DocRegister_CurrentNumbers] with (ROWLOCK)
    set
      @result = [CurrentNumber] + 1,
      [CurrentNumber] = [CurrentNumber] + 1
    where
      [DocRegisterId] = @docregid
      and [Month] = @newmonth
      and [Year] = @newyear
      and [LeadDocument] = @leaddoc
      and [Quarter] = @newquarter
      and [Department] = @newdep
      and [BUnit] = @newbusinessunit
      and [Day] = @newday
end]]></mssql>
    <postgres><![CDATA[-- Создать функцию для получения очередных номеров
CREATE OR REPLACE FUNCTION Sungero_DocRegister_GetNextNumber(
  basevalue int,
  docregid int,
  newmonth int,
  newyear int,
  leaddoc int,
  newquarter int,
  newdep int,
  newbusinessunit int,
  newday int)
RETURNS int AS $$
BEGIN
  IF NOT EXISTS(SELECT *
                FROM sungero_docregister_currentnumbers
                WHERE docregisterid = docregid
                  AND month = newmonth
                  AND year = newyear
                  AND leaddocument = leaddoc
                  AND quarter = newquarter
                  AND department = newdep
                  AND bunit = newbusinessunit
                  AND day = newday)
  THEN
    INSERT INTO sungero_docregister_currentnumbers(docregisterid, currentnumber, month, year, leaddocument, quarter, department, bunit, day)
    VALUES (docregid, basevalue, newmonth, newyear, leaddoc, newquarter, newdep, newbusinessunit, newday);
    RETURN basevalue;
  ELSE
    UPDATE sungero_docregister_currentnumbers
    SET currentnumber = currentnumber + 1
    WHERE docregisterid = docregid
      AND month = newmonth
      AND year = newyear
      AND leaddocument = leaddoc
      AND quarter = newquarter
      AND department = newdep
      AND bunit = newbusinessunit
      AND day = newday;
    RETURN (SELECT currentnumber
            FROM sungero_docregister_currentnumbers
            WHERE docregisterid = docregid
              AND month = newmonth
              AND year = newyear
              AND leaddocument = leaddoc
              AND quarter = newquarter
              AND department = newdep
              AND bunit = newbusinessunit
              AND day = newday);
  END IF;
END;
$$
LANGUAGE plpgsql;]]></postgres>
  </query>
  <query key="CreateIndicesSungeroDocRegisterCurrentNumber">
    <mssql><![CDATA[-- Добавить необходимые индексы
if not exists (select * from sys.indexes where object_id = OBJECT_ID(N'[dbo].[Sungero_DocRegister_CurrentNumbers]') and name = N'Sungero_DocRegister_CurrentNumbers_DocRegisterId')
  create index [Sungero_DocRegister_CurrentNumbers_DocRegisterId] on [dbo].[Sungero_DocRegister_CurrentNumbers] ([DocRegisterId] ASC)
if not exists (select * from sys.indexes where object_id = OBJECT_ID(N'[dbo].[Sungero_DocRegister_CurrentNumbers]') and name = N'Sungero_DocRegister_CurrentNumbers_DocRegisterId_Month')
  create index [Sungero_DocRegister_CurrentNumbers_DocRegisterId_Month] on [dbo].[Sungero_DocRegister_CurrentNumbers] ([DocRegisterId] ASC, [Month])
if not exists (select * from sys.indexes where object_id = OBJECT_ID(N'[dbo].[Sungero_DocRegister_CurrentNumbers]') and name = N'Sungero_DocRegister_CurrentNumbers_DocRegisterId_Month_Year')
  create index [Sungero_DocRegister_CurrentNumbers_DocRegisterId_Month_Year] on [dbo].[Sungero_DocRegister_CurrentNumbers] ([DocRegisterId] ASC, [Month], [Year])
if not exists (select * from sys.indexes where object_id = OBJECT_ID(N'[dbo].[Sungero_DocRegister_CurrentNumbers]') and name = N'Sungero_DocRegister_CurrentNumbers_DocRegisterId_Month_Year_LDoc')
  create index [Sungero_DocRegister_CurrentNumbers_DocRegisterId_Month_Year_LDoc] on [dbo].[Sungero_DocRegister_CurrentNumbers] ([DocRegisterId] ASC, [Month], [Year], [LeadDocument])]]></mssql>
    <postgres><![CDATA[-- Добавить необходимые индексы
CREATE INDEX IF NOT EXISTS Sungero_DocRegister_CurrentNumbers_DocRegisterId ON Sungero_DocRegister_CurrentNumbers (DocRegisterId ASC);
CREATE INDEX IF NOT EXISTS Sungero_DocRegister_CurrentNumbers_DocRegisterId_Month ON Sungero_DocRegister_CurrentNumbers (DocRegisterId ASC, Month);
CREATE INDEX IF NOT EXISTS Sungero_DocRegister_CurrentNumbers_DocRegisterId_Month_Year ON Sungero_DocRegister_CurrentNumbers (DocRegisterId ASC, Month, Year);
CREATE INDEX IF NOT EXISTS Sungero_DocRegister_CurrentNumbers_DocRegisterId_Month_Year_LDoc ON Sungero_DocRegister_CurrentNumbers (DocRegisterId ASC, Month, Year, LeadDocument);]]></postgres>
  </query>
  <query key="CreateIndexOnTable">
    <mssql><![CDATA[if (not exists (select 1 from sys.indexes
                where object_id = (select object_id from sys.objects where name = '{0}')
                and name = '{1}'))
begin
{2}
end]]></mssql>
    <postgres><![CDATA[{2}]]></postgres>
  </query>
  <query key="SungeroWFAssignmentIndex0Query">
    <mssql><![CDATA[CREATE NONCLUSTERED INDEX {1} ON {0}
(
  [Discriminator],
  [Performer],
  [Author],
  [MainTask],
  [CompletedBy],
  [Created]
)]]></mssql>
    <postgres><![CDATA[CREATE INDEX IF NOT EXISTS {1} ON {0} (Discriminator, Performer, Author, MainTask, CompletedBy, Created)]]></postgres>
  </query>
  <query key="SungeroContentEDocIndex0Query">
    <mssql><![CDATA[CREATE NONCLUSTERED INDEX {1} ON {0}
(
  [Discriminator] ASC,
  [Created] ASC,
  [LifeCycleState_Docflow_Sungero] ASC
)
INCLUDE (
  [RegDate_Docflow_Sungero],
  [RegState_Docflow_Sungero]
)
WITH (
  PAD_INDEX = OFF,
  STATISTICS_NORECOMPUTE = OFF,
  SORT_IN_TEMPDB = OFF,
  DROP_EXISTING = OFF,
  ONLINE = OFF,
  ALLOW_ROW_LOCKS = ON,
  ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]]]></mssql>
    <postgres><![CDATA[CREATE INDEX IF NOT EXISTS {1} ON {0} (Discriminator, Created, LifeCycleState_Docflow_Sungero, RegDate_Docflow_Sungero, RegState_Docflow_Sungero)]]></postgres>
  </query>
  <query key="SungeroContentEDocIndex1Query">
    <mssql><![CDATA[CREATE NONCLUSTERED INDEX {1} ON {0}
(
  [Discriminator] ,
  [RegState_Docflow_Sungero] ,
  [RegDate_Docflow_Sungero] DESC,
  [RegNumber_Docflow_Sungero] DESC,
  [Created] ASC
)
WITH (
  PAD_INDEX = OFF,
  STATISTICS_NORECOMPUTE = OFF,
  SORT_IN_TEMPDB = OFF,
  DROP_EXISTING = OFF,
  ONLINE = OFF,
  ALLOW_ROW_LOCKS = ON,
  ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]]]></mssql>
    <postgres><![CDATA[CREATE INDEX IF NOT EXISTS {1} ON {0} (Discriminator, RegState_Docflow_Sungero, RegDate_Docflow_Sungero DESC, RegNumber_Docflow_Sungero DESC, Created)]]></postgres>
  </query>
  <query key="SungeroContentEDocIndex2Query">
    <mssql><![CDATA[CREATE NONCLUSTERED INDEX {1} ON {0}
(
  [Index_Docflow_Sungero],
  [DocRegister_Docflow_Sungero],
  [Id],
  [Discriminator]
)]]></mssql>
    <postgres><![CDATA[CREATE INDEX IF NOT EXISTS {1} ON {0} (Index_Docflow_Sungero, DocRegister_Docflow_Sungero, Id, Discriminator)]]></postgres>
  </query>
  <query key="DropTable">
    <mssql><![CDATA[if exists (select * from information_schema.tables where table_name = '{0}')
  drop table {0}]]></mssql>
    <postgres><![CDATA[DROP TABLE IF EXISTS {0}]]></postgres>
  </query>
  <query key="CreateTempTableForRights">
    <mssql><![CDATA[create table {0} ([Id] [int] NOT NULL, [ReportSessionId] varchar(256) NULL)]]></mssql>
    <postgres><![CDATA[CREATE TABLE {0} (Id int NOT NULL, ReportSessionId citext NULL)]]></postgres>
  </query>
  <query key="InsertIntoTempTableForRights">
    <mssql><![CDATA[insert into {0} ([Id]) values ({1})]]></mssql>
    <postgres><![CDATA[INSERT INTO {0} (Id) VALUES ({1})]]></postgres>
  </query>
  <query key="ReadLicense">
    <mssql><![CDATA[select [Id], [Key] from dbo.Sungero_System_License]]></mssql>
    <postgres><![CDATA[SELECT Id, Key FROM Sungero_System_License]]></postgres>
  </query>
  <query key="DeleteLicense">
    <mssql><![CDATA[delete from dbo.Sungero_System_License]]></mssql>
    <postgres><![CDATA[DELETE FROM Sungero_System_License]]></postgres>
  </query>
  <query key="RestoreLicense">
    <mssql><![CDATA[insert into dbo.Sungero_System_License ([Id], [Key]) values (@id, @key)]]></mssql>
    <postgres><![CDATA[INSERT INTO Sungero_System_License (Id, Key) values (@id, @key)]]></postgres>
  </query>
  <query key="DropProcedureSungeroDocRegisterSetCurrentNumber">
    <mssql><![CDATA[-- Не акльтуально, т.к. процедура ненужна]]></mssql>
    <postgres><![CDATA[-- Процедуры нужно удалять, т.к. create or replace function не работает при изменении параметров.
DROP FUNCTION IF EXISTS Sungero_DocRegister_SetCurrentNumber();]]></postgres>
  </query>
  <query key="CreateProcedureSungeroDocRegisterSetCurrentNumber">
    <mssql><![CDATA[-- Не акльтуально, т.к. процедура ненужна]]></mssql>
    <postgres><![CDATA[create or replace function Sungero_DocRegister_SetCurrentNumber(
  docRegId int,
  currNumb int,
  newMonth int,
  newYear int,
  leadDoc int,
  newQuarter int,
  newdep int,
  newbusinessUnit int,
  newday int)
  returns void as $$
begin
  if exists (select *
             from Sungero_DocRegister_CurrentNumbers
             where DocRegisterId = docRegId
               and Month = newMonth
               and Year = newYear
               and LeadDocument = leadDoc
               and Quarter = newQuarter
               and Department = newdep
               and BUnit = newbusinessUnit
               and Day = newday) then
    update Sungero_DocRegister_CurrentNumbers
       set CurrentNumber = currNumb
     where DocRegisterId = docRegId
       and Month = newMonth
       and Year = newYear
       and LeadDocument = leadDoc
       and Quarter = newQuarter
       and Department = newdep
       and BUnit = newbusinessUnit
       and Day = newday;
  else
    insert into Sungero_DocRegister_CurrentNumbers (DocRegisterId, CurrentNumber, Month, Year, LeadDocument, Quarter, Department, BUnit, Day)
    values (docRegId, currNumb, newMonth, newYear, leadDoc, newQuarter, newdep, newbusinessUnit, newday);
  end if;
end;
$$
language plpgsql;]]></postgres>
  </query>
  <query key="InsertOrUpdateDocflowParamsValue">
    <mssql><![CDATA[if not exists(select 1 from [dbo].[Sungero_Docflow_Params] where [Key] = '{0}')
  insert [Sungero_Docflow_Params] ([Key],Value) values ('{0}', '{1}')
else UPDATE Sungero_Docflow_Params SET Value = '{1}' WHERE ([Key] = '{0}')]]></mssql>
    <postgres><![CDATA[do $$
begin
  if not exists(select 1 from Sungero_Docflow_Params where Key = '{0}')
  then
    insert into Sungero_Docflow_Params (Key, Value) values ('{0}', '{1}');
  else
    UPDATE Sungero_Docflow_Params SET Value = '{1}' WHERE (Key = '{0}');
  end if;
end$$;]]></postgres>
  </query>
  <query key="SelectDocflowParamsValue">
    <mssql><![CDATA[SELECT Value FROM Sungero_Docflow_Params WHERE ([Key] = '{0}')]]></mssql>
    <postgres><![CDATA[SELECT Value FROM Sungero_Docflow_Params WHERE (Key = '{0}')]]></postgres>
  </query>
  <query key="DeleteReportData">
    <mssql><![CDATA[delete from {0}
where [ReportSessionId] = '{1}']]></mssql>
    <postgres><![CDATA[DELETE FROM {0}
WHERE ReportSessionId = '{1}']]></postgres>
  </query>
  <query key="GetAllRecipientMembers">
    <mssql><![CDATA[exec sungero_core_getallrecipientmembers {0}, 1]]></mssql>
    <postgres><![CDATA[select sungero_core_getallrecipientmembers({0}, true)]]></postgres>
  </query>
  <query key="SungeroContentEDocIndex3Query">
    <mssql><![CDATA[CREATE NONCLUSTERED INDEX {1} ON {0}
(
  [Discriminator],
  [DocumentDate_Docflow_Sungero],
  [RegState_Docflow_Sungero],
  [DocumentKind_Docflow_Sungero]
) include (SecureObject)]]></mssql>
    <postgres><![CDATA[CREATE INDEX IF NOT EXISTS {1} ON {0} 
(
  Discriminator, 
  DocumentDate_Docflow_Sungero, 
  RegState_Docflow_Sungero,
  DocumentKind_Docflow_Sungero,
  /*include*/ SecureObject
)]]></postgres>
  </query>
  <query key="OneFieldIndexQuery">
    <mssql><![CDATA[CREATE NONCLUSTERED INDEX {1} ON {0}
(
  [{2}]
)]]></mssql>
    <postgres><![CDATA[CREATE INDEX IF NOT EXISTS {1} ON {0} 
(
  {2}
)]]></postgres>
  </query>
  <query key="SungeroContentEDocIndex4Query">
    <mssql><![CDATA[CREATE NONCLUSTERED INDEX {1} ON {0}
(
  [Discriminator],
  [DocumentKind_Docflow_Sungero]
)]]></mssql>
    <postgres><![CDATA[CREATE INDEX IF NOT EXISTS {1} ON {0} 
(
  Discriminator, 
  DocumentKind_Docflow_Sungero
)]]></postgres>
  </query>
  <query key="SungeroContentEDocIndex5Query">
    <mssql><![CDATA[CREATE NONCLUSTERED INDEX {1} ON {0}
(
  [Discriminator],
  [DocumentDate_Docflow_Sungero],
  [LifeCycleState_Docflow_Sungero],
  [IntApprState_Docflow_Sungero]
) include (SecureObject)]]></mssql>
    <postgres><![CDATA[CREATE INDEX IF NOT EXISTS {1} ON {0} 
(
  Discriminator, 
  DocumentDate_Docflow_Sungero, 
  LifeCycleState_Docflow_Sungero,
  IntApprState_Docflow_Sungero,
  /*include*/ SecureObject
)]]></postgres>
  </query>
  <query key="SungeroWFTaskIndex1Query">
    <mssql><![CDATA[CREATE NONCLUSTERED INDEX {1} ON {0}
(
  [Discriminator],
  [ExecutionState_RecMan_Sungero],
  [IsCompound_RecMan_Sungero],
  [Status]
) include (AssignedBy_RecMan_Sungero, Supervisor_RecMan_Sungero, AssigneeTAI_RecMan_Sungero, MainTask)]]></mssql>
    <postgres><![CDATA[CREATE INDEX IF NOT EXISTS {1} ON {0} 
(
  Discriminator, 
  ExecutionState_RecMan_Sungero, 
  IsCompound_RecMan_Sungero,
  Status,
  /*include*/ AssignedBy_RecMan_Sungero,
  Supervisor_RecMan_Sungero,
  AssigneeTAI_RecMan_Sungero,
  MainTask
)]]></postgres>
  </query>
  <query key="SungeroWFTaskIndex2Query">
    <mssql><![CDATA[CREATE NONCLUSTERED INDEX {1} ON {0}
(
  [Discriminator],
  [Status]
) include (DeadlineTAI_RecMan_Sungero, IsCompound_RecMan_Sungero, ActualDate_RecMan_Sungero, MainTask)]]></mssql>
    <postgres><![CDATA[CREATE INDEX IF NOT EXISTS {1} ON {0} 
(
  Discriminator, 
  Status,
  /*include*/ DeadlineTAI_RecMan_Sungero,
  IsCompound_RecMan_Sungero,
  ActualDate_RecMan_Sungero,
  MainTask
)]]></postgres>
  </query>
  <query key="SungeroContentEDocIndex6Query">
    <mssql><![CDATA[CREATE NONCLUSTERED INDEX {1} ON {0}
(
  [Discriminator],
  [DocumentDate_Docflow_Sungero],
  [RegState_Docflow_Sungero]
) include (SecureObject)]]></mssql>
    <postgres><![CDATA[CREATE INDEX IF NOT EXISTS {1} ON {0} 
(
  Discriminator, 
  DocumentDate_Docflow_Sungero, 
  RegState_Docflow_Sungero,
  SecureObject
)]]></postgres>
  </query>
  <query key="AddGrantRightsTypeToDocflowParams" />
  <query key="SelectDocflowParamsValueByKey">
    <mssql><![CDATA[SELECT Value FROM Sungero_Docflow_Params WHERE ([Key] = @key)]]></mssql>
    <postgres><![CDATA[SELECT Value FROM Sungero_Docflow_Params WHERE (Key = @key)]]></postgres>
  </query>
  <query key="CreateTableForExpiringPowerOfAttorney">
    <mssql><![CDATA[if OBJECT_ID('Sungero_Docflow_ExpiringPoA') is null
create table [Sungero_Docflow_ExpiringPoA] (EDoc int unique, Task int);]]></mssql>
    <postgres><![CDATA[CREATE TABLE IF NOT EXISTS Sungero_Docflow_ExpiringPoA
  (
    EDOC integer,
    Task integer,
    UNIQUE(EDOC)
  )]]></postgres>
  </query>
  <query key="SelectDocumentWithSendedTask">
    <mssql><![CDATA[select EDoc
from {0}
where [Task] is not null]]></mssql>
    <postgres><![CDATA[select EDoc
from {0}
where Task is not null]]></postgres>
  </query>
  <query key="DeleteDocumentIdsWithoutTask">
    <mssql><![CDATA[delete from {0}
where
  [Task] is null
  and EDoc in ({1})]]></mssql>
    <postgres><![CDATA[delete from {0}
 where
  Task is not null
  and EDoc in ({1})]]></postgres>
  </query>
  <query key="AddExpiringDocumentsToTable">
    <default><![CDATA[insert into {0} ( EDoc ) values ({1})]]></default>
  </query>
  <query key="AddTaskExpiringDocumentTable">
    <mssql><![CDATA[if not exists
 (
    select
      1
    from
      [dbo].[{0}]
    where
      [EDoc] = {1}
  )
  insert
    [{0}] ([EDoc], [Task])  values ({1}, {2})
  else
    update
      {0}
    set
      [Task] = {2}
    where
      [EDoc] = {1}]]></mssql>
    <postgres><![CDATA[DO
$$
BEGIN
if not exists
  (select
    1
  from
    {0}
  where
    EDoc = {1})
then
  insert into
    {0} (EDoc, Task)  values ({1}, {2});
else
  update
    {0}
  set
    Task = {2}
  where
    EDoc = {1};
end if;
END$$]]></postgres>
  </query>
  <query key="CountNullExpiringTasks">
    <mssql><![CDATA[select
  count(*)
from
  {0}
where
  [Task] is null]]></mssql>
    <postgres><![CDATA[select
  count(*)
from
  {0}
where
  Task is null]]></postgres>
  </query>
  <query key="UpdateLastExpiringNotificationDate">
    <mssql><![CDATA[if not exists
  (
    select
      1
    from
      [dbo].[Sungero_Docflow_Params]
    where
      [Key] = '{0}'
  )
  insert
    [Sungero_Docflow_Params] ([Key],Value) values ('{0}', '{1}')
  else
    update
      Sungero_Docflow_Params
    set
      Value = '{1}'
    where
      [Key] = '{0}']]></mssql>
    <postgres><![CDATA[DO
$$
BEGIN
if not exists
  (select
    1
  from
    Sungero_Docflow_Params
  where
    Key = '{0}'
  )
then
  insert into
    Sungero_Docflow_Params (Key,Value) values ('{0}', '{1}');
else
  update
    Sungero_Docflow_Params
  set
    Value = '{1}'
  where
    Key = '{0}';
end if;
END$$]]></postgres>
  </query>
  <query key="ClearExpiringTableWithoutTasks">
    <mssql><![CDATA[delete from
  {0}
where
  [Task] is null]]></mssql>
    <postgres><![CDATA[delete from
  {0}
where
  Task is null]]></postgres>
  </query>
  <query key="ClearExpiringTableWithTasks">
    <mssql><![CDATA[delete from
  {0}
where
  [Task] is not null]]></mssql>
    <postgres><![CDATA[delete from
  {0}
where
  Task is not null]]></postgres>
  </query>
  <query key="CreateStoragePolicySettings">
    <mssql><![CDATA[if exists (select * from information_schema.tables where table_name = '{0}')
  drop table {0}

select r.Storage, rdk.DocumentKind,
  case when r.DocDateType = 'DocumentDate' then dateadd(DD, -1 * r.DaysToMove, @now) else @maxDate end as DocumentDate,
  case when r.DocDateType = 'Modified' then dateadd(DD, -1 * r.DaysToMove, @now) else @maxDate end as Modified,
  case when r.Discriminator = '9fed5653-77e7-4543-b071-6586033907ef' then r.[Priority] else r.[Priority] + (select coalesce(max(r2.[Priority]), 0) from Sungero_Docflow_StoragePolicy r2 where r2.Discriminator = '9fed5653-77e7-4543-b071-6586033907ef') end as [Priority],
  case when coalesce(r.NextRetention, @now) <= @now then 1 else 0 end as NeedRetention
into {0}
  from Sungero_Docflow_StoragePolicy r
  join Sungero_Docflow_SPolicyDocKind rdk
    on rdk.StoragePolicy = r.Id
	where r.Status = 'Active';

insert into {0}
select r.Storage, rdk.Id,
  case when r.DocDateType = 'DocumentDate' then dateadd(DD, -1 * r.DaysToMove, @now) else @maxDate end as DocumentDate,
  case when r.DocDateType = 'Modified' then dateadd(DD, -1 * r.DaysToMove, @now) else @maxDate end as Modified,
  case when r.Discriminator = '9fed5653-77e7-4543-b071-6586033907ef' then r.[Priority] else r.[Priority] + (select coalesce(max(r2.[Priority]), 0) from Sungero_Docflow_StoragePolicy r2 where r2.Discriminator = '9fed5653-77e7-4543-b071-6586033907ef') end as [Priority],
  case when coalesce(r.NextRetention, @now) <= @now then 1 else 0 end as NeedRetention
  from Sungero_Docflow_StoragePolicy r
  join Sungero_Docflow_DocumentKind rdk
    on 1=1
	where r.Status = 'Active'
	  and not exists (select 1 from Sungero_Docflow_SPolicyDocKind k where k.StoragePolicy = r.Id);
	  
insert into {0}
select s.Id, rdk.Id, @maxDate, @maxDate, -1, 1
  from Sungero_Core_Storage s
  join Sungero_Docflow_DocumentKind rdk
    on 1=1
  where s.IsDefault = 1;]]></mssql>
    <postgres><![CDATA[DO $$
BEGIN
  IF EXISTS (SELECT * FROM information_schema.tables WHERE table_name = LOWER('{0}')) THEN
    DROP TABLE {0};
  END IF;
END $$;

SELECT r.Storage, rdk.DocumentKind,
  CASE 
    WHEN r.DocDateType = 'DocumentDate' 
    THEN @now - r.DaysToMove * INTERVAL '1 day' 
    ELSE @maxDate 
  END AS DocumentDate,
  CASE 
    WHEN r.DocDateType = 'Modified' 
    THEN @now - r.DaysToMove * INTERVAL '1 day' 
    ELSE @maxDate 
  END AS Modified,
  CASE 
    WHEN r.Discriminator = '9fed5653-77e7-4543-b071-6586033907ef' 
    THEN r.Priority 
    ELSE r.Priority + (SELECT COALESCE(MAX(r2.Priority), 0) FROM Sungero_Docflow_StoragePolicy r2 WHERE r2.Discriminator = '9fed5653-77e7-4543-b071-6586033907ef') 
  END AS Priority,
  CASE 
    WHEN COALESCE(r.NextRetention, @now) <= @now 
    THEN 1 
    ELSE 0
  END AS NeedRetention
INTO {0}
  FROM Sungero_Docflow_StoragePolicy r
  JOIN Sungero_Docflow_SPolicyDocKind rdk
    ON rdk.StoragePolicy = r.Id
  WHERE r.Status = 'Active';

INSERT INTO {0}
SELECT r.Storage, rdk.Id,
  CASE 
    WHEN r.DocDateType = 'DocumentDate' 
    THEN @now - r.DaysToMove * INTERVAL '1 day' 
    ELSE @maxDate 
  END AS DocumentDate,
  CASE 
    WHEN r.DocDateType = 'Modified' 
    THEN @now - r.DaysToMove * INTERVAL '1 day' 
    ELSE @maxDate 
  END AS Modified,
  CASE 
    WHEN r.Discriminator = '9fed5653-77e7-4543-b071-6586033907ef' 
    THEN r.Priority 
    ELSE r.Priority + (SELECT COALESCE(MAX(r2.Priority), 0) FROM Sungero_Docflow_StoragePolicy r2 WHERE r2.Discriminator = '9fed5653-77e7-4543-b071-6586033907ef') 
  END AS Priority,
  CASE 
    WHEN COALESCE(r.NextRetention, @now) <= @now 
    THEN 1 
    ELSE 0 
  END AS NeedRetention
  FROM Sungero_Docflow_StoragePolicy r
  JOIN Sungero_Docflow_DocumentKind rdk
    ON 1=1
    WHERE r.Status = 'Active'
      AND NOT EXISTS (SELECT 1 FROM Sungero_Docflow_SPolicyDocKind k WHERE k.StoragePolicy = r.Id);
      
INSERT INTO {0}
SELECT s.Id, rdk.Id, @maxDate, @maxDate, -1, 1
  FROM Sungero_Core_Storage s
  JOIN Sungero_Docflow_DocumentKind rdk
    ON 1=1
  WHERE s.IsDefault = TRUE;]]></postgres>
  </query>
  <query key="SelectDocumentsToTransfer">
    <default><![CDATA[select doc.Id, t.Storage
	from Sungero_Content_EDoc doc
	join {0} t
	  on t.DocumentKind = doc.DocumentKind_Docflow_Sungero
	  and doc.DocumentDate_Docflow_Sungero <= t.DocumentDate
	  and doc.Modified <= t.Modified
	where t.Priority = (select max(tt.Priority) 
	                      from {0} tt 
						  where tt.DocumentKind = doc.DocumentKind_Docflow_Sungero
	                        and doc.DocumentDate_Docflow_Sungero <= tt.DocumentDate
	                        and doc.Modified <= tt.Modified)
	and t.Storage != doc.Storage_Docflow_Sungero
	and doc.Storage_Docflow_Sungero is not null
	and t.NeedRetention = 1]]></default>
  </query>
  <query key="SungeroContentEDocIndex7Query">
    <mssql><![CDATA[CREATE NONCLUSTERED INDEX {1}
ON {0} (DocumentKind_Docflow_Sungero, DocumentDate_Docflow_Sungero, Modified, Storage_Docflow_Sungero)]]></mssql>
    <postgres><![CDATA[CREATE INDEX IF NOT EXISTS {1}
ON {0} (DocumentKind_Docflow_Sungero, DocumentDate_Docflow_Sungero, Modified, Storage_Docflow_Sungero);]]></postgres>
  </query>
  <query key="ConvertDocumentKindsAccessRights">
    <mssql><![CDATA[declare @documentKindTypeGuid uniqueidentifier
declare @accessRightTypeSid uniqueidentifier
declare @documentKindId int
declare @recipientId int
declare @operations int 
declare @secureObjectid int
declare @accessRightsTypeId int
declare @accessRightsId int
declare @cursor cursor
declare @accessctrlentNewId int
declare @accessrightentNewId int

set @documentKindTypeGuid = '14a59623-89a2-4ea8-b6e9-2ad4365f358c'
set @accessRightTypeSid = 'f3c5d7c0-c5c3-4957-add6-193a2f44f267'
set @recipientId = (select r.id from sungero_core_recipient r where r.sid = '440103EA-A766-47A8-98AD-5260CA32DE46')
set @operations = 16777216;
set @accessctrlentNewId = {0};
set @accessrightentNewId = {1};

begin
  set @accessRightsTypeId = (select art.id from sungero_core_accessrighttyp art where art.sid = @accessRightTypeSid)
  
  if (@accessRightsTypeId is not null)
  begin
    -- Выдача экземплярных прав в sungero_system_accessctrlent на каждый вид документа.
    set @cursor = cursor for select id from sungero_docflow_documentkind dk
      where not exists(select 1 from sungero_system_accessctrlent ace where ace.granted = 'True' and 
                    ace.operationset = @operations and
                    ace.recipient = @recipientid and
                    ace.secureobject = (select so.id from sungero_system_secureobject so where so.entityid = dk.id and so.entitytypeguid = dk.discriminator))
    
    open @cursor
    fetch next from @cursor into @documentKindId
    
    while @@FETCH_STATUS = 0
    begin
      set @secureObjectId = (select so.id from sungero_system_secureobject so where so.entityid = @documentKindId and so.entitytypeguid = @documentKindTypeGuid)
      if (@secureObjectId is not null)
      begin
        insert into sungero_system_accessctrlent(id, granted, operationset, recipient, secureobject)
        values (@accessctrlentNewId, 'True', @operations, @recipientId, @secureObjectId);
        set @accessctrlentNewId = @accessctrlentNewId + 1;
      end
    
      fetch next from @cursor into @documentKindId
    end
    close @cursor
      
    -- Выдача экземплярных прав в sungero_core_accessrightent на каждый вид документа.
    
    set @cursor = cursor for select id from sungero_docflow_documentkind dk
      where not exists(select 1 from sungero_core_accessrightent aren where 
                        aren.accessrights = (select ar.id from sungero_core_accessrights ar where  ar.entityid = dk.id and ar.entitytypeguid = dk.discriminator) and 
                   			aren.recipient = @recipientid and
                   			aren.accessrightstype = @accessRightsTypeId)
    
    open @cursor
    fetch next from @cursor into @documentKindId
    
    while @@FETCH_STATUS = 0
    begin
      set @accessRightsId = (select ar.id from sungero_core_accessrights ar where ar.entityid = @documentKindId and ar.entitytypeguid = @documentKindTypeGuid)
      if (@accessRightsId is not null)
      begin
        insert into sungero_core_accessrightent (id, accessrights, recipient, accessrightstype)
        values (@accessrightentNewId, @accessRightsId, @recipientId, @accessRightsTypeId);
        set @accessrightentNewId = @accessrightentNewId + 1;
      end 
    
      fetch next from @cursor into @documentKindId
    end
    close @cursor
  end
end]]></mssql>
    <postgres><![CDATA[DO $$
declare documentKindTypeGuid uuid;
declare accessRightTypeSid uuid;
declare documentKindId int;
declare recipientId int;
declare operations int; 
declare secureObjectid int;
declare accessRightsTypeId int;
declare accessRightsId int;
declare accessctrlentNewId int;
declare accessrightentNewId int;

begin
	documentKindTypeGuid := '14a59623-89a2-4ea8-b6e9-2ad4365f358c';
  accessRightTypeSid := 'f3c5d7c0-c5c3-4957-add6-193a2f44f267';
	recipientId := (select r.id from sungero_core_recipient r where r.sid = '440103EA-A766-47A8-98AD-5260CA32DE46');
  operations := 16777216;
  accessctrlentNewId := {0};
  accessrightentNewId := {1};

  accessRightsTypeId := (select art.id from sungero_core_accessrighttyp art where art.sid = accessRightTypeSid);
  
  if (accessRightsTypeId is not null) then 
    -- Выдача экземплярных прав в sungero_system_accessctrlent на каждый вид документа.
    for documentKindId in select id from sungero_docflow_documentkind dk
      where not exists(select 1 from sungero_system_accessctrlent ace where ace.granted = true and 
                    ace.operationset = operations and
                    ace.recipient = recipientid and
                    ace.secureobject = (select so.id from sungero_system_secureobject so where so.entityid = dk.id and so.entitytypeguid = dk.discriminator))
    loop
      secureObjectId := (select so.id from sungero_system_secureobject so where so.entityid = documentKindId and so.entitytypeguid = documentKindTypeGuid);
      if (secureObjectId is not null)
      then
        insert into sungero_system_accessctrlent(id, granted, operationset, recipient, secureobject)
        values (accessctrlentNewId, true, operations, recipientId, secureObjectId);
        accessctrlentNewId := accessctrlentNewId + 1;
      end if;
    end loop;
    
    -- Выдача экземплярных прав в sungero_core_accessrightent на каждый вид документа.
    for documentKindId in select id from sungero_docflow_documentkind dk
      where not exists(select 1 from sungero_core_accessrightent aren where 
                        aren.accessrights = (select ar.id from sungero_core_accessrights ar where  ar.entityid = dk.id and ar.entitytypeguid = dk.discriminator) and 
                   			aren.recipient = recipientid and
                   			aren.accessrightstype = accessRightsTypeId)
    loop
      accessRightsId = (select ar.id from sungero_core_accessrights ar where ar.entityid = documentKindId and ar.entitytypeguid = documentKindTypeGuid);
      if (accessRightsId is not null)
      then
        insert into sungero_core_accessrightent (id, accessrights, recipient, accessrightstype)
        values (accessrightentNewId, accessRightsId, recipientId, accessRightsTypeId);
        accessrightentNewId := accessrightentNewId + 1;
      end if;
    end loop;
  end if;
end $$;]]></postgres>
  </query>
  <query key="SungeroWFAssignmentIndex1Query">
    <mssql><![CDATA[CREATE NONCLUSTERED INDEX {1} ON {0}
(
  [Discriminator],
  [Performer],
  [Status],
  [Deadline],
  [Completed],
  [Created],
  [IsRead]
)
INCLUDE (
  [Subject])]]></mssql>
    <postgres><![CDATA[CREATE INDEX IF NOT EXISTS {1} ON {0} (Discriminator, Performer, Status, Deadline, Completed, Created, IsRead, Subject)]]></postgres>
  </query>
  <query key="ReservIdsQuery">
    <mssql><![CDATA[Declare @id int
exec Sungero_System_GetNewId '{0}', @id output, {1}
select @id]]></mssql>
    <postgres><![CDATA[select sungero_system_GetNewId('{0}', {1});]]></postgres>
  </query>
  <query key="InsertDocflowParamsValue">
    <mssql><![CDATA[if not exists(select 1 from [dbo].[Sungero_Docflow_Params] where [Key] = '{0}')
  insert [Sungero_Docflow_Params] ([Key],Value) values ('{0}', '{1}')]]></mssql>
    <postgres><![CDATA[do $$
begin
  if not exists(select 1 from Sungero_Docflow_Params where Key = '{0}')
  then
    insert into Sungero_Docflow_Params (Key, Value) values ('{0}', '{1}');
  end if;
end$$;]]></postgres>
  </query>
  <query key="ParametersTableExist">
    <mssql><![CDATA[SELECT
cast(case
when exists(select 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'Sungero_Docflow_Params') then 1
else 0
end as bit)]]></mssql>
    <postgres><![CDATA[SELECT EXISTS (
   SELECT FROM pg_tables
   WHERE  schemaname = 'public'
   AND    tablename  = 'sungero_docflow_params'
   );]]></postgres>
  </query>
</queries>