MZ@ !L!This program cannot be run in DOS mode. $%|a/a/a/F/`/FJXj~“ړ&҆&tԇ,~̈d6ڏ\f`Z‰pĊ0؅p‹ p „jXND8,"؃΃ăphBx֥V2 hL>(x:N9  :*(&%$# @\n & ots,tС6Vv¢Rt 4p@fJҝҜȠj.tV:ΛvZ.>4'E\'E'E&E &E@&E`&EМE=zK98x8l` vI6Cc-|T]+H`H82T$F H H  P!(p0H2$D P!pH 2G  !pH(2G   !!p H(2G )$ !p H2E !pH 2G  !pH(2G m.!!p H02G 6H!! p(H 82E W!!!! !(p0H 2E !pH 2E !pH 2E !pH 2G !pH2E !pH2!D P!pH2E !pH 2G !p%\[L[ \* f $ .D [\[!\[@6[/ZF!L\[@6[/ZF!L\[@6[+ /      < n $$@@@@@@@ @ @@@@ @ @` @ @@@t@r@p@f@` [. /Z/F[ L6[\\\ \ \ \0 [\ L0\[!\[@6[!R\[@6[ @6L[p[@6[[@6[[@6[ [@6[\[L\[8@LE[2L \ E E E E E E Ev EBl2b@jB` EP E` E@ EB EP# E GOUSE ImpersonateUserNameImpersonatePasswordImpersonateDomainImpersonatePathDllFullPathSOFTWARE\Microsoft\ASP.NET\2.0.50727.0ExtendedProtectionScenarioExtendedProtectionLevelSetExtendedProtectionSettingsRemoveSSLCertificateBindingsCreateSSLCertificateBindingPortListSSLCertificateBindingsIsDhcpEnabledIPVersionIPAddressListIPAddressesHostNameCertNameCertificateHashListSSLCertificatesRemoveURLReserveURLVirtualDirectorySetVirtualDirectoryAccountSIDUrlStringApplicationListReservedURLsURLsApplicationNameGetReportServerUrlsVersionTokensListInstalledSharePointVersionsDisplayNameGetDatabaseVersionDisplayNameAdminSiteURLGetAdminSiteUrlInstallationIDsInstanceNamesMachineNamesListReportServersInDatabaseCredentialsTypeServerSetDatabaseConnectionServerVersionGenerateDatabaseUpgradeScriptIsWindowsUserIsRemoteGenerateDatabaseRightsScriptEnableReportManagerEnableWebServiceEnableWindowsServiceSetServiceStateLogonTimeoutSetDatabaseLogonTimeoutQueryTimeoutSetDatabaseQueryTimeoutReencryptSecureInformationDeleteEncryptedInformationDeleteEncryptionKeyLevelSetSecureConnectionLevelScriptIsSharePointModeGenerateDatabaseCreationScriptRestoreEncryptionKeyKeyFileBackupEncryptionKeyUseBuiltInAccountAccountSetWindowsServiceIdentityRemoveUnattendedExecutionAccountPasswordUserNameSetUnattendedExecutionAccountSendUsingSMTPServerSetEmailConfigurationClientTypeextendedErrorInitializeReportServerErrorsErrorLcidLengthExtendedErrorsHRESULTEditionNameEditionIDInstanceIDVirtualDirectoryReportManagerVirtualDirectoryReportServerVersionMachineAccountIdentityIsSharePointIntegratedIsReportManagerEnabledIsWebServiceEnabledIsWindowsServiceEnabledWindowsServiceIdentityConfiguredWindowsServiceIdentityActualConnectionPoolSizeSecureConnectionLevelInstallationIDDatabaseQueryTimeoutDatabaseLogonTimeoutDatabaseServerNameDatabaseNameDatabaseLogonPasswordDatabaseLogonAccountDatabaseLogonTypeUnattendedExecutionAccountServiceNameIsInitializedSendUsingSmtpServerSenderEmailAddressSMTPServerPathNameInstanceNamebad allocation@@@@@@@@@@@ @  @  @@5D@:D@;D@P 궊O.Q 궊O.prj`DNZ[Be 59N\IPKwвXLrNS0123456789ABCDEF ? @ @0@ P EП EEReport Server (WMI10)"$+,+ ThrowHr() | Error code hr = 0x%x"`+h+ "++ "+, \"P,X,(", , SOFTWARE\Microsoft\Microsoft SQL Server\100SharedCode"d-l-(. #%"--P" . H.pReportManagerReportServerWebServiceProxyDirectAnyRequireAllowOff"..(NT SERVICE\",/D/("// "11%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X"11 "<2l2X%ws%d\%wsReportingServicesWMIResources.rll"3,3(%"x33("<4L4 "44 "44  EE"<5D5  Eг E"55  Eг E"66 vector too long"T6\6 "66 "67 "p7x7 "\8d8 "888 "999 ":x::0";;; "$=< L=X"8>= X>0"t?? "x@@(%02d"@Ah"ABP!!!I!!W!!E!/-:!ReportingServicesWMI!"BCH.log_ReportingServicesWMI_Failed to init logging!"CC8"D$D "tD D SOFTWARE\Microsoft\Microsoft SQL Server\Reporting ServicesRSWMILoggingUSE %ws if exists (select 1 from [dbo].[sysobjects] where id = object_id(N'[dbo].[schedule]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN declare id_cursor cursor for select scheduleId from schedule s join msdb.dbo.sysjobs j on (convert(sysname, s.scheduleid) = j.name) open id_cursor declare @next_id uniqueidentifier, @account nvarchar(260) select @account = %ws fetch NEXT from id_cursor INTO @next_id while (@@fetch_status <> -1) BEGIN if (@@fetch_status <> -2) BEGIN exec msdb.dbo.sp_update_job @job_name = @next_id, @owner_login_name=@account END fetch NEXT FROM id_cursor INTO @next_id END close id_cursor deallocate id_cursor END GO DECLARE @name_in_db nvarchar(260) select @name_in_db = sysusers.name from sysusers inner join master.dbo.syslogins logins on logins.sid = sysusers.sid where logins.name = @AccountName and logins.isntname = 1 if @name_in_db IS NULL BEGIN EXEC sp_grantdbaccess @AccountName, @name_in_db OUTPUT END IF @name_in_db IS NOT NULL AND @name_in_db != 'dbo' AND @name_in_db != 'sys' BEGIN EXEC sp_addrolemember 'RSExecRole', @name_in_db ENDif not exists (select sysusers.name from sysusers inner join master.dbo.syslogins logins on logins.sid = sysusers.sid where logins.name = @AccountName and logins.isntname = 1) BEGIN EXEC sp_grantdbaccess @AccountName BEGIN EXEC sp_grantlogin @AccountName ENDif not exists (select name from syslogins where name = @AccountName and hasaccess = 1 and isntname = 1) SET @AccountName = DECLARE @AccountName nvarchar(260) and issqluser = 1) BEGIN EXEC sp_grantdbaccess if not exists (select name from sysusers where name = and sysadmin =1) BEGIN and hasaccess = 1 and isntgroup = 0 and isntuser = 0) BEGIN RAISERROR('SQL Logon must exist!', 16, 1) ENDif not exists (select name from syslogins where name = EXEC sp_addrolemember 'RSExecRole', END and sysadmin = 1) BEGIN EXEC sp_addrolemember 'RSExecRole', if not exists (select name from master.dbo.syslogins where name = if not exists (select * from sysusers where issqlrole = 1 and name = 'RSExecRole') BEGIN EXEC sp_addrole 'RSExecRole' END SET RECOVERY SIMPLEALTER DATABASE COLLATE Latin1_General_CI_AS_KS_WS) CREATE DATABASE IF NOT EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = ]җc`uSV`uSw`uSEr;%kI0Er;n ui(O,y)OrĤ3OКy|4On0[OPܰ8{|4OKeOknO`uS`Q&kIKnkIg2kI0RkIfh1kI3{]1kI1kI-1kImKkI}9J,n [4J,nݜO,ޘ"O쨛Oը;uؤOըF9(O_R)OLݛ,OZݛ,Ȏݛ,OR^ݛ,OʇǸݛ,O@OPOF+#OըԮ nOPx !nOP)[ѯz62Pѯz6emlѯz6.fѯz6~5Oѣ~5O. 74OWH34OѲQ2!_KGRJJpJ:u4yf0V*h"< L mL?XIITzu F8J5t`jS/"RF9"=`Ps[9(EqݽTࢇϋ="9cbWhJ5v˿Xh"8Dh"$h"6h" 9+@R74t0j@ًs@]GM "EE  Eг E"EE ncalrpcMSSQLSERVER"II \/:*?"<>|;@&=+,{}^[]`.%"JJ(.\"TJ\J "JJ " PKK(Instance %ws: Get the service group name: groupName=%ws$Software\Microsoft\Microsoft SQL Server\100\MachinesOriginalMachineName"LL \SetupSOFTWARE\Microsoft\Microsoft SQL Server\" M $M " NdN ConfiguredDefaultRSConfiguration"tOO(GetSystemWow64DirectoryWkernel32.dllNT Authority\NetworkServiceNT Authority\LocalServiceNT AUTHORITY\SYSTEMLocalSystem"OO GetVirtualDirectory: Leaving method, hr = 0x%xGetVirtualDirectory: Couldn't find the virtual directoryGetVirtualDirectory: Couldn't load config file, hr = 0x%xGetVirtualDirectory: Entering method"\P P SetVirtualDirectory: Couldn't find the applicationm, Application = %s, hr = 0x%xSetVirtualDirectory: Couldn't save the registry value, hr = 0x%xRSVirtualRootServerRSVirtualRootApplicationSetVirtualDirectory: Couldn't save the config file, hr = 0x%xSetVirtualDirectory: Couldn't set the url reservation node, hr = 0x%x"Q$Q ::V60:0:0:0:0:0:0:0V40.0.0.0"tQQ("QQ "4RLR(IsURLReserved: Couldn't get the registered Urls. hr = 0x%x"RR ]://"8SHS(RS__23#_24_5f"SS0"`T T "4UDU invalid vector subscript"UU " VV "\VlV "VV "`WhW "WW ReportingServices$"XX("YY@"ZZ("p[[SeServiceLogonRightSYSTEM"H\`\H <%@ Application Inherits="Microsoft.ReportingServices.WebServer.StoppedApplication" %><%@ Application Inherits="Microsoft.ReportingServices.WebServer.Global" %>\global.asax"L]]xReserverURL(): DeleteUrl returned hr = 0x%xReserveURL() with hr = 0x%xReserveURL(): Couldn't save config hr = 0x%xReserveURL(): Couldn't add to the Url reservation vector hr = 0x%xReserveURL(): Internal ReserveUrl returned hr = 0x%xReserveURL: The url %s has already been reserved.ReserveURL(): ValidateUrlString returned hr = 0x%xReserveURL(): AppendVirtualDirectory returned hr = 0x%xReserveURL(): ValidateApplicationName returned hr = 0x%x"8^@^HThe following error occurred retrieving the error string for a previous error (hr = 0x%x). The previous error was (hr = 0x%x).%s: Couldn't load the resource dll, hr = 0x%x"|^^ %s: Couldn't set error string return value.%s: Couldn't set result return value"__ "\``(Instance %ws: Setting the folder permissions: The new account name is already a member of the groupInstance %ws: Setting the folder permissions: The old account name was not a member of the group"Da La(Checking whether the RPC server came back ended with hr = 0x%xAttempt to connect to RPC server failed with hr = 0x%xAttempt to connect to RPC server succeeded when it should fail.Checking whether the RPC server came back for instance %ws"@b Pb@"bb0"dc(d "e eIsCertificateInstalled(): Couldn't get the list of certificates. hr = 0x%x"`ffVerifyBindingIsRegistered: Couldn't get the list of registered SSL certificates. hr = 0x%x"gTg g "hTh h "iii0"jkListSSLBindings: Couldn't allocate memory for the application nameListSSLBindings: Couldn't allocate memory for the certificate hashListSSLBindings: Couldn't allocate memory for the ip addressListSSLBindings: Couldn't allocate memory for the success error stringListSSLBindings: Couldn't allocate memory for the failed error stringListSSLBindings"k l "mm0=;| E"nn "o`oo "Pp(p p0"qq E"Lr$rdr "s s "ss s "ttt( E:E EFE E E ERE^EjEvEEEEEE Ep E E E E` E ECMSRSCfg_ConfigurationSetting"uu "&gt;<&lt;&&amp;'&apos;"&quot;"T;*; <Name></Name><GroupUserName></GroupUserName>EveryoneS-1-1-0Builtin\AdministratorsS-1-5-32-544May view report definitions.Report BuilderAllows users to view models items in a particular model.Model Item BrowserView system properties and shared schedules.System UserView and modify system role assignments, system role definitions, system properties, and shared schedules.System AdministratorPublish reports and linked reports; manage folders, reports and resources in a users My Reports folder.My ReportsManage content in the Report Server. This includes folders, reports and resources.Content ManagerPublish reports and linked reports to the Report Server.PublisherView folders, reports and subscribe to reports.Browser">=H>8ReportServerTempDB["$?T?@]]N'"? @8TempDB"@@0"4ATA0" AHBHmastermsdb"C%DxDBVERSIONTOKENTCGETDBVERSIONSP"#`FXxG)SUSER_SNAME(0x"J&KINSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'SharePointIntegrated', 'False' )' )CATALOGTEMP_DBINSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'SharePointIntegrated', '" M l6M%+9Yu>m6M%+n6M%+o6M%+p6M%+q6M%+lP]0r6M%+s6M%+t6M%+u6M%+v6M%+w6M%+~XFPOrx6M%+y6M%+z6M%+}P6^AL ey Or{6M%+&@P]{B.Og!0RP]0|6M%+}6M%+xm!}+~6M%+`6eVDEST|q*+ /[0sx6M%+`= ߏTe++Hy EE }Te++Fs.O Q!3)6{O>`3)6{O>`>/'ozw3)6{O>`3)6{O>`3)6{O>`3)6{O>`3)6{O>`3)6{O>`3)6{O>`3)6{O>`3)6{O>`3)6{O>`3)6{O>`3)6{O>`3)6{O>`3)6{O>`3)6{O>`3)6{O>`&>/'ozw(>/'ozw)>/'ozwȄ97EDEj%>/'ozw3)6{O>`3)6{O>`n)nGǽ*"@p uD@1/E*G~ @Fӊ1_MmyEND+,D\ᳯ`M6]̞G܍EՅGD)&wG7NhCxE2HDf/%ɪ<lsO(E1t_[>CނuNznyZN?2 [J U ).MFK&NAU2$-0 F9:s-Xc<bH/f_R5*MUv`ryuKzo{+L~MeNnrJF' >\Aw^rb5NZOf3y0KL R/'ozwb 1u`=9ICOyi迖.MlW(1." Kw R`!Q!6Q!iو_@2Qjو_@2Qs.O Q!9Q!iو_@2Qs.O Q!5Q!iو_@2Q jو_@2QBkVHAQ} @(iو_@2Q jو_@2QWJJB A$16Hq6)n|=LlX jو_@2Q "*Nn zR ==lNJA4jiو_@2Qjو_@2Q>¤pkfD'Uw#x@=J&M;miو_@2Qjو_@2QAMmRwJA/Jx>MT&7iو_@2Qjو_@2Qiو_@2Qiو_@2Qjو_@2QRSDSƧFa*=ճReportingServicesWMIProvider.pdb xxy y @x pyHyyy @pyDL$ LD$HT$HL$VWHhHD$PHH$H$HD$8HD$PHD$0$D$(H$HD$ L$L$H[H R菗HD$HD$HHh_^HT$HL$H8HHBLL$HLD$@HH @HD$ D$ H8LD$HT$HL$HHHȠHlHL$`HL$ LL$XLD$PHH HD$0D$0HHLL$ LD$HT$HL$HHHcHHL$hHL$(HL$`HL$ LL$XLD$PHH 3pHD$0D$0HHLL$ LD$HT$HL$HHHHHL$hHL$(HL$`HL$ LL$XLD$PHH çHD$0D$0HHHT$HL$H8HHLL$HLD$@HH q讕HD$ D$ H8LD$HT$HL$HHH8H2HL$`HL$ LL$XLD$PHH OHD$0D$0HHLL$ LD$HT$HL$HHHӞHbHL$hHL$(HL$`HL$ LL$XLD$PHH HD$0D$0HHLL$ DD$HT$HL$HXD$pH ^HH$HT$0HT$xHT$(D$ LL$hLD$`HH &cHD$@D$@HXLL$ LD$HT$HL$HXHHH$HL$8H$HL$0HL$xHL$(HL$pHL$ LL$hLD$`HH ֓HD$@D$@HXHT$HL$H8HmHLL$HLD$@HH Q莓HD$ D$ H8HT$HL$H8HH@LL$HLD$@HH >HD$ D$ H8HT$HL$H8H͜HjLL$HLD$@HH HD$ D$ H8LD$HT$HL$HHHxHHL$`HL$ LL$XLD$PHH R菒HD$0D$0HHHT$HL$H8HHLL$HLD$@HH >HD$ D$ H8HT$HL$H8H͛HLL$HLD$@HH HD$ D$ H8HT$HL$H8H}HLL$HLD$@HH a螑HD$ D$ H8LD$HT$HL$HHH(HBHL$`HL$ LL$XLD$PHH ?HD$0D$0HHH|$LH3HH|$I̅ HHHE3E3H%̉HH(L$0HHL$0H(^3H(H3H9H H%.H H%3HLtfffff9t HHuHuWMtxL+MIE3HAtI;vWMtEx>HHEtffffffD9 tHHuAWMAHtH+AIMH\$Hl$Ht$WH ILL$PHZIHLH3xHH;wuf|]H f|]zHtHH\$0Hl$8Ht$@H _̉DAHH\$WH HL_H\$0LHH _H\$WH HHJLcLCH\$0GHH _H% H\$Hl$Ht$H|$ ATHPDH3AAHHt?L$3DHD$@LT$8D$0DAHf|$(HD$ HʋH\$`Hl$hHt$pH|$xHPA\̅ynWHpHD$ H$DHڴ3kHL$(8H=QH|$(\$@HL$HH|$HD$@D$`HHL$H/@UH HHM(H ]̅WHpHD$ H$فtVDH.37kHL$(H=H|$(\$@HL$HqH|$HD$@D$`HHL$HH$Hp_@UH HHM(H ]̅WHpHD$ H$فtVDH~3jHL$(ܐH=H|$(\$@HL$HH|$HD$@D$`H=HL$HH$Hp_@UH HHM(^H ]H\$WH`HHT$PLD$Xu3ۋ3M@ǃHt$pj}CtbH73HHADH3HHteA%uUH3͈HHt>AH\$@HD$PfAHD$8\$0fHf|$(H\$ HHt$pH\$xH`_@WHPHD$ H\$`Hl$hHt$pIHHHPHGE3H]H,HL I;u2dLE3HT$(HHHHL$(LGL M HT$(HHHHL$(H\$`Hl$hHt$pHP_@UH HHM(}H ]@UH HHM(]H ]@SUVWHHHD$(IIHHL$0D$ JD$ E3HH+HHH98tFfffffffffLLFHHLELHHHH H9uHHHH_^][@UH HE te HM0H ]HXHH3H$@HL$ 3A{HL$ D$ 2uHL$ D$ D$$uiD$(uH$@H3HXÃuH$@H3HXÅu?H$@H3HXÃrH$@H3HX3H$@H3}HX@WHHD$ H$H}H3H$H+HL$xHHHL$(-HHL$PLD$xHT$(HL$P:HL$PȉHL$(yHL$xHT$xHHL$x3H$H3H$Hİ_@UH HHMxMH ]@UH HHM(-H ]@UH HHMP H ]3A AAH̋ADBA;}~ËADBA;|DA;|I R ;|3;@SUVHH!|H3HD$Ht$PHl$X3HAAIM؉ELu !H|$0H<$fE3Izf,tGftBf.t^HL$(H=H|$(\$@HL$HxH|$HD$@D$`HHL$Hf>AID$ A+DIcHNIIHĈA]A\_^][@UH HHMHH ]@UH HHM(H ]@UH HHM(H ]@UH HHM(~H ]@UH HE te HMhH ]H\$WH HH3_3H$PH3*H`_^[H\$Ht$WH0IAHt#tuA@8DL$@AuA uA H{ rHSHSE3HHt$ YH\$HHt$PH0_HAHuHIH+HgfffffffHHHH?HHQHgfffffffH+QHHHH?HHQHu3HAH+HHAH+AHHHD$ H HL$(]HL$Pb_HzHD$PHT$(HL$hu]HHD$PHIHL$PW@UH HHM(E]H ]@UH HHMP^H ]HL$WH0HD$ H\$HHH^HԆHHSHO\HH\$HH0_@UH HHM@m^H ]HHHD$ HنHL$(~\HL$P2^HJHD$PHT$(HL$hE\HeHD$PHHL$P'@UH HHM(\H ]@UH HHMP]H ]HH\$WH HHHHtH;t5]HOHgfffffffH+KH\$0HHHH?HH _H\$WH HHHHtH;t\HGH+CH\$0HH _HL$WH0HD$ H\$HHH\HHHSHOZHHHH\$HH0_@UH HHM@}\H ]HHHHHfffffffH?H\$WH H9HHu[HH<HCH HH;HwH;Hss[H{HH\$0H _H\$WH H9HHu<[HCHH HH;HwH;Hs{HH\$0H _HHHuH HHH3HHH(s3HT$PHL$PHL$ ZLHHL$ L\$ HHHu HHHv3HHHs3HT$PHL$PHL$ ?H$H3>HİA_A^A]A\_^[@UH HHMx>H ]HT$SUH8HLEHH]@HHMPnH33H8][HT$UH0HHE@L HMPHANHE8HPJ33H0]HVWATAUAVHPHD$0HXMLHA1pHAHu3 HYH+HMoLaIH+HH?HH+I;slLI;2HHH+H;s3HI;IBHHtL3HHHs=HDŽ$H$HL$8?LNgL\$8HHL$8HHH$3D$(D$DD$ LLIVHOL3D$($L$ LL$IIyO3D$($D$ LHWINcHOHGH+HLHtHHGJHGHwINIH+HI;JL 3D$($D$ LIHOHI+FHL+3D$($D$ LL$IH_HOH+IFH;t{0HH;un3III+݈D$($D$ LMIHfHGINH;tL+ffffHAH;uID H;tfffff1HH;uH$HPA^A]A\_^HT$UH0HH{33~H0]HT$UH0H33ZH0]H\$Hl$Ht$WATAUH0HHHIH{IgfffffffLL+IMIIHHH?Hu3=H;vgHHEtffffffD9 tHHuAWMAHtH+AIMH\$Hl$Ht$WH ILL$PHZIHLH32xHH;wuf|]H f|]zHtHH\$0Hl$8Ht$@H _H\$WH0HH3H3LL$Hf\$HH\$ HDD H $.u)Ë莟H $LL$HHs\AH\$ J.u؋XH\$@H0_@SH HH Ht -HH [HH@SH HH Ht -HH [Ht$WH 3HHt HvWxHH\$0HZH0x"HH;wH;uf<^H\$0Ht$8H _f<^zH\$0Ht$8H _@WH`HD$(H$HB"H3HD$XHHL$0D$ -D$ DL[HL$8qʝHT$8HT.HHL$XH3LH$H`_@UH HE te HM0-H ]@SUVWHxHD$hIIHHHL$`D$ ,D$ HL$(,T$(HL$8HH-HL$8-HHX-T$*HL$8HH<-HL$8P-HH$-T$.HL$8uHH-HL$8-HH,T$0HL$8AHH,HL$8,HH,T$2HL$8 HH,HL$8,HH,T$4HL$8HHl,HL$8,HHx_^][@UH HE te HM`O,H ]@UH HHM8-,H ]@UH HHM8 ,H ]@UH HHM8+H ]@UH HHM8+H ]@UH HHM8+H ]@UH HHM8+H ]@W;H+HD$PH$H$H$HH3H$HHL$XD$$(~)H=XH<*D$$HL$(8HH*HL$(*HWH*HL$(HH*HL$(*HWHR*HWHL$()HWH$)HWHL$`)LL$(L$HT$`H$OHH*H$#*HL$`*H$*HL$()D$ HT$ H$ %t!HVH)H$Ht)uHVH`)HGuHVHF)H-uH}VH,)HH`VH)HH$H3\L$I[Ik Is(I_@UH HE$te$HMX)H ]@UH HHM((H ]@UH HHM((H ]@UH HHM((H ]@UH HH(H ]@UH HHM`m(H ]@UH HHJ(H ]LWHPHD$HI[HH3H$@HIK1'H{uTH$'H$腝y H U4&H$H$'H$'HH$'H$H$&HTH$'HTHL$Pt&HTHL$xa&HTH$K&LL$PLD$xH$H$ HH$&H$&H$&HL$x&HL$P&H,TH$V&H$H$HC$3H\$0D$(D$ E3ɺDC$Hu8Py$H$<&H$-&HHfD$@\$DH\$ LL$DAHT$@H=$u,؅y!H$%H$%H$%H$%H$@H3螳H$hHP_@UH HHZ%H ]@UH HH:%H ]@UH HH%H ]@UH HHMP$H ]@UH HHMx$H ]@UH HH$H ]@UH HH$H ]HHT$LD$LL$ SW4H+HD$8HH3H$pt 0HL$@L$3ۋL$HL$p%xHH=wH=uf$n f$nz5HT$pHL$@m#=uHL$HH|$`HCL$H"HT$HH|$`HCT$H\$03HHfHDD H\$ LL$0H !uGË謒H\$ LL$0AHOH h!u؋vHL$@"H$pH3HĈ_[@UH HHM@"H ]H(yDHѹH(HhHD$ H H3HD$PHL$(!HL$(HL$(B"HL$PH3EHh@UH HHM("H ]@SHHD$ HH3H$HL$P!HL$P HPHL$x H+PHL$( LD$PHT$xHL$(HL$(!HL$x!tdx`HL$XH|$pHCL$X"ttt 9u.HL$xg HL$xHL$x! |HL$P!H$H3Hİ[@UH HHMP H ]@UH HHMx H ]@UH HHM( H ]@UH HHMxm H ]HL$WH0HD$ H\$HHH"H4JHHOH4 HhHHH\$HH0_@UH HHM@!H ]@SH HIHHHAHH [H%!H\$WH HIHHHAHC!tHjHH\$0H _@WH HDBHLdu H _H%<Fu#H\$0'H<H\$0H _3H _@WH HHHt83u#H\$0HH\$0H _H3H _HL$SH0HD$ HHK(HKXHxHjHH0[@UH HHM@ H ]@UH HHM@H(H ]@UH HHM@HXH ]@UH HHM@HH ]@SH HHD$0HHH [3HLtfffff9t HHuHuWMtxL+MIE3HAtI;vWMtEx>HHEtffffffD9 tHHuAWMAHtH+AIMH\$IE3HMLt8HD$(fffHt$AftfHIHIIuMuHAzIHfAtLH\$H\$Hl$Ht$WH ILL$PHZIHLH3xHH;wuf|]H f|]zHtHH\$0Hl$8Ht$@H _HcHdf;tHH;|3H\$WH0HD$PH3LHD$(HdE33H\$ H\$PxuHL$PH^u HIt ؁H|$Pt HL$PKH\$@H0_H\$Ht$ WHHgH3H$H3Ht$PHt$@HD$PHD$(Ht$ LE3Hac3؅t)؁HT$@HL$P؅t؁D$XLD$XHT$p[u;؁D$`D$dD$hD$lHD$`HD$0t$(Ht$ A EAHT$pHL$@؅t~e؁ZHL$@؅t~E؁:HHL$@~؉D$H%=u 1\$H~ ؁\$HH|$PtHL$Pt~1 'H|$@tHL$@bt~  H$H3L$I[ Is(I_@UH@HH-H@]LI[IsWH@IH3I[ I[ICICI[LE3HWa3tR؁GHT$hHL$8t+؁ HL$hft ؁H|$8t HL$8fx 3H$H$H$H$H$H$LL$XAH$3Pt9 |HHD$pHtjH Ht3HHfHHHwBHT$xffL$pffL$rALD$pHHL$Xt­  H:EHL$XHt腭H$H$H3DL$I[Is I_@UH HHʵH ]@UH HHMPH ]@UH HHMHH ]@UH HHMhźH ]@UH HHMhH ]LWHHD$HI[IsHH3H$HIKHk HL$xHL$PmtH HL$P^H HL$PJ3HH$H$HC$Ht$0D$(D$ E3ɺDFHu)iy!HL$PpHL$xLH؉t$@HT$XH|$pHCT$XHt$ LL$@DD$hHeu8 y-Ht H8HL$PHL$xHt$ LL$@AHr H u5谀y*Ht HܱHL$PHL$x(Ht HHL$P~HL$xZ3H$H3XAL$I[Is I_@UH HHMxH ]@UH HHMPH ]@UH HH[H ]@SUVWATAUAVHHD$xH>H3H$EMHL3H$H$H$藟ȰHLL$ WDGsu Q!Wu=HL$ Pߋu!IHL$(H$HơHT$ Ht,3+uHL$  HL$ ߋ!H0؅yDH 3 BHD$ Ht H&HHD$(HD$ HHL$(sHIHL$PbL$LHI؅yDH 3茌HD$(HD$ HHL$(HH$HL$PLHHJ؅yDH 335H$pHL$PïH$H;Et]H$HL$PH$Hu2L$H$LC$H 3跋<y`HD$(HD$ H$HL$(4HH$HL$PLHH؅yDH 3PUMHH$?؅yDHV3$H$؅yDH3H 軌y.t*IHL$P}HH:DH3蹊HtHlH(;H$H$H$H$H3<HA^A]A\_^][@UH HHH ]@UH HHH ]@UH HH{H ]@UH HHM H ]@UH HHM B:H ]@UH HHM H ]@UH HHM H ]@UH HHM ݭH ]@SVWH HD$HHUH3H$ IAHEoAC3HD$@HL$@=y"DLH 3߈Hf1AL$HL$@MHL$@Ht˫u~ ہsH$H3HD$@EDHD$0D$(HD$@HD$ 3ҹftHT$@HoĪH;HL$P~ ہLD$XH|$pLCD$Xt$ D˺H$4H$HOHL$P;HL$@Ht I0H$ H3 :Hİ _^[@UH HHMPH ]@SUVWATH`HD$ HeH3HD$PAEHH3EH YHuLH 3HL$(LL$(DAHLD$0H|$HLCD$0HXHuLHd3譆HL$(HL$PH39H`A\_^][@UH HHM(H ]H\$Ht$WH HA3HH+AHH~0H;rFHOH HGH+GHH;|H\$0Ht$8H _H\$WH H9HHHHAHHBuޫHHHH9Kr˫HCH\$0HH _H\$WH H9HHHHAHHBu~HHHH9KrkHkH\$0HH _H\$WH HHHHtH;t%HSH\$0H9WH _H\$WH H9HHHHAHHBuުHHHH9Kr˪HCH\$0HH _H\$WH HHHHtH;tHSH\$0H9WH _HHHH\$Ht$WH MIHHHt I9PwI;PvHH\$0HwHt$8HH _H\$Ht$WH MIHHHt I9PwI;PvHH\$0HwHt$8HH _@SH H9HucHHPH9SrPHCH [HHHHLuII8HH3HIH=sE3HT$XHL$ LD$X¨LHHL$ L\$ -3HHHHLuJ s7HH3HIHsE3HT$XHL$ LD$X3LlH%HL$ L\$ 2H\$Ht$WH MIHHHt I9PwI;PvHH\$0HwHt$8HH _H\$WH H9HHuHCHH HH;HwH;Hs{H{HH\$0H _H\$WH HHHHtH;t5HGH+CH\$0HH _H?HHHLuJ 5HH3HIHsE3HT$XHL$ LD$XLHHL$ L\$ 1H\$WH H9HHulHCHH HH;HwH;HsKH{HH\$0H _H\$WH HHHHtH;tHGH+CH\$0HH _H\$Ht$WH MIHHHt I9PwI;PvHH\$0HwHt$8HH _H@SH H+IHHH+H~LLHHHH [H@SH H+IHHH+H~LLHHVHH [{(H8HD$ HHT$HHT$XHtIH)H8@UH HHUHHMX@H ]HAHtffffffffIHHHAuHtffffffffAHHAu@SH H+IHHJtLLHHH [@SH H+IHHJtLLHۢHH [@SUVWATAUAVAWHxH8H3HD$`IL$H$L$3HHL$PMDHI@H}HAH$HL$0HL$(DOILIHD$@H|$0A<$|$ 1=dt =itf=>u1LD$@HD$0AHD$(IIΉ|$ u[؁"tu,Ht'(D$PLD$PLAHfD$PA$HL$0HtFHL$0LD$8H|$8-u s HL$0Ht|HL$8HMHL$`H34.HxA_A^A]A\_^][H\$ WHHH3H$HAHHH LD$ HEȺRu)ѝD~ DA@EAHL3MDt IvAWExqMIHDt:LAM+L+IHtA ftfHHuHu HAzEfxLD$ IHHA؋H$H3,H$HĐ_@SUVWHHD$(HTH3H$IIHHH$IH$HH$HH9uHnH$PHHuHEH$'H$HD$0HD$ HHL$0 HH$HL$X E3HH=au$H rLGLGH(y=y9H$H$HO(zHpHD$0HD$ HHL$0yHH$HL$XcAHH=bu$H rLGLGH;x3H$H$HO(לH͜H$H3*H_^][@UH HH H ]@UH HHjH ]@UH HHJH ]@UH HHM -H ]@UH HH H ]@UH HHM H ]@UH HHʛH ]@UVWHpHD$(H$H-H3H$`HHHL$0HuHL$0`WHL$0[D$ H} r H}HH}HLL$ LD$`X_u+.؅~ ؁y"HL$0HT$`HL$0HL$8H|$PHCL$8HT$ 辚؅yHL$0p|$ uYH} rH?AH$`H؅yHL$0q4HH$`轓؅y=1u3HL$0;H$`H39(H$Hp_^]@UH HHM0H ]LSHH~H3H$Hy IkIsI{ McHr LAHYHYLHuE3H Ld$8ArHH$H$H+EfffHHt ftfHHuHu HAzf)ALD$@H$+Lu!!~ @HL gH$AH$AL+IH~HtA ftfHHuHu Hzf)IH$Affff9tHHuWIHu WIIH+хxZL+HTAt7LL$@IL+HtAftfHHIuMu Hzf(xA܅@L$AlHD$0L$HHD$(E33ALd$0Ld$ ԚtR؁GHL$0HT$8t+؁ HL$8{t ؁H9l$0t HL$0|A;HrL9d$8HL$84tALd$8u؁guHD$0L$HD$(HtE33Ld$ ALd$0ətR؁GHL$0HT$8t+؁ HL$8pt ؁L9d$0HL$0mHD$0L$HD$(HE33Ld$ ALd$0tR؁GHL$0HT$8t+؁ HL$8t ؁L9d$0t HL$0=AH9|$8tHL$8AEHD$0L$HHD$(E33ALd$0Ld$ MtR؁GHL$0HT$8t+؁ HL$8t ؁L9d$0t HL$0fffA;HDùoL9d$8HL$8tALd$8u؁gHD$0L$HD$(HE33Ld$ ALd$0:tR؁GHL$0HT$8 t+؁ HL$8t ؁L9d$0HL$0ޖ.HD$0L$HD$(H-E33Ld$ ALd$0tR؁GHL$0HT$8St+؁ HL$8)t ؁L9d$0t HL$0*:L$H|$8L$H$H$H$t HL$8וt ؁HcDùmH$H3d H[HVWATHHD$@HXHh HH3H$HHHL$p6E3Ld$(HL$0HHL$pD$ H~ r H~HH~HLL$ L$Uu+؅~ ؁y%HL$py H$HL$pgHL$xH$HCL$xHT$ A؅yHL$p0|$ H~ rH?AH$H؅xuHT$(H$膋؅y=1ADHޏIHT$(HL$0 HT$HHL$0. HHHL$HHHHL$(Ht{HL$pgH$H3eL$I[0Ik8IA\_^@UH HHMpH ]@UH HHMHH ]@UVWATAUHpHD$0H$HiH3H$`MHHHL$8E3Ll$(H{ rHKHK*HIHL$8D$ H~ r H~HH~HLL$ LD$`Su+V؅~ ؁y"HL$8HT$`HL$8 HL$@H|$XHCL$@HT$ ؅yHL$8ՎH~ rH?AH$`H؅x=LD$(HH$`s؅y=1ADIHT$(IsHL$(HtcHt HUHL$8AH$`H3?H$HpA]A\_^]@UH HHM8H ]H\$Ht$WH HqHHH;qHv\HsHt$8H;HH\$0H _H\$Ht$WH HqHHH9qHv HsHt$8H;HH\$0H _H\$Ht$WH HqHHH;qHvHsHt$8H;HH\$0H _H\$Ht$WH HqHHH9qHvlHsHt$8H;HH\$0H _H\$WH@E3HHLALALAHu 2H\$XH@_HH;v苶HHu,IHHHHGHGH_H\$XH@_3HHH=sHT$PHL$ LD$PLѵHHL$ L\$ H\$WH@E3HHLALALAHu 2H\$XH@_HH;v{HHu)IH"HGHGHH\$XHGH@_3HHHsHT$PHL$ LD$P͌LHHL$ L\$ 8H\$Ht$WH MIHHHt I9PwI;PvHH\$0HwHt$8HH _H\$Ht$WH0HHHT$ HHAIHBH|$ Hu HD$(HH;_wH;_sH\$(H\$@HL$ HHHAHFHHt$HH0_H\$WH@E3HHLALALAHu 2H\$XH@_H?H;v苵HHu)IHrHGHGHH\$XHGH@_3HHHsHT$PHL$ LD$PLVHHL$ L\$ H\$Ht$WH0HHHT$ HHAIHBH|$ HuЊHD$(HH;_wH;_sH\$(H\$@HL$ HHHAHFHHt$HH0_H\$Ht$WH MIHHHt I9PwI;Pv2HH\$0HwHt$8HH _H;tffffffffIHH;HAu@SH H+IHHH+H~LLHH&HH [H;tffffffffAHH;ʉAu@SH H+IHHH+H~LLHHHH [H HALD$SVWH0HD$ IHHH\$PH;t*H\$XH\$(Ht HH HH\$`HHH0_^[@UH HHUXHM($H ]HT$SUWH HH]PH}`H;tfffH HH;u33H _][HtffffffffIHHHAuHtffffffffAHHAu@SH H+IHHJtLLH HH [@SH H+IHHJtLLHˆHH [3HAHAHAHH\$Ht$WH HqHHH;qHvHsHt$8H;HH\$0H _H\$Ht$WH HqHHH9qHvHsHt$8H;HH\$0H _H\$Ht$WH0HHIHH_HH+HH;w_H;v;H\$(H|$ (D$ HfD$ H;_wH;_sHL$ H;YrHt$HHH\$@H0_3HAHAHAH@SH HHIHt 3HCHCHCH [H\$Ht$WH HqHHH;qHvLHsHt$8H;HH\$0H _H\$Ht$WH HqHHH9qHvHsHt$8H;HH\$0H _H8HRHI3D$(D$@D$ H8HtffffffffIHHHAuHtffffffffAHHAuH;t+H\$WH HHHHH;uH\$0H _@SH H+IHHJtLLH[HH [@SH H+IHHJtLLHHH [@SH HHIHt 3HCHCHCH [H\$Ht$WH0HHIHH_HH+HH;w菩H;v H\$(H|$ (D$ HfD$ H;_wH;_sHL$ H;YrςHt$HHH\$@H0_HXIMLL$0II@LD$@IAHLIHBHT$8I@HL$H3D$(D$hMˆD$ oHXHtffffffffIHHHAuHtffffffffAHHAuH;t+H\$WH HHHHH;uH\$0H _@SH L+LIIJJ tLMHHH [@SH L+LIIJJ tLMHHH [LVWATAUAVHHDŽ$I[IkHsH3H$LIKAE3Lt$8Lt$@Lt$HMsMsMsMsMsMsDt$PANHD$`Ht HHIHD$PHD$ LL$pL$HT$0HyDHJ3CZE2H\$8H;\$@vAHD$0HD$`H\$h(D$`fD$`H|$`H\$hfffHt$@H9t$8vHt HD$0H;tH;sfffH;r ~HL$xH >HH$HL$xH+H;|HtHJH HL$xHtLt$xL$L$H$HtL$L$L$H\$8HtHLt$8Lt$@Lt$HI|AH$H3 L$I[8Ik@IA^A]A\_^@UH HH:|H ]@UH HHM0>H ]@UH HHH ]@UH HHMpH ]@UH HHM`H ]LUVWATAUAVAWHPHDŽ$I[H$oH3H$HAEHHT$pHH$IKISE3Lt$XLt$`Lt$hLt$8Lt$@Lt$HMMM EAN H$Ht HL\$ L$LD$0HT$PIDyDH3GV\H\$8H;\$@vH|HD$0H$H$($f$H$H$fffffffH\$@H9\$8v{Ht HD$0H;t{H;Hu{H;~r{H$H$HH$8yHHH$yHHIcH$HH$H+HH;@H;vG{H$H$H$H$($f$HH;w H;$szH$H;XrzD;+tHl$pAH;~rzHIcHT$`HHL$XH+HH;w轟HH;vzHT$`HL$XHD$PH$H$($f$HH;wH;sRzH$H;Xr>zHH$Hjxt A8Hl$pHl$p腠A:H$E3AHD$`H+D$XHI܅~3H;ryHL$XH 9{HHD$`H+D$XH;|AHD$@H+D$8HI܅~3H;ryHL$8H zHHD$@H+D$8H;|MtIIH$HtHL$L$L$H\$8HtH|Ld$8Ld$@Ld$HHL$XHt^Ld$XLd$`Ld$hHBwH8wAH$HH35H$HPA_A^A]A\_^]@UH HH8vH ]@UH HH@vH ]@UH HHMP H ]@UH HHM0 H ]@UH HH H ]@UH HHOH ]@UH HH*vH ]MILtfffIIHIBuJMILtfffAIHABuJI;t+H\$WH IHHHH;uH\$0H _@WATAUAVAWH@HD$ H\$xH$MLHIHAHu3 HyH+HM[LaIH+HHHH+I;sןLI;HHH+H;s3HI;IBHHtF3HHHs7HD$pHT$pHL$(&vL_L\$(HHL$(HLH$IOLFI+HHL4t LH[uIIHt HHHK HVMGI+HtHL!uHNHFH+HLHtIHFKHFLfMGII+HI;s~K M+ItJLtHVHI+GHIH+Ht HHHJHFHNH+IGH;fffffffHHH;u~III+IH+HHN4"tLLI)tLvMGI+HH~HL+LIsIGILH;tffffffHHH;uH\$xH$H@A_A^A]A\_HT$UH HH33H ]HT$UH H33jH ]@WATAUAVAWH@HD$ H\$xH$MLHAHAHu3 HyH+HMJLaIH+HH?HH+I;sgLI;HHH+H;s3HI;IBHHtF3HHHs7HD$pHT$pHL$(rL/L\$(HHL$(aHLH$IOLFI+HHL4t LH+rIIHt HHK HVMGI+HtHLqHNHFH+HLHtIHFKHFLfMGII+HI;suK M+ItJLqHVHI+GHIH+Ht HHJHFHNH+IGH;HH;uwIII+IH+HHN4"tLLIqLvMGI+HH~HL+LIpIGILH;t fHH;uH\$xH$H@A_A^A]A\_HT$UH HHk33nH ]HT$UH H33JH ]H\$WH HYHHt-Ht$0HqH;tHTHH;uHOHt$0H\$83HGHGHGH _H\$Hl$Ht$WATAUH0HHIMHoHMH+HHu3+H;voI$HtH;toI\$H+HI$HL$ HT$ HID$MHAHAHoH;ovoH|$ Hl$((D$ H\fD$ H;_wH;_sxoHl$XH\$(H\$PHL$ HHHAHFHHt$`H0A]A\_H\$Hl$Ht$WATAUH0HHIMHoHMH+HHu3+H;vnI$HtH;tnI\$H+HI$HL$ HT$ HID$MHAHAHoH;ovnH|$ Hl$((D$ H\fD$ H;_wH;_shnHl$XH\$(H\$PHL$ HHHAHFHHt$`H0A]A\_HL$VWATHPHD$0H$HHHZH+ZHALALALAHH;vTHHuID3HHH=s3LD$xHT$xHL$8mLL\$8HuHL$8HuHGHGHHH_H^H9^vNmLfL;fv>m3D$(D$pD$ LLGHI5HGHH$HPA\_^HT$UH0HHMp*33QH0]H\$WH HYHHt-Ht$0HqH;tHdHH;uHOHt$0H\$83HGHGHGH _H\$Ht$H|$ ATH0LA3LMHuH HII+HHsHI+HH;sHHHFHCL;Hl$@vkHKHkH\$ HHt$(H+HtH;vkHH+H(D$ HT$ MAHfD$ HsHl$@H;svkHH;CwH;CskkH\$HHt$PH|$XH0A\H\$Ht$H|$ ATH0LA3LMHuH HII+HHsHI+HH;sHFHCL;Hl$@vjHKHkH\$ HHt$(H+HtH;vjHH+H(D$ HT$ MAHfD$ HsHl$@H;svsjHH;CwH;Cs]jH\$HHt$PH|$XH0A\@SUVWATAUAVAWHHDŽ$H\H3H$IIT$0LH$L$PL$XH$`HD$8L$h3HAHD$(H;AviI_I9_viHD$(H;I;Gr iHD$(HH$P~H$XH$pHC$X]jLHD$ H_HVHu3 HNH+HH^HH+HH;sLHCHFH;vhHt$PH\$XHNH~HH+Hu3H;vhH+H(D$Pf$LL$ AH$HH~H;~vhHH;FwH;FsyhH$H$HC$aiLHD$ H@HUHu3 HMH+HH]HH+HH;sLHCHEH;vhHl$`H\$hHMH}HH+Hu3H;vgH+H(D$`f$LL$ AH$HH}H;}vgHH;EwH;Es}gH$H$HC$ehLHD$ H!IT$Hu3 IL$H+HI\$HH+HH;sLHCID$H;vgL$H$IL$I|$HH+Hu3H;vfH+H($f$LL$ AH$II|$I;|$vfHI;D$wI;D$snfD$DD$ IUHu3 IMH+HI]HH+HH;sDHCIEH;vfLl$@H\$HIMI}HH+Hu3H;veH+H(D$@f$LL$ AH$II}I;}veHI;EwI;EseH$xH$ cHPDD\$ IVHu3 INH+HI^HH+HH;sDHCIFH;v)eLt$pH\$xINI~HH+Hu3H;vdH+H(D$pf$LL$ AH$II~I;~vdHI;FwI;FsdH$ HD$ H$H$ bHH$xH$aE3D$HH yuH$ aL$ DNjT$0H 蹴H$(H$@HC$( eHD$ HttHT$ HL$83H$ @b'H 7dHD$ HtqHT$ HL$8XH$PjH\$(I;_rcHH\$(H3X=H$ aH$PH3#=H$PhHG3=H$PEH3H[HH(H;uHsIL;tHEHH(H;uLcH{8H9{0vIHs0H;s8vIH;tkHk8HH+IHHHH?HHL$H;tH+fffH >HGH(H;uHs8IL;tHGH(H;uLc8H{0Ht*Hs8H;tffffHGH(H;uHK0y3Hk0Hk8Hk@H{Ht)HsH;tfffHGGH(H;uHK9HkHkHk H\$XHl$`Ht$hH0A]A\_@UH HHMPHH ]@UH HHMPH(H ]@SVWATAUAVAWH`HD$ H@:H3HD$PMLHHQH+QIgfffffffIHLIIH?L3fffA;HcHNH+NIHHHH?HH;rGH HFHHL$(>EHL$0H|$HHCL$0ML+DB D+uHuEuSHN8H+N0HgfffffffHHHH?HH;rMGH HF0H IEHL$(ErHL$(EIgfffffffIHL$(DHHNx HL$(LEIHL$(nDHN(HQ HL$(%E2HL$PH3!H`A_A^A]A\_^[@UH HHM(DH ]@UH HHM(DH ]@UH HHM(DH ]HT$UH HHlH ]@VWATAUAVHHD$(H$ H7H3H$HH1EHHD$ HH!EHffffHHL$X4CH$%CH$CHHL$XCE3HHL$XBH؃LcE3HT$0HL$XCHH$~CHL$0zCD$p+ÃLcȍCLcHT$0HL$XHCHH$>CHL$0:CHNH$I HN(H$8 H3DHH$BH$BHL$XBH^H9^v`DH~H;~vPDH;toLfIH+IgfffffffIHHHH?HHL,ffI;tHHgBH(H(H~IH;tHPBH(Ln IgfffffffH^8H9^0vCH~0H;~8vCH;t`Lf8IH+IHHHH?HHL,I;tHHAH(H(H~8IH;tHAH(Ln8H$AH$AHL$XA2Ht HC2H$H3tH$ HA^A]A\_^@UH HHMX-AH ]@UH HH AH ]@UH HH@H ]@UH HHM0@H ]@UH HHM0@H ]HT$UH HHM Ht$BHH ]H\$WH HLtHCHH\$0H _HHH3HLtfffff9t HHuHuWMtxL+MIE3HAtI;vWMtEx>HHEtffffffD9 tHHuAWMAHtH+AIMH\$IE3HMLt8HD$(fffHt$AftfHIHIIuMuHAzIHfAtLH\$@SH HDLLHH [@SH HHHD$8H=HH [HiHH%B̸#H\$WH HH3HIBHzEH/BtH\$0H _̸@WH0HD$ H\$HHt$PHHHL$@9BLD$@HH{BLHT$@HA3ɄEHL$@BH\$HHt$PH0_@UH HHM@eBH ]@SH@HD$ H0H3H$0HHL$PH-)u8H$H$hĬ$ L$ MLHH8}H H(u8H$H$Px$ L$ MLHHz@HH(u8H$H$(,$ L$ MLHH`HHI(u8H$H$$ L$ MLHHH~H'u8H$H$X蔫$ L$ MLHHM\HJH'u8H$H$`H$ L$ MLHHPHHe'u8H$H$$ L$ MLHHHH'u8H$H$谪$ L$ MLHHԎxHH&u8H$H$pd$ L$ MLHH(,HH&u8H$H$ $ L$ MLHH̶HfH5&u8H$H$̩$ L$ MLHHRHBH%u5H$H$耩$ L$ MLHHKH!H%H$H$3$ L$ MLHHZLD$lH)I+|$l|H$H$H0H$ ]&H$N&H$@ HL$`+p$ D$(Ld$ LLII+H$ %H$%H$@ ˆHL$`.+ \$h\$hH$ H3迳H0 A_A^A]A\_^[@UH HHM`*H ]@UH HH@ Z%H ]@UH HH@ H(6%H ]@UH HH@ HX%H ]@UH HH@ H$H ]@UH HH@ 談H ]@UH HH$H ]@UH HHMp$H ]@UH HH#H ]@UH HHJ$H ]@UH HH*$H ]@UH HH $H ]@UH HH#H ]@UH HH#H ]@UH HH#H ]@UH HH#H ]@UH HHj#H ]@UH HHJ#H ]@UH HH*#H ]@UH HH #H ]HT$UH`HꋅEhH$HH`]HT$UH`HEhHH`]@UVWATAUHHD$hH$H H3H$MHHHL$pE3Ll$PLl$XLl$@Ll$HLl$`Hy rLALAHL$xEHD$xL+HHtAftfHHuHu HAzfD)A>AH$HL$x趁yHK(!H!lHD$`HD$(HD$HHD$ LL$@LD$XHT$PH$yHK(U!HK!H~ rHvHf>{uHDl$0AHL$@HtyDl$4fffffLl$8LD$8HT$4k#RA$HHL$8!t%HL$8#D\$4AD\$4D;}1HL$@LD$0HT$4HL$H#HL$8#D$0A$HL$P8 HL$X. HL$@$ HL$H HL$` HK(5 H+ H$H3)H$HİA]A\_^]@UH HHMpnH ]@UH HHMpH ]@UH HHMpH ]@UH HHM8^H ]@UH HHMpmH ]H\$WH H9HHHHAHHBu HHHH9Kr HCH\$0HH _@SH EHHtHt H#HH [H(H Ht#H(H\$Ht$WH MIHHHt I9PwI;Pv HH\$0HwHt$8HH _+LWH@HD$(I[Is HH3H$0HHIKIh3H$H yHHH$H$H$H$HC$H$yHHHH$HVH$HH;HL$0mLHH$%=uHH (xHH$ HHHL$XLHxLD$ H8L$ 3҅HʈpH$H$H$HN(Hu3H$0H3sL$@I[ Is(I_@UH HHH ]@UH HH H ]@UH HHH ]@UH HHH ]@UH HHH ]H\$Ht$WH MIHHHt I9PwI;PvHH\$0HwHt$8HH _H~@WHHD$8H$ HH3H$HHL$(LD$(HaHH$H$H$HH$pH$HT$(H$H$H1H$Nt#H$}HL$(cHD$@HD$0H$HHL$@2HH$HL$hD$@LHH$H$ H$H$$HH$dj؅yLH$ H$H$sH$E|HL$(L$H$LC$HHL$H$LC$HH^L$H$LC$H}H4D$HlHH$(H$@HC$(HL$ HzHL$ stH=HL$ UH$H$HC$HL$ 0LD$ HH#D$HHD$HHkL$xH$LC$xHH9D$HH)L$PH$hLC$PHHD$Eu}H$H$HL$H$LC$HHD$HdHH$`EH$`&~ yH$`L$hH$LC$hHHH$HI;H$L$H$H$&H$eyH$cL$H$0LC$HHH$8SH:H$5L$8H$H$7&H$yH$83L$@H$XLC$@HHL$H$LC$HHL$H$LC$HHH$86H$'H$`HL$ dH$H$H$H$uHL$(H$H3ĠH$ H_@UH HHM(H ]@UH HHjH ]@UH HHH(FH ]@UH HHHX&H ]@UH HHHH ]@UH HHtH ]@UH HHH ]@UH HHM0H ]@UH HHH ]@UH HH[H ]@UH HH:H ]@UH HHM uH ]@UH HHH ]@UH HH`H ]@UH HHH ]@UH HHH ]@UH HH8zH ]@UH HHZH ]@UH HH:H ]LWH0HD$ I[Is HH3H$ HHIIH$hH$H$H$HHL$0H$@HLHL$0lt!H$@;rHQHD$0HD$(H$HL$0RHH$hHL$X<D$LHH$8H$H$RHH_@~H$H$+HHp؋~H$H$H$@[qHqH$ H3oL$0I[ Is(I_@UH HH*H ]@UH HH@ H ]@UH HH@H( H ]@UH HH@HX H ]@UH HH@H H ]@UH HH@[pH ]@UH HHM0] H ]@UH HHM(= H ]@UH HH H ]@UH HH H ]H\$Ht$WH HqHHH;qHvLHsHt$8H;HH\$0H _H\$Ht$WH HqHHH9qHv HsHt$8H;HH\$0H _H;t.H\$WH HHHoHH;uH\$0H _H;t.H\$WH HHHnHH;uH\$0H _I;t.H\$WH IHHnHH;uH\$0H _H\$WH HYHHt0Ht$0HqH;tH4nHH;uHOCHt$0H\$83HGHGHGH _H\$WH HYHHt0Ht$0HqH;tHmHH;uHOӖHt$0H\$83HGHGHGH _LWATAUAVAWHHDŽ$I[Is HH3H$LLH$H$Ƅ$Ƅ$Ƅ$Ƅ$Ƅ$Ƅ$3@2HD$hHD$P\$H\$@\$8\$0\$(\$ A DC Iu؅~ ؁DILD$dHT$h3iu؅~؁ |$d@HL$hHt=DDDH|u@H$ğH$HH$H+HKh/HHHH?H3H;v H$HD$pH\$x(D$pfD$pHt$xLd$pfffffffH$H9$vP Mt H$L;t8 H;IIs HHD$hMu I;t$r HH$hH$H;$v H$L;t H;u4D$`HT$`H$LDx|$`u3H$nH$H$qhMHIA<u%H$jHH H$H$HC$Hu @LHH IAHIHt$xLd$pH\$hL$L$Hu @H DvH$iHt H I;t$rHHt$x H$Ht0H$fffH;tHiHH$衒 Dl$dDl$dAH$H3脔L$I[@IsHIA_A^A]A\_@UH HH+H ]@UH HHMhNH ]@UH HHhH ]HT$UH`HHH`]HT$UH`HꋅEdH}H H`]HT$UH`HEdHH`]3HLtfffff9t HHuHuWMtxL+MIE3HAtI;vWMtEx>HHEtffffffD9 tHHuAWMAHtH+AIMH\$IE3HMLt8HD$(fffHt$AftfHIHIIuMuHAzIHfAtLH\$HL$SH0HD$ Ht HpHHKX'HHH0[@UH HHM@-H ]@UH HHM@HXH ]HL$SH0HD$ HHpHHVHKXKHH0[H%@UH HHM@H ]@UH HHM@HXH ]̸#LWH`HD$ I[Is HPH3HD$XIHISAIKHL$(2x؅yHL$(qHgHoHL$(HL$0H|$HHCL$0Hu+L؅tHL$(H wHpoHHt9H rHWHWAߠ7ЉHL$(H3)؅tHL$(HHL$XH3蓏H\$pH$H`_@UH HHMP]H ]@UH HHM(=H ]@SH AHD$@Ag$tjAiMtHA, |Ot&AqkHoHHH [HoHHH [H[oHHH [HoHHH [HnHHH [AtA텤t]Aet;A߷tHLD$(HH$HLD$ HHLD$0HL$ y:L$HL$ .y:D$D+D$0AHHtE3HH΄DˋHL$h?#HL$H5#H |BWHL$ Ht%xHL$ wHL$ HIHL$ HL$(Ht%oxHL$(HHL$(HIHL$(HL$PHtYHt$PHt$XHt$`HL$pHtYL$I[Is I_@UH HHMhndH ]@UH HHMHNdH ]@UH HHM(NH ]@UH HHM .H ]@SVWATAUAVAWHHD$@H]H3H$pMILLL$HL$8[LD$8H.IH$H$H$H$zH$@kHLL$0DBMu +3%/uHL$0(33ۋI;HT$8HL$hH$HG@HL$h@taHT$0Ht,3uHL$0 HL$0:H$6.HL$8HT$0Ht,3uDHL$0W HL$0Js:HHuE$D$(L|$ MLH$IH$-HL$8E$D$(L|$ MLIIH$Y-HL$8D$0H$pH3eXHĀA_A^A]A\_^[@UH HHM8H ]@UH HH H ]@UH HHH(H ]@UH HHHXH ]@UH HHHH ]@UH HH[,H ]@UH HHM0H ]@UH HHMh=H ]HT$UH0HE`E0HMHHH0]HT$UH0HE0H|H0]H%H(t5 t%t"tPt!@ 5̹W4̹4̋H(H(Nt5 t%t"tPt!@4̹W4̹4H(H H%~@SVAUH HIcLH0H Ht EHl$@Ld$PwH ]@UH HHH ]@SVWHHD$ HH3H$IHHAuhƁHH!HH!H H!HHpHH`E@HL$x耽HL$P|HL$(pLD$(HT$PHL$x1u-HL$(HL$PHL$xLHHT$PؾHT$(HƾE3HHH H;t-HL$(HL$PHL$xH HfHH` bHHL NƇHL$(4HL$P(HL$xkƁHH HHH H߽HH˽HHƇ 3H$H3KHİ_^[@UH HHMxmH ]@UH HHMPMH ]@UH HHM(-H ]@WH@HD$ H\$`HH3HD$0HHHT$(H(ݼLE3Hd5HLv,L0E3H4H,v,LXE3Hd4H v,HO(zHp3HL$0H3qJH\$`H@_@UH HHM(辻H ]@UH HHM(H ]@SH0H HvZH(r LLHl4E3D$ 8+LH3E3HD$ +HHv8HPr L8L8H3E3HD$ 踖*Hpv]Hxr L`L`H3E3HD$ v*LH3E3HD$ Qj*3H0[HHLAHL+AIIHHH?HH(H HtHPH(HHHH9H(H HtHPH(HHHH(H HtHPH(HHH@SH H9HuHHPH9SrHCH [HAHuHIH+H%I$I$IHHHH?HHQH%I$I$IH+QHHHH?HHHQHu3HAH+HHHHHH@SH HHHt HHPHH [HHHH@SH H9HusHHPH9Sr`HHkH [HCHHD$ HHL$(HL$PRHjHD$PHT$(HL$heHHD$PH9HL$PGC@UH HHM(5H ]@UH HHMP͸H ]HHBHI$I$IH\$WH HHHHtH;t%HOH%I$I$IH+KH\$0HHHH?HH _H\$WH HHHHtH;tŷHGH+CH\$0HH _HH\$WH H9HHu|HCHkpH HH;HwH;Hs[H{HH\$0H _H\$WH H9HHuHCHH HH;HwH;HsH{HH\$0H _HHD$ HHL$(>HL$PH HD$PHT$(HL$hH%HD$PHHL$P@@UH HHM(մH ]@UH HHMPmH ]H"""""""HHHu HkpHHD3HHHps3HT$PHL$PHL$ LHHL$ L\$ '@HHHu HkxHHD3HHHxs3HT$PHL$PHL$ \LHNHL$ L\$ ?HH̊D$̊D$̊D$H;t>H\$Ht$WH IHHffHHu9HH;uH\$0Ht$8H _̊D$HAHuHIH+HHHHHH?HHH\$Ht$WH H;IHHtffHH8HHH;uHt$8HH\$0H _H̊D$HL$SH0HD$ HHPHK(HH0[H%@UH HHM@ݱH ]@UH HHM@H(H ]H\$Ht$WH H;IHHtffHǀHÀHH7H;uHt$8HH\$0H _HH8HD$ HL$@HL$PHtH8@UH HHU@HMPNH ]HAHH\$Ht$WH H;IHHtffHHHxHxH;uHt$8HH\$0H _H\$WH HH HH;t.:HtHIJHHuHHH\$0H _H\$WH HHHHHDH\$0H _H\$WH HHu43HE3AHH˃@H\$0@H _HHHuLWHHD$ I[Is HH3H$HHISHzHrHR0H0`[HHL$(N1LHHAPHN(ŮHH$H3<L$I[ Is(I_@UH HHH ]@UH HHZH ]H(H HtHPH(H(H HtHPH(H(H HtHPH(HHHH@SH HHHt HHPHH [H9HHHHH\$WH H9HHHHAHHBuHHHH9Kr{HkH\$0HH _H@SH H9Hu3HHPH9Sr HCH [@SH H9HuHHPH9SrHHCpH [HI$I$IHHHLuMkpI<HH3HIHpsE3HT$XHL$ LD$XTLHF HL$ L\$ 7H\$WH HHHHtH;tHOH%I$I$IH+KH\$0HHHH?HH _H\$WH HHHHtH;tHGH+CH\$0HH _H\$WH H9HHu|HCHkpH HH;HwH;Hs[H{HH\$0H _H\$WH H9HHuHCHH HH;HwH;HsH{HH\$0H _HH"""""""HHHLuMkxI:HH3HIHxsE3HT$XHL$ LD$XTLHF HL$ L\$ 5HH\$Hl$Ht$WH HIHH+HHIH;tH+H H/HH;uH\$0Hl$8HHt$@H _HH\$Ht$WH MIHHHt I9PwI;PvrHH\$0HwHt$8HH _H\$Hl$Ht$WH HIIH+HHHH+H;t#H+ffffffffHÀHH .H;uH\$0Ht$@HHl$8H _HL$WH0HD$ H\$HHHP HO(Ht H3HHH\$HH0_@UH HHM@H ]@UH HHM@H(H ]H8HD$ HHT$HHT$XHtIHfH8@UH HHUHHMXEH ]HAHH\$Hl$Ht$WH LHHL+IHII,HHH?HHkxIH;tH+H H#HxH;uH\$0Ht$@HHl$8H _@SWH8HD$ HHD$XHHLD$XH!(HL$XHuH 蒁DHD$PHLD$PH` (HL$PHu%LL$PLD$XH? H~0HL$PHr HHHu 3H\$h&H*HHD$hHu HL$PHHHD$`HL$XHLD$`H](H|$`u LL$`LD$XH>Hf}Hr HHH;t6HHt!HyHHD$hHu23H\$hHL$`HHHL$`HtHRHHL$PHtHPHL$XHtHPH8_[@UH HHMXH ]@UH HHMPH ]@UH HHMhH ]@UH HHM`H ]H(HH;tH(H(HHH;tH(@SH H9HuHHPH9SrHCH [H\$WH H9HHHHAHHBuHHHH9KrHCpH\$0HH _H\$WH@E3HHLALALAHu 2H\$XH@_HI$I$IH;v HHu,IHkp23HkpHGHGHذH_H\$XH@_3HHHpsHT$PHL$ LD$PڣLHHL$ L\$ E.H\$Ht$WH MIHHHt I9PwI;PvHH\$0HwHt$8HH _H\$Ht$WH0HHHT$ HHAIHBHt$ Hu HD$(HkpHH;^wH;^sHt$HH\$(H\$@HL$ HHHAHGHH0_H\$Ht$WH0HHHT$ HHAIHBHt$ HuHD$(HHH;^wH;^srHt$HH\$(H\$@HL$ HHHAHGHH0_H\$WH@E3HHLALALAHu 2H\$XH@_H"""""""H;vHHu,IHkx0HkxHGHGHذH_H\$XH@_3HHHxsHT$PHL$ LD$PLH|HL$ L\$ +H\$Hl$Ht$WH HIHH+HHIH;tH+H H%HH;uH\$0Hl$8HHt$@H _H;t>H\$Ht$WH IHHffHHu%HH;uH\$0Ht$8H _H\$Hl$Ht$WH HIIH+HHHH+H;t#H+ffffffffHÀHH %H;uH\$0Ht$@HHl$8H _H\$Ht$WH HqHHH;qHvHsHt$8H;HH\$0H _H\$Ht$WH HqHHH9qHvHsHt$8H;HH\$0H _HAH\$Hl$Ht$WH LHHL+IHII,HHH?HHkxIH;tH+H HHxH;uH\$0Ht$@HHl$8H _HL$SH0HD$ HHP0HK(%HH0[H%@UH HHM@H ]@UH HHM@H(ٜH ]LD$SVWH0HD$ IHHH\$PH;t*H\$XH\$(Ht HH#HH\$`HHH0_^[@UH HHUXHM(::H ]HT$SUWH HH]PH}`H;tfffHx!HH;u33(H _][@SUVWATAUAVH`HD$PIHHI8t 3IH DNHHD$XHu E3Ll$HHHLD$HH( HL$HHuHb=Ll$@HLD$@H  HL$@HH$P@D IH$AD9$mL5:fHt3H$#HL$@HL$P8/ Ll$8H$HHT$8 Ll$0HL$8HLD$0HP8 L$HL$0HH$D D$(Lt$ AL$AQ ZtSH$HL$0HtHPHL$8HtHP;$} H$H$FEH$ȜHL$0HtHPHL$8HtHPH$H$}uHt3H$H$H9tHHH$HtHPHL$@HtHPHL$HHtHPH!AH`A^A]A\_^][@UH HHMXH ]@UH HHMHH ]@UH HHM@H ]@UH HHKH ]@UH HHM8nH ]@UH HHM0H ]@UH HHH ]HVWATAUAVH`HD$PHXHhIMLHI9t 3IH cHHD$XHu E3Lt$HHHLD$HH(HL$HHuHwLt$@HLD$@HĪ HL$@HH$P@IH$AD9$0Ht3H$BHL$@HL$P8NLt$8H$HLD$8H(#HL$8tiHtdLt$0HHT$0D$(Ll$ ALD$0AQ tBHL$0[HL$8HtHP HtHP;$}BH$ A$HL$0HL$8HtHPH$H$H$A<$uHt3H$ H$H9MtHHH$HtHPHL$@HtHPHL$HHtHPHrL\$`I[0Ik@IA^A]A\_^@UH HHMXH ]@UH HHMHH ]@UH HHM@H ]@UH HHH ]@UH HHM8nH ]@UH HHM0^H ]@SUVWATAUHHD$HHH3HD$xMIHLD$ 3H\$0H\$8H\$(H\$@HL$P^LL$0LHT$ I8\$ u&yLH3loHHL$PH|$pr H|$XHt0H|$X3HOHHD$@Hu HL$0HLD$(H(yLLH3nTHL$(Hu6LL$(LD$0HIkyLLH3nHL$(HLD$8IUDHw}nfHL$PHHL$(HtHPHL$8HtHPHL$0HtHPHL$xH3 HĈA]A\_^][@UH HHM0.H ]@UH HHM8H ]@UH HHM(H ]@UH HHM@H ]@UH HHMPH ]@SUVWATAUHHD$HH`H3HD$xIMHLD$ 3H\$0H\$(H\$@HH\$8HL$PLL$0LHT$ I]8\$ tyLH)3lIHL$PLH|$pr Ht$XHt0Ht$X3+HHHD$8Hu sHL$0HLD$(H(UHL$(Hu!LL$(LD$0IIi/HL$(Ht.3HDHHD$@Hu HL$(HHHL$PfHdHZHL$(HtHPHL$0HtHPHL$xH31HĈA]A\_^][@UH HHM0H ]@UH HHM(H ]@UH HHM@H ]@UH HHM8nH ]@UH HHMP}H ]@UVWH0HD$ H\$PIHHI8t 3IH vБHHD$`Hu HD$XHHLD$XH(yDHw3`jHT$XHtEH9t H +HL$XHtHPHH\$PH0_^]@UH HHM`NH ]@UH HHMXH ]HVWATAUAVH`HD$PHXHhL@E3LhLhLHLHPuD8$Ll$0HL$HHLD$0H(y.DMHU3>iHL$0H@HP5HL$0HL$HH$PhAH$HAfffLl$8LHT$8HAH$HH$PP$u{Ll$@H$HHT$@P8VH gyHHE3AHHL$@@HA@AEHL$@t=u6Ll$@HL$0HLD$@H$xkHL$@HtHPH$HL$8H;tHH$vH$HL$8HtHPH$HtqgD$ MDH 3^gHL$@HtHPHL$8HtHPH$HtHPHL$0Ht.HP&HtHHRHL$0HL$0HtHPHL$HHtHPL\$`I[0Ik8IA^A]A\_^@UH HHMXH ]@UH HHMHH ]@UH HHM0H ]@UH HHH ]@UH HHM8nH ]@UH HHM@^H ]@UH HHM@.H ]3HAHAHAH3HAHAHAHH\$Ht$WH HqHHH;qHvHsHt$8H;HH\$0H _H\$Ht$WH HqHHH9qHvH ]@UH HHM@H ]@UH HHM(H ]H\$Hl$Ht$WH HPHH_H;_vfHwH9wvH;t}H;t3H;_rlHH`tH;_rPHpH3H\$0Hl$8Ht$@H _LWATAUAVAWHHD$HI[IkIsHL-^MHLEMMMEMMMEH$ HLEIIKT3HPH_H;_vHwH9wvH;tH;t3H;_rvHT$xHhtH;_rXHpHHL$xHuMHM3\6IHL$ HT$ HPHHL$ bHt@$(t!HK(INHKPIA3MHH3[3sIH$<IHL$P-IHL$ L$LD$PHT$ HHL$ HL$PH$3L$I[0Ik8Is@IA_A^A]A\_@UH HHMxmH ]@UH HHM MH ]@UH HH*H ]@UH HHMP H ]@UH HHM ~H ]HL$SUVWATAUAVAWHHDŽ$LHZ]H'IGHD$PIHLD$PH(HL$PHu &: HD$0HLD$0H($H|$0u'LL$0LD$PH{ISV$eIPH$H^H;^vnHt$`H\$h(D$`fD$`H|$hH|$@Ld$`fH^H9^v8MtL;t(H;I HDŽ$ H HH$H Mu~I;|$r~H r LwI>LwIH{LcHHmHcB\-;} 3ELHu H2t@LMHcHLI}t$ E 1 "( P KT-I lLLY}t$ )  " PID-fADH<IL$33H SzLcHt u3H]~HcB';} 36~HHu H#~t@LMHcHLH|t$ xd"[PGK$HL}LLF|t$ XD";P'I̹@3̹W(̹̹@̹W̹̹@̹W̹HL$0HtHPHL$PHtHP$HA_A^A]A\_^][@UH HHMPH ]@UH HHM0H ]@UH HH kH ]@UH HH[H ]@UH HHMp.H ]@UH HHMXH ]@UH HHM8H ]@UH HH(H ]@UH HHMXH ]@UH HHMxH ]@UH HHMH~H ]@SUVWATHHD$PH"dH3H$IHLH$o3HD$@HD$HD$0HD$8H~ r H^LH^LLL$8HT$0I|$0u &I$HHL$XoH$H蓂H rHHL$H$LC$H} rLELEH~ rHD$(H|$ HIHL$8HtHR3rrH$[oH$H3YHİA\_^][@UH HHoH ]@UH HHM@H ]@UH HHMHH ]@UH HHM8~H ]H\$Hl$Ht$H|$ ATH HPMHH_H;_vpffffffHwH9wvoH;toH;t>H;_roHHmtH;_roHpHt IHH\$0Hl$8Ht$@H|$H3H A\H\$Hl$Ht$H|$ ATH HIILlHPH_H;_v5oHwH9wv%oH;toH;t@H;_r oIHltH;_rnHpHt HS(H5mH\$0Hl$8Ht$@H|$H3H A\H\$Hl$Ht$H|$ ATH HPMHH_H;_vqnffffffHoH9ovXnH;tMnH;H;_r8nHH,ltH;_rnHpHtyHAu&H~ rLFLFHE3G>kHK(I2lH~ rLNLNI|$ rMD$MD$H~G3$H~ rLFLFH3aG6H\$0Hl$8Ht$@H|$HH A\HWATAUAVAWH@HDŽ$HXHhHp H_H3H$0L3Hl$pHHLD$pH(DyDH3F H|$pt93HL$pcgHTI DyDH3tFx IpHGH+GH_ H_H;_v^lH$ H$(($ f$ L$ L$(fffH_H9_vlMtL;tlL; MukM;wrkIH$Hl$0@2H plHH$H Hl$xIHLD$xH(DyDHx3aEHT$xHt@H9T$0t HL$0fA(HL$xHtHPHlE @Hl$@IHLD$@H(DHL$@HxHl$PHLD$PH(DHL$PHu)LL$PLD$@HqIYADHL$PHLD$0H2(DRH|$0u$LL$0LD$PHIADHL$PHtHPHL$@HtHPHl$8LL$8LD$0HI@Dl Hl$HLL$HLD$8H |I@DH$rH$HuHHl$@H$jHHD$@HHL$HHHD#Hl$XLL$XLD$8H?zI@DH$rH$HuHH$"H$!jHH$H6HL$XHHDHl$`LL$`LD$8HKyI?DH$rH$HuHH$"H$iHH$HHL$`HHDHl$hLL$hLD$8H?xI>DA EAH$ $]gH$ iHH$HHL$hHHDL$H$LC$L$H$LC$$D$ HioAHhHL$hHtHPHhHL$`HtHPHhHL$XHtHPHhHL$HHtHPHL$8HtHPHL$0HtHPH$M;wrfIIp3DH3@HL$PHtHPHL$@HtHPHL$0HtHPH$CgDHT3M@HL$PHtHPHL$@HtHPHL$0HtHPH$DH3?HL$PHtHPHL$@HtHPHL$0HtHPH$DH3?HL$PHtHPHL$@HtHPHL$0HtHPH$>bA&EH3B?HL$@HtHPHL$0HtHPH$DHs3>HL$@HtHPHL$0HtHPH$DH3>H4fHL$hHtHPHfHL$`HtHPHeHL$XHtHPHeHL$HHtHPHL$8HtHPHL$0HtHPH$DHP3=HL$hHtHPHfeHL$`HtHPHKeHL$XHtHPH0eHL$HHtHPHL$8HtHPHL$0HtHPH$GkDH3Q=HdHL$`HtHPHdHL$XHtHPHdHL$HHtHPHL$8HtHPHL$0HtHPH$DH3H ]@UH HHMPH ]@UH HHM8H ]@UH HHMHޮH ]@UH HHM@H ]@UH HHMX螮H ]@UH HHH ]@UH HHM`^H ]@UH HHKH ]@UH HHMhH ]@UH HH H ]HH3D$(D$0D$ HHH;tUHL$WH0HD$ H\$HHHHKP[HK([H[HxH\$@H;uH\$HH0_@UH HHM@}[H ]@UH HHM@H(Y[H ]H8HRHI3D$(D$@D$ H8H83D$(D$@D$ 8H8H83D$(D$@D$ HH8H\$Hl$VWATHH4NH3H$HHLuLHr LLH+{HH@r L(L(HkHclH@vZHpr LXLXHAHD$ 5*HHr L0A;L0A/LHzE3HD$ 4E3LiHHD$ 4Hv"Hr LALA E3LHHD$ T4mHu^E3D$ D8HHLhuLդ4)Hv"Hr LALA E3LHHD$ 3Hv"Hr LALA E3L2HsHD$ n3H8v"H@r L(AL(A E3LHHD$ 36$A EA HT$XXL%HvLd$@HD$8H-Hl$0H5HLHT$XMHHt$(H\$ hHA EAHT$PXLd$@HuHD$8Hl$0LIHT$PMHHt$(H\$ hH`v8Hhr LPLPHE3HD$  2&LHH5iLHHLEE3D$ 1LLLEHwHE3D$ 1LLLEHHE3D$ {1MLLEHoHE3D$ O1hNHHEHE3LD$ #1H3H$MHHHL$PHT$8LD$@IH$HFHu3 H^H+HMLvIH+HHHH+I;suN!I;^HHH+H;s3HI;IBHHtH3HHH=s7HD$8HT$8HL$`LLGtL\$`HHL$`yHLHD$@HD$HLo3D$(T$0T$ LMIHNmHHD$H3D$(D$0D$ LL$IHIHHH|$H3D$(D$0D$ LLHVIH~HFH+HLHt#LnI;tHHI;uHNHIH^IMLfLvHIH+HI;MIMD=3D$(D$0D$ LIHvHNHH+HL+3D$(D$0D$ LL$ILnH^I+H;fffffffffH$HHH;u^III+3D$(D$0D$ LMIH۫HFMHH IH33H8][HT$UH0HLM@IHMPHAMHE8HPI33H0]HL$VWATHPHD$0H$HHLBL+BHIIHHH?HALALALAH"""""""H;vɑHHuIB3HHHxs3LD$xHT$xHL$8_HLpL\$8HLHL$8HkxLHGHGHkxHH_H^H9^v%HLfL;fvH3D$(D$pD$ LLGHI̾HGHH$HPA\_^HT$UH0HHMp331H0]@VWATH0HD$ H\$XHl$`HHYH9YvyGH~H;~viGH;LfIH+HHH,HHH?HHkxHI;tH+H HfHxI;uH~HH\$PH;t-HKP`EHK(UEHKEHxH\$PH;uHnH\$XHl$`H0A\_^@UH HHMP EH ]@UH HHMPH(DH ]@WH0HD$ H\$HHt$PHHYHtDHqH\$@H;t-HKPDHK(DH~DHxH\$@H;uHOk3HGHGHGH\$HHt$PH0_@UH HHM@-DH ]@UH HHM@H( DH ]H\$Hl$Ht$WATAUH0HHIMHoHMH+HHu3+H;v?EI$HtH;t+EI\$H+HI$HL$ HT$ HID$MHAHAHoH;ovDH|$ Hl$((D$ HfD$ HH;_wH;_sDHl$XH\$(H\$PHL$ HHHAHFHHt$`H0A]A\_HL$WH0HD$ H\$HHHAHS(HO(AHSPHOPHH\$HH0_@UH HHM@}BH ]@UH HHM@H(YBH ]@VWATAUAVH@HD$0H\$xH$LHH; LjHzML+IIIM IIH?Lu HLAHiIH+IHHHHH?HL;IH+IHHHHH?HHkxHI;tH+ffH /HaHxI;uH~H\$pH;t-HKPCAHK(8AH.AHxH\$pH;uIL$I+L$IHHHHH?HHkxHVHVHHu3HNH+IHHHHH?HL;wAHHkxHLHʢ3D$(D$pD$ LLFIT$HHFH|HtHHHNiIL$I+L$IHHHHH?HH蜟t.3D$(D$pD$ LLFIT$IL$蓹HFHHHH\$xH$H@A^A]A\_^@UH HHMp?H ]@UH HHMpH(?H ]@WH0HD$ H\$HHHHL$@HL$PHt&>HW(HK(z>HWPHKPH\$HH0_@UH HHU@HMP H ]@UH HHMP>H ]@UH HHMPH(>H ]HL$WH0HD$ H\$PHt$XHHYXHtMHq`H\$HH;t6ffffffHKPv>HK(k>Ha>HxH\$HH;uHOXN3HGXHG`HGhHO(2>HH\$PHt$XH0_H%>@UH HHM@=H ]@UH HHM@H(=H ]@UH HHMH=H ]@UH HHMHH(=H ]H\$VWATH@LA3LMHuH HII+HHsHI+HH;s;3LLˈD$(D$`HΈD$ LL[H\$pH@A\_^L;Hl$hv>HKHkH\$0HHt$8H+HtH;va>HH+H(D$0HT$0MAHfD$0HsHl$hH;sv!>HH7H;CwH;Cs>H\$pH@A\_^H\$WH HH2(؅tL$H$HL$H<(؅Ll$0H$HLD$0H<(؅Ll$8H$HLD$8Hj;(؅HD$8HD$ LL$0L$H$I؅x^HL$8HtHPHL$0HtHPH$HtHPH$HtHP;$DDH3HL$8HtHPHL$0HtHPH$HtHPH$HAHP6DDH{3DHL$8HtHPHL$0HtHPH$HtHPH$HHPDDHd3HL$0HtHPH$HtHPH$HHP|DDHQ3H$HtHPH$HtFHP>DDHS3LH$HtHPDDHy3"DHH$HtHPHL$@HtHPHL$HHt HPHhA]A\_^][@UH HHMHxH ]@UH HHM@xH ]@UH HHxH ]@UH HHMX~xH ]@UH HH[xH ]@UH HH;xH ]@UH HHM0xH ]@UH HHM8wH ]Hl$H|$ ATH HH+H%I$I$IILHHHH?HHkpH+H;t[H\$0Ht$8HI+IXPffffffHpHpHKH%HW(HK%HHaI;uHt$8H\$0H|$HHHl$@H A\LL$ HL$SVWH@HD$ IHHHL$hHtHH\$(H\$0Ht*HHP$HV(HK(A$HVPHKPHHpH\$`H@_^[@UH HHU(HM0H ]@UH HHM0$H ]@UH HHM0H($H ]HT$SUVWH(HH]hH}`H;tHuxHHHpH;u33bH(_^][H;HL$VWATH0HD$ H\$`Hl$hHHE3H{XHtKHs`H|$XH;t4fffffHOP#HO(#H#HxH|$XH;uHKX辯LcXLc`LchHK(#H#HpH\$PH;zH\$`Hl$hH0A\_^@UH HHMP]#H ]@UH HHMPH(9#H ]@UH HHMX#H ]@UH HHMXH("H ]H83D$(D$@D$ (H8HH3D$(D$0D$ (HHH;VWATH0HD$ H\$`Hl$hHHHL$XE3H{XHtKHs`H|$PH;t4fffffHOP&"HO("H"HxH|$PH;uHKXLcXLc`LchHK(!H!HpH\$XH;zH\$`Hl$hH0A\_^@UH HHMX!H ]@UH HHMXH(y!H ]@UH HHMP]!H ]@UH HHMPH(9!H ]H83D$(D$@D$ hH8H\$WH03MID$(D$HHLMHHˈD$ MHkpH;H\$@H0_I;VWATH0HD$ H\$PHl$hIHHT$`E3H{XHtKHs`H|$XH;t4fffffHOPF HO(; H1 HxH|$XH;uHKXLcXLc`LchHK( HHpH\$`H;zH\$PHl$hH0A\_^@UH HHM`H ]@UH HHM`H(H ]@UH HHMX}H ]@UH HHMXH(YH ]H83D$(D$@D$ H8@UVWATAUAVAWH0HD$ H\$pIMLLIHtI;tk MD$H[L;'IoHH+H%I$I$IHLIIH?LMkpMH;tAIxPHI+ffHOHkHS(HO]H>HHpHpH;uIoIL$L;3fH_XHtOHw`H\$xH;t6ffffffHKPHK(HHxH\$xH;uHOXީ3HGXHG`HGhHO(HHpH$H;nMoI$IID$IFIH\$pH0A_A^A]A\_^]@UH HHZH ]@UH HHH(6H ]@UH HHMxH ]@UH HHMxH(H ]@UVWATAUH0HD$ H\$pHHYE3HLaH\$hI;H{XHtMHs`H|$`H;t6ffffffHOPvHO(kHaHxH|$`H;uHKXNLkXLk`LkhHK(4H*HpH\$hI;xHMLmLmLmH\$pH0A]A\_^]@UH HHMhH ]@UH HHMhH(H ]@UH HHM`H ]@UH HHM`H(yH ]@SH03MM؈D$(D$HHLMIHˈD$ H0[;@VWATAUAVH0HD$ H\$pHl$xLHYH9YvuIt$I;t$vcH;Ml$IH+H%I$I$IHLIIH?LMkpLI;tAH~PHH+ffHOHkHS(HO]H/HHpHpI;uIl$ILt$hL;E3ffH_XHtMHw`H\$`H;t6ffffffHKPHK(HHxH\$`H;uHOXޥLoXLo`LohHO(HHpH|$hH;xMt$H\$pHl$xH0A^A]A\_^@UH HHMhmH ]@UH HHMhH(IH ]@UH HHM`-H ]@UH HHM`H( H ]@SVWATAVAWHHD$xHo H3H$IMLHT$XHHL$PHT$HLD$@IH$HS(H$HSPH$LFMu3I%I$I$I(HNI+I%I$I$IIHHHHH?HM"LVLT$8II+IHHHH?HHI$I$IHH+I;sH`N"I;dHHH+H;s3HI;IBHHtF3HHHps7HD$HHT$HHL$`LOAL\$`HwHL$`聣HkpHHD$@HD$83D$(D$0D$ LLIVHNLHD$83D$(D$0D$ LL$IIIHkpLLt$83D$(D$0D$ LMHVHL$XHI5LNHNI+IHHHH?HLMtLFIHHN虢HkpHH^MkpLLfH~sI~IH+IHHHH?HI;MMkpM>3D$(D$0D$ LIHLVIH+IHHHH?HL+3D$(D$0D$ LL$IIpLvH^I+H;H$HHO(H$HOPH$WHpH;uMkpII+3D$(D$0D$ LMIHHFLD$8HHI4HHEtffffffD9 tHHuAWMAHtH+AIMH\$IE3HMLt8HD$(fffHt$AftfHIHIIuMuHAzIHfAtLH\$H\$Hl$Ht$WH ILL$PHZIHLH3xHH;wuf|]H f|]zHtHH\$0Hl$8Ht$@H _HH\$WH HtHxHH\$0H _H(H _3ɅH(H(H HtHPH(HHHHHHQHu3HAH+HHAH+AHHHQHu3HAH+HHAH+AHHH\$WH HHHHtH;tHSH\$0H9WH _H(H UOxH Ht H H(H\$WH HI؋HtЅxH LËH\$0H _HHD$ HHL$(^HL$PH*HD$PHT$(HL$h%HEHD$PHHHL$Pv@UH HHM(H ]@UH HHMPH ]HHHD$ HHL$(HL$PRHjHD$PHT$(HL$heHHD$PH9HHL$PGu@UH HHM(5H ]@UH HHMPH ]HHt@SH H9HuSHHPH9Sr@HCH [@SH H9HuHHPH9SrHHCH [HHHHH\$WH H9HHu\HCHH HH;HwH;Hs;H{HH\$0H _H\$WH HHHHtH;tHGH+CH\$0HH _H\$WH H9HHuHCHH HH;HwH;HsH{HH\$0H _H\$WH HHHHtH;tUHGH+CH\$0HH _HHHu HHH&w3HHHs3HT$PHL$PHL$ L%HEHL$ L\$ WrHHHu HHHv3HHHs3HT$PHL$PHL$ LH~EHL$ L\$ qH@SH H+MHHHJ~LLHIHH [H̊D$@SH H+MHHHJ~LLHIEHH [H;tffffffffIHH;HAůD$H;tffffffffIHH;HAůD$HH@SH H+IHHH+H~LLHHFHH [@SH H+IHHH+H~LLHHHH [HHHtffffffffIHHHAuHtffffffffIHHHAu@SH H+IHHJtLLH+HH [@SH H+IHHJtLLHHH [@SH 3HHHHAHAHAHA CHCC HHC@tHy H [C8H [H\$WH yHt9HytHHCHK@HtHPHKCH\$0H _H(H HtHPH(E3HAt HvWx\Iv fDWHt2L+L+fffIHtAftfHHuHu HAzfA@SVWATAUHHD$@HH3H$MIHHHL$(7HHL$0(HHL$8HL$h 3I}LL$0LD$(HT$8HL$huy6HL$hHL$8HL$0HL$(H$HT@LHT$pH$HCT$pHKDHt HvAWExWHv AWfADϐHt)Ht.DfEt$fDHHHHHHAzfA;OMe t$ t$ HL$hHL$8HL$0HL$(H$H3mHĠA]A\_^[@UH HHM(H ]@UH HHM0H ]@UH HHM8eH ]@UH HHMhH ]HT$UH HE`E HMHHH ]HT$UH HE @HH ]@SVWATAUAVH8HD$8HH3H$(MEHL$3H$hH$YI>HHL$`?L$EċH؅y$H$H$D$ LAIH$؅y$H$H$pH H$H$H$HH$uH$H$HH$H$HT@HHH$H$HC$HKDHt HvAWExYHv AWfCDLHt)Ht.DfEt$fDHHHHIHAzfAKI6H$UH$F |$0|$0H$+H$H$(H3jH8A^A]A\_^[@UH HHH ]@UH HHH ]@UH HHH ]@UH HHzH ]HT$UH0HEXE0HM@#HH0]HT$UH0HE0@HH0]HH@SH H9HusHHPH9Sr`HCH [@SH H9Hu3HHPH9Sr HCH [@SH H9HuHHPH9SrHCH [H\$WH HHHHtH;tHSH\$0H9WH _H\$WH yHt9HytH$HCHK@HtHPHKCH\$0H _HH@SH H9HuHHPH9SrHHCH [@SH H9HuHHPH9SrHHCH [@SH H9HusHHPH9Sr`HCH [@SH H9Hu3HHPH9Sr HHCH [@SH 3HHHHAHAHAHA CHCC HHC@$Hy VH [C8H [HHHHLuJ chHH3HIHsE3HT$XHL$ LD$X#L\H7HL$ L\$ cHHHHLuJ gHH3HIHsE3HT$XHL$ LD$XLH6HL$ L\$ bH\$WH H9HHu\HCHH HH;HwH;Hs;H{HH\$0H _H\$WH HHHHtH;tHGH+CH\$0HH _H\$WH H9HHuHCHH HH;HwH;HsH{HH\$0H _H\$WH HHHHtH;tUHGH+CH\$0HH _H\$Ht$WH MIHHHt I9PwI;PvHH\$0HwHt$8HH _HH@SH H+IHHH+H~LLHHHH [@SH H+IHHH+H~LLHHHH [HtffffffffIHHHAuHtffffffffIHHHAu@SH H+IHHJtLLHHH [@SH H+IHHJtLLHHH [H\$Hl$Ht$H|$ ATH@HHL$0IALHD$0yHL$0HtHRqHt$HHtHL$0LCHPHSHHuHHT$0HP(x"HD$0H E3DIHD$ ?HL$0HtHRH\$PHl$XHt$`H|$hH@A\H\$WH H9HHHHAHHBuHHHH9KrHCH\$0HH _H\$WH H9HHHHAHHBuHHHH9KrHCH\$0HH _H\$WH H9HHHHAHHBuNHHHH9Kr;HCH\$0HH _H\$WH 3HHHHAHAHAHA GHGG H=HG@0y eG8HH H;sHHt P@H HH;rHH\$0H _H\$WH HOHPHH;sHHt 3P@H4HH;rt9HtHOHGHO@HtHPHOcGH\$0H _H\$WH@E3HHLALALAHu 2H\$XH@_HH;vHHu)IH`HGHGHH\$XHGH@_3HHHsHT$PHL$ LD$P=LvH//HL$ L\$ [H\$WH@E3HHLALALAHu 2H\$XH@_HH;vHHu)IH_HGHGHH\$XHGH@_3HHHsHT$PHL$ LD$P}LHo.HL$ L\$ ZH\$Ht$WH MIHHHt I9PwI;Pv2HH\$0HwHt$8HH _H\$Ht$WH0HHHT$ HHAIHBH|$ HuHD$(HH;_wH;_sH\$(H\$@HL$ HHHAHFHHt$HH0_H\$Ht$WH MIHHHt I9PwI;PvBHH\$0HwHt$8HH _H\$Ht$WH0HHHT$ HHAIHBH|$ HuHD$(HH;_wH;_sH\$(H\$@HL$ HHHAHFHHt$HH0_@SH H+MHHHJ~LLHIHH [@SH H+MHHHJ~LLHIuHH [H;tffffffffIHH;HAu@SH H+IHHH+H~LLHHHH [H;tffffffffIHH;HAu@SH H+IHHH+H~LLHHvHH [HtffffffffIHHHAuHtffffffffIHHHAu@SH H+IHHJtLLHHH [@SH H+IHHJtLLHHH [H\$Hl$VWATH0HHL$hIADHD$hyHL$hHtHRyHt+HHt#fffffHL$hLCHPHSHHuHHT$hHP(x#HD$hH AE3DHD$ HL$hHtHRH\$PHl$XH0A\_^LI[IkVWATHPH-HDIC3H=IKI[ICICICI{yHL$xHtHR~HD$0Ht)Ht$fffHL$xLCHHPH{HHuHEHT$xHP(x$HD$xH E3EĺHD$  HL$xHtHRH\$pH$HPA\_^H\$WH 3HHHHAHAHAHA GHGG H=HG@ y UG8HH H;sHHt P@H }HH;rH\$0HXHHH _̸̸̃A ̃A ̋A @VH0HHu @H0^H\$@HY@H|$H3H9;u%L DGH 3H\$ xH HH HRH\$@H|$HH0^HHL~HH`H\$WH HHHH;sHHt 3P@HHH;rt9HtHOHGHO@HtHPHOGH\$0H _H\$Ht$WH HjHH hH;ًsHHt 3P@H MHH;rt9HtHOHGHO@HtHPHO|G@tHsQH\$0Ht$8HH _3HAHAHAHH\$Ht$WH HqHHH;qHvHsHt$8H;HH\$0H _H\$Ht$WH HqHHH9qHvLHsHt$8H;HH\$0H _3HAHAHAHH\$Ht$WH HqHHH;qHvHsHt$8H;HH\$0H _H\$Ht$WH HqHHH9qHvHsHt$8H;HH\$0H _H\$WH0HHHT$ HHAHBH|$ Hu8HD$(HH;_wH;_sH;_rHH\$@H0_H\$WH0HHHT$ HHAHBH|$ HuHD$(HH;_wH;_sH;_rHH\$@H0_H\$Hl$Ht$WH IIIHHHtI;tUHKLFI;t)HEI+HHHH4 ~ LHuHHl$8Ht$@HHCH\$0HGHH _H\$Hl$Ht$WH IIIHHHtI;tHKLFI;t)HEI+HHHH4 ~ LHuHHl$8Ht$@HHCH\$0HGHH _@SH HHIHtM3HCHCHCH [̹3HtffffffffIHHHAuHtffffffffIHHHAu@SH H+IHHJtLLHHH [@SH H+IHHJtLLHHH [@WHPHD$ H\$`Ht$hHHHHH;vHٴHʴHH;v HH;taH;rHT$(HhHHSHL$(ݿu&HzH;r _HhHHU뉰2H\$`Ht$hHP_@UH HHM(}H ]H\$Ht$WH HqHH9qvH{H;{vH;t9HCHl$0H+HHHH,:~LLH!HkHl$0H\$8Ht$@H _@SH HHIHtJ3HCHCHCH [H\$Ht$WH HqHH9qvH{H;{vH;t9HCHl$0H+HHHH,:~LLHQHkHl$0H\$8Ht$@H _H\$Ht$WH Լbx/H EE3:xHHt H yЋ؋Ht$8H\$0H _H\$Ht$WH YDLMt AӅxH E3؅x 3؋Ht$8H\$0H _HtffffffffIHHHAuHtffffffffIHHHAu@SH L+LIIJJ tLMHHH [@SH L+LIIJJ tLMHHHH [@WHPHD$ H\$`Ht$hH wvHHH;vuH~ffffHH9fv VH_H;H;r;HT$(H Hx rL@L@HMvHL$(gHH;w H;s HH;r ҼHۯH HtHH¯H;r HH/HH9v HHH;v lHuH;t.H+HHH4H~LLHH5BHt HBHCH;vH1ffffffHH9v HH;t^H;w H;s ƻHH;r HݮH HtHHĮH;r HHHH9v jHHH;v QHzH;t.H+HHH4H~LLHH5GHsH\$`Ht$hHP_ߔ@UH HHM(=H ]H(t1u1H H qH\$ H\$ H(H(H\$WH 9x/H E33xH̬Ht H PЋ؋dH\$0H _H\$WH @+L|Mt AӅxH E33l؅x 3؋H\$0H _MILtfffIIHIBuJMILtfffIIHIBuJ@WATAUAVAWH@HD$ H\$xH$MLHIHAHu3 HyH+HM[LaIH+HHHH+I;sLI;HHH+H;s3HI;IBHHtF3HHHs7HD$pHT$pHL$(FLL\$(H3HL$(BH3GLH$IOLFI+HHL4t LH{IIHt HHHK HVMGI+HtHLAHNHFH+HLHtBIHFKHFLfMGII+HI;s~K M+ItJLڶHVHI+GHIH+Ht HHHJHFHNH+IGH;fffffffHHH;u~III+IH+HHN4"tLLIILvMGI+HH~HL+LIIGILH;tffffffHHH;uH\$xH$H@A_A^A]A\_HT$UH HH@33@H ]HT$UH H33@H ]@WATAUAVAWH@HD$ H\$xH$MLHIHAHu3 HyH+HM[LaIH+HHHH+I;sGLI;HHH+H;s3HI;IBHHtF3HHHs7HD$pHT$pHL$(LOL\$(HHL$(?HDLH$IOLFI+HHL4t LHKIIHt HHHK HVMGI+HtHLHNHFH+HLHt>IHFKHFLfMGII+HI;s~K M+ItJLHVHI+GHIH+Ht HHHJHFHNH+IGH;fffffffHHH;u~III+IH+HHN4"tLLILvMGI+HH~HL+LIIGILH;tffffffHHH;uH\$xH$H@A_A^A]A\_HT$UH HH{=33~=H ]HT$UH H33Z=H ]H\$Hl$Ht$WATAUH0HHIMHoHMH+HHu3+H;vI$HtH;tkI\$H+HI$HL$ HT$ HID$MHAHA HoH;ov$H|$ Hl$((D$ H\fD$ H;_wH;_sHl$XH\$(H\$PHL$ HHHAHFHHt$`H0A]A\_H\$Hl$Ht$WATAUH0HHIMHoHMH+HHu3+H;voI$HtH;t[I\$H+HI$HL$ HT$ HID$MHAHA,HoH;ovH|$ Hl$((D$ H\fD$ H;_wH;_sHl$XH\$(H\$PHL$ HHHAHFHHt$`H0A]A\_H\$Ht$H|$ ATH0LA3LMHuH HII+HHsHI+HH;sHHHFHCL;Hl$@vHH;wH;sL$H$LC$LydH$.L$H$LC$LcH$.MuM;grIH$mHxHrL@0L@0H$c:H$>6HD$ HtL$HbHaHHH|$ Huut$(Hb3؀H$IH$:HL$8Ht0H|$@HfffffH;tHHHL$81THH$ݤH~HuHH }H+HHgHH+HH;s*HHt H9HHHBH3HH;vHH Lt$`H|$hHH+HuHH;vڥH+H(D$`f$LL$ AH$IHHH H;vH HHH;wH;slXf4HD$ HtL$H!`H eHHD$ Hupt$(HJ`3H$tH$eHL$8Ht+H|$@HfH;tH#HHL$84/HT$ IH$H$MuM;grILd$8Mt&H\$@L;tIIHL$8.t$(H^~H$0H30L$@I[ Is(I{0Mc8IA_A^A]@UH HHM0>H ]@UH HH*H ]@UH HH H ]@UH HHH ]@UH HHH ]@UH HHM -H ]@UH HHM -H ]@UH HHKH ]@UH HHM R-H ]@UH HHM 2-H ]HT$UH HH\3|HNH ]H\$Hl$Ht$WH HH ziHH@IHDHH;uHCH;Gu3t@axX1HtDHuHHt3LLHHAyH7H;,HHRH\$0Hl$8Ht$@H _H\$WH HHHS(HO(ԟD[PHSXHOXD_PHHDHDHH\$0H _H%oHL$WATAUH0HD$ H\$XHl$`Ht$hLLvIM(kIMX`IRIDIIIT$(IM(E\$PE]PIT$XIMXОI$IE$EA$AI$IIH\$XHl$`Ht$hH0A]A\_@UH HHMP]H ]@UH HHMPH(9H ]@UH HHMPHXH ]@UH HHMPHH ]@UH HHMPH֝H ]H\$WH H;HHtnHW(HK(D_PHWXHKXD[PyHHeDHDH5HH\$0H _HL$SH0HD$ HHHHKXHK(ٜHH0[H%ɜ@UH HHM@H ]@UH HHM@H(H ]@UH HHM@HXiH ]@UH HHM@HFH ]h@WHPHD$ H\$`Hl$hHt$pIHHHL$x蟫|$xtxH[HL$(LDHHL$(TFHL$(ytH[HL$(LDHHL$(FHL$(j9Hk[HL$(LDHHL$(EHL$(/H\$`Hl$hHt$pHP_@UH HHM(H ]@UH HHM(ݚH ]@UH HHM(H ]@WHPHD$ H\$`Ht$hI؋HHZHL$(LDHHL$( EHL$(\3HH\$`Ht$hHP_@UH HHM(-H ]LWHHD$XI[HH3H$HIKHYHL$0L$DHHL$0[DHL$0HH$ʘH$H$cHtZH$&HL$`H3ZHL$0LL$`DHT$0H$CHL$0(y-HL$`H$ H$3]HL$ HT$hH$HCT$hHL$ )3ۃ|$$ HL$`H$H$H$H3&H$H_@UH HHZH ]@UH HHM0=H ]@UH HHH ]@UH HHM`H ]@UH HHM0ݗH ]HAHuHIH+HKh/HHHH?HHHHHHD$ HHL$(^HL$PH*HD$PHT$(HL$h%HEHD$PHHL$P#@UH HHM(H ]@UH HHMPH ]HHKh/H\$WH HHHHtH;tHOHKh/H+KH\$0HHHH?HH _H\$WH H9HHuHCHiH HH;HwH;HsxH{HH\$0H _HHHuHiHHC&3HHH=s3HT$PHL$PHL$ L@HHL$ L\$ r!H;H\$Ht$WH IHHH;ttHHHW(HK(D_PHWXHKXD[PHHޔDHDHHH;wH\$0Ht$8H _H̊D$̊D$HH8HD$ HL$@HL$PHtH8@UH HHU@HMP1H ]H\$Ht$WH H;IHHHHH;ttHHHS(HO(D[PHSXHOXD_PtHH`DHDH0H;pH\$0Ht$8HH _HA@UVWATAUAVAWjH+HD$8H$HoH3H$AMLLHL$0H$L$L$L$H$HD$(H$IL$(IL$XI$I$zIIL$(+IIAt$PIIL$X HT$(I$D$E$AƄ$HD$@HD$ IT$XHL$@HIT$(HL$hEL$PLHH$H$p~H$H$HH$p-y0H$p\H$8MH$>I$IL$(wA$uLD$ HT$ H$zu-H$pH$8ڐH$ːFI$IL$(wpH$p袂H$8H$IzIpIfHL$(ZIH$H3WH$HĐA_A^A]A\_^]@UH HH H ]@UH HHH ]@UH HHʏH ]@UH HHH ]@UH HHM0H ]@UH HHM0H(iH ]@UH HHM0HXIH ]@UH HHM0H&H ]@UH HHM0HH ]@UH HHM H ]@UH HHKH ]@UH HHp諀H ]@UH HHH ]@UH HHjH ]@UH HHJH ]@SUVWATAUAVAWHHDŽ$HH3H$IELLH;H$ IH$HH$nH$PH$PH*HL$@L$PEHT$@H$ 8HL$@\y,t$H$PBH$32AH$xSH$xHHL$@*L$xEHT$@H$|7HL$@όuE27y3H$xH$PH$2H$(H$H$(oHOHL$@}L$(EHT$@H$6HL$@"yQH$H$(H$xH$PH$ԋ2"IH$(H$(H$HMH$(IHZMH$4L\$@L\$xH$HD$pH$HD$hH$HL$@mHH$(H$THIH$@HIH$,Dl$0Ht$(H|$ ELHH$H$H;H$HHM(H$D$ D]PHMXH$(HH$PnD$xD$yHH$;H$4H$P%H$(H$H$H$H$(ډH$xˉH$PH$H$H3HA_A^A]A\_^][@UH HHjH ]@UH HHPJH ]@UH HHM@-H ]@UH HHx H ]@UH HHM@H ]@UH HH(ʈH ]@UH HHH ]@UH HHM@H ]@UH HHMxmH ]@UH HHMpMH ]@UH HHMh-H ]@UH HHH ]@UH HHH ]@UH HHH(ƇH ]@UH HHHXH ]@UH HHHH ]H\$WH HAHHH+AHH;rHCH\$0HH _HHHKh/HHHLuMiIqHH3HIH=sE3HT$XHL$ LD$X/LhH!HL$ L\$ H\$WH HHHHtH;tHOHKh/H+KH\$0HHHH?HH _H\$WH H9HHuHCHiH HH;HwH;HsxH{HH\$0H _HH8HD$ HHT$HHT$XHtIHH8@UH HHUHHMXJ#H ]@UATAUH LLHKh/L+MHIHHH?HHiL+I;H\$@Ht$HH|$PI|$XIXPM+HHHKHwH;tWHHWHKEHKHDHW(HK0D_PHWXD[XOQKYHK`dH;uH|$PHt$HH\$@IH A]A\]HA@UVWHHD$PH$HwH3H$HHHL$X)HL$XHL$ 苓؅|$ tzHCHL$(LL$XDHHL$(=.HL$(y|HCHL$(LL$XDHHL$(-HL$(R@HTCHL$(iLL$XDHHL$(-HL$(|$$uHL$X2*bLDHT$XHHL$XтH$H3H$HĐ_^]@UH HHMXH ]@UH HHM(mH ]@UH HHM(MH ]@UH HHM(-H ]H\$Ht$WH HqHHH;qHvHsHt$8H;HH\$0H _H\$Ht$WH HqHHH9qHvH)eHH A]][@UH HHH ]@UH HH cH ]@UH HHH(bH ]@UH HHHXbH ]@UH HHHbH ]H%YcH%AV@SH@HAHtHHtCH|$P3H|$8H|$0DD$(HL$ LA3ҋ#aHDH|$PHH@[3H@[H%IdH\$WH HfHHrdHHCuHt _HH\$0H _H%cH(LcDII~ @HVUUUUUUUILI?LAuVUUUЍR+DkAADRkL+tƒ+t +DAuGPAH(̋LL$ SUVATH(HIIDHPHGM>Ll$XDl$pAA9E}3Ll$XH(A\^][E3H|$PLt$`VUUUL|$ AEPEADkADF<ADAADAE;uAAkL+DAEAL= %ffffffFNHH  B9CB9CB9C?HB8CuF<EBÃ?/DAUH HMLQMHHl$8Ht$@3H|$HcHMLd$@H;DH\$0Lt$L<$D~Dv?A82DƋދL;s^A AwA.AwA!AЃ wA+uA /ADM׃uA+ AD A׃|uÙAA;AOù+˃A~Du AAMAI+uL;3Lt$H\$0L<$H|$Hl$8@E!Ld$Ht$@H A]3H A]Hw 33HLtfffff9t HHuHuWMtxL+MIE3HAtI;vWMtEx>HHEtffffffD9 tHHuAWMAHtH+AIMH\$IE3HMLt8HD$(fffHt$AftfHIHIIuMuHAzIHfAtLH\$@SH`HD$PHT$HIHD$0DD$@HL HL$@E3E3D$(HD$ zWuH`[HD$XH$HD$PH`[@SH`HD$PIDD$@HD$0HT$HHL$@E3E33D$(HD$ VuH`[HD$XH$HD$PH`[H(H HtHPH(HH9H(H HtHPH(HHHH(H HtHPH(HHHHH ,H(H HtHPH(HHHHH9HHHHHHHH@SH HHHt HHPHH [@SH HuHHH [3;ZHHu9@SH HH Hu3H [YH H [H%PZH%YH\$WH HHYHfYHHCuHtf CHH\$0H _H(H HtHPH(H(HmHHHtHPH(H(H HtHPH(H(H HtHPH(HVWATAUAVHpHD$@HXHhMMHLHt7HH3ff9t HHuHu W3H+y W3zT?33T$PH\$XHD$`HD$0D$(H|$ E3E3H5HL$PzRu3MEIԹH|$hl$`HcH3Hu @HVUUUUUUUHLI?L¸VUUUЍRD+DŸkADJkLA+tƒ+t +DC Aȉ$HcHVHHD$HHtD$ L$LHHt HJSHu #uMEIԹ3HHHуHFHc΍PUHHu t$(H|$ AL33RuHUMEIԹ]I>H&L\$pI[0Ik@IA^A]A\_^@UH HHMHH ]@UATAUAVAWHpHl$@H]`HuhH}pHZGH3HE(3HMMLLtAdH‹Hfff9tHHuWHHu WHH+y WHHuWO_TI3FMkIQP?cHcHHHH;w HHHkcH+Ht$@Ht1H\$8H\$0D$(AM3ҋψHt$ QHDHHH3HPHыMHcSLMLHL~u$ITMFIչEHME3ɉEHEE3HD$03D$(H\$ LeNu H] uISuMFIչP%HNRHLu4HAPHM(H3H]`HuhH}pHe0A_A^A]A\]LHH|3HHHOM'3H(H HtHPH(H(H D$8Htt 3H@IE3HչfD$8H rtOHD$@Hu  JHT$PHL$8HHHAHBHAHBHHLD$PHHL$8NHqOH$Hp_^]@UH HH H ]@UH HHM8~H ]@UH HHM8^H ]@WH`HD$ H\$pHHuHQE3H{fD$(HL$(MfD$(H8NHD$0HuHtfD$( D$0HT$@HL$(HHHAHBHAHBHHHT$@HL$(}M薺H\$pH`_@UH HHM(~H ]@UVWHpHD$HH$Hm>H3H$`HHHD$ Hu 3H\$8!HHL$@H|$XHCL$@AH3HL$ HHL$(HuRHHLD$ HLLLD$(HT$ HA؋,HAHL$ HT$(HtLHAPHL$ HtHPHL$8~>HL$`H3L\$pI[ Is(I_@UH HHM8=>H ]@UH HHM H ]@UH HHM(辏H ]HT$WH0HD$ H\$@H3D$PHD$PIHt1HyDHs3HHHH\$@H0_@UH HEPt ePHMH H ]HT$UVWH0HD$(H\$PIIHD$hMu 3H\$ !I?HHD$ Hu WHD$hHMHLH(yDLH3*H?HH\$PH0_^]@UH HHM >H ]@UH HEht ehHMXH ]@WH0HD$(H\$@HHD$ HT$ H|$ u HH$LD$ HHHL$ HtHPHH\$@H0_@UH HHM nH ]HT$UVWH0HD$(H\$PIIH3ۉ\$hHD$hMuH\$ !I=HHD$ Hu 谧HMHLH yDLHI3{H >HH\$PH0_^]@UH HEht ehHMX谌H ]@UH HHM ~H ]HT$WH0HD$ H\$@Ht$XAH3D$PHD$PIHLAP8y DDH3謩HHH\$@Ht$XH0_@UH HEPt ePHMHH ]HWATAUHHDŽ$HXHhHp ILH3Mu HHX!IGH ]@UH HHM`H ]@UVWHHD$@H$HH3HD$pHHHHL$H-)@3HD$0HD$8HD$ HHL$(Ht HPHL$(HHT$ PX؅HD$ HtsHL$(H;tHHL$(%HD$ HL$(Ht3HL$ %HL$(HHT$ PX؅@uHHL$H(@2HD$ HuHL$PH|$hHCL$P+HHuUHHLD$0HiLLD$8HT$0HA؋IH|$8Ht H+HL$(HtHPHL$ HtHPHL$8HtHPHL$0HtHPHL$Ht(HL$pH3uH$HĀ_^]@UH HHMH=(H ]@UH HHM0H ]@UH HHM8yH ]@UH HHM yH ]@UH HHM(~yH ]@WH@HD$0H\$PHl$`Ht$hIIHHu 3H\$(!H*HHD$(Hu ˓HD$ HHHT$X詖f|$XuHH菖HH}HHLD$ Hx^HHLHT$ CHH/HL$ HtHRH)H\$PHl$`Ht$hH@_@UH HHM(>H ]@UH HHM H ]HHPUVWATAUH@HD$0HXIMHL3ۉX Mu HHX!I(HHD$ Hu RH$HuH\$(g(HHD$(Hu  LMHI^DŽ$H>uLMHIHHHϔH](HS(HH\$pH@A]A\_^]@UH HHM H ]@UH HHM(ΑH ]@UH HꋅtHMxvH ]@UVWHHDŽ$H$H*H3H$DL$0LD$hHHT$HHL$@H$3H$f/H %HHD$`Hu &蔓3Ht,H͋ffWf9t HHuHu WƋSLL+IIv f$UHH$H$LL+fffffMtAftfHIHuHu Hzf8֒H$DH$HT$`H+ffffffffHHtD ftfHHuHu HAzf9AqHu HH\$p!H%HHD$pHu BH$c%HH$Hu H|$XHD$@HuHPE3賮HD$@HHLD$XH($ uőH|$XH|$8Hl$@HHLD$8H(萑H|$8u>D$ E3L H$HIHHLD$8H(JH$l$HHD$xHu %H|$`HL$8HHT$Tf|$TuHT$8HL$@>HT$8HL$@ѐHD$@HHLD$`Hx譐HL$8HLD$XHT$`莐HT$8HL$@D$PtHL$`HtHRH#L$PPHL$8Ht HPHl$HHl$H|$0H|$HLLD$HHT$hHL$@uLD$@IHչ責Hl$HHuH|$h!H#HHD$hHu HL$XHHD$PHt H!l$P蒏H #]H|$HHl$hHt)3#H"HHD$HHu OHL$XHH4H"HL$XHtHPH"H"H$H3蓭H$H_^]@UH HHMp.H ]@UH HH H ]@UH HHMXpH ]@UH HHM8pH ]@UH HHMx讋H ]@UH HHM`H ]@UH HHMhnH ]@UH HHMHNH ]H% H\$WH HHH u H\$0H _H LD$@HHD$@xH !L\$@LH\$0H _H\$WH H:HH? t.H LD$8HHD$8HxH  L\$8LHH\$0H _Ë3H%#H%#HH@SH H9HtH HHH;uH [HHH(H HtHPH(HHH(H HtHPH(HHH(H HtHPH(HHHHHHHt$ WH0HɋHH\$@Hl$HLd$PsDLD33҉D$(AHD$ uP3HHtCDL3Ảl$(HD$ ;t%HQ3Hl$HH\$@Ld$PHt$XH0_H3Ht$XH0_HHH\$WH HHHHHDRy.HH\$0H _@SUWH0HHHHt$PLd$XLl$`<3AL3ҋȉ\$(DH\$ 3ɍPDHHt,AL3ADd$(HD$ A;t HHHLl$`Ld$XHt$PHu_3HHH0_][@VWH8H\$PHH Hl$XLd$`HLl$0Htlc 3AL3ҋȉ\$(DH\$ 3ɍPDHHt,AL3ADd$(HD$ A;t HDH3Ll$0Ld$`Hl$XHHH\$PuHt xHH8_^@SH H HH3eHH [HHH%WH(H HtHPH(H(H HtHPH(H(H HtHPH(HHHHH\$WH HHHtHأHH\$0H _@UVWATAUAVAWHHD$pH$H5 H3H$DL$0MLLE3Ld$@D$`HT$`H$uHL$@HtHP@Ld$836 Dd$(Ld$ AL3ҋoP3ZHHt.|$(HD$ ALV3ҋ<;t HIH\$8Hu  H$yLcHHcB|%;3HHHtQLMHcHLH*t5 t%t"tPt!@萂̹W腂̹zK$H nLL$t5 t%t"tPt!@>̹W3̹(I,fFHHH\$8 Q E3Dd$(Ld$ AL3ҋP3HHt.t$(HD$ AL3ҋ;t H-IH|$hHu ~Hlt6Ld$HLD$HHHyxHH\$HH\$8;HL\$@L\$(HPVHD$ AE33H#y!HHL$@HtHR,Ld$XHl$@Mu ILd$H!IHHD$HHu 言DDd$(Ld$ ALu3ҋwDP3aHHt6Dd$(HD$ AL@3AAA;tHE3IE3Ht$hHu HELL$XLHHPhHHy2HL$XHtHPHkHL$@HtHPLd$PHL$XHLD$PHTyCHL$PHtHRHL$XHtHPHHL$@HtHPHXHL$8IDIHL$8Jy"sDd$(Ld$ AL3ҋ؍P3HHt.\$(HD$ AL3ҋ;t HRIH|$hHu ~Ht;Ld$HLD$HHH\$8H xHL\$HL\$8[~HIDIHL$8Iy-~̀|$0tHL$PHH\$8HHL$PHH\$8HHL$PHtHPHL$XHtHPH`HL$@HtHPH$H3EH$HĠA_A^A]A\_^]@UH HHM@^H ]@UH HHM8}H ]@UH HHMh}H ]@UH HHMXH ]@UH HHMHN}H ]@UH HHMh.}H ]@UH HHMPH ]@UH HHMh|H ]HMLtH<$HIfH<$IH3HLtfffff9t HHuHuWMtxL+MIE3HAtI;vWMtEx>HHEtffffffD9 tHHuAWMAHtH+AIMH\$IE3HMLt8HD$(fffHt$AftfHIHIIuMuHAzIHfAtLH\$@SVWHHD$PH%H3H$IIHH$Hy rLALAHaHL$@HL$HHL$8D$1LD$@HH)uBHL$8RHL$HFHL$@:HK( H W~LD$8HwHuBHL$8HL$HHL$@HK(| Hr W#LD$1H$HsuBHL$8HL$HHL$@HK(! H WLD$0HHuBHL$8AHL$H5HL$@)HK( H WmHL$@HL$@HL$8HL$8H$ H$|$0tHL$@xu ,HL$8xuhHHL$X虎HH$\{H$H$HC$|$0t(HHL$XTHT$1H @{H|$8D$1D$ LDD$0HT$@H$H$H$HC$HL$HLD$HHJHYu_H$XH$I HL$8HL$HHL$@}HK( H DH,H[uPH$H$ HL$8HL$HHL$@H& ZH FH$H$t HL$8HL$HHL$@H 3H$H3EH_^[@UH HH H ]@UH HHM@EH ]@UH HHMH%H ]@UH HHM8H ]@UH HH H ]@UH HHj H ]@UH HHJ H ]@UH HH* H ]@UH HH H ]@UH HHH ]@UH HHH ]@SVWHHD$0H5H3H$IIHH$Hy rLALAHqHL$( HL$  H$iLD$ HH; uEH$ HL$ U HL$(I HK(HWLD$(HH uEH$HL$  HL$( HK(H~WAHHL$8׉LL$ LD$(H$H=L$H$LC$HbH uEH$HL$ [ HL$(O HK(HDHH- uBH$HL$  HL$( HK(HLH &H$bHL$  HL$( HK(?H53H$H33H_^[@UH HH{H ]@UH HHM(5 H ]@UH HHM  H ]@UH HHH ]@UH HHzH ]@UH HHZH ]@UH HH:H ]@UH HHH ]@UH HHH ]@SVWHHD$XHeH3H$IIHH$Hy rLALAHHL$@D HL$88 HL$H, D$0LD$@HzHi uBHL$H HL$8 HL$@z HK(H WqHT$@H$ H$LD$PHHu`H$H$HL$HHL$8HL$@HK({HqWLD$0HHruWaH$HL$`\H$HL$ DL$0DD$PHH!x%H$H$HC$HL$8LD$8HHu`H$H$HL$HHL$8HL$@HK(HwDHHu]H$HH$9HL$HHL$8yHL$@mHK( HgH ;H$H$HL$HHL$8 HL$@HK(H3H$H3蒏H_^[@UH HHH ]@UH HHM@H ]@UH HHM8uH ]@UH HHMHUH ]@UH HHH ]@UH HHH ]@UH HHH ]@UH HHzH ]@UH HHZH ]@UH HH:H ]@UH HHH ]@SVWHHD$8HH3H$IIHH$Hy rLALAH'HL$0dHL$(XLD$ H Hu6HL$(HL$0HK(THJWLD$0HHKu6HL$(tHL$0hHK(HWnLD$(H}Hu6HL$(%HL$0HK(HWH$HHL$@HH$7OmD\$ D$HT$0H$WHT$(H$DH$7mDHLH{uAH$HL$(NHL$0BHK(HKH uH$HL$(HL$0HK(H3H$H3胋H_^[@UH HHH ]@UH HHM0H ]@UH HHM(eH ]@UH HHH ]@UH HHH ]@UH HHH ]@UH HHH ]@UH HHjH ]@UH HHJH ]@SVWHHD$(HH3H$IIHH$Hy rLALAHWH$ LD$ HHu,H$HK(HW|$ vGHHL$0}HH$LjD\$ D$H$4jDHUHu)H$ HK(H3H v1H$HK(H3H$H3輈Hİ_^[@UH HH H ]@UH HHkH ]@UH HHJH ]@UH HH*H ]@UH HH H ]@UVWH@HD$@H$hHmH3H$0IIHH$Hy rLALAHyHL$ LHL$(@HL$84HL$0(H$H$zH$ tLD$ HH>uzH$  H$H$HL$0;HL$8/HL$(#HL$ HO(HWLD$(HDHuzH$ zH$kH$\HL$0HL$8HL$(HL$ HO(!HWHL$ RxuH$H$FHT$ HL$HL$H$HL$HCjHL$HtyHHL$pyHH$ ;HfH$H$pVH$H$H@HT$(H$=H$ 0fDHEHtHL$(uzH$ H$H$HL$0HL$8HL$(HL$ HO(HH H$ dH$UH$FHL$0HL$8HL$(zHL$ nHO( H3H$0H3H$hH@_^]@UH HH;H ]@UH HHM H ]@UH HHM(H ]@UH HHM8H ]@UH HHM0H ]@UH HHH ]@UH HHH ]@UH HH H ]@UH HHH ]@UH HHH ]@UH HHMH}H ]@UH HHZH ]@UH HH:H ]LWHHD$@I[IsHH3H$IHIHy rLALAHCHL$ HL$(tHL$0hHL$8\H$HHL$HuHH$(DbHZUH$THEUH$?H0UH$(*H$,|bDH2HauYH$HL$84HL$0(HL$(HL$ HK(HcH H$HL$8HL$0HL$(HL$ HK(EH;3H$H39L$I[Is I_@UH HH{H ]@UH HHM 5H ]@UH HHM(H ]@UH HHM0H ]@UH HHM8H ]@UH HH[H ]@UH HH:H ]@UH HHH ]@SVWHHD$(HH3H$IIHH$Hy rLALAH'H$LD$!H%Hu,H$sHK(hH^WqLD$ HH_u,H$.HK(#HW,LD$"HHu,H$HK(HWHHL$0-rHH$m@_D\$!D$D$ $D$"$H$(^T$ H:^DH|Hu)H$2HK('H3H XH$HK(H3H$H3|Hİ_^[@UH HH+H ]@UH HHH ]@UH HHjH ]@UH HHJH ]@UH HH*H ]@UH HH H ]@UH HHH ]LUVWHHD$@I[HOH3H$IIHIKHy rLALAHoHL$(2HL$0&H$HH$pxH$iH$ZLD$(HH,urH$H$H$pH$HHL$0HL$( HO(HW[LD$0HZHurH$oH$`H$pQH$HBHL$0HL$(HO(HWLD$ HHurH$H$H$pH$HHL$0HL$(HO(HWEHT$(H$ |$ tH$ H$ 0؅H$HH&؅H$PH$hHC$PH$pE؅H$ HL$HHH$ HL$HV_H$(H$@HC$(LD$8螐؅5u9t$8u @ H$(H$@HC$(H$PH$hHC$PLD$0-؅t=!T$ H$ /؅T$ H&؅HH$SlL$HH l؅xgL$HH$ HL$H,jHH$HL$HHHL$pkL$L$pH$HJDHHH$ 6H$'H$H$p H$HHL$0FHL$(:HO(HH H$ H$H$H$pyH$HjHL$0HL$(HO(GH=3H$H3;vH$(H_^]@UH HH{H ]@UH HHM(5H ]@UH HHM0H ]@UH HHHH ]@UH HHpzH ]@UH HHZH ]@UH HH:H ]@UH HHH ]@UH HHH ]@UH HHH ]@UH HH H ]@UH HHMHH ]@UH HHMH}H ]@UH HHZH ]@UH HH:H ]@SVWH HD$HHH3H$IIHH$Hy rLALAHGHL$(HL$ xHL$0lHL$@`H$LD$(HHu\H$cHL$@HL$0HL$ HL$(HK((HWLD$ HHu\H$HL$@:HL$0.HL$ "HL$(HK(HWCLD$8HHu\H$yHL$@HL$0HL$ HL$(HK(>H4WLD$0H>H5u\H$HL$@PHL$0DHL$ 8HL$(,HK(HWYLD$@HѾHu\H$HL$@HL$0HL$ HL$(HK(THJW|$8v HL$(txHL$ _xHL$0Jxu |$8HH$IeHH$32RHT$@HL$PHT$0HL$xDL$8LD$PHT$xH$"HL$xwHL$PkxPHT$(H$x\HT$ H$ID\$8D$H$Q,DH=HluMH$HL$@?HL$03HL$ 'HL$(H:WH *H$HL$@HL$0HL$ HL$(H3H$H3\oH _^[@UH HHH ]@UH HHM(eH ]@UH HHM EH ]@UH HHM0%H ]@UH HHM@H ]@UH HHH ]@UH HHjH ]@UH HHJH ]@UH HH*H ]@UH HH H ]@UH HHH ]@UH HHMPH ]@UH HHMxH ]@SVWHHD$(H%H3H$IIHH$Hy rLALAHǺLD$ HH*uHK($HWH$CHHL$0eaHH$/NND\$ D$H$D+NDHHu)H$HK(H3H ҳ轻H$_HK(THJ3H$H3HlHİ_^[@UH HHH ]@UH HHH ]@UH HHH ]@UH HHH ]@UH HHH ]@SVWHHD$(HH3H$IIHH$Hy rLALAHѳ藸LD$ HHuHK(HWH$HHL$05_HH$u-LD\$ D$H$KDHHu)H$gHK(\HR3H 荹H$/HK($H3H$H3jHİ_^[@UH HH[H ]@UH HHH ]@UH HHH ]@UH HHzH ]@UH HHZH ]@SVWHHD$8HH3H$IIHH$Hy rLALAH!gHL$0HL$(D$ H$LD$0HHuHh3W#LD$(HcHuHdz3WLD$ HH9uHF3诵WHL$(kuH3艵 HT$0H$H$_X؅yDH3HbHT$(HL$hHT$0HL$@LD$hHT$@H"HL$@HL$hyyDH3H 覶DDD$ HH \_-H$/HL$({HL$0oHO( HH$H3gH_^[@UH HHKH ]@UH HHM0H ]@UH HHM(H ]@UH HHjH ]@UH HHMhMH ]@UH HHM@-H ]@UH HH H ]@SVWHHD$8HuH3H$IIHHL$@Hy rLALAHD$ HL$0OHL$(CHL$pHL$HLD$0HNHmuH"3軲WLD$(H%H$J?H$hH$H$@HL$8HL$@HL$HH$[2H$mIL$(aIW3H$H3U]H$HA]A\_^]@UH HHH ]@UH HHH ]@UH HHH ]@UH HHH(H ]@UH HHHXH ]@UH HHHcH ]@UH HH1H ]@UH HHMHuH ]@UH HHM@UH ]@UH HHM85H ]@UH HH@H ]@UH HHH ]@UH HHhzH ]@UH HHMXbYH ]@UH HHMX=H ]@UH HHM`H ]@UH HHM`H ]@UH HHMXH ]@UH HHH ]@SVWHHD$0H%H3H$IIHH$Hy rLALAHǧHL$(HL$ H$YH$JH$DLD$(HרHubH$ݽH$H$HL$  HL$(HK(HWLD$ HdHubH$bH$SH$DHL$ HL$(HK(!HWHT$(H$HT$ H$H$H$IyDH3;fHHL$8MHH$\:H$H$wH$H$aH$9DHyHu_H$/H$ H$HL$ ]HL$(QHK(HiH TH$H$H$HL$ HL$(HK(Hv3H$H3tWH_^[@UH HHH ]@UH HHM(uH ]@UH HHM UH ]@UH HHH ]@UH HHH ]@UH HH蛺H ]@UH HHzH ]@UH HHZH ]@UH HH:H ]@UH HHH ]HH\$WH zHH LD$@y54H LD$8ly4̋D$8H\$0+D$@H _̊D$@SH H+IHHJtLLH[HH [̊D$@SH H+IHHJtLLH HH [HAHA@UVWATAUHHD$0H$H9H3H$pMIHHL$8Hy r HyLHyLHءHL$ LD$ HHWu*HL$ HK(HW3Ht$(DH{ rH?HL$@DHD$@H+HHtftfHHuHu HAzf1A5AHT$pHL$@%x<3HL$ HLD$(HHL$py=u H^+DLD$(HwI&HL$(HtHL$ >@u*HL$ ^HK(HyDH I8EHI#u'HL$ HK(HFyH éΡAH 轡HL$ HK(VHL3H$pH3JRH$HĀA]A\_^]@UH HHM8H ]@UH HHM EH ]@UH HHM8H ]@UH HHM8H ]@UH HHM8H ]@UH HHM8mH ]HVWATHpHD$(HXHhHڶH3H$`MHHL$0Hy r HYLHYLH|3Hl$ H rHHL$8DHD$8H+ffffHHt ftfHHuHu HAzf)A2AHT$`HL$8}"x(HT$ HL$`踭y=u Ha(LD$ H{I*HL$ uHO(HyDH-I\DHIGuHO(H9yH ӧH çHO(H3H$`H3OL$pI[(Ik0IA\_^@UH HHM0H ]@UH HHM0H ]@UH HHM0H ]@UH HHM0H ]HVWATHpHD$(HXHhHJH3H$`MHHL$0Hy r HYLHYLH3Hl$ H rHHL$8DHD$8H+ffffHHt ftfHHuHu HAzf)Ar/AHT$`HL$8x(HT$ HL$`y=u H%LD$ HIHL$ muHO(HyDHIDHIuHO(AH79yH 3nH #^HO(H3H$`H3LL$pI[(Ik0IA\_^@UH HHM0.H ]@UH HHM0H ]@UH HHM0mH ]@UH HHM0MH ]@SUVWATAUAVHHD$8HH3H$MIHHL$XHy r HyLHyLH7]HL$ LD$ HHu*HL$ HK(HWLD$0HrHqu*HL$ HK(_HUW>LD$@H7Hnu*HL$ HK(HWLl$H3f|$@LDHl$(DH{ rH?HL$`DHD$`H+HHtftfHHuHu HAzf)A,AH$HL$`zxf3HL$ HLL$(MHH$<3HHfHHtL 3H]Jyu H!"DLD$(H:IHL$(輻HtHL$ @u*HL$ !HK(HyDH̔IEHIu'HL$ HK(dHZFyH F葘AH 5耘HL$ |HK(H3H$H3 IHĠA^A]A\_^][@UH HHMXNH ]@UH HHM H ]@UH HHMXH ]@UH HHMXmH ]@UH HHMXMH ]@UH HHMX-H ]@UH HHMX H ]@UH HHMXH ]@UVWATAUHHD$PH$HYH3H$MIHHL$XHy r HyLHyLHHL$ 53HL$8fD$8 Hl$@LD$ H/H^u*HL$ HK($HW_Hl$(Hl$0LH{ rH?HL$`DHD$`H+fffHHtftfHHuHu HAzf)A(AH$HL$`xe3HL$ LLL$(LD$0HH$3HIfHHtL 3IkFxHD$0HthHD$@LD$(HKIHL$(ͷMtHL$ @u5HL$0諷HL$ 'HK(ķHLD$8HIۻHL$8ݹ@u*HL$ ռHK(rHhDHIu'HL$ HK(1H'oDHFIuu'HL$ VHK(H1H $HL$  HK(H3H$H3DH$HĠA]A\_^]@UH HHMXH ]@UH HHM H ]@UH HHMX-H ]@UH HHMX H ]@UH HHMXH ]@UH HHMX͵H ]@UH HHMXH ]@UH HHMXH ]@SUVWATHHD$0HH3H$pMIHHL$8Hy r HYLHYLH;衐HL$ ޹3Ht$(LD$ HjHu*HL$ BHO(ߴHմW`H rHHL$@HD$@H+HHt ftfHHuHu Hzf#AHT$pHL$@\x/3HL$ yLD$(HHL$pwHL$ OLD$(HSIHL$(ճu'HL$ NHO(HoDHI/u'HL$ HO(H1H SސHL$ ڸHO(wHm3H$pH3kAHĀA\_^][@UH HHM8讲H ]@UH HHM eH ]@UH HHM8H ]@UH HHM8ͲH ]@UH HHM8H ]@UH HHM8H ]@UVWATAUHHD$xH$HH3H$MHH$Hy r HYLHYLH"蘍3Hl$0Hl$@Hl$8Hl$HHl$PHl$XDH rHH$DH$H+HHt ftfHHuHu HAzf)A!AH$H$wxyHD$PHD$(HD$HHD$ LL$8LD$@HT$0H$xCHD$@PHD$09Pu'HD$8H;uHD$H;HuHT$XHƾ ,LD$0H$IӴu  LD$@H Iu LD$8HIu HL$`̲fD$` HD$XHD$hLD$`HIHL$`uyHD$0HtDhEHmIuMDH?Inu/H =LD$PHIȳDHL$0蒯HL$@舯HL$8~HL$HtHL$PjHO(HH$H3=H$HA]A\_^]@UH HH軮H ]@UH HHH ]HVWATHpHD$(HXHhHzH3H$`MHHL$0Hy r HyLHyLH3H\$ H~ rH?HL$8DHD$8H+fffHHtftfHHuHu HAzfAAHT$`HL$8xHT$ HL$`蘣LD$ HIuWHD$ HthDH_I.u,DHIuH 4ߊHL$ UHN(zHpH$`H3n;L$pI[(Ik0IA\_^@UH HHM0讬H ]@UH HHM0 H ]@SUVWATHHD$@HH3H$MIHH$Hy r HyLHyLHHL$0[HL$(O3Ht$8LD$0HHu6HL$(HL$0HK(DH:WH{ rH?H$H$H+HHtftfHHuHu Hzf@AH$H$ xtD$ HHL$H .HT$ HpxOHL$0HHu'LD$8HH$+HT$8HL$(aHt HCLD$(HIHL$8Ht@u6HL$([HL$0OHK(HDHI-u3HL$(HL$0HK(H=H 5ЇHL$(̯HL$0HK(]HS3H$H3Q8HA\_^][@UH HH蛩H ]@UH HHM0UH ]@UH HHM(5H ]@UH HHH ]@UH HHH ]@UH HHzH ]@UH HHZH ]@UVWHHD$8H$HH3H$IHH$Hy r HYLHYLH\HL$(E3LD$0H rHH$H$H+ffffHHt ftfHHuHu HAzfAAH$H$E؅xID$ HHL$@*HT$ H؅x$HT$0H$(HT$0HL$(LD$(HJHѬHL$0Ht֪@u'HL$(HO(HoDHȀHu'HL$(جHO(uHk1H 覄HL$(HO(?H53H$H335H$H_^]@UH HH{H ]@UH HHM(5H ]@UH HHH ]@UH HHH ]@UH HHzH ]@UVWHpHD$@H$HݙH3H$`IIHH$@Hy rLALAHH$P2H$pH$ H$H$H$ ߤH$pHf!uH;3@HH$'HH$PHL$(HL$ H$eH$VH$HGLD$(HHuH3gW>LD$ HHuH}36W LD$0H}HuH 3WHT$(H$pH$"؅yDH[3HT$ H$44HD$8Ht HH3HD$HHD$8H$HL$HHH$HL$pL$HLHH_؅yDHO3(HD$HHD$8H$HL$HHH$HHL$pLHH؅yDH3~H$HHL$pZHH؅yDHג3~ZL$H$H$PA4؅yDH3Z~$H$PK؅yDH{34~HtHH.H DDD$0HH ?؋H$HbH$SH$DHL$ HL$(H$pH$PHN(HH$`H3/H$Hp_^]@UH HH@;H ]@UH HHP蛓H ]@UH HHpzH ]@UH HHpH(VH ]@UH HHpHX6H ]@UH HHpHH ]@UH HHpH ]@UH HHM(%H ]@UH HHM H ]@UH HHH ]@UH HHjH ]@UH HHHJH ]@UH HHM82,H ]@UH HHM8 H ]@UH HHM8H ]@UH HH@ʟH ]@SH H9AHt @H [Ht5t1LfHHu H [HH [H% WH [@SH HH Ht$ѡxH xHH [3H [HAHA@SH DD$4HHT$0LD$0fHHu H;y HH [@SH HH HtxH ܠxHH [H\$Ht$WH HqHHH;qHvHsHt$8H;HH\$0H _H\$Ht$WH HqHHH9qHvLHsHt$8H;HH\$0H _HAHA@SH HBMLAI+HHJt LIVHH [@SH HBMLAI+HHJt LIHH [@SH@IHL$ MHI@HAHHL$0HHBHAHD$(LD$8I+HHJ t LIHH@[@SH@IHL$ MHI@HAHHL$0HHBHAHD$(LD$8I+HHJ t LIHH@[HL$VWATH@HD$ H\$pHHHZH+ZHALALALAHH;v7HHuIB3HHHs3LD$hHT$hHL$(L&L\$(HHL$(X'H+HGHGHHGH^H9^vLfL;fvHOI+HHH t LMH_HH\$pH@A\_^HT$UH HHM`33&H ]HL$VWATH@HD$ H\$pHHHZH+ZHALALALAH?H;vHHuIB3HHHs3LD$hHT$hHL$(LL\$(HHL$(&H*HGHGHHGH^H9^vfLfL;fvVHOI+HHH t LMH_HH\$pH@A\_^HT$UH HHM`J033q%H ]LUVWATAUHHDŽ$I[HȌH3H$MHIKHy rLALAHېqtE3L$L$L$L$L$L$Ll$xL$L$Dl$`Ll$0D$HDl$LLD$HAUfHD$0Hu HyLl$8D$PDl$TLD$PfHD$8Hu Hɚy~Ll$@D$hDl$lLD$hfWHD$@Hu H}y2S(HD$HHt HeHIHD$`HD$ LL$pL$H$H6؅yDH3r H$H$襬HT$0H.H$H$胬HT$8H.HT$pH$dHT$@H.LD$\HL$0yGLD$XHL$0yy&̋l$X+l$\LD$HHL$8yLD$PHL$8,y̋D$P+D$H;LD$PHL$8PyLD$HHL$8טy̋l$H+l$PLD$XHL$@yXLD$\HL$@y7̋D$\+D$X;uSLD$PHL$0yLD$HHL$09y̋D$H+D$PD$`H-3pH$dH$WHL$pMHtH`H!LD$0H4qIuH83qpLD$8HqIǘuH|3EpLD$@HpIuH3pDD$`HmIuH3oDHmIuHj3oH qHL$@Ht%xHL$@HL$@IIHL$@HL$8Ht%xHL$8jHL$8IIHL$8HL$0Ht%bxHL$0;HL$0IIHL$0HL$xHtLl$xL$L$H$HtiL$L$L$H$Ht?L$L$L$HO(H3H$H3 !H$HHA]A\_^]@UH HHKH ]@UH HH)H ]@UH HH)H ]@UH HHMp)H ]@UH HHM0莠H ]@UH HHM8nH ]@UH HHM@NH ]@UH HHMHH ]@UH HHʑH ]LVWATAUAVHHDŽ$I[IkH#H3H$MHIKHy rLALAHlE3L$L$L$Lt$`Lt$hLt$pL$L$L$ALt$ D$0Dt$4LD$0AVfRHD$ Hu Hxy-Lt$(D$@Dt$DLD$@fHD$(Hu H,yLt$8D$PDt$TLD$PfHD$8Hu Hy HD$0Ht HLML$HT$XHL$xyyDH3RkHT$xH$HT$ HN'HT$XH$HT$(H/'H$H$HT$8H*LD$HHL$ hyLD$LHL$ y̋\$L+\$HLD$0HL$(ypLD$@HL$(yŐD$@+D$0;LD$@HL$(ƑyLD$0HL$(My̋\$0+\$@LD$LHL$8yyLD$HHL$8y̋D$H+D$L;uOLD$@HL$ (y}LD$0HL$ y\̋l$0+l$@H3PiHL$xHL$XMtIILD$ HiI}uHB3hLD$(HiIQuH3hH$fDŽ$ HD$8H$L$HniIMH$LuH3jhDHfI:uH3@hDHeIuH]3hH iHL$8Ht%xHL$8HL$8IIHL$8HL$(Ht%xHL$(HL$(IIHL$(HL$ Ht%xHL$ HL$ IIHL$ H$HtL$L$L$HL$`HtLt$`Lt$hLt$pH$HtL$L$L$HN(rHh3H$H3fL$I[8Ik@IA^A]A\_^@UH HH蛊H ]@UH HHMx"H ]@UH HHMX!H ]@UH HH"H ]@UH HHM ޘH ]@UH HHM(辘H ]@UH HHM8H ]@UH HHM0BH ]@UH HHH ]@UVWATAUHHD$hH$Hy}H3H$MILH$Hy rLALAHeH$vH$H$H$H$@H$p{HL$HHL$@HL$8H$HH$h9H$@*H$Iu @CIH$3 HH$sLD$PHaHuH3dWLD$HH'eHuHۈ3cWLD$@HdHUuH*3cW}LD$8HdH$uH3rcWLLD$0HdHˌuH3AcWHT$HH$HT$@H$hHT$8H$@HH$@AuHH$@XHD$XHt HH3D$0D$ L$@L$hH$H$7y=:tDHI3bb,H$PyDH39bH$HD$XHD$pHD$`H$@H$HH$hHL$pHHzH$jDL$0LHHV(HD$pHD$`H$HD$XH$@HL$pH+H($f$LL$0AH$H$L$IH$L;v~H$L$H H;wI;s ~33H;]r~H{ rHKHKLHD$0HH|$XHuH HT$hH+HHL$`HH+HH;sLHAHD$`HH;v<~HL$`H|$XHD$PH$PH$XHH+Hu3H;v~H+H($Pf$LL$0AH$HL$PL\$XIHD$`L;v}HD$`L\$XH H;wI;s}H;]r}H{prHKXHKXz~LHD$0HH$Hu3H$H+HH$HH+HH;sLHAH$HH;v}H$H$H$H$ H$(HH+Hu3H;v|H+H($ f$LL$0AH$H$L$IH$L;vm|H$L$H H;wI;sI|H;]r=|H{HrHK0HK0.}LHD$0HFH|$xHu3H$H+HH$HH+HH;sLHAH$HH;v{H$H|$xHD$pH$`H$hHH+Hu3H;v{H+H($`f$0LL$0AH$0HL$pCL\$xIH$L;v0{H$L\$xH H;wI;s{I3H;]rzHxM;erzIpH$PH$H AHz3T0AH3TAHH3qTAH~3XTH$H$0HT$@HQHT$PH$0HT$ H2H$H$0ݍHT$(HHT$pH$0辍HT$HHL$HL$@I{yL$HL$@zyz̋$+$L$HL$ zyEL$HL$ tzy!̋$+$;L$HL$ zyL$HL$ zy̋$+$L$HL$(6zyL$HL$(yyg̋$+$;L$HL$(yy*L$HL$(Yyy̋$+$LD$0HL$HyyL$HL$Hyy̋$+D$0;'EHOOH$HvzuHC{3|QAEH'OHFzuHz3LQALD$@HmQHyuHy3QALD$ HCQHjyuH?y3PArLD$(HQH;yuHx3PACLD$HHPH yu*Hw3PAH[w3tPAH$HL$PH$HL$pAH vRHL$HHt,Hwx&HL$H!wHL$HHIHL$H33HL$(Ht% wxHL$(vHL$(HIHL$(HL$ Ht%vxHL$ vHL$ HIHL$ HL$@Ht%vxHL$@vHL$@HIHL$@HL$xHtH\$xH$H$H$HtH$H$H$HL$XHtH\$XH\$`H\$hH$HtmH$H$H$H$$H$6eH$HK(#sHs3H$ H3H$X H A_A^A]A\_^]@UH HHKrH ]@UH HHdH ]@UH HHrH ]@UH HHH(frH ]@UH HHHXFrH ]@UH HHH#rH ]@UH HHH ]@UH HHH ]@UH HHMPH ]@UH HHH ]@UH HHMpH ]@UH HHM@H ]@UH HHM ~H ]@UH HHM(^H ]@UH HHMH>H ]@UH HHpH ]@UVWATAUHHDŽ$H$( H6dH3H$MIHH$Hy rLALAHRKH$]H$toH$eoH$HVoH$pGoH$8oE3L$L$L$L$L$L$L$L$L$L$L$L$ L$L$L$L$8L$@L$HLl$pD$PDl$TLD$PAUfqHD$pHu HqyLl$`D$HDl$LLD$HfkqHD$`Hu HqyFLl$@D$PDl$TLD$PfqHD$@Hu HEqyLl$xD$HDl$LLD$HfpHD$xHu HpyLl$hDŽ$(D$,L$(f~pHD$hHu HpyYAH$HuH*|3CI@)L$HFHruH{3IWPHH$HH$%yDHz3HH$@H$hH$0HL$8H$HL$0H$HL$(H$HL$ L$L$$HAyDHy3JHH$H$hHT$pHCH$H$hHT$`H!H$H$h́HT$@HH$H$h誁HT$xHH$H$hHT$hHLD$XHL$poykLD$\HL$pnyJ̋\$\+\$XLD$PHL$`nyLD$HHL$`Pny̋D$H+D$P;1LD$HHL$`tnyLD$PHL$`my̋\$P+\$HLD$\HL$@'ny|LD$XHL$@my[̋D$X+D$\;LD$HHL$@my'LD$PHL$@Ymy̋\$P+\$HLD$\HL$hmyLD$XHL$h my̋D$X+D$\;LD$HHL$h0myLD$PHL$hlyd̋\$P+\$HLD$\HL$xly8LD$XHL$xjly̋D$X+D$\;uOLD$HHL$@lyLD$PHL$@ly̋l$P+l$HHu3DH$HH$;H$.H$!LD$pH]EIluHt3ZDLD$`H9EIluHs3.DLD$@HEIluH)s3DLD$xHAIXluHmr3CH$PjfDŽ$P HD$hH$XL$PHDITlH$PSj!HL$hHt%jxHL$hljHL$hIIHL$hHL$xHt%djxHL$x=jHL$xIIHL$xHL$@Ht%5jxHL$@jHL$@IIHL$@HL$`Ht%jxHL$`iHL$`IIHL$`HL$pHt%ixHL$piHL$pIIHL$pH$8HtL$8L$@L$HH$HtL$L$L$H$HtL$L$L$ H$HtL$L$L$H$HtZL$L$L$H$Ht0L$L$L$H$H$WHN(eHeDH?I/juHIjuHn3 AH nBHL$hHt%hxHL$hgHL$hIIHL$hHL$xHt%gxHL$xgHL$xIIHL$xHL$@Ht%gxHL$@gHL$@IIHL$@HL$`Ht%{gxHL$`TgHL$`IIHL$`HL$pHt%LgxHL$p%gHL$pIIHL$pH$8HtwL$8L$@L$HH$HtML$L$L$H$Ht#L$L$L$ H$HtL$L$L$H$HtL$L$L$H$HtL$L$L$H$\H$nUHN(ccHYcH$H3WH$( HA]A\_^]@UH HHbH ]@UH HHTH ]@UH HHbH ]@UH HHH(bH ]@UH HHHXbH ]@UH HHHsbH ]@UH HH+H ]@UH HHKH ]@UH HH+H ]@UH HH H ]@UH HH+H ]@UH HHH ]@UH HH0H ]@UH HHMpoH ]@UH HHM`oH ]@UH HHM@noH ]@UH HHMxNoH ]@UH HHMh~H ]@UH HH`H ]@UH HH`H ]3HLtfffff9t HHuHuWMtxL+MIE3HAtI;vWMtEx>HHEtffffffD9 tHHuAWMAHtH+AIMH\$IE3HMLt8HD$(fffHt$AftfHIHIIuMuHAzIHfAtLH\$H\$Hl$Ht$WH ILL$PHZIHLH3axHH;wuf|]H f|]zHtHH\$0Hl$8Ht$@H _H!nAHHH\$WH HstHHH\$0H _@UHpHl$ HEH]hHQH3HE@HHM3EHul]HLD fEtAf'uIfAfuHHHAH;w HH_nH+HL$ LfEt#f:'u f'HfHHf:ufIHM\HUH\EHMz]HHM@H3{H]hHeP]@UH Hj EteHM>]H ]@UH Hj HM]H ]@SUVWATAUAVHpHD$0HPH3HD$hMMHHHL$(HT$`D$ HL$8[E3IH[LHuAHHL$8\HT$8H[D$ HL$8x\Hn\H 3HIfHIt E3HHL$8[LIH:[LHtZffffffIHL$8R[ML+LHHL$8[[3HIfHIt LIHZLHuH{ rH{H{3HfHHIHL$8ZH+LLHHL$8ZHT$8HZD$ HL$8i[H_[HHL$hH3_HpA^A]A\_^][@UH HHM`[H ]@UH HHM8ZH ]@UH HE te HM(ZH ]H\$VH HY3LD$8K3҉\$8gXuyX=uaT$8K@H|$0HIXHHXLD$8KHH$Xu jX HHBZHt HXH|$0H\$@H ^ËH\$@H ^LVWATHHD$8I[Ik HzMH3H$IHAD$0HT$0IK)XuW H$HL$hXHiHL$h'YHL$@XHT$@L%iIkyHL$@>YHL$h2YSD$(H\HD$ ALAQ 1WD$(HhHD$ ALAQ VD$(Ld$ ALAQ VHT$pH$HCT$pHHHL$(pHH$QHL$(Q$|H$HL$`PL EeL6eHHL$(qHH$gQHL$(cQH$HL$`xPL dLdHHL$(%HH$QHL$(QH$HL$`,PL dLzdHHL$(HH$PHL$(PH$HL$`OL )dLdHHL$(HH$PHL$(PH$HL$`OL cLcHHL$(AHH$7PHL$(3PHHWOD$ H$HOHHOH$OHH$H3H_^][@UH HHOH ]@UH HHM(OH ]@UH HHM(}OH ]@UH HHM(]OH ]@UH HHM(=OH ]@UH HHM(OH ]@UH HHM(NH ]@UH HE te HMPNH ]@UVWATAUH@ HDŽ$ H$ H6BH3H$0 MLHH$(H$3|$0MD$0|$@D$DeH|$HHVhHD$PD$XD$\fH|$`HgHD$h|$pD$tgH|$xHgH$DŽ$DŽ$hH$HfH$$DŽ$iH$HfH$DŽ$DŽ$jH$HeH$$DŽ$kH$HeH$DŽ$DŽ$lH$HdH$$DŽ$mH$H.dH$DŽ$DŽ$nH$ H)cH$($0DŽ$4oH$8HbH$@DŽ$HDŽ$LpH$PHSbH$X$`DŽ$dqH$hHbH$pDŽ$xDŽ$|rH$H]aH$$DŽ$H$H aH$DŽ$DŽ$H$H`H$DŽ$$H^`H$H`H$DŽ$$H[H$HH$DŽ$$H_H$H_H$DŽ$$ H$H$HT4DtAL$0IyN,6H$`JH$`HL4H]yH\4PD$(D$ L =^L6^HH$.H$hH$HC$hD$(D$ L ]L]H$8HH$HTIL$@H$XLC$@L$H$0LC$HH$HHIH$ID$(D$ L O]LH]HH$TH$hH$HC$hD$(D$ L ]L]H$HH$zHL$H$LC$L$H$LC$HH$0HHHH$0HD$(D$ L ]L\HH$zH$hH$HC$hD$(D$ L \L\H$:HH$GL$H$(LC$L$H$LC$HH$$HHHH$HH$ HH$GH$GH$GH$8GH$GH$`GD$(D$ L -[L&[HT4PH$80D$(D$ L [LZH$0H$HH$hFL$H$0LC$L$@H$XLC$@HH$XHHFH$XFH$FH$8FH\4PD$(D$ L ;ZL4ZHH$@D$(D$ L ZL ZH$0H$HH$pxEL$H$LC$L$H$LC$HH$HHEH$ED$(D$ L YLYHH$8xD$(D$ L YLYH$0H$JHH$ DL$H$0LC$L$@H$XLC$@HH$4HH/EH$(EH$EH$8 EH$DH$DHHH4\4@IDHH$0 H3H$ H@ A]A\_^]@UH HHzDH ]@UH HE0te0H(LDH ]@UH HH*DH ]@UH HH DH ]@UH HHCH ]@UH HH8CH ]@UH HHCH ]@UH HHCH ]@UH HH8jCH ]@UH HHJCH ]@UH HHX*CH ]@UH HH` CH ]@UH HHBH ]@UH HH8BH ]@UH HHBH ]@UH HHBH ]@UH HHjBH ]@UH HH0JBH ]@UH HH*BH ]@UH HH BH ]@UH HHAH ]H\$WH HHHHtH;tECHSH\$0H9WH _LVWATHHD$8I[ H5H3H$MHH$P3ۉ\$0IKu@H$HL$@Y@LHH$^HH$AH$@H\$(\$ L LN[HH$~H$H$?L$H$LC$LZHHL$@yHH$o@HL$@k@H$\@H$H$HC$3HfHHH H@=LHu#8>H$@{H$H$HC$HtEHw<Ht)Ht(DfEtfDHHHHHHfM$H$?D$0H$H3H$HHA\_^@UH HH:?H ]@UH HH?H ]@UH HH>H ]@UH HHM@>H ]HT$UH0HꋅE0HMh@H$H0]HT$UH0HE0HH0]HT$UH0HE0@HH0]@WHHD$@H$H1H3H$HHHL$8D$0HXHL$H=HwHL$p2HH$)2HH$2HH$1HhH$1H[H$1H6H$1HaMH$1HH$1HH$1H"H$l1HH$W1HH$B1HH$-1H$H$?1HH$1HsH$0HH$0HAH$0H4H$0H$H0H$0H$0H$0H$0H$@0H$hH3蚾H$Hp_@UH HHMP]0H ]@UH HH@:0H ]@UH HH0H ]@UH HHM /H ]@UH HHM /H ]@UH HH/H ]@UH HH/H ]@UH HHMx}/H ]@UH HHZ/H ]@SUVWATHHDŽ$xH"H3H$IIHHHL$@4HIHL$@3H-H$ .H#>H$Ƅ$HJH$0-H$-H[JH$X-HD$0E2>-HL$0r=)uAH"HD$0 y话HHL$HI3HL$H3HT$HH$B-H$u ,NH$B؅7D$!HOH$)!H$H$;!H,H$ HH$ HH$ H=H$ H0H$ H H$ HH$ H$ HL$8HH$ HL$8 H$  HH$/ HH$ HH$ HnH$HaH$HH$HH$H$H$HH$HH$qHH$\HH$GHH$2H$HHL$88HH$6HL$8JHkH$H^H$HyH$H,H$HH$HH$HH$oH$H$HrH$DHH$/HH$HH$HfH$H9H$HDH$H7H$HRH$HH$HH$rH{H$]HnH$HH$H$ZHKH$H^H$HqH$HdH$H?H$Hj8H$HH$HH$HH$uHH$`H$H$rHcH$5HvH$ HH$ H|H$H$HL$8HH$ HL$8 H"H$HM7H$HH$HH$mHH$XHH$CHH$.HH$H$H$+HH$HWH$HJH$H%H$H`6H$HH$HH$pHH$[HH$FHH$1HH$HH$ H$ HL$8HH$HL$8"H$ H4H$H'H$HBH$HH$wHH$bHH$MH$HHL$`SHH$QHL$`eHH$HyH$HH$HGH$H:H$H$pHT$0H$H$pHHHL$`LHHL$8HH$HL$8H$HT$0H$H$HH$HHL$`LHHL$8_HH$HL$81H$HT$0H$H$6HHt3HL$8)LHH$HH$H$H$HT$0H$H$HH2H$LHH$HH$CH$TH$HT$0H$H$YHHH$MLHH$)HH$H$H$0HT$0H$H$0HH+2H$LHH$HH$gH$xH$XHT$0H$H$X}HH1H$mLHH$0IHH$H$0H$HT$0H$H$ HH$HH$0LHH$XHH$H$X3IIHfHLAIH=fHHyH$IHHI@HۧHHHH$p^H$pH$ H$p H$H$HC$L$(H$@LC$(HL$ LHH>HH$eH豣H$ H$H}H$vH$HgH$X3H$H3VH$HĠ_^]@UH HHH ]@UH HHHH ]@UH HHH ]@UH HHH ]@UH HHpH ]@UH HH zH ]@UH HHM`]H ]@UH HHM8=H ]@UH HH H ]@UH HHM8H ]@UH HHM8H ]@UH HHM8H ]@UH HH H ]@UH HHM8}H ]@UH HHM`]H ]@UH HHM0=H ]@UH HHM8H ]@UH HHM0H ]@UH HHM8H ]@UH HHM0H ]@UH HHH ]@UH HHM0}H ]@UH HHZH ]@UH HHM0=H ]@UH HHH ]@UH HHM0H ]@UH HHH ]@UH HHM0H ]@UH HH0H ]@UH HHM0}H ]@UH HHXZH ]@UH HHp:H ]@UH HH H ]@SUVWATAUAVHpHDŽ$H{H3H$`EEHHH$H$H$L$H$H$@H$HL$03H$H$hHe!HL$HrH~ r H~HH~HHL$POHD$@HV,H$(HH$8HH$ Hxu@HH$HT$@H؅ HT$@HHL$@H~ rHHH$PHD$8AHL$8Z؅L y+AHT$8HL$`tHH$ HL$`L /+AHT$8HL$`:HH$ HL$` HD$XH~ rHHH$@ Hw(H$@I H$H$HC$H$HH$`HC$HHD$8HD$ ELD$X؅LLD$HHT$PH$h؅H$H$HC$HL$0 H HL$0H$@HL$`Hx rHPHPHL$0HL$` HHL$0{HHL$0iH$H$HC$HL$0DHHL$02HcHL$0 H~ rH?HHL$`P HT$`H$Hx rHPHPHL$0H$ HL$` HHL$0HHL$0HT$XHL$0HHL$0wH$vIHHL$0ZH$pH$HC$pHL$05HnHL$0#HT$0I5 EtH$8H$ H$H$j H(H$% IHL$` L$ H$8LC$ L&'HH$薭HI H$ HL$8/ ux؅~ ؁H$T H$8E H$6 HL$PHL$HvH$h H$ HL$0LH$ H$@ H$ H H H$`H3豗HpA^A]A\_^][@UH HHH ]@UH HHJ H ]@UH HH* H ]@UH HH@ H ]@UH HHH ]@UH HHM0%H ]@UH HHH ]@UH HHhH ]@UH HHMH H ]@UH HHMP H ]@UH HH*H ]@UH HH8 H ]@UH HHH ]@UH HHM`H ]@UH HHM`H ]@UH HHM`H ]@UH HHM`mH ]@UH HHJH ]@UH HH*H ]@SUVWATHHD$0HH3H$MIHHH$XHL$( H$0HUH$`HD$ HHD$@D$HH$0HH$݈HT$ H谱؅HT$ HL$(^ HL$ C LL$(MHH؅x_HL$@؅xOL$HT$(HL$@K!=6u/L$0H$`Hu؅xH$0H3HL$ HtHL$@(H$`H$0HL$( HO(sHiH$H3gHĐA\_^][@UH HHXH ]@UH HHM(e H ]@UH HH0H ]@UH HH`H ]@UH HHM@.H ]@UH HHXH ]@SUVWATHHD$8HH3H$MAHH$XHHD$pD$xH$HL$pyusHD$HHD$0HeHL$HHHeH$E3LHH$HeH$`HD$0HD$@H$HL$0HHH$0Ld$(H\$ DDHH$PH$`@H$1H$"HL$pH H$H3 HA\_^][@UH HHXH ]@UH HHMp.H ]@UH HHM0H ]@UH HHH ]@UH HH`JH ]@UH HHM@H ]@UH HH H ]@UVWATAUHHD$@H$HiH3H$EALHHT$xH$HL$0aHD$8HD$HHT$0HL$8HIHL$PH|$(H\$ EDHHPHL$0I9H$H37H$HĐA]A\_^]@UH HHMxH ]@UH HHM05H ]@UH HHMHH ]HWATAUAVAWHHD$ HXHhHp LLE3LxLxLxLxLxLxLxLxLxAOH$Ht HDHILD$`H$HL$@bDyDH3H\$HHt$PH;v Ht$PHD$@HD$0H\$8(D$0fD$0H|$0H\$8H9t$HvKHt HD$@H;t6H;tCHu&H;_rHINtH;_rHHt$PAEHtHDHEHL$hHt5L|$hL|$pL|$xH$HtL$L$L$H\$HHt HAAL$I[8Ik@IsHIA_A^A]A\_@UH HHM@辕H ]@UH HH蛕H ]@UH HHM`辕H ]@UH HH?H ]LWH`HD$8I[Is HH3H$PHHIIHHL$h8HH$ xNy)H$ HK(HGH$H$E3H"H$bH ;H9t7LE3HT$@H$%HH$HL$@L$H$LC$D$(H#HD$ AAQ XL$H$LC$D$(HHD$ AAQ L$H$LC$D$(HHD$ AAQ rL$H$LC$D$(H`HD$ AAQ (zD$4HT$4H$0TuA~ H$H$ HMH$H$HC$H$0'u,H$UH$ GH3H$aH$[tH~ H$H$H$ HTH$H$HC$H$H$HC$Su;H$H$rH$ dH3D$0H$HL$0tH~ H$H$ H$ Hv|$0t8H$H$H$ H43nH$H$H$ H33H$gH$ YHK(NHD3H$PH3BL$`I[ Is(I_@UH HH{H ]@UH HH H ]@UH HHH ]@UH HHH ]@UH HHM@}H ]@UH HHZH ]@UH HH:H ]@UVWHHD$ H$HH3HD$xHHzlHL$PHL$( LD$(HT$PHNjuHHL$(Ht$0HD$0LD$HIHCH=D fu/HDH|HL$(hHL$P\3Ht$0IHCH=fu,HCH&HL$(HL$P3fHt$0IHCH= fu,HCHHL$(HL$P3HL$(HL$PHL$xH3蟄H$HĀ_^]@UH HHMP]H ]@UH HHM(=H ]LUVWATAUH`HD$@I[HH3HD$PHHIK3I[HI[Hy rHIHHT$0HHL$08DhAH(@2HHuFH u AAHN(uxkLL$0A HN(uREE3LF(AQHu2%H\$ LL$8DBHu t!؁HT$8HHL$0Ht>Ht H0HL$8Ht HHL$PH3菂H$H`A]A\_^]@UH HHMHMH ]H\$Hl$ VWATH`HH3H$P3Hy LHD$DHyH\$@rHHHD$HLL$@E3HD$0HD$D3HD$(HD$PHD$ u =4t1=t*=t#zujT$@@HHuSLH~ rH?HD$HLL$@LHD$0HD$DHHD$(HD$P3HD$ u S HI,$H$PH3L$`I[0Ik8IA\_^@WHPHD$0H\$pHt$xH`H3HD$@HHHL$8Hy r HYLHYLD$(H?HD$ AAQ uHHbH rLLD$(HO?HD$ AAQ OuH;HH rLLD$(H>HD$ AAQ uHHJH rHD$(HG>HD$ ALAQ uHPHwHe3HL$@H3fH\$pHt$xHP_@UH HHM8-H ]LUVWHpHD$0I[HH3HD$hHHIK3ICICHIKHT$(HH\$(x,H8LD$ HiFxHT$ HHt HHL$ HtHmHL$hH3n~H$Hp_^]@UH HHM`-H ]HHH |HHL$SVWATAUH`HD$XLLH3$$HD$@HD$0H$HD$(Ht$ L$E3I3z$HHH@HHHD$H$HH@H輁HHD$PHD$@HD$0H$HD$(H|$ L$LI3btg$$TI+9$vHIHIfHIZ/L$t$DH\$HH|$P HlzHcz Mt IH`A]A\_^[@UH HHMHH ]@UH HHMPH ]HT$UH@HEDH&H@]@SH HHT$@HD$@u~ \HL$@HzH [LWHpHD$0I[Ik HH3HD$hHHIK3ICICHy rHIHt+HHL$8HHHHHL$8HT$ Ht؅x8HT$(HL$ u؅~؁HT$(H~H|$ t HL$ HL$(Ht[HBHL$hH3CzL\$pI[ Ik(I_@UH HHM` H ]H\$WHPHHHHL$ HHD$pHT$pHHL$pyHt5H\$`HP_HH\$`HP_H(HHHIPHtKH(H\$WH 3HALyHO@HHCPuH\$0H _H HHCPH LxHCPHHHCPxHCPHH HCPx(HCPHH0HCPH HH8HCPH @@@HCPHHHHCPH @PHCPHHXHCPH @`HCPHHhHCPH jHHpHCPH K@xHCPHHCPH ǀHCPHHCPH ǀHCPHHCPH v HHCPH , ǀHCPHHCPH ǀHCPHHCPH ǀHCPHHCPH T HHCPH ǀHCPHHCPH ǀHCPHHCPH b ǀHCPH HHCPH HHCPH ǀ HCPH(HCPH I ǀ0HCPH8HCPH ǀ@HCPHHHCPH HPHCPǀXHKPH`HKPH\ ǁhHKPHpHKPH ǁxHKPHCH\$0H _H\$WH`E3HHD8AuDHKPHT$ HHHAHBHAHBHAHBHA HB HA(HB(HA0HL$ HB0HCHHHAHGHAHGHAHGHA HG HA(HG(HA0HG0AH\$pH`_H\$WH`E3HHD8IuDHKPLcCLLT$ IHk8HD IHD IBHD IBHD IBHD IB HD IB(HD HL$ IB0A@CHHHHAHGHAHGHAHGHA HG HA(HG(HA0HG0AH\$pH`_H\$Ht$WH3HH@8q8WuHy+HOPLD$XHIHAI@HAI@HAI@HA I@ HA(I@(HA0HL$XI@0HLD$ IHAwHI@HAI@HAI@HA I@ HA(I@(HA0I@0HHL$ HHBHAHBHAHBHAHB HA HB(HA(HB0HA0GLOH;}ULD$ AHOPHcЉGHHk8H IHD I@HD I@HD I@HD I@ HD (I@(HD 0I@06HD$ HH HHHKHHHKHHHKHH HK HH(HK(HH0HK0L$I[IsI_@UVWHHD$ H$H-H3H$IHHyu P38WuHЅyHOPLD$`HIHAI@HAI@HAI@HA I@ HA(I@(HA0I@0GHLD$(HL$`HIHAI@HAI@HAI@HA I@ HA(I@(HA0I@0څyHH$HT$(H$jt-HT$(H=6tHT$(H$=uHL$(HHHAHFHAHFHAHFHA HF HA(HF(HA0HF0H$H$H3qH$H_^]@UH HHH ]H\$Hl$Ht$WH`yIIHHu ExcLD$ HHDyDCHHL$ HHEHAHEHAHEHAHEHA HE HA(HE(HA0HE0AH\$pHl$xH$H`_H\$WH HHHLGHH\$0H _2@WHPHD$ H\$`Ht$hIHHH(IHOPHHHL_Mt]H^HI;vH rHGHGfD$ H{v;HCHxH;vH{ rHCHCfH{ rHCHCfIIIL\$PI[(Ik0Is8IA]A\_@UH HHMpH ]@UH HHMpH(H ]@UH HHMpHPH ]@UH HHM(H ]@SH ILB(HHD$00HH [@SH H9HuHHPH9SrHCH [@SH H9HuHHPH9SrHHCxH [H\$WH HHHHtH;tUHOHH+KH\$0HHHHH?HH _H\$WH H9HHuHCHkxH HH;HwH;HsH{HH\$0H _H\$Ht$WH0DL$@H3ɈL$(3HIHD$ H+H\$HHHHHHH?HHkxH+HHt$PH0_@SH H9Hu#HHPH9SrHCH [H\$WH H9HHHHAHHBuHHHH9KrHCxH\$0HH _H\$Ht$WH0HHHT$ HHAIHBHt$ Hu`HD$(HkxHH;^wH;^sBHt$HH\$(H\$@HL$ HHHAHGHH0_ H\$Ht$WH0DL$@H3ɈL$(3HIHD$ H+H\$HHHHHHH?HHkxH+HHt$PH0_3HAHAHAHH\$Ht$WH0DL$@H3ɈL$(3HIHD$ NH+H\$HHHHHHH?HHkxH+HHt$PH0_LL$ HL$SVWATAUH`HD$ MLHH$MH\$(H\$0HH#HK(HKP IT$(HK(IT$PHKPIHHKHt`I|$HH;v%H{ rHCHCfHFMHH$I4qH O33 OH8][@UH HHM8H ]@UH HHM8H(H ]HT$UH0HLM@MkxHMPHAMHE8HPIp33NH0]@UH HHMxMH ]@UH HHMx-H ]@UH HH H ]@UH HHH(H ]H\$Hl$Ht$WATAUH0HHHIH_ILL+IMIIIHHH?Hu3=H;vHHtH;tHNIH+HHHHH?HHHL$ HT$ HHFMHAHAQHwH;wvHkxH|$ Ht$((D$ HH;_fD$ wH;_skHt$`H\$(H\$PHL$ HHEHAHEHHl$XH0A]A\_H\$Ht$ WATAUH@LI3LMHIuLHIII+HLIIH?LHsIHI+HHHHH?HI;s/3LMĈD$(D$`HΈD$ L^xL[L;Hl$hvqLCHkIIH\$0Ht$8H+HHHHH?Ht&I;v5H+IHH<HHH?H(D$0HT$0MAHfD$0HsHl$hH;svHkxH7H;CwH;CsH\$pHt$xH@A]A\_@SUVWHHD$ HH3H$IIHHHL$P HL$xH$HHL$xHH$HHL$PL\$hMtbH^HI;vHD$XH|$pHCD$XfH$H@A_A^A]A\_^]@UH HHM0-H ]H\$Hl$Ht$ WH`3Hz IHl$@l$PrHBHBHl$8HD$HAHD$xLD$@AQHD$03ɉl$(Hl$ zuc\$xHH0HHuQHl$8AHD$xHD$0LD$@AQ3ɉ\$(H|$ buHWHW ~ ہHt HL\$`I[Ik Is(I_H\$WH HHHHtH;tHSH\$0H9WH _@SH H+MHHHJ~LLHIHH [@SH H+MHHHJ~LLHIeHH [E3HMAt HvWxTHt?AL+L+IHt%A tHHuHAzAHu HAzAH\$H|$HILt8Hw/3LHDfffff8t HIuMt LM+ 3LAWExmI+I tKHI+H+NMt0t(HIHuHzH\$H|$Hu HzH\$H|$H\$H|$ALVWATHHD$PI[Ik HJH3H$IHLISMCЀ9IKH3A8$t_3HD$@HD$HH} r HEHD$@ HEHD$@H\$ ALD$@AQ3=tt؁Hy'H rLGLGDH3]H$H~ rHVHVHL$XݪH$Hm؋E3L\$0L\$8H r HOHL$0 HGHD$0H$H$HC$HD$8L\$ ALD$0AQ3)t! ؁H$H$HHH$H38L$I[ Ik8IA\_^@UH HHH ]@UH HHzH ]@UH HHZH ]H\$UVATAUAVH0L3MD<HHuH\$hH0A^A]A\^]EH|$`E/E $LHL$xtPu_LD$xHL+ŋfffH~Ht&AtHHuHz@1Hu Hz@1Hŋ8tHHuWLHu WL AL+xQI(I+t5LL$xNL+MtA tHIHuHu Hz@0IA;IL33Ẻt$(Ht$ HcHI@H ;HHu(؁EL33ɉ|$(HD$ uJ~Y؁NHHIu=H3ɻu(H HIuHg3ɻKH6HH|$`tH6H\$hH0A^A]A\^]H\$WH HHHHtH;tHSH\$0H9WH _H\$VH HHHHE3LL$0D$0APu'*H3DyH\$@H ^ËL$0H|$8k9HHu#H,3EH|$8H\$@H ^DD$03H4LL$0LǺHu6HD3Ho5H|$8H\$@H ^ËT$0LHHϋD5H|$8H\$@H ^H_3蘁H\$@WH ^LATAUAVHHD$HI[IsI{ HtH3H$LIKE3Aމ\$0ILt$8HHD$ AE3AVJ NLHfHI,HHD$8HuHL$XHD$@HDt$4LL$4E3APHu%EDH3蔀\$0L$47HHuHN3g\$0DD$43H3LL$4LƺHIVHDD\$Hu3 INH+HI^HH+HH;sHCDIFH;vINI~Lt$pHH\$xH+Hu3H;vH+H(D$pLL$HH$AIf$xI~I;~v@HI;FwI;Fs*H\$@fFH$f>DH$LE3HHD$ tf='uQHL$@$@HHHHD$@H$LE3HHD$ ؅H\$@HuHLHD$HTHUHu3 HMH+HH]HH+HH;s!$(LD$hHCH\$@HEH;vHMH}H$HH$H+Hu3H;vЉH+H($LL$HH$AHf$H}H;}vHH;EwH;Es2wH\$@D$h$(iH\$@D$h$(SH\$@D$h$(=AA=t:D1DA$AH3AbAML$L$H$H$H$t IHL$t HAHA_[HVATHHrHXHxE3H9rLhLpHvUH_H;_vEH;H$t/HGH+HHHH,~LLHHoIED$`Dd$pLd$8AH$HD$0LD$`AQ3Dt$(Ht$ +zDufHt HD$@IHH@Ld$8AH$HD$0LD$`AQ3Dt$(Ht$ DEHHBHLH$HWHuI HOH+HH_HH+HH;sHCLHGH;v߆HOHoH|$@HH\$HH+HuIH;vH+H(D$@L$HT$PAHfD$PzHoH;ovrHDH;GwH;Gs[D$pEWAH3A`HL$L$H$H$H$t HAHĘA\^@WATAUAVAWH@HD$0H\$pH$MML3ۉ\$xHrH9rvII;vH;t/IGH+HHL$:H~LLHՄMgIvI9vvAI~I;~v1H;t/IFH+HHL$:H~LLHMfIuI9uvI}I;}v݄H;t/IEH+HHL$:H~LLH-MeH$Hv^HH,HD$ AE3APJ HHtoffffffHHlHHtFH$tMMIH؉D$xyDH3]3H~3H~\$xDHJ]H\$pH$H@A_A^A]A\_HT$UH0HHH0]@SUVWATHpHD$8HruH3H$`IILH$L$L$H$HD$@HD$HHD$0IH$HHHL$HHIHL$pH$HL$(H$HL$ D$LHH؅y$DH3\&'3HD$ AXL$AQ3}=uDHD$HHD$0HHL$HHHHL$pE3D$HH&t" ؁DHT3[DH[H$Ht~It%uH HHH\$VH Ht=DAL M H|$0@t HKHCH|$0H\$8H ^ @tH`HH\$8H ^H%u%u%t%t%t%t@SH AHLDLAtA@McPLHcL#IcJHCHHKAt HLL3IH [H(II8ML‹DAtALcALHcL#IcN IBHIJAt HHI3H#H(fffffffH; euHfuH%|sH\$Hl$Ht$H|$ ATH IY8HMHLCIHIEfD[uAAEtLMHHGH\$0Hl$8Ht$@H|$HH A\%r%r%r%r%~rH(H8csmt3H(5H\$DD$HL$VWATH@IALHك|$pxI+H\$`HH\$hH@A\_^@UH HHM8HM(HE(HHM0HE08csmt E E H ]LL$ DD$HT$SVWATH8MIcHD$ HHHH\$`ffffff|$pxH+H\$`HAD$ H8A\_^[@UH H} uLMxDEpHUhHM`H ]%p%p%p@SH HH joHD$8Hu Ho~H j\oHD$8H jJoHD$@HdoHLD$@HT$8BHHL$8DoHujHL$@2oH[jHH [@UH HH ]H('H؃H(H\$Hl$Ht$H|$ ATH MQ8HMAHIHHII\LEfDuAAEtLMHH(H\$0Hl$8Ht$@H|$HH A\%n%n%n%n%n%zn%fn%Rn%>n%*n%n%n%m%m%m%m%m%m%vm%bmH aDH\$WH H'H= H;sffHHtHH;rH\$0H _H\$WH HH=H;sffHHtHH;rH\$0H _%l%zl3f9MZuHcQ<< PEu f|  LcAk%*k%k@WH HC^H2-+HD$0H;tHH)^H _HL$0H\$@#hH\$0gDI3hDI3hHL$8DI3gL\$8L3H\$@HL#H3-+L;LDL]IL]H _HL$HH _?gH`HD$XE3HT$`HL$X}HD$PH|$PtAHD$8HD$HHD$0HD$@HD$(HX_HD$ LL$PLD$XHT$`3%"H$H$`H$HH_H `H{^H$H|_R^ L^H\HD$hH\HD$pzf^3jfH ef=^u jTf HNfHĈ%h%h%h%h%i%i%i%6h%"h%h%g%g%g%g% g%g%g%f%g%ng%jg%fg%bg%~g%zg%vg%rg%g%f%f%f%f%f%f%zf%ff%Rf%>f%*f%f%f%e%e%b%b%b%b%b%b3HAA H̋AHHHH@SH HH Ht H#cc H [H(Ot5 t%t"tPt!@̹W̹H(H(b3H(H(b3H(H(HuW9HuHa0H!uH(3HAA H@SH HH Ht H#cc H [@SH HH :bC3H [@SH Hx}DQA;}tAB;taD+HcABIcLcHHH ILAt5 t%t"tPt!@̹W̹̃C3H [H(x;Q}HHcHH(E3E3AQaHHcH HtIH@SH HH "aCH [@SH HH Ht H#cc H [@SH 3HHDB(3HC8C@CDHH [@SH HHI8Ht !Hc8c@cDH [H\$Hl$Ht$WH HHHuWd9t]9Hu39y@~)3Hxa;{@}\HC8H 0PfH;{@|HK8Ht Hc8c@cDHK`#3H\$0Hl$8Ht$@H _E3E3AQP`@SH EHHAt H_CHH [@SH yHt H t_CH [@SH 3HH(DB(3HCPCXC\HH [@SH HHIPHt HcPcXc\H [@SH HH(}_HKPHt kHcPcXc\H [H\$Ht$WH HH(H^DGX3E~"3HxNA;}IHGPH94t(HA;|HO(n^2H\$0Ht$8H _HOP3HO(I^E3E3AQ^H\$Ht$WH HH(Hc^;^X>x:;^XuH^HN(]H.} HFPHE3E3AQO^HN(]3H\$0Ht$8H _H\$Ht$WH yLcA HA;HuOL I;rK H;s @pEuAx xSwKHcAIoHt5{ HHcSH LMtHICH\$0Ht$8H _3H\$WH 3HHDB(Hg8g@gDHg0HOHCoy xS'HH\$0H _HYH\$Ht$WHHRH3H$3HDB(IHcPcXc\HIHL$ L3HCHC`CHL$ t$ [|$0u |$$r9t$0u|$$w u |$(v@sHؤHK(CHC Dn }RHHΈ oRH$H3?L$I[Is I_H\$HT$WH Hy(HHe[HKPHT$8HυA[H\$0H _@SH HXHHK8Ht Hc8c@cDH [H\$Ht$WH 9Ht=HyH;ys&H7HtHN HtHPHf HH;{rHK /[#H\$0Ht$8H _@SH 3HH DB(:HH [H\$WH 3HH DB('HGHGHgHO HGHXHGly PHHH\$0H _@SH0HOH3HD$(3?[DKLD$ Yt%D$ HT$ tH \HЊuubY؋HL$(H3 H0[̸HHrOH3H$HL$ D$ Y|$0u|$$HsH,HYOSOH$H3H%VY%RY%NY%JY%FY%BY%>Y%:Y%6Y%2Y%.Y%*Y%&Y%"Y%Y%2X%Y%Y%Y% Y%Y%Y%X%X%X%X%X%X%X%X%X%X%X%X%6X%W%W%W%nW%ZW%FW%2W%W% W%V%V%V%V%VV%V%~V%jV%VV%BV%.VHT$HL$HHD$(HD$XHD$ ALD$PVu D$0D$0D$0HHHT$HL$HHD$4HL$XWD$0HL$PWD$8D$89D$0KD$0D$(HD$PHD$ DL$0LD$X&Vu D$<D$<D$3H$PH3HhÐ (C^yLL$ LD$T$HL$HH4H3H$H$uW&>3H$tH$uHH$LD$0$H$u>$$=3!L$L$$HL$0BH$H3bHĨLD$HT$HL$HH3H3H$H$uW:=3HԈH$tL LHL$@F*H$HD$ L LHL$@HL$@@H$H$9$wBH$uW<3FH$LD$@HH$ H$$zK<3H$H3HLL$ LD$T$HL$HHo2H3H$H$uW;3~H$tH$uHiH$LD$0$H$u~<$$;3L$H$HL$0H$H3,HĨLD$HT$HL$HhH1H3H$XH$uW:3H$puW:3HwH$ptLGHL$@p*H$pHD$ L ʆLHL$@HL$@>H$PH$9$PwBH$xuW=:3FH$LD$@HH$xr H$$Pz93H$XH3HhLL$ LD$T$HL$HhH0H3HD$XD$PH$uW93nH|$puL"HL$(*0LD$PHT$(HL$pTu*:D$TL$T493L$L$T$xHL$(HL$XH3HhLL$ LD$T$HL$HXH?/H3H$HH$xuW83H$`$h$@$@Hc$@H &HLԆHL$0AL$`HL$0LHL$0AL$`HL$0RL4HL$0AL$`HL$0LHL$0mAL$`HL$0PLHL$05AL$`HL$0LDHL$0L HL$0wLلHL$0_LHL$0GLYHL$0AL$`HL$0}W63H$h$D$DHc$DH $HLHL$0LHL$0LhHL$0LHL$0LHL$0L׃HL$0rLHL$0xZLoHL$0`BL/HL$0H*LGHL$00W[53HL$0y9HD$ H$x9D$ wBH$puW53CH$xLD$0HH$pPH$xL$ z43H$HH3HX-e (@Xp)D_zLL$ LD$HT$HL$HHALD$8HT$XHL$PND$0|$0|QH|$hv D$0W/HvW*3HD$pH L"HL$08H/yHL$p-tJHD$pHH.HvW*3sHD$pHL"HL$0DHxHL$ptJHD$pHH.HvW?*3HD$pHL"HL$0zH)zHL$potJHD$pHH!.HvW)3HD$pHL"HL$0HwHL$ptJHD$pHH-HvW)3VHD$pHL"HL$0'HkwHL$ptGHD$pHHc-HvW")3HD$pHL"HL$0`HovHL$pUtGHD$pH H-HvW(3HD$pH L"HL$0l3zHL$0,HD$ H$9D$ wH$H$u WX$H$\uH$HH$HoH$t&L$HT$@H ou3%L$HT$@H$du3yH$$H$tjHL$@'H$H$'H$HDH=r3LcKHL$@L$HL$@L$$HL$@H$HD$ D$E3HT$@H $$t$"3H$HD$(H$HD$ E3E3H$H$w $H$Z $t+3ҋ$H$$a"3H$H3 HLL$ LD$T$HL$HHH3H$H$uW!3H$tH$uHvmH$LD$@$H$u"$$!3/H$HD$ L$L$H$HL$@tH$H3$HĸLD$HT$HL$HhHH3HD$XH$uW!3EH|$pt H|$xtHD$pt HD$xuW 3 A"3HL$0諱HmHL$ptAL3lHL$0$KHnHL$puWY 3"HD$pHALHL$0f$HL$0S$HD$ H$9D$ warFWhy#4BPz^lF<HR`|nS8D$.SSSSSSSSSSSxS &AJ/8SSSSSSSSSSSxLSHPICMS8ICIC0MSICH$ICyHT$@3%*%%%.%R%.%B%&%%n%j%f%b%%%%%%%fffffffHL$L\$M3LT$L+MBeL%M;sfAMAM;uL$L\$HH Y鴀H 销H )t@SH 33HHHHH uHfH o eH H cHOy  08HH H;s"fffHHt P@H HH;rHH uHH [H(H H ]H(lH(3H DB({H%%%H%H Hjy%H H(~H(3H DB(p{%H HHMH HHMHy " VHH H(v~H(H -HtHH(@SH HHH;s$fffffHHt 3R@HHH;r=4tD3H91tH HH DHtHPH H [H(H Htw3HrHsHtH(H(H eHtw3HRHSHTH(H 1ԉH(H!H r9H Ht 0zH%%%H(H 鄍p`bbbbbbbbtBBdT42p  4 2p  4 2p tdT 4 2P4 p`9؄2P4 p902P4 p:p4^88d 4 p2P2PdT 4 p(:$1Yf2P p`P0X:Ј+@2P2P2P,4 pp:Њ$7MYhw!ٌ0-!tٌ0-`P02P&4pp ;R̍B2P2Pd4 pX; P Bя2P2P2P2P2P p`P0;p0Pp#|&}  4 2pd T 4Rp2P p`0pH<Z@ 2P2P2P&4 p`Pp<B0`  4 2p2P2Pd 4 Rp< ŗ  4 2p20BBB  4 2p  4 2pBBBB20!td@t0!@t0! td@t0  4 2P! D0!t D0  4 2`!Ν0!4Ν0!4Ν0B p `!0a<1!40a<1!40a<1B p `t d 4R  4 2p2P# #4!p`P<0ߠ2P4 ph=СPǡ2P2P2P2P2P2P.de4d `pp=`8Uh{6£ 20==t"2P2P4p> pƦӦ2P2PT4 p`H>@@bƧT 4 R `EE4 d 2pEE4 d 2p  4 2p  4 2p202020202P2PR p ` P0p>ЮDiy2PR p ` P0>$K2PR p ` P0> İ  20  4 2p2P4 Rp>p E]20  4 2p2P4 Rp0?@e}20  4 2p p`0Pd 4 R p2P2Ph?p2P4 Rp?p E^2P2P?0øϸ  4 2p  4 2p2P4 Rp?`%>  4 2p  4 2p20d42p2P b @׽  4 2pd 4 R p!?7!d?7 p0P  4 2p  4 2p  4 2pd42 p  4 2pd42 p2P bH@Pj|d42 p  2Pp@ bp@8@8!t89!dt89 p0Pd42 pd 4R pd42 pd 4R pd42p  2P@ b@9@8dT42p  2pP0@2P2P+d4 pp@s:@H0?Snbd42 pd42 pd42 pd42 pdT42p  2pP0@2Pd 4 rp@;@@H @O|b42 pb  4 RpR042 pb  4 Rp42 pR0  RPA  bP0A2P.  p`0pA=<@pH@0X@(<0>d}  RP8A  RP8A4 p`8A$>>@H@H> d T 4 Rp d T 4 Rp!@>!T @>d4r p!,4?!T ,4?  4 r p`2P2P. p`P0p`APpXfd T 4 rpB20  4 rpbdT42p  4 Rp2020!L@!4L@!4L@  d 2p2P&4ppAZ`2P2P2P2P2P2P2P p`P0A @`0N -Ta2P2P2P2P2P2P2PB 0d#(T" 4!ppA @`)6^k 2P2P2P2P2P2P2P*4- *ppxBB0Pp(>s&8GVbBQcr2PB'p0pCrPB2Pp8CR2P2P2P2P$ 0p`C@`@^qB2P4 Rp] 20  4 2p!XE!4XE2p!@]E!4@]E2p2P2P2P2P R0] @`204dT42p  4 RprP$dW4VR p@RP d 4 r pt..RP td 4 tnRP td 4 tPRP  4 rpt"77RP d 4 r ptfRP td 4 t@RP td 4 tHHRP td 4 t0RP  4 rptpB  BRP  4 rpt )  ) RP  4 rptb w  w RP d 4 r pt    RP  4 rpt `RP  4 rpt2GGRP  4 rptrRP d 4 r pt02P4Rp^0p 2P2P,4 ppp^PP2P R0^BXXd 4 R pP2PT4 p`^` 4, (p02P2P2P2P2P2P2P2P2P& p`0p^0Pp0 5Ra(AP\gw2P2P+4 p`Pp8`z``$2P2P2P.4 p`Pp`  3o{!@^M!t@^M2P2P2P2P2P2P2P2P2P*4#  pp`!!!"0"P"p"""   , Y l {     !!+!7!F!R!]!j!v!!!T "<#DO!T "<#DORp`02P2P0p`ab$$#$S$ H0020R0d42 p2P& p`0pxb(p''H(2P2P2P2P2P.4 p`PpPd2P+p++++(())**2*H****++  4 2p2P(d 4 rpp0g2-@,s,,2P2P2P.d4 ppgP.p..0-e-p--. ..2P! 0pgz /...2P2P2P(d4ppgb 0@0`0@/o/z/////2P2P2P,4 p`PphZ22200y1111n22P2P(d4pphB543.3@342P2P2P(d4pp ijp7P7705^5n5557!77T!477T2p2P2P2P2P2P2P,4 p`PpHi99: :@:`:08k8x88889*9`9o9{9920  4 2p20202P2Ppi@<`<;;;<20202P2Pi==0=S=_=|=20  4 2p20  4 2p2P2Pi??@?c?o??2P2Pjp@@@#@/@L@2P2P0j0APA@@@ A20  4 2p  4 2p  4 2p  4 2p2020  4 2p2P bXjGFFF2020  4 2p  4 2p2P4 Rpj`II%I>I  t4rP!Vp`0MPMMPM 4 p!4Q7QxX!4Q7QxX  d 2p2P2P2P2P2P,4E Bppj0TPTpTTTR;RRRRRR SS.SGSZSpSSSSSS2P2P2P2P2P+ p`P0pjPWpWWWWTU"V,V02P2P1 T]4\Vp`pv#s2P2 4WNp`Pp(wb0w@RԆd42 pd42 pd42 pd42 p  4 rp  4 rpd42 pd 4R p  4 rpd 4R pd42 p2020  2pP0Pw2P Rp`0Pwc@PH0Ѝ"P_2020d42 pd42 pd 4R p20d42 pd42 pb42 p202020d 4R p42 p20202P2P2P2P2P8 &T""4! p`pxwИ0Pϕ$#Bl2P2P2P2P2P2P2P7 %44* p`Pp8xJ @`pəۙ#-i՝ߝ42 p  2Py  2Py$ $d4r pyg|g@8@8Ǣ  2P@y  2P@y$ $d4r p@yh|h@Х8@8GԤåݥ!8i!d8i  4 2p d T 4 Rp d T 4 Rp  RPhy4 p`hyi@HZͩ!(j!d(j  4 2p!`Xj!T`Xjt d 4 R!pͫj!Tpͫjt d 4 R2P2P2P2P2 = p`P0py`C:Q|Ҳ 5IXj~ijӳ2P2P2P2P2P- & p`P0p|"ж>˵PZ2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P/  p`P0p|@` Pp  л 00ͷܷ ` w    " : HWft ùѹ2P2PdT 4 p}0P`ȼ  4 2p  4 2pd42 p  4 2pdT42p  2P0}2P0 !d4 pp0}Sto@@8 [  2PX}2P2P2P2P6 $d! 4  ppX}$>>>DCPC\C2P2P2P2Pd4 p`GGH HDkDzDDMEGIGxGG  RP  RP2P2P2P2P2P2P2P2P. 0 p`0ps ďhHKH@ LHJK K@K`KKKK@HHHHHHHHHIYIoIIIIIYJgJvJJJJJK L-L 4LBB!M P Z k u óճ    (9J[m   ƴ״  !2CTf xǵ);L]l~2P2P4 R p0S^ibbb' T4 p `  4 Rp2P2P4 RpPs~bR0 d T 42p!! ! Td 4 2 p2P2P4 RpطPs~R02P2P T4 R p`Pp@ 2P-  p`P0p(N@_!7$!7<!7<!T7$d 42 p2P2Pd 4 RpPPp   RPx  bP0x2P,# p`0px@PH@XQD]  RP4 p`@H2P2PT 4 Rp`ȸ 2P2Pd 4 RpP d T 4 Rp2P2P4 Rp@et2P2P# #T4 r p`@@`2P2P2P4 Rph02P2P2P2Pd 4 Rp0Pp`!!T   4 r p`  4 2p2P2P2P4Rp DVesd42 p2P2P2P2P4 Rp`P @``d42 p2P2P2P).p`P0pbPp !!  d4t T2 !!Td 42p!S0!  d4S0t T2 2P2P2P2Pd 4 Rp&T_2P2P2P2PT4 p`  TY^cy!@!  d4@t T2 ! ط! 4 ط  2p`P! !  d4 t T2 2P2P2P2Pd 4 Rp0P@`  B p`P0(2P2P2PR p ` 0(@`X @`p2P2P2P2P2P2P2P2P p`P0P0Pp/,H]n+@U!3l!  d43lt T2   B p`P0H2P2P2Pr p ` 0HԻ@X0Pp%2P2P2P2P))T $4 Rp`p0;Fr}b2P2P2P2P$$T 4 R p `p2=b  4 Rp2P2P2P2P$$T 4 R p `Ppb2P2P2P2P 4R p`P&T_2P2P2P2P4 Rp`P0Pp@R02P2P2P2P T4 R p`8&R]2P2P2P2P  RP`  bP0`2P2P2P,! p`0p`@H@@X  00LA@ K V@Nt2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P R00Pp0 P p   0Pp`|   . < JXft2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P  T 4 R p` @ `       @  `       @ `        Mhv )7 E S a o }2P2P2P2P2P2Pd 4 Rp 0 P p   P v       2P2P2P2P2P R00` *8F d T 4 Rp  4 2p2P2P2P2P2P4 RpX0Pp!!T d4r p2P2P2P2P2P2P2P2P2 4) p`Ppp0PPWf~ &52P2P2P2P2P2P2P2P2P2P2P2Pp`P00Pp0 P p+6G^+GL     +7ey2P2P2P2P2P2P2P2P2P2P2P0 4>6 p`Pp"""#0#P#p#####^   !!"")"5"D"S"b"q" |"2P bt%$%@%$%d42 p  4 2p4dT42p  4 2pBB  4 2pB  4 2p2P2P0+P+*** +2P2P+,++++2020  4 2p  4 2p  4 2p  4 2p20202020202020  4 2pB  2P8  2P82P2P2P2P*p`0p8hH@68@p68556 63"414@4L4R4q4}4444Y5e5q5}55@6M6^6}66  RP`  RP`2P2P2P2P,' p`0p`+<h@9H@9H09P9p996677-7<7Q7r777778888899999202020  4 2p  4 2p2020202020  4 2p  4 2p  4 2p  4 2pd42 p20202020 t d T 4 r  4 2p  4 2p  4 2p  4 2p  4 2p  4 rp  4 rpd42 pd 4R pd42 pd 4R p202020202020T 4 R p `T4 p `  4 2p''t 4R`  4 2pd42 pd42 pd42 pd42 pd42 p  4 Rp  4 RpdT42pdT42p2020202Pd 4 pUT)U8U!UUD!TUUDd42 p20!VV!TVVd42 pd42 pd42 p20202Pd 4 p[YYY![ \$!4[ \$B  4 2p  4 2p  2Px  2Px$ $d4r px@`8@``8]^^___``m````  2P  2P$ $d4r p@c8@c8`a(bbbccccc d T 4 Rp d T 4 Rp!fof!Tfoft d 4 R! gg!T ggt d 4 R  2P2P2P2P2P2P2P2P2P2P2P> ,į(t$d 4 p3 @t8rrs s@s`sssss0hhhSމ  C ފ  )8GVe  4 2p  4 2p  4 2p2P bp!'(!t d 4'(  2P2P2P2P2P.4 p`Pp(0nÑ'Dd42 pd42 p  4 rp  4 rpd 4R p!ӕX!4ӕXd2p  B p`P0P2P2P2P2P2P2P"R p ` 0P@X0Pp!,:Hԗ  B p`P0x2P2P2P2P2P2P"R p ` 0x@XPpК Pcv4 abb  B p`P02P2P2P2P2P2P"r p ` 0\@XPpН Sfy4 abb  4 Rp20b20R0  RP4 p`@Hߡ  2P2P2P2P  RP  bP02P2P2P2P2P2P. . p`0pc @H@X @pP p  0ĢNak z   Χ  > d T 4 Rp! ɪ0!T ɪ0d4r p2P2P2P2P2P  2 P02P2P2P2P2P2P2P2P2P2P9 'dD#4C< pp  h@H0Ppа   @`ܫ#2Gg7FUds  ɮخ +cP  ȱ!ɲ!t ɲr0  4 2pB!P !! !t P ! P B `P0!0Nx!NX! 4NX!!!t dT0Nx2400BBBB202020  4 2pBBBB2P T4 p` ,- Etd4C PhB!!4BB2020  4 2p  4 2pt  4 2p2P2P2P4p`Pha2P4p02P2P2P2P2P.4 p`Ppb00m .'BSdnx2P2P4Rp`P&3?2P2P2P# #T4 r p`@INsz2P2P2P2P2P2PT4 p`h0Pp<AFv~!2INXgq8BQ[l}*4EVj|2P2P2P(d4ppbw2P4 Rp0K2P2P4 Rp`PP:~2P4Rp`,1B2P2P4 Rp`P 0`2Pd 4 Rp2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P' 'd#T4px @` @`0.?Pdu &7H\m~ 3FWhyB Zl}R j|=N_p/ GYj{H .g})t(9JZw4EVg{ ".?Sdu2P2P2P2P2P+4 p`Ppr0P$.38P]n2P2Pd T 4 rppbs2P2P2P4r p `P0 ?q2P2P2P2P2P2P2P2P14 p`Pp 0PppOx}lq.A]gx  4 2p  4 2p20BBB!@`4! T 4@`4! T 4@`4  d Rp  4 2p!x! d xRpP0!PW! T 4 PWbp`20BBB  4 2p2P2P2P2P2P2P2P2P6 $4_T p`PpP0Pp`Vu"96!!t42P2P2P2P2P2P2P2P2P2P2P& p`0p  @ `       @ '3?J]v,8DP[n          1 ? N Z f r        2P2P2P2P2P2P2P2P2P& p`0p0Ppp       $ 0 ; N g v     *5H_nz2P2P2P2P2P2P2P2P2P2P2P& p`0p0Pp@w 1@YhwSbq}  '6ET`lx 2P2P2P2P2P2P2P2P2P& p`0p @` W/HT`k~+7BRao{2P2P2P2P2P& p`0p'Wp~!1@NY2P2P2P2P2P2P2P2P2P2P2P2P2P.4 p`Ppx2Pp 0 P p    0o#2>JVbm S r&4CR^jv   2P2P2P2P2P2P2P2P.d4 ppp#0#P#p#####!;!i!u!!!!+"9"E"Q"]"i"t"""""""""2P2P2P2P2P2P2P& p`0p`&&&&&' ' $W$$$$$$$$$%*%8%C%V%%%% &&'&2&2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P,4E @p`PpX-0-P-p-----.0.P. p. ...P''''''''('(6(E(T(`(l(w((((((((()).)=)L)[)j)v)) ))) 8* J* u+ + +++ ,,',3,?, J,], l,{,,,,,,,,2P2P2P2P2P2P2P2P2P2P2P2P2P& p`0px34 4@4`444445 5@5 `5/7/e/q/}////////// 0%030?0K0W0c0n000000000011)151A1M1 X1k1111111 11o2 2 2 2 3.3:3F3R3^3m3|3333332P2P2P2P2P& p`0pP7 7@7`77555566|66666662P2P2P2P2P& p`0pH09P9p99977"8-8@8N888888882P2P2P2P2P2P2P& p`0p8@<`<<<<<=9:E:Q:h:k;|;;;;;; <<2P2P2P2P2P2P& p`0p0?P?p????0=d=====>>>>>?2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P5 #4p`PpF F@F`FFFFFG0G PG pG G G GG H0HPH?6@f@u@@@@@@@@ @ @ A B C kCCC DDD GE VE eE tEEEEEEE2P2P2P2P2P2P2P2P2P2P& p`0ppKKL0LPLpLLLLLHHHHIII6IDISIbInIzIIIIIIIIIJJJJKKK(K3KCKRK`KoK~KKK K  4 2p20202P2P2P2P2P2P2 470p`Pp0rQ Q@Q`QQQ`NNNNNOOPP&P9PiPuPPPPPP2P2P2P2P1 T443.p`pbSST0TQQRSSESPS`SSS2P2P2P2P1 T443.p`pb`VVVVPTTUUUUUUVV2P2P2P2P2P2P2P2P- 4 p`P0p@Z`ZZZZZ[ [VWOWhWtWWWWWWWWWXXLYXYcYvYYYYYYYZ2P2P2P2P2P2P2P2P2 4;4p`Pp^^^_ _@_`__@[[[[[[\F]R]]]p]]]]]]]]^^#^.^>^M^Y^d^2P2P2P2P2P2P)0p`P0prab b@b`bb__ `+`7`B`U`a+a6aFa]aiataaaaa2P2P2 4?8p`Ppeebbee2P2P1 T443.p`pbgh f\fgg2P2P2P2P2P2P2P)<p`P0pjk0kPkpkkk hZhhhhhhhhjj*j5jHj_jkjwjjjjjjj2P2P2P2P2P.4A <p`Ppn0nPnpnnklPlWmcmnm~mmmmmmmm2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P.4 p`PpxbPspsssss t@t`tt t t t u u@unn/o>oMo\okozoooo p p q q 7q Kq qq r r rrrrsss20202020d42 pd42 p2020r0r0  2Px4 r p`xP+@Pz80yy;zPz]zpz  2P4 r p`+@{8zB{{{{{2P2P2P2P2P2P2P2P2P3 !4)" p`Pp@` @{ |J|b|w||}_}n}}'VӁ2P2P2P2P2P2P2P2P2P8 &T*"4)" p`p` 0PpЊpd  Ԉ2\z2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2 4p`Pp`0Pp  Б   0P p cϋދ   / ߍ  ǎ (?   я  ,2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P9 '4+" p`Pp @`0Pp   У  04ds%4L a   I p  ۠  9 ]ϡݡ2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P5 #4%p`Pp0Pp  @ `    @``֤!<Tl     K8%T   : d  (3F߯= l  Ű  Cm4dT42p  4 2p2P2P%%4 #Pp$b2P2P2P' p`P0p$j0Ua!`P7!t`P7  4 2`2P2P2P2P1 T)4'"p`p$pп ׻Ӽ߼,8J*<Ͼ޾)/;202P2P2P.d746 2ppp&0Ppp9I  4 2p2P2P2P2P2P2P2P2P' p`P0pX(0PpAS8J2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P5 #4p`Pp(2  @`   @ `  `X   9F } W '6 E T c % 2 AP"Y&Q  4 2p  RP@/  RP@/  RP@/2P2P2P2P-4)"p`p@/=hhPH0H@H0S%]q2P2P2P2P,4 pp/` @@@BUp|R02P2P2P2P2P2P+ p`P0p/`4^s 32P2P2P2P# p`0p0r 0\ss}2P2P2P2P# p`0p00r@lGQ2P2P2P2P2P2P2P2P2P,42 .ppX0j0PPpNa~* <] <KZix2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P,Rp`P0p00Pp0Pp0P$Ne{ 8 E  $ 1gt:G2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P14Z Tp`Pp10PPp 0Pp 0Pp0Pp p Sbq 9HWfu$9HWoU h z     JYj|(<N*^t >Ui{ "|2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P2P0 N p`P0p`1b     @ `        @  `      }  ) ? U   7I Sp   1 @  {         ! - < K Z d 2P2P2P2P2P2P)2p`P0p3 @`MYh{ny2P2P2P2P2P2P2P)@p`P0p@3@`:Pg} 2P2P2P2 4p`Pph30P0|2P2P2P2P( (d$T 4 p3pp(2P2P2P2P2P2P2P.d4 ppH4R0Pp;Kn|et'6DS"18GVdps2P2P+4 p`Pp4zDPMYht2P*4 p`Pp5R $ ' TS4RL p `P2P(d4pp85B#@"s"#2P&4 p`Pp`5j$$0$$  rP52P2P p`05S0@'X' '0%%%2&&&&@'M'T'202P(T4pp5j)'(A(Q((  4 pB  4 2p  4 p  4 pd4 p2P.4! p`Pp902p0{11dT4p  4 2p2Pd 4 p:4P3332P2P2P2P""dT4 p@:05P5p5504_4j4u44452Pd 4 ph:65N6[62Prp`0:766  4 2p  4 2p2P&&d!T 4  p:98o9|92P# #tdT 4 ::9::2P2P2P2P% %d!T4 p;<0<P<p<;8;D;P;;;;202020  4 2p  4 2pd 4 R p20  4 2pd 4R pd 4 R pd 4 R p  B p`P00;2P2P2P2P2P p ` 00;X@BXB B@B`BB@A#A6AAALAAAAABBB t d T 4Rd42 pb  4 Rpb2P2PT4 rp`X;0FPFpEEEER02P2P2P2P""dT4 p;GGGGFFF GYGgGsG2P2P2P2P2P6 $4 p`Pp;JJJK0KHUHHHIJ@JKJVJsJ2P2P2P2P  RP;2P2P  bP0;2P2P2P2P2P. , p`0p;Sd\ P\@pRH@QXPQpQQQQ0RPRRRS S`KKKKTLfLuLM NBNMNXNN 5OO OP PP Q QQQ$R}R R d T 4 Rp!T:U]!T T:U]d4r p2P2P2P2P2P2P2P' p`P0p;`WWWWWX XVOV[VjVVVWW!W-W4 <0202P2P2P2P.d4 pp0<[[[[ZZZZ [/[A[K[  4 rp2P2P(d4ppX<B]p]\\\D]2P2P2P2P2P)p`P0p<_ _@_`__]]^S^`^^^^^^!d4__Pa!__Pa!d4__Pa!4__Pa!4__Pa!4__Pa2p!0aRaa!aaa!d aaa! 40aRaa! 40aRaa  T Rp2P0 !4r p`PpB:db3cddT4p  4 2p2020  t42P2P2P1 T4p`pCpjjjPhhWij)j3j!j*kb!t j*kb4 R `P  4 2p!m;ndc!tm;ndc!tm;ndc!tm;ndc  4 2`  RPG2P2P7 %t!d4 pGc@qHqq o^opoopp$q0q2qJqoqq2P1d"4! pphHt rXrFt2020dT42pdT42p!vve!Tvved42 p! w[w8e!T w[w8ed42 p[ [d pP0 !{{ f!||e! ||e!T||e! d 4{{ f! 4 d {{ f! d {{ f p!JXj~“ړ&҆&tԇ,~̈d6ڏ\f`Z‰pĊ0؅p‹ p „jXND8,"؃΃ăphBx֥V2 hL>(x:N9  :*(&%$# @\n & ots,tС6Vv¢Rt 4p@fJҝҜȠj.tV:ΛvZ.>??3@YAXPEAX@ZI_CxxThrowException_vsnwprintf ??0exception@std@@QEAA@XZE?what@exception@std@@UEBAPEBDXZ??1exception@std@@UEAA@XZc__CxxFrameHandler3 ??0exception@std@@QEAA@AEBV01@@Zmemset8_itowfwcschrfree_invalid_parameter_noinfo#??_V@YAXPEAX@Z??0exception@std@@QEAA@AEBQEBD@Z??2@YAPEAX_K@Zt_wtoiY__C_specific_handlermalloctwcspbrkcallocmemmove_s!??_U@YAPEAX_K@Z{wcstok_wcsdup_wcsnicmp_wcsicmpmemcpy_s9_itow_sx_wtoluwcsrchrmemcpyywcsstrc_stricmp#sprintf_sswcsnlenpwcsncmp<_encode_pointerW_malloc_crt_initterm_initterm_e=_encoded_null2_decode_pointer_amsg_exitZ__CppXcptFilterMSVCR80.dllC?terminate@@YAXXZ_unlock__dllonexitF_lock_onexit{__clean_type_info_names_internal8?_type_info_dtor_internal_method@type_info@@QEAAXXZ__crt_debugger_hook_??1?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEAA@XZ??4?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEAAAEAV01@AEBV01@@Z ?substr@?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEBA?AV12@_K0@Z ?npos@?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@2_KB?find@?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEBA_KPEBG_K@ZE?clear@?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEAAXXZ ?replace@?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEAAAEAV12@_K0AEBV12@@Z?find@?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEBA_KAEBV12@_K@Z??0?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEAA@AEBV01@@Z??0?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEAA@PEBG@Z??0?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEAA@XZ?append@?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEAAAEAV12@PEBG@Z`??Y?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEAAAEAV01@G@Z??4?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEAAAEAV01@G@Z?assign@?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEAAAEAV12@PEBG_K@Za?compare@?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEBAHPEBG@Z_??Y?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEAAAEAV01@AEBV01@@Z??4?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEAAAEAV01@PEBG@Zr??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QEAA@AEBV01@@Z^??1?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QEAA@XZw??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QEAA@PEBD@Z ?swap@?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEAAXAEAV12@@Za??Y?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEAAAEAV01@PEBG@Z ?replace@?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEAAAEAV12@_K0PEBG@Z ?rfind@?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEBA_KG_K@Z ?insert@?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEAAAEAV12@_KPEBG@Z`?compare@?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEBAHAEBV12@@Z??4?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QEAAAEAV01@PEBD@Z|??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QEAA@XZ?erase@?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEAAAEAV12@_K0@ZB??$?9GU?$char_traits@G@std@@V?$allocator@G@1@@std@@YA_NAEBV?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@0@PEBG@Z?append@?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEAAAEAV12@AEBV12@@Z/??$?8GU?$char_traits@G@std@@V?$allocator@G@1@@std@@YA_NAEBV?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@0@0@Z?append@?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEAAAEAV12@AEBV12@_K1@Z ?reserve@?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEAAX_K@ZM??A?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@QEAAAEAG_K@Z?_Xran@_String_base@std@@SAXXZMSVCP80.dllATL80.DLLTRaiseExceptionDeleteCriticalSectionvGetVersionExW$SizeofResourceLockResourceLoadResourceGetLastError:FindResourceWUCompareStringWLoadLibraryExWCCloseHandleCreateFileWWriteFileGetLocalTimeGetCurrentThreadIdGetCurrentProcessId5OutputDebugStringWGetCurrentThreadyGetComputerNameWLocalFreeLocalAlloc GetProcAddressGetModuleHandleWIFormatMessageWMFreeLibrary%SleeplstrcmpiWLoadLibraryWAGetSystemDefaultLCIDlstrlenWInitializeCriticalSection SetThreadLocale_GetThreadLocale~WideCharToMultiByteMultiByteToWideCharGlobalFreeGlobalLockGlobalAllocxGetComputerNameExWNQueryPerformanceCounterfGetTickCountOGetSystemTimeAsFileTime1TerminateProcessGetCurrentProcessBUnhandledExceptionFilterSetUnhandledExceptionFilterIsDebuggerPresentRtlVirtualUnwindRtlLookupFunctionEntryRtlCaptureContextEnterCriticalSectionLeaveCriticalSectionuGetVersionExASGetACPGetLocaleInfoAKERNEL32.dllUnregisterClassWLoadStringWUnregisterClassAUSER32.dlloNetApiBufferFreeNetServerGetInfoNETAPI32.dllDeregisterEventSourceReportEventW}RegisterEventSourceW*RegCloseKeyhRegQueryValueExW[RegOpenKeyExWxRegSetValueExWLRegEnumValueW_GetUserNameWRevertToSelfOpenThreadTokenSetThreadTokenSCloseServiceHandle#QueryServiceStatusExOpenServiceWOpenSCManagerWQueryServiceConfigWUnlockServiceDatabaseIChangeServiceConfig2WKChangeServiceConfigW QueryServiceLockStatusWLockServiceDatabaseLsaCloseLsaAddAccountRightsLsaNtStatusToWinErrorLsaOpenPolicyLookupAccountNameWDuplicateTokenLogonUserWFreeSidMCheckTokenMembershipAllocateAndInitializeSidfConvertSecurityDescriptorToStringSecurityDescriptorWSetSecurityDescriptorDaclAddAccessAllowedAcepInitializeAclqInitializeSecurityDescriptor0GetLengthSidpConvertStringSidToSidWLookupAccountSidWhConvertSidToStringSidW.RegConnectRegistryWADVAPI32.dllOLEAUT32.dllCoCreateInstance CLSIDFromStringACoInitializeoCoUninitializeole32.dllCryptProtectDataCryptUnprotectDataFCertGetEnhancedKeyUsageuCertVerifyTimeValidityJCertGetNameStringWECertGetCertificateContextPropertyCertCloseStore?CertFreeCertificateContext,CertEnumCertificatesInStoreVCertOpenStore=CertFreeCertificateChainrCertVerifyCertificateChainPolicyDCertGetCertificateChainCRYPT32.dll9??1CHString@@QEAA@XZ6?GetData@CHString@@IEBAPEAUCHStringData@@XZ?TrimRight@CHString@@QEAAXXZ?TrimLeft@CHString@@QEAAXXZ ??0CHString@@QEAA@PEBG@Z?Mid@CHString@@QEBA?AV1@H@ZN??4CHString@@QEAAAEBV0@AEBV0@@Z?Mid@CHString@@QEBA?AV1@HH@Z?Empty@CHString@@QEAAXXZ ??0CHString@@QEAA@XZ?ReverseFind@CHString@@QEBAHG@Z?SetCHString@CInstance@@QEAA_NPEBG0@Z?SetDWORD@CInstance@@QEAA_NPEBGK@Z&??0Provider@@QEAA@PEBG0@Z?OnFinalRelease@CThreadBase@@MEAAXXZ?DeleteInstance@Provider@@MEAAJAEBVCInstance@@J@Z\?GetObject@Provider@@MEAAJPEAVCInstance@@J@Z?ExecQuery@Provider@@MEAAJPEAVMethodContext@@AEAVCFrameworkQuery@@J@Z?Flush@Provider@@MEAAXXZ"?ValidateEnumerationFlags@Provider@@MEAAJJ@Z$?ValidateGetObjFlags@Provider@@MEAAJJ@Z&?ValidateMethodFlags@Provider@@MEAAJJ@Z(?ValidateQueryFlags@Provider@@MEAAJJ@Z!?ValidateDeletionFlags@Provider@@MEAAJJ@Z'?ValidatePutInstanceFlags@Provider@@MEAAJJ@ZG??1Provider@@UEAA@XZ?IsPropertyRequired@CFrameworkQuery@@QEAA_NPEBG@Z?GetCHString@CInstance@@QEBA_NPEBGAEAVCHString@@@Z?Release@CInstance@@QEAAJXZ?AddRef@CInstance@@QEAAJXZ?ExecMethod@Provider@@MEAAJAEBVCInstance@@QEAGPEAV2@2J@Z3?GetDWORD@CInstance@@QEBA_NPEBGAEAK@Z?SetCHString@CInstance@@QEAA_NPEBGAEBVCHString@@@Z??YCHString@@QEAAAEBV0@PEBG@Z?Setbool@CInstance@@QEAA_NPEBG_N@Z?Commit@CInstance@@QEAAJXZ?CreateNewInstance@Provider@@IEAAPEAVCInstance@@PEAVMethodContext@@@Z ?SetStringArray@CInstance@@QEAA_NPEBGAEBUtagSAFEARRAY@@@Z@??1CWbemGlueFactory@@QEAA@XZ?FrameworkLogoffDLL@CWbemProviderGlue@@SAHPEBG@Z?FrameworkLoginDLL@CWbemProviderGlue@@SAHPEBG@Z??0CWbemGlueFactory@@QEAA@XZT??4CHString@@QEAAAEBV0@PEBG@Z?Getbool@CInstance@@QEBA_NPEBGAEA_N@Z?ReleaseBuffer@CHString@@QEAAXH@Z?GetBuffer@CHString@@QEAAPEAGH@Zz?GetVariant@CInstance@@QEBA_NPEBGAEAUtagVARIANT@@@Z ?SetVariant@CInstance@@QEAA_NPEBGAEBUtagVARIANT@@@Z?Compare@CHString@@QEBAHPEBG@Z?Right@CHString@@QEBA?AV1@H@Z?MakeUpper@CHString@@QEAAXXZ??0CHString@@QEAA@AEBV0@@Zframedyn.dllNdrClientCall2RpcStringFreeWRpcMgmtIsServerListening_RpcBindingFromStringBindingWRpcStringBindingComposeW]RpcBindingFreenRpcBindingSetAuthInfoExWRPCRT4.dllGetUserNameExWGetComputerObjectNameWSecur32.dllACTIVEDS.dll9GetAdaptersAddressesIPHLPAPI.DLLgetnameinfoVWSAStringToAddressWWSAAddressToStringWWS2_32.dllHttpInitialize!HttpTerminate HttpDeleteServiceConfigurationHttpQueryServiceConfigurationHttpSetServiceConfigurationHTTPAPI.dll_recallocmwcslenrwcsncpy_sEswprintf_sSetLastErrorHeapFree#GetProcessHeap(wKh`(@t@\\ps36Ѧ1CWiReportingServicesWMI.DLL?NativeRpcActivateWebService@@YAJPEAG0PEAPEAUtagSAFEARRAY@@@ZDllCanUnloadNowDllGetClassObjectDllRegisterServerDllUnregisterServerNativeRemoteLogon__GenerateDatabaseAnyUpgradeScript__GenerateLatestDatabaseScript]+H`` E`6 E@6 E(6 E6 E5 E5 E5 E5 EP5 E(5 E4 E4 E4 E4 EP4 E 4 E4 E3 E3 Eh3 E 3 E2 E2 E2 E`2 E02 E 2 E1 E1 E1 Ep1 EX1 E`2 E 2 EH1 E(1 E1 E1 E0 E0 E0 E4 E0 E0 EP0 E(0 E6 E5 E/ E/ E/ Ep/ E0/ E / E/ E. E. E/ E1 E. E. E/ E1 E. EP. E4 E(. E. E- E- E- E4 Ep- E8- E- E, E, E, Ex, EH, E , E+ E+ E/ E4 E+ E+ E. E@+ E4 E + E. E* E* E4 E* E/ E/ E* Eh* EH* E(* E5 E* E) E) E 2 E) EP) E() E1 E) E( E( E( E( Ex( E / E`( E8( E( E( E' E( Ex( E' E( Ex( E' E' E' Eh' EH' E0' E' E& E& E( E' E0' E& Ex& E( E' E0' E& E8& E( E' E0' E& E% E% E% E@% E(% E% E% E$ E$ E$ Ex$ Eh$ EX$ EP[ E.?AVCAtlException@ATL@@P[ E.?AVCHrException@@P[ E.?AVexception@std@@9 E`6 E@6 E(6 E6 E5 E5 E5 E5 EP5 E(5 E4 E4 E4 E4 EP4 E 4 E4 E3 E3 Eh3 E 3 E2 E2 E2 E`2 E02 E 2 E1 E1 E1 Ep1 EX1 E`2 E 2 EH1 E(1 E1 E1 E0 E0 E0 E4 E0 E0 EP0 E(0 E6 E5 E/ E/ E/ Ep/ E0/ E / E/ E. E. E/ E1 E. E. E/ E1 E. EP. E4 E(. E. E- E- E- E4 Ep- E8- E- E, E, E, Ex, EH, E , E+ E+ E/ E4 E+ E+ E. E@+ E4 E + E. E* E* E4 E* E/ E/ E* Eh* EH* E(* E5 E* E) E) E 2 E) EP) E() E1 E) E( E( E( E( Ex( E / E`( E8( E( E( E' E( Ex( E' E( Ex( E' E' E' Eh' EH' E0' E' E& E& E( E' E0' E& Ex& E( E' E0' E& E8& E( E' E0' E& E% E% E% E@% E(% E% E% E$ E$ E$ Ex$ Eh$ EX$ EP[ E.?AVlength_error@std@@P[ E.?AVlogic_error@std@@P[ E.?AVbad_alloc@std@@`6 E@6 E(6 E6 E5 E5 E5 E5 EP5 E(5 E4 E4 E4 E4 EP4 E 4 E4 E3 E3 Eh3 E 3 E2 E2 E2 E`2 E02 E 2 E1 E1 E1 Ep1 EX1 E`2 E 2 EH1 E(1 E1 E1 E0 E0 E0 E4 E0 E0 EP0 E(0 E6 E5 E/ E/ E/ Ep/ E0/ E / E/ E. E. E/ E1 E. E. E/ E1 E. EP. E4 E(. E. E- E- E- E4 Ep- E8- E- E, E, E, Ex, EH, E , E+ E+ E/ E4 E+ E+ E. E@+ E4 E + E. E* E* E4 E* E/ E/ E* Eh* EH* E(* E5 E* E) E) E 2 E) EP) E() E1 E) E( E( E( E( Ex( E / E`( E8( E( E( E' E( Ex( E' E( Ex( E' E' E' Eh' EH' E0' E' E& E& E( E' E0' E& Ex& E( E' E0' E& E8& E( E' E0' E& E% E% E% E@% E(% E% E% E$ E$ E$ Ex$ Eh$ EX$ E`6 E@6 E(6 E6 E5 E5 E5 E5 EP5 E(5 E4 E4 E4 E4 EP4 E 4 E4 E3 E3 Eh3 E 3 E2 E2 E2 E`2 E02 E 2 E1 E1 E1 Ep1 EX1 E`2 E 2 EH1 E(1 E1 E1 E0 E0 E0 E4 E0 E0 EP0 E(0 E6 E5 E/ E/ E/ Ep/ E0/ E / E/ E. E. E/ E1 E. E. E/ E1 E. EP. E4 E(. E. E- E- E- E4 Ep- E8- E- E, E, E, Ex, EH, E , E+ E+ E/ E4 E+ E+ E. E@+ E4 E + E. E* E* E4 E* E/ E/ E* Eh* EH* E(* E5 E* E) E) E 2 E) EP) E() E1 E) E( E( E( E( Ex( E / E`( E8( E( E( E' E( Ex( E' E( Ex( E' E' E' Eh' EH' E0' E' E& E& E( E' E0' E& Ex& E( E' E0' E& E8& E( E' E0' E& E% E% E% E@% E(% E% E% E$ E$ E$ Ex$ Eh$ EX$ EV EU EU EU EPU EPT ES E@S E0S ER EpR EQ ES EPQ E0S EP EpP E0S E P EO EX$ E O EN EM E0S EI E0D EP[ E.?AVout_of_range@std@@`6 E`6 E@6 E(6 E6 E5 E5 E5 E5 EP5 E(5 E4 E4 E4 E4 EP4 E 4 E4 E3 E3 Eh3 E 3 E2 E2 E2 E`2 E02 E 2 E1 E1 E1 Ep1 EX1 E`2 E 2 EH1 E(1 E1 E1 E0 E0 E0 E4 E0 E0 EP0 E(0 E6 E5 E/ E/ E/ Ep/ E0/ E / E/ E. E. E/ E1 E. E. E/ E1 E. EP. E4 E(. E. E- E- E- E4 Ep- E8- E- E, E, E, Ex, EH, E , E+ E+ E/ E4 E+ E+ E. E@+ E4 E + E. E* E* E4 E* E/ E/ E* Eh* EH* E(* E5 E* E) E) E 2 E) EP) E() E1 E) E( E( E( E( Ex( E / E`( E8( E( E( E' E( Ex( E' E( Ex( E' E' E' Eh' EH' E0' E' E& E& E( E' E0' E& Ex& E( E' E0' E& E8& E( E' E0' E& E% E% E% E@% E(% E% E% E$ E$ E$ Ex$ Eh$ EX$ E`6 E@6 E(6 E6 E5 E5 E5 E5 EP5 E(5 E4 E4 E4 E4 EP4 E 4 E4 E3 E3 Eh3 E 3 E2 E2 E2 E`2 E02 E 2 E1 E1 E1 Ep1 EX1 E`2 E 2 EH1 E(1 E1 E1 E0 E0 E0 E4 E0 E0 EP0 E(0 E6 E5 E/ E/ E/ Ep/ E0/ E / E/ E. E. E/ E1 E. E. E/ E1 E. EP. E4 E(. E. E- E- E- E4 Ep- E8- E- E, E, E, Ex, EH, E , E+ E+ E/ E4 E+ E+ E. E@+ E4 E + E. E* E* E4 E* E/ E/ E* Eh* EH* E(* E5 E* E) E) E 2 E) EP) E() E1 E) E( E( E( E( Ex( E / E`( E8( E( E( E' E( Ex( E' E( Ex( E' E' E' Eh' EH' E0' E' E& E& E( E' E0' E& Ex& E( E' E0' E& E8& E( E' E0' E& E% E% E% E@% E(% E% E% E$ E$ E$ Ex$ Eh$ EX$ EV EU EU EU EPU EPT ES E@S E0S ER EpR EQ ES EPQ E0S EP EpP E0S E P EO EX$ E O EN EM E0S EI E0D E`6 E@6 E(6 E6 E5 E5 E5 E5 EP5 E(5 E4 E4 E4 E4 EP4 E 4 E4 E3 E3 Eh3 E 3 E2 E2 E2 E`2 E02 E 2 E1 E1 E1 Ep1 EX1 E`2 E 2 EH1 E(1 E1 E1 E0 E0 E0 E4 E0 E0 EP0 E(0 E6 E5 E/ E/ E/ Ep/ E0/ E / E/ E. E. E/ E1 E. E. E/ E1 E. EP. E4 E(. E. E- E- E- E4 Ep- E8- E- E, E, E, Ex, EH, E , E+ E+ E/ E4 E+ E+ E. E@+ E4 E + E. E* E* E4 E* E/ E/ E* Eh* EH* E(* E5 E* E) E) E 2 E) EP) E() E1 E) E( E( E( E( Ex( E / E`( E8( E( E( E' E( Ex( E' E( Ex( E' E' E' Eh' EH' E0' E' E& E& E( E' E0' E& Ex& E( E' E0' E& E8& E( E' E0' E& E% E% E% E@% E(% E% E% E$ E$ E$ Ex$ Eh$ EX$ E( E`6 E@6 E(6 E6 E5 E5 E5 E5 EP5 E(5 E4 E4 E4 E4 EP4 E 4 E4 E3 E3 Eh3 E 3 E2 E2 E2 E`2 E02 E 2 E1 E1 E1 Ep1 EX1 E`2 E 2 EH1 E(1 E1 E1 E0 E0 E0 E4 E0 E0 EP0 E(0 E6 E5 E/ E/ E/ Ep/ E0/ E / E/ E. E. E/ E1 E. E. E/ E1 E. EP. E4 E(. E. E- E- E- E4 Ep- E8- E- E, E, E, Ex, EH, E , E+ E+ E/ E4 E+ E+ E. E@+ E4 E + E. E* E* E4 E* E/ E/ E* Eh* EH* E(* E5 E* E) E) E 2 E) EP) E() E1 E) E( E( E( E( Ex( E / E`( E8( E( E( E' E( Ex( E' E( Ex( E' E' E' Eh' EH' E0' E' E& E& E( E' E0' E& Ex& E( E' E0' E& E8& E( E' E0' E& E% E% E% E@% E(% E% E% E$ E$ E$ Ex$ Eh$ EX$ EV EU EU EU EPU EPT ES E@S E0S ER EpR EQ ES EPQ E0S EP EpP E0S E P EO EX$ E O EN EM E0S EI E0D EP E`6 E@6 E(6 E6 E5 E5 E5 E5 EP5 E(5 E4 E4 E4 E4 EP4 E 4 E4 E3 E3 Eh3 E 3 E2 E2 E2 E`2 E02 E 2 E1 E1 E1 Ep1 EX1 E`2 E 2 EH1 E(1 E1 E1 E0 E0 E0 E4 E0 E0 EP0 E(0 E6 E5 E/ E/ E/ Ep/ E0/ E / E/ E. E. E/ E1 E. E. E/ E1 E. EP. E4 E(. E. E- E- E- E4 Ep- E8- E- E, E, E, Ex, EH, E , E+ E+ E/ E4 E+ E+ E. E@+ E4 E + E. E* E* E4 E* E/ E/ E* Eh* EH* E(* E5 E* E) E) E 2 E) EP) E() E1 E) E( E( E( E( Ex( E / E`( E8( E( E( E' E( Ex( E' E( Ex( E' E' E' Eh' EH' E0' E' E& E& E( E' E0' E& Ex& E( E' E0' E& E8& E( E' E0' E& E% E% E% E@% E(% E% E% E$ E$ E$ Ex$ Eh$ EX$ E`6 E@6 E(6 E6 E5 E5 E5 E5 EP5 E(5 E4 E4 E4 E4 EP4 E 4 E4 E3 E3 Eh3 E 3 E2 E2 E2 E`2 E02 E 2 E1 E1 E1 Ep1 EX1 E`2 E 2 EH1 E(1 E1 E1 E0 E0 E0 E4 E0 E0 EP0 E(0 E6 E5 E/ E/ E/ Ep/ E0/ E / E/ E. E. E/ E1 E. E. E/ E1 E. EP. E4 E(. E. E- E- E- E4 Ep- E8- E- E, E, E, Ex, EH, E , E+ E+ E/ E4 E+ E+ E. E@+ E4 E + E. E* E* E4 E* E/ E/ E* Eh* EH* E(* E5 E* E) E) E 2 E) EP) E() E1 E) E( E( E( E( Ex( E / E`( E8( E( E( E' E( Ex( E' E( Ex( E' E' E' Eh' EH' E0' E' E& E& E( E' E0' E& Ex& E( E' E0' E& E8& E( E' E0' E& E% E% E% E@% E(% E% E% E$ E$ E$ Ex$ Eh$ EX$ E`6 E@6 E(6 E6 E5 E5 E5 E5 EP5 E(5 E4 E4 E4 E4 EP4 E 4 E4 E3 E3 Eh3 E 3 E2 E2 E2 E`2 E02 E 2 E1 E1 E1 Ep1 EX1 E`2 E 2 EH1 E(1 E1 E1 E0 E0 E0 E4 E0 E0 EP0 E(0 E6 E5 E/ E/ E/ Ep/ E0/ E / E/ E. E. E/ E1 E. E. E/ E1 E. EP. E4 E(. E. E- E- E- E4 Ep- E8- E- E, E, E, Ex, EH, E , E+ E+ E/ E4 E+ E+ E. E@+ E4 E + E. E* E* E4 E* E/ E/ E* Eh* EH* E(* E5 E* E) E) E 2 E) EP) E() E1 E) E( E( E( E( Ex( E / E`( E8( E( E( E' E( Ex( E' E( Ex( E' E' E' Eh' EH' E0' E' E& E& E( E' E0' E& Ex& E( E' E0' E& E8& E( E' E0' E& E% E% E% E@% E(% E% E% E$ E$ E$ Ex$ Eh$ EX$ E`6 E@6 E(6 E6 E5 E5 E5 E5 EP5 E(5 E4 E4 E4 E4 EP4 E 4 E4 E3 E3 Eh3 E 3 E2 E2 E2 E`2 E02 E 2 E1 E1 E1 Ep1 EX1 E`2 E 2 EH1 E(1 E1 E1 E0 E0 E0 E4 E0 E0 EP0 E(0 E6 E5 E/ E/ E/ Ep/ E0/ E / E/ E. E. E/ E1 E. E. E/ E1 E. EP. E4 E(. E. E- E- E- E4 Ep- E8- E- E, E, E, Ex, EH, E , E+ E+ E/ E4 E+ E+ E. E@+ E4 E + E. E* E* E4 E* E/ E/ E* Eh* EH* E(* E5 E* E) E) E 2 E) EP) E() E1 E) E( E( E( E( Ex( E / E`( E8( E( E( E' E( Ex( E' E( Ex( E' E' E' Eh' EH' E0' E' E& E& E( E' E0' E& Ex& E( E' E0' E& E8& E( E' E0' E& E% E% E% E@% E(% E% E% E$ E$ E$ Ex$ Eh$ EX$ EV EU EU EU EPU EPT ES E@S E0S ER EpR EQ ES EPQ E0S EP EpP E0S E P EO EX$ E O EN EM E0S EI E0D E`6 E@6 E(6 E6 E5 E5 E5 E5 EP5 E(5 E4 E4 E4 E4 EP4 E 4 E4 E3 E3 Eh3 E 3 E2 E2 E2 E`2 E02 E 2 E1 E1 E1 Ep1 EX1 E`2 E 2 EH1 E(1 E1 E1 E0 E0 E0 E4 E0 E0 EP0 E(0 E6 E5 E/ E/ E/ Ep/ E0/ E / E/ E. E. E/ E1 E. E. E/ E1 E. EP. E4 E(. E. E- E- E- E4 Ep- E8- E- E, E, E, Ex, EH, E , E+ E+ E/ E4 E+ E+ E. E@+ E4 E + E. E* E* E4 E* E/ E/ E* Eh* EH* E(* E5 E* E) E) E 2 E) EP) E() E1 E) E( E( E( E( Ex( E / E`( E8( E( E( E' E( Ex( E' E( Ex( E' E' E' Eh' EH' E0' E' E& E& E( E' E0' E& Ex& E( E' E0' E& E8& E( E' E0' E& E% E% E% E@% E(% E% E% E$ E$ E$ Ex$ Eh$ EX$ EV EU EU EU EPU EPT ES E@S E0S ER EpR EQ ES EPQ E0S EP EpP E0S E P EO EX$ E O EN EM E0S EI E0D E`6 E@6 E(6 E6 E5 E5 E5 E5 EP5 E(5 E4 E4 E4 E4 EP4 E 4 E4 E3 E3 Eh3 E 3 E2 E2 E2 E`2 E02 E 2 E1 E1 E1 Ep1 EX1 E`2 E 2 EH1 E(1 E1 E1 E0 E0 E0 E4 E0 E0 EP0 E(0 E6 E5 E/ E/ E/ Ep/ E0/ E / E/ E. E. E/ E1 E. E. E/ E1 E. EP. E4 E(. E. E- E- E- E4 Ep- E8- E- E, E, E, Ex, EH, E , E+ E+ E/ E4 E+ E+ E. E@+ E4 E + E. E* E* E4 E* E/ E/ E* Eh* EH* E(* E5 E* E) E) E 2 E) EP) E() E1 E) E( E( E( E( Ex( E / E`( E8( E( E( E' E( Ex( E' E( Ex( E' E' E' Eh' EH' E0' E' E& E& E( E' E0' E& Ex& E( E' E0' E& E8& E( E' E0' E& E% E% E% E@% E(% E% E% E$ E$ E$ Ex$ Eh$ EX$ E`6 E@6 E(6 E6 E5 E5 E5 E5 EP5 E(5 E4 E4 E4 E4 EP4 E 4 E4 E3 E3 Eh3 E 3 E2 E2 E2 E`2 E02 E 2 E1 E1 E1 Ep1 EX1 E`2 E 2 EH1 E(1 E1 E1 E0 E0 E0 E4 E0 E0 EP0 E(0 E6 E5 E/ E/ E/ Ep/ E0/ E / E/ E. E. E/ E1 E. E. E/ E1 E. EP. E4 E(. E. E- E- E- E4 Ep- E8- E- E, E, E, Ex, EH, E , E+ E+ E/ E4 E+ E+ E. E@+ E4 E + E. E* E* E4 E* E/ E/ E* Eh* EH* E(* E5 E* E) E) E 2 E) EP) E() E1 E) E( E( E( E( Ex( E / E`( E8( E( E( E' E( Ex( E' E( Ex( E' E' E' Eh' EH' E0' E' E& E& E( E' E0' E& Ex& E( E' E0' E& E8& E( E' E0' E& E% E% E% E@% E(% E% E% E$ E$ E$ Ex$ Eh$ EX$ E`6 E`6 E@6 E(6 E6 E5 E5 E5 E5 EP5 E(5 E4 E4 E4 E4 EP4 E 4 E4 E3 E3 Eh3 E 3 E2 E2 E2 E`2 E02 E 2 E1 E1 E1 Ep1 EX1 E`2 E 2 EH1 E(1 E1 E1 E0 E0 E0 E4 E0 E0 EP0 E(0 E6 E5 E/ E/ E/ Ep/ E0/ E / E/ E. E. E/ E1 E. E. E/ E1 E. EP. E4 E(. E. E- E- E- E4 Ep- E8- E- E, E, E, Ex, EH, E , E+ E+ E/ E4 E+ E+ E. E@+ E4 E + E. E* E* E4 E* E/ E/ E* Eh* EH* E(* E5 E* E) E) E 2 E) EP) E() E1 E) E( E( E( E( Ex( E / E`( E8( E( E( E' E( Ex( E' E( Ex( E' E' E' Eh' EH' E0' E' E& E& E( E' E0' E& Ex& E( E' E0' E& E8& E( E' E0' E& E% E% E% E@% E(% E% E% E$ E$ E$ Ex$ Eh$ EX$ E`6 EP[ E.?AVtype_info@@2-+] f@E[ E[ E[ EEP[ E.?AV_com_error@@uyz*zz$*z/{,*@{{4*{|<* |b|D*p||L*|0}T*@}}\*}:~d*@~~l*~~t*~"|*0**"*0r*р****ЂF*`*ԃ**+(+0L+؅D+n+p++++Ɉ+Јw8,0,h,Њ,ً,,x,ٌ0-ٌ- -L-D-|- - G-Ph-p.-(-0H-Ph-p-..>.@Y.`/ /)/0I.Pl/// =x/P//2/@r///@z000'$0p,0640@t0th0X0<0 D0Dq0q0Ν0Ν0000a<1a(111H1П\1/p10Hh1Pʡ1С1U2`|2 22٤1110X2`[2p33 92@\37T3@YL3`+3@3ЩO3333+3@k44 4Ȯ4Ю4t444 84` 55 k(5p 5\58d5@x5p55H5P5 5pڷ555 l@6p86 6)|60It6`66V6`y6W7`$707087@7'H7`7 X7P7о7?7?77A7P77@8 8`8p(8 48PL8D8<|888t89t$990L9\9 pl9|9W999o$:\:T:L:%8:0M;`;;F(;P8;H;OP; ; <x;@d;< <,<0r4<@<H<4P<@]\<pd<p<5|<@<)<0l<p<===!>04>@>v>v>,4?, ??IT?PiL?pD?? ;???0j?0?C?Pt@ @L@08@0@$@@K@``@'X@0@@@@ 9@@Y@`y@@AA 9A@YA`yAAAABBB B)B0IBPlBpBBCPiCpCD D8\D@YTD`yLDDDU0>i>Up>>U>>U@??U??U??U@j@LVp@@DV@@@>>>>>/?@?z???@K@`@@AFAPAAApB BB$B3C0@CC<C2DH@DDTDE`EIFlPFFxF.G@GGGH@H|HHHIKIII@JvJJJJKKLLLMMdNNO, OO8O6PH@PPXPPhQFQxPQQQ%R0RRR_SpSS0TfTpTTTUUUUUDU V0 V0V @VkVTVVVVlVW\WWWXXXXXY[[[[ \$ \)\)\8\@\\,\(]8]W`d```T``D`cdccTccDcdDef\fofofffgt ggggg#h0hrDrr<rr4ss, s@\>`>?`?`|???? ?)?0@@|@t@ 9l@@vAA AA @AAA A)A0IAPlApAAA0`C0IXCPlPCpHC@C8C0C (C, C0ICPiCpCCBB B)B0IBPiBp@F 8F,0F0L(FPl FpFFFF E)E0IEPiEpEEEE E)E0IEPiEpEEEE xE)pE0LhEPi`EpXEPEHE@E 8E  J  J  J  J  J < J@ Y J` | J  J  J  J  xJ  pJ < hJ@ Y `J` y XJ  PJ  HJ  @J  8JLLL <L@\L`xLL3M@\M`xMMMMMM0N)N0INPiNpcHOp@O8O0O(OP+P0KPPlOpOOOOQQQ R  R +"R@"#R##R$$8S$$0S0%&S''S '8'S@'d'tSp''DT'(TT))LT ))T))T),T--T-.T.j0Tp0-2T02L2T`2 34U3>3HUP34\U4)4TU04&5U05I5UP5m5Up55U55U560V66(V67pV77hV8T8V`88V89V99V9:W::V; <`W<)<XW0<M<PWP<m<HWp<<@W<<W<<W=6=W@==W==W>m>X>>X>? X ??,X?-@ -1) -- -1 == FETCH statement failed or the row was beyond the result set. BEGIN if (@@FETCH_STATUS <> -2) -- - 2 == Row fetched is missing. BEGIN exec msdb.dbo.sp_delete_job @job_name = @next_id -- delete the schedule END FETCH NEXT FROM id_cursor INTO @next_id END CLOSE id_cursor DEALLOCATE id_cursor GO -------------------------------------------------- ------------- Running jobs tables CREATE TABLE [dbo].[RunningJobs] ( [JobID] nvarchar(32) NOT NULL, [StartDate] datetime NOT NULL, [ComputerName] nvarchar(32) NOT NULL, [RequestName] nvarchar(425) NOT NULL, [RequestPath] nvarchar(425) NOT NULL, [UserId] uniqueidentifier NOT NULL, [Description] ntext NULL, [Timeout] int NOT NULL, [JobAction] smallint NOT NULL, [JobType] smallint NOT NULL, [JobStatus] smallint NOT NULL ) ON [PRIMARY] GO GRANT SELECT, UPDATE, INSERT, DELETE, REFERENCES ON [dbo].[RunningJobs] TO RSExecRole GO ALTER TABLE [dbo].[RunningJobs] ADD CONSTRAINT [PK_RunningJobs] PRIMARY KEY CLUSTERED ( [JobID] ) GO CREATE INDEX [IX_RunningJobsStatus] ON [dbo].[RunningJobs]([ComputerName], [JobType]) ON [PRIMARY] GO CREATE TABLE [dbo].[ServerParametersInstance] ( [ServerParametersID] nvarchar(32) NOT NULL, [ParentID] nvarchar(32) NULL, [Path] [nvarchar] (425) NOT NULL, [CreateDate] datetime NOT NULL, [ModifiedDate] datetime NOT NULL, [Timeout] int NOT NULL, [Expiration] datetime NOT NULL, [ParametersValues] image NOT NULL ) ON [PRIMARY] GO ALTER TABLE [dbo].[ServerParametersInstance] ADD CONSTRAINT [PK_ServerParametersInstance] PRIMARY KEY CLUSTERED ( [ServerParametersID] ) GO CREATE INDEX [IX_ServerParametersInstanceExpiration] ON [dbo].[ServerParametersInstance]([Expiration] DESC) ON [PRIMARY] GO EXEC sp_tableoption N'[dbo].[ServerParametersInstance]', 'text in row', 'ON' GO -------------------------------------------------- ------------- Creation of Stored Procedures -------------------------------------------------- -- START STORED PROCEDURES if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetKeysForInstallation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetKeysForInstallation] GO CREATE PROCEDURE [dbo].[SetKeysForInstallation] @InstallationID uniqueidentifier, @SymmetricKey image = NULL, @PublicKey image AS update [dbo].[Keys] set [SymmetricKey] = @SymmetricKey, [PublicKey] = @PublicKey where [InstallationID] = @InstallationID and [Client] = 1 GO GRANT EXECUTE ON [dbo].[SetKeysForInstallation] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAnnouncedKey]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAnnouncedKey] GO CREATE PROCEDURE [dbo].[GetAnnouncedKey] @InstallationID uniqueidentifier AS select PublicKey, MachineName, InstanceName from Keys where InstallationID = @InstallationID and Client = 1 GO GRANT EXECUTE ON [dbo].[GetAnnouncedKey] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AnnounceOrGetKey]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AnnounceOrGetKey] GO CREATE PROCEDURE [dbo].[AnnounceOrGetKey] @MachineName nvarchar(256), @InstanceName nvarchar(32), @InstallationID uniqueidentifier, @PublicKey image, @NumAnnouncedServices int OUTPUT AS -- Acquire lock IF NOT EXISTS (SELECT * FROM [dbo].[Keys] WITH(XLOCK) WHERE [Client] < 0) BEGIN RAISERROR('Keys lock row not found', 16, 1) RETURN END -- Get the number of services that have already announced their presence SELECT @NumAnnouncedServices = count(*) FROM [dbo].[Keys] WHERE [Client] = 1 DECLARE @StoredInstallationID uniqueidentifier DECLARE @StoredInstanceName nvarchar(32) SELECT @StoredInstallationID = [InstallationID], @StoredInstanceName = [InstanceName] FROM [dbo].[Keys] WHERE [InstallationID] = @InstallationID AND [Client] = 1 IF @StoredInstallationID IS NULL -- no record present BEGIN INSERT INTO [dbo].[Keys] ([MachineName], [InstanceName], [InstallationID], [Client], [PublicKey], [SymmetricKey]) VALUES (@MachineName, @InstanceName, @InstallationID, 1, @PublicKey, null) END ELSE BEGIN IF @StoredInstanceName IS NULL BEGIN UPDATE [dbo].[Keys] SET [InstanceName] = @InstanceName WHERE [InstallationID] = @InstallationID AND [Client] = 1 END END SELECT [MachineName], [SymmetricKey], [PublicKey] FROM [Keys] WHERE [InstallationID] = @InstallationID and [Client] = 1 GO GRANT EXECUTE ON [dbo].[AnnounceOrGetKey] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetMachineName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetMachineName] GO CREATE PROCEDURE [dbo].[SetMachineName] @MachineName nvarchar(256), @InstallationID uniqueidentifier AS UPDATE [dbo].[Keys] SET MachineName = @MachineName WHERE [InstallationID] = @InstallationID and [Client] = 1 GO GRANT EXECUTE ON [dbo].[SetMachineName] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListInstallations]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListInstallations] GO CREATE PROCEDURE [dbo].[ListInstallations] AS SELECT [MachineName], [InstanceName], [InstallationID], CASE WHEN [SymmetricKey] IS null THEN 0 ELSE 1 END FROM [dbo].[Keys] WHERE [Client] = 1 GO GRANT EXECUTE ON [dbo].[ListInstallations] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListInfoForReencryption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListInfoForReencryption] GO CREATE PROCEDURE [dbo].[ListInfoForReencryption] AS SELECT [DSID] FROM [dbo].[DataSource] WITH (XLOCK, TABLOCK) SELECT [SubscriptionID] FROM [dbo].[Subscriptions] WITH (XLOCK, TABLOCK) SELECT [InstallationID], [PublicKey] FROM [dbo].[Keys] WITH (XLOCK, TABLOCK) WHERE [Client] = 1 AND ([SymmetricKey] IS NOT NULL) GO GRANT EXECUTE ON [dbo].[ListInfoForReencryption] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDatasourceInfoForReencryption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDatasourceInfoForReencryption] GO CREATE PROCEDURE [dbo].[GetDatasourceInfoForReencryption] @DSID as uniqueidentifier AS SELECT [ConnectionString], [OriginalConnectionString], [UserName], [Password], [CredentialRetrieval], [Version] FROM [dbo].[DataSource] WHERE [DSID] = @DSID GO GRANT EXECUTE ON [dbo].[GetDatasourceInfoForReencryption] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetReencryptedDatasourceInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetReencryptedDatasourceInfo] GO CREATE PROCEDURE [dbo].[SetReencryptedDatasourceInfo] @DSID uniqueidentifier, @ConnectionString image = NULL, @OriginalConnectionString image = NULL, @UserName image = NULL, @Password image = NULL, @CredentialRetrieval int, @Version int AS UPDATE [dbo].[DataSource] SET [ConnectionString] = @ConnectionString, [OriginalConnectionString] = @OriginalConnectionString, [UserName] = @UserName, [Password] = @Password, [CredentialRetrieval] = @CredentialRetrieval, [Version] = @Version WHERE [DSID] = @DSID GO GRANT EXECUTE ON [dbo].[SetReencryptedDatasourceInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSubscriptionInfoForReencryption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSubscriptionInfoForReencryption] GO CREATE PROCEDURE [dbo].[GetSubscriptionInfoForReencryption] @SubscriptionID as uniqueidentifier AS SELECT [DeliveryExtension], [ExtensionSettings], [Version] FROM [dbo].[Subscriptions] WHERE [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetSubscriptionInfoForReencryption] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetReencryptedSubscriptionInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetReencryptedSubscriptionInfo] GO CREATE PROCEDURE [dbo].[SetReencryptedSubscriptionInfo] @SubscriptionID as uniqueidentifier, @ExtensionSettings as ntext = NULL, @Version as int AS UPDATE [dbo].[Subscriptions] SET [ExtensionSettings] = @ExtensionSettings, [Version] = @Version WHERE [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[SetReencryptedSubscriptionInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteEncryptedContent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteEncryptedContent] GO CREATE PROCEDURE [dbo].[DeleteEncryptedContent] AS -- Remove the encryption keys delete from keys where client >= 0 -- Remove the encrypted content update datasource set CredentialRetrieval = 1, -- CredentialRetrieval.Prompt ConnectionString = null, OriginalConnectionString = null, UserName = null, Password = null GO GRANT EXECUTE ON [dbo].[DeleteEncryptedContent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteKey]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteKey] GO CREATE PROCEDURE [dbo].[DeleteKey] @InstallationID uniqueidentifier AS if (@InstallationID = '00000000-0000-0000-0000-000000000000') RAISERROR('Cannot delete reserved key', 16, 1) -- Remove the encryption keys delete from keys where InstallationID = @InstallationID and Client = 1 GO GRANT EXECUTE ON [dbo].[DeleteKey] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAllConfigurationInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAllConfigurationInfo] GO CREATE PROCEDURE [dbo].[GetAllConfigurationInfo] AS SELECT [Name], [Value] FROM [ConfigurationInfo] GO GRANT EXECUTE ON [dbo].[GetAllConfigurationInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetOneConfigurationInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetOneConfigurationInfo] GO CREATE PROCEDURE [dbo].[GetOneConfigurationInfo] @Name nvarchar (260) AS SELECT [Value] FROM [ConfigurationInfo] WHERE [Name] = @Name GO GRANT EXECUTE ON [dbo].[GetOneConfigurationInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetConfigurationInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetConfigurationInfo] GO CREATE PROCEDURE [dbo].[SetConfigurationInfo] @Name nvarchar (260), @Value ntext AS DELETE FROM [ConfigurationInfo] WHERE [Name] = @Name IF @Value is not null BEGIN INSERT INTO ConfigurationInfo VALUES ( newid(), @Name, @Value ) END GO GRANT EXECUTE ON [dbo].[SetConfigurationInfo] TO RSExecRole if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddEvent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddEvent] GO CREATE PROCEDURE [dbo].[AddEvent] @EventType nvarchar (260), @EventData nvarchar (260) AS insert into [Event] ([EventID], [EventType], [EventData], [TimeEntered], [ProcessStart], [BatchID]) values (NewID(), @EventType, @EventData, GETUTCDATE(), NULL, NULL) GO GRANT EXECUTE ON [dbo].[AddEvent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteEvent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteEvent] GO CREATE PROCEDURE [dbo].[DeleteEvent] @ID uniqueidentifier AS delete from [Event] where [EventID] = @ID GO GRANT EXECUTE ON [dbo].[DeleteEvent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanEventRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanEventRecords] GO CREATE PROCEDURE [dbo].[CleanEventRecords] @MaxAgeMinutes int AS -- Reset all notifications which have been add over n minutes ago Update [Event] set [ProcessStart] = NULL, [ProcessHeartbeat] = NULL where [EventID] in ( SELECT [EventID] FROM [Event] WHERE [ProcessHeartbeat] < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) ) GO GRANT EXECUTE ON [dbo].[CleanEventRecords] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddExecutionLogEntry]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddExecutionLogEntry] GO CREATE PROCEDURE [dbo].[AddExecutionLogEntry] @InstanceName nvarchar(38), @Report nvarchar(260), @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @RequestType bit, @Format nvarchar(26), @Parameters ntext, @TimeStart DateTime, @TimeEnd DateTime, @TimeDataRetrieval int, @TimeProcessing int, @TimeRendering int, @Source tinyint, @Status nvarchar(32), @ByteCount bigint, @RowCount bigint AS -- Unless is is specifically 'False', it's true if exists (select * from ConfigurationInfo where [Name] = 'EnableExecutionLogging' and [Value] like 'False') begin return end Declare @ReportID uniqueidentifier select @ReportID = ItemID from Catalog with (nolock) where Path = @Report insert into ExecutionLog (InstanceName, ReportID, UserName, RequestType, [Format], Parameters, TimeStart, TimeEnd, TimeDataRetrieval, TimeProcessing, TimeRendering, Source, Status, ByteCount, [RowCount]) Values (@InstanceName, @ReportID, @UserName, @RequestType, @Format, @Parameters, @TimeStart, @TimeEnd, @TimeDataRetrieval, @TimeProcessing, @TimeRendering, @Source, @Status, @ByteCount, @RowCount) GO GRANT EXECUTE ON [dbo].[AddExecutionLogEntry] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ExpireExecutionLogEntries]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ExpireExecutionLogEntries] GO CREATE PROCEDURE [dbo].[ExpireExecutionLogEntries] AS -- -1 means no expiration if exists (select * from ConfigurationInfo where [Name] = 'ExecutionLogDaysKept' and CAST(CAST(Value as nvarchar) as integer) = -1) begin return end delete from ExecutionLog where DateDiff(day, TimeStart, getdate()) >= (select CAST(CAST(Value as nvarchar) as integer) from ConfigurationInfo where [Name] = 'ExecutionLogDaysKept') GO GRANT EXECUTE ON [dbo].[ExpireExecutionLogEntries] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUserIDBySid]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUserIDBySid] GO -- looks up any user name by its SID, if not it creates a regular user CREATE PROCEDURE [dbo].[GetUserIDBySid] @UserSid varbinary(85), @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS SELECT @UserID = (SELECT UserID FROM Users WHERE Sid = @UserSid AND AuthType = @AuthType) IF @UserID IS NULL BEGIN SET @UserID = newid() INSERT INTO Users (UserID, Sid, UserType, AuthType, UserName) VALUES (@UserID, @UserSid, 0, @AuthType, @UserName) END GO GRANT EXECUTE ON [dbo].[GetUserIDBySid] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUserIDByName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUserIDByName] GO -- looks up any user name by its User Name, if not it creates a regular user CREATE PROCEDURE [dbo].[GetUserIDByName] @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS SELECT @UserID = (SELECT UserID FROM Users WHERE UserName = @UserName AND AuthType = @AuthType) IF @UserID IS NULL BEGIN SET @UserID = newid() INSERT INTO Users (UserID, Sid, UserType, AuthType, UserName) VALUES (@UserID, NULL, 0, @AuthType, @UserName) END GO GRANT EXECUTE ON [dbo].[GetUserIDByName] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUserID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUserID] GO -- looks up any user name, if not it creates a regular user - uses Sid CREATE PROCEDURE [dbo].[GetUserID] @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS IF @AuthType = 1 -- Windows BEGIN EXEC GetUserIDBySid @UserSid, @UserName, @AuthType, @UserID OUTPUT END ELSE BEGIN EXEC GetUserIDByName @UserName, @AuthType, @UserID OUTPUT END GO GRANT EXECUTE ON [dbo].[GetUserID] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPrincipalID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPrincipalID] GO -- looks up a principal, if not there looks up regular users and turns them into principals -- if not, it creates a principal CREATE PROCEDURE [dbo].[GetPrincipalID] @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS -- windows auth IF @AuthType = 1 BEGIN -- is this a principal? SELECT @UserID = (SELECT UserID FROM Users WHERE Sid = @UserSid AND UserType = 1 AND AuthType = @AuthType) END ELSE BEGIN -- is this a principal? SELECT @UserID = (SELECT UserID FROM Users WHERE UserName = @UserName AND UserType = 1 AND AuthType = @AuthType) END IF @UserID IS NULL BEGIN IF @AuthType = 1 -- Windows BEGIN -- Is this a regular user SELECT @UserID = (SELECT UserID FROM Users WHERE Sid = @UserSid AND UserType = 0 AND AuthType = @AuthType) END ELSE BEGIN -- Is this a regular user SELECT @UserID = (SELECT UserID FROM Users WHERE UserName = @UserName AND UserType = 0 AND AuthType = @AuthType) END -- No, create a new principal IF @UserID IS NULL BEGIN SET @UserID = newid() INSERT INTO Users (UserID, Sid, UserType, AuthType, UserName) VALUES (@UserID, @UserSid, 1, @AuthType, @UserName) END ELSE BEGIN UPDATE Users SET UserType = 1 WHERE UserID = @UserID END END GO GRANT EXECUTE ON [dbo].[GetPrincipalID] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateSubscription] GO CREATE PROCEDURE [dbo].[CreateSubscription] @id uniqueidentifier, @Locale nvarchar (128), @Report_Name nvarchar (425), @OwnerSid varbinary (85) = NULL, @OwnerName nvarchar(260), @OwnerAuthType int, @DeliveryExtension nvarchar (260) = NULL, @InactiveFlags int, @ExtensionSettings ntext = NULL, @ModifiedBySid varbinary (85) = NULL, @ModifiedByName nvarchar(260), @ModifiedByAuthType int, @ModifiedDate datetime, @Description nvarchar(512) = NULL, @LastStatus nvarchar(260) = NULL, @EventType nvarchar(260), @MatchData ntext = NULL, @Parameters ntext = NULL, @DataSettings ntext = NULL, @Version int AS -- Create a subscription with the given data. The name must match a name in the -- Catalog table and it must be a report type (2) or linked report (4) DECLARE @Report_OID uniqueidentifier DECLARE @OwnerID uniqueidentifier DECLARE @ModifiedByID uniqueidentifier DECLARE @TempDeliveryID uniqueidentifier --Get the report id for this subscription select @Report_OID = (select [ItemID] from [Catalog] where [Catalog].[Path] = @Report_Name and ([Catalog].[Type] = 2 or [Catalog].[Type] = 4)) EXEC GetUserID @OwnerSid, @OwnerName, @OwnerAuthType, @OwnerID OUTPUT EXEC GetUserID @ModifiedBySid, @ModifiedByName, @ModifiedByAuthType, @ModifiedByID OUTPUT if (@Report_OID is NULL) begin RAISERROR('Report Not Found', 16, 1) return end Insert into Subscriptions ( [SubscriptionID], [OwnerID], [Report_OID], [Locale], [DeliveryExtension], [InactiveFlags], [ExtensionSettings], [ModifiedByID], [ModifiedDate], [Description], [LastStatus], [EventType], [MatchData], [LastRunTime], [Parameters], [DataSettings], [Version] ) values (@id, @OwnerID, @Report_OID, @Locale, @DeliveryExtension, @InactiveFlags, @ExtensionSettings, @ModifiedByID, @ModifiedDate, @Description, @LastStatus, @EventType, @MatchData, NULL, @Parameters, @DataSettings, @Version) GO GRANT EXECUTE ON [dbo].[CreateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeliveryRemovedInactivateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeliveryRemovedInactivateSubscription] GO CREATE PROCEDURE [dbo].[DeliveryRemovedInactivateSubscription] @DeliveryExtension nvarchar(260), @Status nvarchar(260) AS update Subscriptions set [DeliveryExtension] = '', [InactiveFlags] = [InactiveFlags] | 1, -- Delivery Provider Removed Flag == 1 [LastStatus] = @Status where [DeliveryExtension] = @DeliveryExtension GO GRANT EXECUTE ON [dbo].[DeliveryRemovedInactivateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteSubscription] GO CREATE PROCEDURE [dbo].[DeleteSubscription] @SubscriptionID uniqueidentifier AS -- Delete the given subscription delete from [Subscriptions] where [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[DeleteSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSubscription] GO CREATE PROCEDURE [dbo].[GetSubscription] @SubscriptionID uniqueidentifier, @AuthType int AS -- Grab all of the-- subscription properties given a id select S.[SubscriptionID], S.[Report_OID], S.[Locale], S.[InactiveFlags], S.[DeliveryExtension], S.[ExtensionSettings], SUSER_SNAME(Modified.[Sid]), Modified.[UserName], S.[ModifiedDate], S.[Description], S.[LastStatus], S.[EventType], S.[MatchData], S.[Parameters], S.[DataSettings], A.[TotalNotifications], A.[TotalSuccesses], A.[TotalFailures], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], CAT.[Path], S.[LastRunTime], CAT.[Type], SD.NtSecDescPrimary, S.[Version] from [Subscriptions] S inner join [Catalog] CAT on S.[Report_OID] = CAT.[ItemID] inner join [Users] Owner on S.OwnerID = Owner.UserID inner join [Users] Modified on S.ModifiedByID = Modified.UserID left outer join [SecData] SD on CAT.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType left outer join [ActiveSubscriptions] A with (NOLOCK) on S.[SubscriptionID] = A.[SubscriptionID] where S.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListSubscriptionsUsingDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListSubscriptionsUsingDataSource] GO CREATE PROCEDURE [dbo].[ListSubscriptionsUsingDataSource] @DataSourceName nvarchar(450), @AuthType int AS select S.[SubscriptionID], S.[Report_OID], S.[Locale], S.[InactiveFlags], S.[DeliveryExtension], S.[ExtensionSettings], SUSER_SNAME(Modified.[Sid]), Modified.[UserName], S.[ModifiedDate], S.[Description], S.[LastStatus], S.[EventType], S.[MatchData], S.[Parameters], S.[DataSettings], A.[TotalNotifications], A.[TotalSuccesses], A.[TotalFailures], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], CAT.[Path], S.[LastRunTime], CAT.[Type], SD.NtSecDescPrimary, S.[Version] from [DataSource] DS inner join Catalog C on C.ItemID = DS.Link inner join Subscriptions S on S.[SubscriptionID] = DS.[SubscriptionID] inner join [Catalog] CAT on S.[Report_OID] = CAT.[ItemID] inner join [Users] Owner on S.OwnerID = Owner.UserID inner join [Users] Modified on S.ModifiedByID = Modified.UserID left join [SecData] SD on SD.[PolicyID] = CAT.[PolicyID] AND SD.AuthType = @AuthType left outer join [ActiveSubscriptions] A with (NOLOCK) on S.[SubscriptionID] = A.[SubscriptionID] where C.Path = @DataSourceName GO GRANT EXECUTE ON [dbo].[ListSubscriptionsUsingDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSubscriptionStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSubscriptionStatus] GO CREATE PROCEDURE [dbo].[UpdateSubscriptionStatus] @SubscriptionID uniqueidentifier, @Status nvarchar(260) AS update Subscriptions set [LastStatus] = @Status where [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[UpdateSubscriptionStatus] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSubscription] GO CREATE PROCEDURE [dbo].[UpdateSubscription] @id uniqueidentifier, @Locale nvarchar(260), @OwnerSid varbinary(85) = NULL, @OwnerName nvarchar(260), @OwnerAuthType int, @DeliveryExtension nvarchar(260), @InactiveFlags int, @ExtensionSettings ntext = NULL, @ModifiedBySid varbinary(85) = NULL, @ModifiedByName nvarchar(260), @ModifiedByAuthType int, @ModifiedDate datetime, @Description nvarchar(512) = NULL, @LastStatus nvarchar(260) = NULL, @EventType nvarchar(260), @MatchData ntext = NULL, @Parameters ntext = NULL, @DataSettings ntext = NULL, @Version int AS -- Update a subscription's information. DECLARE @ModifiedByID uniqueidentifier DECLARE @OwnerID uniqueidentifier EXEC GetUserID @ModifiedBySid, @OwnerName,@OwnerAuthType, @ModifiedByID OUTPUT EXEC GetUserID @OwnerSid, @ModifiedByName, @ModifiedByAuthType, @OwnerID OUTPUT -- Make sure there is a valid provider update Subscriptions set [DeliveryExtension] = @DeliveryExtension, [Locale] = @Locale, [OwnerID] = @OwnerID, [InactiveFlags] = @InactiveFlags, [ExtensionSettings] = @ExtensionSettings, [ModifiedByID] = @ModifiedByID, [ModifiedDate] = @ModifiedDate, [Description] = @Description, [LastStatus] = @LastStatus, [EventType] = @EventType, [MatchData] = @MatchData, [Parameters] = @Parameters, [DataSettings] = @DataSettings, [Version] = @Version where [SubscriptionID] = @id GO GRANT EXECUTE ON [dbo].[UpdateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[InvalidateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[InvalidateSubscription] GO CREATE PROCEDURE [dbo].[InvalidateSubscription] @SubscriptionID uniqueidentifier, @Flags int, @LastStatus nvarchar(260) AS -- Mark all subscriptions for this report as inactive for the given flags update Subscriptions set [InactiveFlags] = S.[InactiveFlags] | @Flags, [LastStatus] = @LastStatus from Subscriptions S where SubscriptionID = @SubscriptionID GO GRANT EXECUTE ON [dbo].[InvalidateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanNotificationRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanNotificationRecords] GO CREATE PROCEDURE [dbo].[CleanNotificationRecords] @MaxAgeMinutes int AS -- Reset all notifications which have been add over n minutes ago Update [Notifications] set [ProcessStart] = NULL, [ProcessHeartbeat] = NULL, [Attempt] = 1 where [NotificationID] in ( SELECT [NotificationID] FROM [Notifications] WHERE [ProcessHeartbeat] < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) and [Attempt] is NULL ) Update [Notifications] set [ProcessStart] = NULL, [ProcessHeartbeat] = NULL, [Attempt] = [Attempt] + 1 where [NotificationID] in ( SELECT [NotificationID] FROM [Notifications] WHERE [ProcessHeartbeat] < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) and [Attempt] is not NULL ) GO GRANT EXECUTE ON [dbo].[CleanNotificationRecords] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateSnapShotNotifications]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateSnapShotNotifications] GO CREATE PROCEDURE [dbo].[CreateSnapShotNotifications] @HistoryID uniqueidentifier, @LastRunTime datetime AS update [Subscriptions] set [LastRunTime] = @LastRunTime from History SS inner join [Subscriptions] S on S.[Report_OID] = SS.[ReportID] where SS.[HistoryID] = @HistoryID and S.EventType = 'ReportHistorySnapshotCreated' and InactiveFlags = 0 -- Find all valid subscriptions for the given report and create a new notification row for -- each subscription insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) select NewID(), S.[SubscriptionID], NULL, S.[Report_OID], NULL, S.[ExtensionSettings], S.[Locale], S.[Parameters], GETUTCDATE(), S.[LastRunTime], S.[DeliveryExtension], S.[OwnerID], 0, S.[Version] from [Subscriptions] S with (READPAST) inner join History H on S.[Report_OID] = H.[ReportID] where H.[HistoryID] = @HistoryID and S.EventType = 'ReportHistorySnapshotCreated' and InactiveFlags = 0 and S.[DataSettings] is null -- Create any data driven subscription by creating a data driven event insert into [Event] ( [EventID], [EventType], [EventData], [TimeEntered] ) select NewID(), 'DataDrivenSubscription', S.SubscriptionID, GETUTCDATE() from [Subscriptions] S with (READPAST) inner join History H on S.[Report_OID] = H.[ReportID] where H.[HistoryID] = @HistoryID and S.EventType = 'ReportHistorySnapshotCreated' and InactiveFlags = 0 and S.[DataSettings] is not null GO GRANT EXECUTE ON [dbo].[CreateSnapShotNotifications] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateDataDrivenNotification]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateDataDrivenNotification] GO CREATE PROCEDURE [dbo].[CreateDataDrivenNotification] @SubscriptionID uniqueidentifier, @ActiveationID uniqueidentifier, @ReportID uniqueidentifier, @ExtensionSettings ntext, @Locale nvarchar(128), @Parameters ntext, @LastRunTime datetime, @DeliveryExtension nvarchar(260), @OwnerSid varbinary (85) = null, @OwnerName nvarchar(260), @OwnerAuthType int, @Version int AS declare @OwnerID as uniqueidentifier EXEC GetUserID @OwnerSid,@OwnerName, @OwnerAuthType, @OwnerID OUTPUT -- Insert into the notification table insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) values ( NewID(), @SubscriptionID, @ActiveationID, @ReportID, NULL, @ExtensionSettings, @Locale, @Parameters, GETUTCDATE(), @LastRunTime, @DeliveryExtension, @OwnerID, 1, @Version ) GO GRANT EXECUTE ON [dbo].[CreateDataDrivenNotification] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateNewActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateNewActiveSubscription] GO CREATE PROCEDURE [dbo].[CreateNewActiveSubscription] @ActiveID uniqueidentifier, @SubscriptionID uniqueidentifier AS -- Insert into the activesubscription table insert into [ActiveSubscriptions] ( [ActiveID], [SubscriptionID], [TotalNotifications], [TotalSuccesses], [TotalFailures] ) values ( @ActiveID, @SubscriptionID, NULL, 0, 0 ) GO GRANT EXECUTE ON [dbo].[CreateNewActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateActiveSubscription] GO CREATE PROCEDURE [dbo].[UpdateActiveSubscription] @ActiveID uniqueidentifier, @TotalNotifications int = NULL, @TotalSuccesses int = NULL, @TotalFailures int = NULL AS if @TotalNotifications is not NULL begin update ActiveSubscriptions set TotalNotifications = @TotalNotifications where ActiveID = @ActiveID end if @TotalSuccesses is not NULL begin update ActiveSubscriptions set TotalSuccesses = @TotalSuccesses where ActiveID = @ActiveID end if @TotalFailures is not NULL begin update ActiveSubscriptions set TotalFailures = @TotalFailures where ActiveID = @ActiveID end GO GRANT EXECUTE ON [dbo].[UpdateActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteActiveSubscription] GO CREATE PROCEDURE [dbo].[DeleteActiveSubscription] @ActiveID uniqueidentifier AS delete from ActiveSubscriptions where ActiveID = @ActiveID GO GRANT EXECUTE ON [dbo].[DeleteActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAndHoldLockActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAndHoldLockActiveSubscription] GO CREATE PROCEDURE [dbo].[GetAndHoldLockActiveSubscription] @ActiveID uniqueidentifier AS select TotalNotifications, TotalSuccesses, TotalFailures from ActiveSubscriptions with (XLOCK) where ActiveID = @ActiveID GO GRANT EXECUTE ON [dbo].[GetAndHoldLockActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateCacheUpdateNotifications]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateCacheUpdateNotifications] GO CREATE PROCEDURE [dbo].[CreateCacheUpdateNotifications] @ReportID uniqueidentifier, @LastRunTime datetime AS update [Subscriptions] set [LastRunTime] = @LastRunTime from [Subscriptions] S where S.[Report_OID] = @ReportID and S.EventType = 'SnapshotUpdated' and InactiveFlags = 0 -- Find all valid subscriptions for the given report and create a new notification row for -- each subscription insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) select NewID(), S.[SubscriptionID], NULL, S.[Report_OID], NULL, S.[ExtensionSettings], S.[Locale], S.[Parameters], GETUTCDATE(), S.[LastRunTime], S.[DeliveryExtension], S.[OwnerID], 0, S.[Version] from [Subscriptions] S inner join Catalog C on S.[Report_OID] = C.[ItemID] where C.[ItemID] = @ReportID and S.EventType = 'SnapshotUpdated' and InactiveFlags = 0 and S.[DataSettings] is null -- Create any data driven subscription by creating a data driven event insert into [Event] ( [EventID], [EventType], [EventData], [TimeEntered] ) select NewID(), 'DataDrivenSubscription', S.SubscriptionID, GETUTCDATE() from [Subscriptions] S inner join Catalog C on S.[Report_OID] = C.[ItemID] where C.[ItemID] = @ReportID and S.EventType = 'SnapshotUpdated' and InactiveFlags = 0 and S.[DataSettings] is not null GO GRANT EXECUTE ON [dbo].[CreateCacheUpdateNotifications] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCacheSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetCacheSchedule] GO CREATE PROCEDURE [dbo].[GetCacheSchedule] @ReportID uniqueidentifier AS SELECT S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], RS.ReportAction FROM Schedule S with (XLOCK) inner join ReportSchedule RS on S.ScheduleID = RS.ScheduleID inner join [Users] Owner on S.[CreatedById] = Owner.[UserID] WHERE (RS.ReportAction = 1 or RS.ReportAction = 3) and -- 1 == UpdateCache, 3 == Invalidate cache RS.[ReportID] = @ReportID GO GRANT EXECUTE ON [dbo].[GetCacheSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteNotification]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteNotification] GO CREATE PROCEDURE [dbo].[DeleteNotification] @ID uniqueidentifier AS delete from [Notifications] where [NotificationID] = @ID GO GRANT EXECUTE ON [dbo].[DeleteNotification] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetNotificationAttempt]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetNotificationAttempt] GO CREATE PROCEDURE [dbo].[SetNotificationAttempt] @Attempt int, @SecondsToAdd int, @NotificationID uniqueidentifier AS update [Notifications] set [ProcessStart] = NULL, [Attempt] = @Attempt, [ProcessAfter] = DateAdd(second, @SecondsToAdd, GetUtcDate()) where [NotificationID] = @NotificationID GO GRANT EXECUTE ON [dbo].[SetNotificationAttempt] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateTimeBasedSubscriptionNotification]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateTimeBasedSubscriptionNotification] GO CREATE PROCEDURE [dbo].[CreateTimeBasedSubscriptionNotification] @SubscriptionID uniqueidentifier, @LastRunTime datetime as insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) select NewID(), S.[SubscriptionID], NULL, S.[Report_OID], NULL, S.[ExtensionSettings], S.[Locale], S.[Parameters], GETUTCDATE(), @LastRunTime, S.[DeliveryExtension], S.[OwnerID], 0, S.[Version] from [Subscriptions] S where S.[SubscriptionID] = @SubscriptionID and InactiveFlags = 0 and S.[DataSettings] is null -- Create any data driven subscription by creating a data driven event insert into [Event] ( [EventID], [EventType], [EventData], [TimeEntered] ) select NewID(), 'DataDrivenSubscription', S.SubscriptionID, GETUTCDATE() from [Subscriptions] S where S.[SubscriptionID] = @SubscriptionID and InactiveFlags = 0 and S.[DataSettings] is not null update [Subscriptions] set [LastRunTime] = @LastRunTime where [SubscriptionID] = @SubscriptionID and InactiveFlags = 0 GO GRANT EXECUTE ON [dbo].[CreateTimeBasedSubscriptionNotification] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteTimeBasedSubscriptionSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteTimeBasedSubscriptionSchedule] GO CREATE PROCEDURE [dbo].[DeleteTimeBasedSubscriptionSchedule] @SubscriptionID as uniqueidentifier as delete ReportSchedule from ReportSchedule RS inner join Subscriptions S on S.[SubscriptionID] = RS.[SubscriptionID] where S.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[DeleteTimeBasedSubscriptionSchedule] TO RSExecRole GO -------------------------------------------------- ------------- Provider Info if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListUsedDeliveryProviders]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListUsedDeliveryProviders] GO CREATE PROCEDURE [dbo].[ListUsedDeliveryProviders] AS select distinct [DeliveryExtension] from Subscriptions where [DeliveryExtension] <> '' GO GRANT EXECUTE ON [dbo].[ListUsedDeliveryProviders] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id('[dbo].[AddBatchRecord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddBatchRecord] GO CREATE PROCEDURE [dbo].[AddBatchRecord] @BatchID uniqueidentifier, @UserName nvarchar(260), @Action varchar(32), @Item nvarchar(425) = NULL, @Parent nvarchar(425) = NULL, @Param nvarchar(425) = NULL, @BoolParam bit = NULL, @Content image = NULL, @Properties ntext = NULL AS IF @Action='BatchStart' BEGIN INSERT INTO [Batch] (BatchID, AddedOn, [Action], Item, Parent, Param, BoolParam, Content, Properties) VALUES (@BatchID, GETUTCDATE(), @Action, @UserName, @Parent, @Param, @BoolParam, @Content, @Properties) END ELSE BEGIN IF EXISTS (SELECT * FROM Batch WHERE BatchID = @BatchID AND [Action] = 'BatchStart' AND Item = @UserName) BEGIN INSERT INTO [Batch] (BatchID, AddedOn, [Action], Item, Parent, Param, BoolParam, Content, Properties) VALUES (@BatchID, GETUTCDATE(), @Action, @Item, @Parent, @Param, @BoolParam, @Content, @Properties) END ELSE BEGIN RAISERROR( 'Batch does not exist', 16, 1 ) END END GO GRANT EXECUTE ON [dbo].[AddBatchRecord] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[GetBatchRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetBatchRecords] GO CREATE PROCEDURE [dbo].[GetBatchRecords] @BatchID uniqueidentifier AS SELECT [Action], Item, Parent, Param, BoolParam, Content, Properties FROM [Batch] WHERE BatchID = @BatchID ORDER BY AddedOn GO GRANT EXECUTE ON [dbo].[GetBatchRecords] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteBatchRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteBatchRecords] GO CREATE PROCEDURE [dbo].[DeleteBatchRecords] @BatchID uniqueidentifier AS DELETE FROM [Batch] WHERE BatchID = @BatchID GO GRANT EXECUTE ON [dbo].[DeleteBatchRecords] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanBatchRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanBatchRecords] GO CREATE PROCEDURE [dbo].[CleanBatchRecords] @MaxAgeMinutes int AS DELETE FROM [Batch] where BatchID in ( SELECT BatchID FROM [Batch] WHERE AddedOn < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) ) GO GRANT EXECUTE ON [dbo].[CleanBatchRecords] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanOrphanedPolicies]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanOrphanedPolicies] GO -- Cleaning orphan policies CREATE PROCEDURE [dbo].[CleanOrphanedPolicies] AS DELETE [Policies] WHERE [Policies].[PolicyFlag] = 0 AND NOT EXISTS (SELECT ItemID FROM [Catalog] WHERE [Catalog].[PolicyID] = [Policies].[PolicyID]) DELETE [Policies] FROM [Policies] INNER JOIN [ModelItemPolicy] ON [ModelItemPolicy].[PolicyID] = [Policies].[PolicyID] WHERE NOT EXISTS (SELECT ItemID FROM [Catalog] WHERE [Catalog].[ItemID] = [ModelItemPolicy].[CatalogItemID]) GO GRANT EXECUTE ON [dbo].[CleanOrphanedPolicies] TO RSExecRole GO -------------------------------------------------- ------------- Snapshot manipulation if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[IncreaseTransientSnapshotRefcount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[IncreaseTransientSnapshotRefcount] GO CREATE PROCEDURE [dbo].[IncreaseTransientSnapshotRefcount] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @ExpirationMinutes as int AS DECLARE @soon AS datetime SET @soon = DATEADD(n, @ExpirationMinutes, GETDATE()) if @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET ExpirationDate = @soon, TransientRefcount = TransientRefcount + 1 WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET ExpirationDate = @soon, TransientRefcount = TransientRefcount + 1 WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[IncreaseTransientSnapshotRefcount] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DecreaseTransientSnapshotRefcount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DecreaseTransientSnapshotRefcount] GO CREATE PROCEDURE [dbo].[DecreaseTransientSnapshotRefcount] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS if @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET TransientRefcount = TransientRefcount - 1 WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET TransientRefcount = TransientRefcount - 1 WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[DecreaseTransientSnapshotRefcount] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[MarkSnapshotAsDependentOnUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[MarkSnapshotAsDependentOnUser] GO CREATE PROCEDURE [dbo].[MarkSnapshotAsDependentOnUser] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS if @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET DependsOnUser = 1 WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET DependsOnUser = 1 WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[MarkSnapshotAsDependentOnUser] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSnapshotChunksVersion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSnapshotChunksVersion] GO CREATE PROCEDURE [dbo].[SetSnapshotChunksVersion] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @Version as smallint AS if @IsPermanentSnapshot = 1 BEGIN if @Version > 0 BEGIN UPDATE ChunkData SET Version = @Version WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ChunkData SET Version = Version WHERE SnapshotDataID = @SnapshotDataID END END ELSE BEGIN if @Version > 0 BEGIN UPDATE ReportServerTempDB.dbo.ChunkData SET Version = @Version WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.ChunkData SET Version = Version WHERE SnapshotDataID = @SnapshotDataID END END GO GRANT EXECUTE ON [dbo].[SetSnapshotChunksVersion] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[LockSnapshotForUpgrade]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[LockSnapshotForUpgrade] GO CREATE PROCEDURE [dbo].[LockSnapshotForUpgrade] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS if @IsPermanentSnapshot = 1 BEGIN SELECT ChunkName from ChunkData with (XLOCK) WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN SELECT ChunkName from ReportServerTempDB.dbo.ChunkData with (XLOCK) WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[LockSnapshotForUpgrade] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[InsertUnreferencedSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[InsertUnreferencedSnapshot] GO CREATE PROCEDURE [dbo].[InsertUnreferencedSnapshot] @ReportID as uniqueidentifier = NULL, @EffectiveParams as ntext = NULL, @QueryParams as ntext = NULL, @ParamsHash as int = NULL, @CreatedDate as datetime, @Description as nvarchar(512) = NULL, @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @SnapshotTimeoutMinutes as int, @Machine as nvarchar(512) = NULL AS DECLARE @now datetime SET @now = GETDATE() IF @IsPermanentSnapshot = 1 BEGIN INSERT INTO SnapshotData (SnapshotDataID, CreatedDate, EffectiveParams, QueryParams, ParamsHash, Description, PermanentRefcount, TransientRefcount, ExpirationDate) VALUES (@SnapshotDataID, @CreatedDate, @EffectiveParams, @QueryParams, @ParamsHash, @Description, 0, 1, DATEADD(n, @SnapshotTimeoutMinutes, @now)) END ELSE BEGIN INSERT INTO ReportServerTempDB.dbo.SnapshotData (SnapshotDataID, CreatedDate, EffectiveParams, QueryParams, ParamsHash, Description, PermanentRefcount, TransientRefcount, ExpirationDate, Machine) VALUES (@SnapshotDataID, @CreatedDate, @EffectiveParams, @QueryParams, @ParamsHash, @Description, 0, 1, DATEADD(n, @SnapshotTimeoutMinutes, @now), @Machine) END GO GRANT EXECuTE ON [dbo].[InsertUnreferencedSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[PromoteSnapshotInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[PromoteSnapshotInfo] GO CREATE PROCEDURE [dbo].[PromoteSnapshotInfo] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @PageCount as int, @HasDocMap as bit AS IF @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET PageCount = @PageCount, HasDocMap = @HasDocMap WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET PageCount = @PageCount, HasDocMap = @HasDocMap WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[PromoteSnapshotInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapshotPromotedInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapshotPromotedInfo] GO CREATE PROCEDURE [dbo].[GetSnapshotPromotedInfo] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS IF @IsPermanentSnapshot = 1 BEGIN SELECT PageCount, HasDocMap FROM SnapshotData WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN SELECT PageCount, HasDocMap FROM ReportServerTempDB.dbo.SnapshotData WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[GetSnapshotPromotedInfo] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[AddHistoryRecord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddHistoryRecord] GO -- add new record to History table CREATE PROCEDURE [dbo].[AddHistoryRecord] @HistoryID uniqueidentifier, @ReportID uniqueidentifier, @SnapshotDate datetime, @SnapshotDataID uniqueidentifier, @SnapshotTransientRefcountChange int AS INSERT INTO History (HistoryID, ReportID, SnapshotDataID, SnapshotDate) VALUES (@HistoryID, @ReportID, @SnapshotDataID, @SnapshotDate) IF @@ERROR = 0 BEGIN UPDATE SnapshotData -- Snapshots, when created, have transient refcount set to 1. Here create permanent reference -- here so we need to increase permanent refcount and decrease transient refcount. However, -- if it was already referenced by the execution snapshot, transient refcount was already -- decreased. Hence, there's a parameter @SnapshotTransientRefcountChange that is 0 or -1. SET PermanentRefcount = PermanentRefcount + 1, TransientRefcount = TransientRefcount + @SnapshotTransientRefcountChange WHERE SnapshotData.SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[AddHistoryRecord] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[SetHistoryLimit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetHistoryLimit] GO CREATE PROCEDURE [dbo].[SetHistoryLimit] @Path nvarchar (425), @SnapshotLimit int = NULL AS UPDATE Catalog SET SnapshotLimit=@SnapshotLimit WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[SetHistoryLimit] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[ListHistory]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListHistory] GO -- list all historical snapshots for a specific report CREATE PROCEDURE [dbo].[ListHistory] @ReportID uniqueidentifier AS SELECT S.SnapshotDate, (SELECT SUM(DATALENGTH( CD.Content ) ) FROM ChunkData AS CD WHERE CD.SnapshotDataID = S.SnapshotDataID ) FROM History AS S -- skipping intermediate table SnapshotData WHERE S.ReportID = @ReportID GO GRANT EXECUTE ON [dbo].[ListHistory] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanHistoryForReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanHistoryForReport] GO -- delete snapshots exceeding # of snapshots. won't work if @SnapshotLimit = 0 CREATE PROCEDURE [dbo].[CleanHistoryForReport] @SnapshotLimit int, @ReportID uniqueidentifier AS DECLARE @cmd varchar(2000) SET @cmd = 'DELETE FROM History WHERE ReportID = ''' + cast(@ReportID as varchar(40) ) + ''' and SnapshotDate < (SELECT MIN(SnapshotDate) FROM (SELECT TOP ' + CAST(@SnapshotLimit as varchar(20)) + ' SnapshotDate FROM History WHERE ReportID = ''' + cast(@ReportID as varchar(40) ) + ''' ORDER BY SnapshotDate DESC ) AS TopSnapshots )' EXEC( @cmd ) GO GRANT EXECUTE ON [dbo].[CleanHistoryForReport] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanAllHistories]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanAllHistories] GO -- delete snapshots exceeding # of snapshots for the whole system CREATE PROCEDURE [dbo].[CleanAllHistories] @SnapshotLimit int AS DECLARE @cmd varchar(2000) SET @cmd = 'DELETE FROM History WHERE HistoryID in (SELECT HistoryID FROM History JOIN Catalog AS ReportJoinSnapshot ON ItemID = ReportID WHERE SnapshotLimit is NULL and SnapshotDate < (SELECT MIN(SnapshotDate) FROM (SELECT TOP ' + CAST(@SnapshotLimit as varchar(20)) + ' SnapshotDate FROM History AS InnerSnapshot WHERE InnerSnapshot.ReportID = ReportJoinSnapshot.ItemID ORDER BY SnapshotDate DESC ) AS TopSnapshots ) )' EXEC( @cmd ) GO GRANT EXECUTE ON [dbo].[CleanAllHistories] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteHistoryRecord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteHistoryRecord] GO -- delete one historical snapshot CREATE PROCEDURE [dbo].[DeleteHistoryRecord] @ReportID uniqueidentifier, @SnapshotDate DateTime AS DELETE FROM History WHERE ReportID = @ReportID AND SnapshotDate = @SnapshotDate GO GRANT EXECUTE ON [dbo].[DeleteHistoryRecord] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteAllHistoryForReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteAllHistoryForReport] GO -- delete all snapshots for a report CREATE PROCEDURE [dbo].[DeleteAllHistoryForReport] @ReportID uniqueidentifier AS DELETE FROM History WHERE HistoryID in (SELECT HistoryID FROM History JOIN Catalog on ItemID = ReportID WHERE ReportID = @ReportID ) GO GRANT EXECUTE ON [dbo].[DeleteAllHistoryForReport] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteHistoriesWithNoPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteHistoriesWithNoPolicy] GO -- delete all snapshots for all reports that inherit system History policy CREATE PROCEDURE [dbo].[DeleteHistoriesWithNoPolicy] AS DELETE FROM History WHERE HistoryID in (SELECT HistoryID FROM History JOIN Catalog on ItemID = ReportID WHERE SnapshotLimit is null ) GO GRANT EXECUTE ON [dbo].[DeleteHistoriesWithNoPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Get_sqlagent_job_status]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[Get_sqlagent_job_status] GO CREATE PROCEDURE [dbo].[Get_sqlagent_job_status] -- Individual job parameters @job_id UNIQUEIDENTIFIER = NULL, -- If provided will only return info about this job -- Note: Only @job_id or @job_name needs to be provided @job_name sysname = NULL, -- If provided will only return info about this job @owner_login_name sysname = NULL -- If provided will only return jobs for this owner AS BEGIN DECLARE @retval INT DECLARE @job_owner_sid VARBINARY(85) DECLARE @is_sysadmin INT SET NOCOUNT ON -- Remove any leading/trailing spaces from parameters (except @owner_login_name) SELECT @job_name = LTRIM(RTRIM(@job_name)) -- Turn [nullable] empty string parameters into NULLs IF (@job_name = N'') SELECT @job_name = NULL -- Verify the job if supplied. This also checks if the caller has rights to view the job IF ((@job_id IS NOT NULL) OR (@job_name IS NOT NULL)) BEGIN EXECUTE @retval = msdb..sp_verify_job_identifiers '@job_name', '@job_id', @job_name OUTPUT, @job_id OUTPUT IF (@retval <> 0) RETURN(1) -- Failure END -- If the login name isn't given, set it to the job owner or the current caller IF(@owner_login_name IS NULL) BEGIN SET @owner_login_name = (SELECT SUSER_SNAME(sj.owner_sid) FROM msdb.dbo.sysjobs sj where sj.job_id = @job_id) SET @is_sysadmin = ISNULL(IS_SRVROLEMEMBER(N'sysadmin', @owner_login_name), 0) END ELSE BEGIN -- Check owner IF (SUSER_SID(@owner_login_name) IS NULL) BEGIN RAISERROR(14262, -1, -1, '@owner_login_name', @owner_login_name) RETURN(1) -- Failure END --only allow sysadmin types to specify the owner IF ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1) AND (ISNULL(IS_MEMBER(N'SQLAgentAdminRole'), 0) = 1) AND (SUSER_SNAME() <> @owner_login_name)) BEGIN --TODO: RAISERROR(14525, -1, -1) RETURN(1) -- Failure END SET @is_sysadmin = 0 END IF (@job_id IS NOT NULL) BEGIN -- Individual job... EXECUTE @retval = master.dbo.xp_sqlagent_enum_jobs @is_sysadmin, @owner_login_name, @job_id IF (@retval <> 0) RETURN(1) -- Failure END ELSE BEGIN -- Set of jobs... EXECUTE @retval = master.dbo.xp_sqlagent_enum_jobs @is_sysadmin, @owner_login_name IF (@retval <> 0) RETURN(1) -- Failure END RETURN(0) -- Success END GO GRANT EXECUTE ON [dbo].[Get_sqlagent_job_status] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateTask] GO CREATE PROCEDURE [dbo].[CreateTask] @ScheduleID uniqueidentifier, @Name nvarchar (260), @StartDate datetime, @Flags int, @NextRunTime datetime = NULL, @LastRunTime datetime = NULL, @EndDate datetime = NULL, @RecurrenceType int = NULL, @MinutesInterval int = NULL, @DaysInterval int = NULL, @WeeksInterval int = NULL, @DaysOfWeek int = NULL, @DaysOfMonth int = NULL, @Month int = NULL, @MonthlyWeek int = NULL, @State int = NULL, @LastRunStatus nvarchar (260) = NULL, @ScheduledRunTimeout int = NULL, @UserSid varbinary (85) = null, @UserName nvarchar(260), @AuthType int, @EventType nvarchar (260), @EventData nvarchar (260), @Type int AS DECLARE @UserID uniqueidentifier EXEC GetUserID @UserSid, @UserName, @AuthType, @UserID OUTPUT -- Create a task with the given data. Insert into Schedule ( [ScheduleID], [Name], [StartDate], [Flags], [NextRunTime], [LastRunTime], [EndDate], [RecurrenceType], [MinutesInterval], [DaysInterval], [WeeksInterval], [DaysOfWeek], [DaysOfMonth], [Month], [MonthlyWeek], [State], [LastRunStatus], [ScheduledRunTimeout], [CreatedById], [EventType], [EventData], [Type] ) values (@ScheduleID, @Name, @StartDate, @Flags, @NextRunTime, @LastRunTime, @EndDate, @RecurrenceType, @MinutesInterval, @DaysInterval, @WeeksInterval, @DaysOfWeek, @DaysOfMonth, @Month, @MonthlyWeek, @State, @LastRunStatus, @ScheduledRunTimeout, @UserID, @EventType, @EventData, @Type) GO GRANT EXECUTE ON [dbo].[CreateTask] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateTask] GO CREATE PROCEDURE [dbo].[UpdateTask] @ScheduleID uniqueidentifier, @Name nvarchar (260), @StartDate datetime, @Flags int, @NextRunTime datetime = NULL, @LastRunTime datetime = NULL, @EndDate datetime = NULL, @RecurrenceType int = NULL, @MinutesInterval int = NULL, @DaysInterval int = NULL, @WeeksInterval int = NULL, @DaysOfWeek int = NULL, @DaysOfMonth int = NULL, @Month int = NULL, @MonthlyWeek int = NULL, @State int = NULL, @LastRunStatus nvarchar (260) = NULL, @ScheduledRunTimeout int = NULL AS -- Update a tasks values. ScheduleID and Report information can not be updated Update Schedule set [StartDate] = @StartDate, [Name] = @Name, [Flags] = @Flags, [NextRunTime] = @NextRunTime, [LastRunTime] = @LastRunTime, [EndDate] = @EndDate, [RecurrenceType] = @RecurrenceType, [MinutesInterval] = @MinutesInterval, [DaysInterval] = @DaysInterval, [WeeksInterval] = @WeeksInterval, [DaysOfWeek] = @DaysOfWeek, [DaysOfMonth] = @DaysOfMonth, [Month] = @Month, [MonthlyWeek] = @MonthlyWeek, [State] = @State, [LastRunStatus] = @LastRunStatus, [ScheduledRunTimeout] = @ScheduledRunTimeout where [ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[UpdateTask] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateScheduleNextRunTime]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateScheduleNextRunTime] GO CREATE PROCEDURE [dbo].[UpdateScheduleNextRunTime] @ScheduleID as uniqueidentifier, @NextRunTime as datetime as update Schedule set [NextRunTime] = @NextRunTime where [ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[UpdateScheduleNextRunTime] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListScheduledReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListScheduledReports] GO CREATE PROCEDURE [dbo].[ListScheduledReports] @ScheduleID uniqueidentifier, @AuthType int AS -- List all reports for a schedule select RS.[ReportAction], RS.[ScheduleID], RS.[ReportID], RS.[SubscriptionID], C.[Path], C.[Name], C.[Description], C.[ModifiedDate], SUSER_SNAME(U.[Sid]), U.[UserName], DATALENGTH( C.Content ), C.ExecutionTime, S.[Type], SD.[NtSecDescPrimary] from [ReportSchedule] RS Inner join [Catalog] C on RS.[ReportID] = C.[ItemID] left outer join [SecData] SD on SD.[PolicyID] = C.[PolicyID] AND SD.AuthType = @AuthType Inner join [Schedule] S on RS.[ScheduleID] = S.[ScheduleID] Inner join [Users] U on C.[ModifiedByID] = U.UserID where RS.[ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[ListScheduledReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListTasks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListTasks] GO CREATE PROCEDURE [dbo].[ListTasks] AS select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], (select count(*) from ReportSchedule where ReportSchedule.ScheduleID = S.ScheduleID) from [Schedule] S inner join [Users] Owner on S.[CreatedById] = Owner.UserID where S.[Type] = 0 -- Type 0 is shared schedules GO GRANT EXECUTE ON [dbo].[ListTasks] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListTasksForMaintenance]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListTasksForMaintenance] GO CREATE PROCEDURE [dbo].[ListTasksForMaintenance] AS declare @date datetime set @date = GETUTCDATE() update [Schedule] set [ConsistancyCheck] = @date from ( SELECT TOP 20 [ScheduleID] FROM [Schedule] WITH(UPDLOCK) WHERE [ConsistancyCheck] is NULL ) AS t1 WHERE [Schedule].[ScheduleID] = t1.[ScheduleID] select top 20 S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type] from [Schedule] S where [ConsistancyCheck] = @date GO GRANT EXECUTE ON [dbo].[ListTasksForMaintenance] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ClearScheduleConsistancyFlags]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ClearScheduleConsistancyFlags] GO CREATE PROCEDURE [dbo].[ClearScheduleConsistancyFlags] AS update [Schedule] with (tablock, xlock) set [ConsistancyCheck] = NULL GO GRANT EXECUTE ON [dbo].[ClearScheduleConsistancyFlags] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAReportsReportAction]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAReportsReportAction] GO CREATE PROCEDURE [dbo].[GetAReportsReportAction] @ReportID uniqueidentifier, @ReportAction int AS select RS.[ReportAction], RS.[ScheduleID], RS.[ReportID], RS.[SubscriptionID], C.[Path] from [ReportSchedule] RS Inner join [Catalog] C on RS.[ReportID] = C.[ItemID] where C.ItemID = @ReportID and RS.[ReportAction] = @ReportAction GO GRANT EXECUTE ON [dbo].[GetAReportsReportAction] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetTimeBasedSubscriptionReportAction]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetTimeBasedSubscriptionReportAction] GO CREATE PROCEDURE [dbo].[GetTimeBasedSubscriptionReportAction] @SubscriptionID uniqueidentifier AS select RS.[ReportAction], RS.[ScheduleID], RS.[ReportID], RS.[SubscriptionID], C.[Path] from [ReportSchedule] RS Inner join [Catalog] C on RS.[ReportID] = C.[ItemID] where RS.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetTimeBasedSubscriptionReportAction] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetTaskProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetTaskProperties] GO CREATE PROCEDURE [dbo].[GetTaskProperties] @ScheduleID uniqueidentifier AS -- Grab all of a tasks properties given a task id select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], SUSER_SNAME(Owner.[Sid]), Owner.[UserName] from [Schedule] S with (XLOCK) Inner join [Users] Owner on S.[CreatedById] = Owner.UserID where S.[ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[GetTaskProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteTask] GO CREATE PROCEDURE [dbo].[DeleteTask] @ScheduleID uniqueidentifier AS -- Delete the task with the given task id DELETE FROM Schedule WHERE [ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[DeleteTask] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSchedulesReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSchedulesReports] GO CREATE PROCEDURE [dbo].[GetSchedulesReports] @ID uniqueidentifier AS select C.Path from ReportSchedule RS inner join Catalog C on (C.ItemID = RS.ReportID) where ScheduleID = @ID GO GRANT EXECUTE ON [dbo].[GetSchedulesReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddReportSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddReportSchedule] GO CREATE PROCEDURE [dbo].[AddReportSchedule] @ScheduleID uniqueidentifier, @ReportID uniqueidentifier, @SubscriptionID uniqueidentifier = NULL, @Action int AS Insert into ReportSchedule ([ScheduleID], [ReportID], [SubscriptionID], [ReportAction]) values (@ScheduleID, @ReportID, @SubscriptionID, @Action) GO GRANT EXECUTE ON [dbo].[AddReportSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteReportSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteReportSchedule] GO CREATE PROCEDURE [dbo].[DeleteReportSchedule] @ScheduleID uniqueidentifier, @ReportID uniqueidentifier, @SubscriptionID uniqueidentifier = NULL, @ReportAction int AS IF @SubscriptionID is NULL BEGIN delete from ReportSchedule where ScheduleID = @ScheduleID and ReportID = @ReportID and ReportAction = @ReportAction END ELSE BEGIN delete from ReportSchedule where ScheduleID = @ScheduleID and ReportID = @ReportID and ReportAction = @ReportAction and SubscriptionID = @SubscriptionID END GO GRANT EXECUTE ON [dbo].[DeleteReportSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapShotSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapShotSchedule] GO CREATE PROCEDURE [dbo].[GetSnapShotSchedule] @ReportID uniqueidentifier AS select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], SUSER_SNAME(Owner.[Sid]), Owner.[UserName] from Schedule S with (XLOCK) inner join ReportSchedule RS on S.ScheduleID = RS.ScheduleID inner join [Users] Owner on S.[CreatedById] = Owner.[UserID] where RS.ReportAction = 2 and -- 2 == create snapshot RS.ReportID = @ReportID GO GRANT EXECUTE ON [dbo].[GetSnapShotSchedule] TO RSExecRole GO -------------------------------------------------- ------------- Time based subscriptions if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateTimeBasedSubscriptionSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateTimeBasedSubscriptionSchedule] GO CREATE PROCEDURE [dbo].[CreateTimeBasedSubscriptionSchedule] @SubscriptionID as uniqueidentifier, @ScheduleID uniqueidentifier, @Schedule_Name nvarchar (260), @Report_Name nvarchar (425), @StartDate datetime, @Flags int, @NextRunTime datetime = NULL, @LastRunTime datetime = NULL, @EndDate datetime = NULL, @RecurrenceType int = NULL, @MinutesInterval int = NULL, @DaysInterval int = NULL, @WeeksInterval int = NULL, @DaysOfWeek int = NULL, @DaysOfMonth int = NULL, @Month int = NULL, @MonthlyWeek int = NULL, @State int = NULL, @LastRunStatus nvarchar (260) = NULL, @ScheduledRunTimeout int = NULL, @UserSid varbinary (85) = NULL, @UserName nvarchar(260), @AuthType int, @EventType nvarchar (260), @EventData nvarchar (260) AS EXEC CreateTask @ScheduleID, @Schedule_Name, @StartDate, @Flags, @NextRunTime, @LastRunTime, @EndDate, @RecurrenceType, @MinutesInterval, @DaysInterval, @WeeksInterval, @DaysOfWeek, @DaysOfMonth, @Month, @MonthlyWeek, @State, @LastRunStatus, @ScheduledRunTimeout, @UserSid, @UserName, @AuthType, @EventType, @EventData, 1 -- scoped type -- add a row to the reportSchedule table declare @Report_OID uniqueidentifier select @Report_OID = (select [ItemID] from [Catalog] with (HOLDLOCK) where [Catalog].[Path] = @Report_Name and ([Catalog].[Type] = 2 or [Catalog].[Type] = 4)) EXEC AddReportSchedule @ScheduleID, @Report_OID, @SubscriptionID, 4 -- TimedSubscription action GO GRANT EXECUTE ON [dbo].[CreateTimeBasedSubscriptionSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetTimeBasedSubscriptionSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetTimeBasedSubscriptionSchedule] GO CREATE PROCEDURE [dbo].[GetTimeBasedSubscriptionSchedule] @SubscriptionID as uniqueidentifier AS select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], SUSER_SNAME(Owner.[Sid]), Owner.[UserName] from [ReportSchedule] R inner join Schedule S with (XLOCK) on R.[ScheduleID] = S.[ScheduleID] Inner join [Users] Owner on S.[CreatedById] = Owner.UserID where R.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetTimeBasedSubscriptionSchedule] TO RSExecRole GO -------------------------------------------------- ------------- Running Jobs if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddRunningJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddRunningJob] GO CREATE PROCEDURE [dbo].[AddRunningJob] @JobID as nvarchar(32), @StartDate as datetime, @ComputerName as nvarchar(32), @RequestName as nvarchar(425), @RequestPath as nvarchar(425), @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @Description as ntext = NULL, @Timeout as int, @JobAction as smallint, @JobType as smallint, @JobStatus as smallint AS DECLARE @UserID uniqueidentifier EXEC GetUserID @UserSid, @UserName, @AuthType, @UserID OUTPUT INSERT INTO RunningJobs (JobID, StartDate, ComputerName, RequestName, RequestPath, UserID, Description, Timeout, JobAction, JobType, JobStatus ) VALUES (@JobID, @StartDate, @ComputerName, @RequestName, @RequestPath, @UserID, @Description, @Timeout, @JobAction, @JobType, @JobStatus) GO GRANT EXECUTE ON [dbo].[AddRunningJob] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RemoveRunningJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RemoveRunningJob] GO CREATE PROCEDURE [dbo].[RemoveRunningJob] @JobID as nvarchar(32) AS DELETE FROM RunningJobs WHERE JobID = @JobID GO GRANT EXECUTE ON [dbo].[RemoveRunningJob] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateRunningJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateRunningJob] GO CREATE PROCEDURE [dbo].[UpdateRunningJob] @JobID as nvarchar(32), @JobStatus as smallint AS UPDATE RunningJobs SET JobStatus = @JobStatus WHERE JobID = @JobID GO GRANT EXECUTE ON [dbo].[UpdateRunningJob] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetMyRunningJobs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetMyRunningJobs] GO CREATE PROCEDURE [dbo].[GetMyRunningJobs] @ComputerName as nvarchar(32), @JobType as smallint AS SELECT JobID, StartDate, ComputerName, RequestName, RequestPath, SUSER_SNAME(Users.[Sid]), Users.[UserName], Description, Timeout, JobAction, JobType, JobStatus FROM RunningJobs INNER JOIN Users ON RunningJobs.UserID = Users.UserID WHERE ComputerName = @ComputerName AND JobType = @JobType GO GRANT EXECUTE ON [dbo].[GetMyRunningJobs] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListRunningJobs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListRunningJobs] GO CREATE PROCEDURE [dbo].[ListRunningJobs] AS SELECT JobID, StartDate, ComputerName, RequestName, RequestPath, SUSER_SNAME(Users.[Sid]), Users.[UserName], Description, Timeout, JobAction, JobType, JobStatus FROM RunningJobs INNER JOIN Users ON RunningJobs.UserID = Users.UserID GO GRANT EXECUTE ON [dbo].[ListRunningJobs] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredJobs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredJobs] GO CREATE PROCEDURE [dbo].[CleanExpiredJobs] AS DELETE FROM RunningJobs WHERE DATEADD(s, Timeout, StartDate) < GETDATE() GO GRANT EXECUTE ON [dbo].[CleanExpiredJobs] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateObject]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateObject] GO -- This SP should never be called with a policy ID unless it is guarenteed that -- the parent will not be deleted before the insert (such as while running this script) CREATE PROCEDURE [dbo].[CreateObject] @ItemID uniqueidentifier, @Name nvarchar (425), @Path nvarchar (425), @ParentID uniqueidentifier, @Type int, @Content image = NULL, @Intermediate uniqueidentifier = NULL, @LinkSourceID uniqueidentifier = NULL, @Property ntext = NULL, @Parameter ntext = NULL, @Description ntext = NULL, @Hidden bit = NULL, @CreatedBySid varbinary(85) = NULL, @CreatedByName nvarchar(260), @AuthType int, @CreationDate datetime, @MimeType nvarchar (260) = NULL, @SnapshotLimit int = NULL, @PolicyRoot int = 0, @PolicyID uniqueidentifier = NULL, @ExecutionFlag int = 1 -- allow live execution, don't keep history AS DECLARE @CreatedByID uniqueidentifier EXEC GetUserID @CreatedBySid, @CreatedByName, @AuthType, @CreatedByID OUTPUT UPDATE Catalog with (XLOCK) SET ModifiedByID = @CreatedByID, ModifiedDate = @CreationDate WHERE ItemID = @ParentID -- If no policyID, use the parent's IF @PolicyID is NULL BEGIN SET @PolicyID = (SELECT PolicyID FROM [dbo].[Catalog] WHERE Catalog.ItemID = @ParentID) END -- If there is no policy ID then we are guarenteed not to have a parent IF @PolicyID is NULL BEGIN RAISERROR ('Parent Not Found', 16, 1) return END INSERT INTO Catalog (ItemID, Path, Name, ParentID, Type, Content, Intermediate, LinkSourceID, Property, Description, Hidden, CreatedByID, CreationDate, ModifiedByID, ModifiedDate, MimeType, SnapshotLimit, [Parameter], PolicyID, PolicyRoot, ExecutionFlag ) VALUES (@ItemID, @Path, @Name, @ParentID, @Type, @Content, @Intermediate, @LinkSourceID, @Property, @Description, @Hidden, @CreatedByID, @CreationDate, @CreatedByID, @CreationDate, @MimeType, @SnapshotLimit, @Parameter, @PolicyID, @PolicyRoot , @ExecutionFlag) IF @Intermediate IS NOT NULL AND @@ERROR = 0 BEGIN UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount + 1, TransientRefcount = TransientRefcount - 1 WHERE SnapshotData.SnapshotDataID = @Intermediate END GO GRANT EXECUTE ON [dbo].[CreateObject] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteObject]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteObject] GO CREATE PROCEDURE [dbo].[DeleteObject] @Path nvarchar (425), @Prefix nvarchar (850) AS -- Remove reference for intermediate formats UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 FROM Catalog AS R WITH (XLOCK) INNER JOIN [SnapshotData] AS SD ON R.Intermediate = SD.SnapshotDataID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Remove reference for execution snapshots UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 FROM Catalog AS R WITH (XLOCK) INNER JOIN [SnapshotData] AS SD ON R.SnapshotDataID = SD.SnapshotDataID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Remove history for deleted reports and linked report DELETE History FROM [Catalog] AS R INNER JOIN [History] AS S ON R.ItemID = S.ReportID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Remove model drill reports DELETE ModelDrill FROM [Catalog] AS C INNER JOIN [ModelDrill] AS M ON C.ItemID = M.ReportID WHERE (C.Path = @Path OR C.Path LIKE @Prefix ESCAPE '*') -- Adjust data sources UPDATE [DataSource] SET [Flags] = [Flags] & 0x7FFFFFFD, -- broken link [Link] = NULL FROM [Catalog] AS C INNER JOIN [DataSource] AS DS ON C.[ItemID] = DS.[Link] WHERE (C.Path = @Path OR C.Path LIKE @Prefix ESCAPE '*') -- Clean all data sources DELETE [DataSource] FROM [Catalog] AS R INNER JOIN [DataSource] AS DS ON R.[ItemID] = DS.[ItemID] WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Update linked reports UPDATE LR SET LR.LinkSourceID = NULL FROM [Catalog] AS R INNER JOIN [Catalog] AS LR ON R.ItemID = LR.LinkSourceID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') AND (LR.Path NOT LIKE @Prefix ESCAPE '*') -- Remove references for cache entries UPDATE SN SET PermanentRefcount = PermanentRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC on SN.SnapshotDataID = EC.SnapshotDataID INNER JOIN Catalog AS C ON EC.ReportID = C.ItemID WHERE (Path = @Path OR Path LIKE @Prefix ESCAPE '*') -- Clean cache entries for items to be deleted DELETE EC FROM ReportServerTempDB.dbo.ExecutionCache AS EC INNER JOIN Catalog AS C ON EC.ReportID = C.ItemID WHERE (Path = @Path OR Path LIKE @Prefix ESCAPE '*') -- Finally delete items DELETE FROM [Catalog] WHERE (Path = @Path OR Path LIKE @Prefix ESCAPE '*') EXEC CleanOrphanedPolicies GO GRANT EXECUTE ON [dbo].[DeleteObject] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindObjectsNonRecursive]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindObjectsNonRecursive] GO CREATE PROCEDURE [dbo].[FindObjectsNonRecursive] @Path nvarchar (425), @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.[UserName], SUSER_SNAME(MU.Sid), MU.[UserName], C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Catalog AS P ON C.ParentID = P.ItemID INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE P.Path = @Path GO GRANT EXECUTE ON [dbo].[FindObjectsNonRecursive] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindObjectsRecursive]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindObjectsRecursive] GO CREATE PROCEDURE [dbo].[FindObjectsRecursive] @Prefix nvarchar (850), @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.UserName, SUSER_SNAME(MU.Sid), MU.UserName, C.MimeType, C.ExecutionTime, C.Hidden from Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE C.Path LIKE @Prefix ESCAPE '*' GO GRANT EXECUTE ON [dbo].[FindObjectsRecursive] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindObjectsByLink]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindObjectsByLink] GO CREATE PROCEDURE [dbo].[FindObjectsByLink] @Link uniqueidentifier, @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.UserName, SUSER_SNAME(MU.Sid), MU.UserName, C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE C.LinkSourceID = @Link GO GRANT EXECUTE ON [dbo].[FindObjectsByLink] TO RSExecRole GO -------------------------------------------------- ------------- Procedures used to update linked reports if exists (select * from sysobjects where id = object_id('[dbo].[GetIDPairsByLink]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetIDPairsByLink] GO CREATE PROCEDURE [dbo].[GetIDPairsByLink] @Link uniqueidentifier AS SELECT LinkSourceID, ItemID FROM Catalog WHERE LinkSourceID = @Link GO GRANT EXECUTE ON [dbo].[GetIDPairsByLink] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[GetChildrenBeforeDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetChildrenBeforeDelete] GO CREATE PROCEDURE [dbo].[GetChildrenBeforeDelete] @Prefix nvarchar (850), @AuthType int AS SELECT C.PolicyID, C.Type, SD.NtSecDescPrimary FROM Catalog AS C LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE C.Path LIKE @Prefix ESCAPE '*' -- return children only, not item itself GO GRANT EXECUTE ON [dbo].[GetChildrenBeforeDelete] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAllProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAllProperties] GO CREATE PROCEDURE [dbo].[GetAllProperties] @Path nvarchar (425), @AuthType int AS select Property, Description, Type, DATALENGTH( Content ), ItemID, SUSER_SNAME(C.Sid), C.UserName, CreationDate, SUSER_SNAME(M.Sid), M.UserName, ModifiedDate, MimeType, ExecutionTime, NtSecDescPrimary, [LinkSourceID], Hidden, ExecutionFlag, SnapshotLimit FROM Catalog INNER JOIN Users C ON Catalog.CreatedByID = C.UserID INNER JOIN Users M ON Catalog.ModifiedByID = M.UserID LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[GetAllProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetParameters] GO CREATE PROCEDURE [dbo].[GetParameters] @Path nvarchar (425), @AuthType int AS SELECT Type, [Parameter], ItemID, SecData.NtSecDescPrimary, [LinkSourceID], [ExecutionFlag] FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[GetParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetObjectContent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetObjectContent] GO CREATE PROCEDURE [dbo].[GetObjectContent] @Path nvarchar (425), @AuthType int AS SELECT Type, Content, LinkSourceID, MimeType, SecData.NtSecDescPrimary, ItemID FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[GetObjectContent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCompiledDefinition]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetCompiledDefinition] GO -- used to create snapshots CREATE PROCEDURE [dbo].[GetCompiledDefinition] @Path nvarchar (425), @AuthType int AS SELECT MainItem.Type, MainItem.Intermediate, MainItem.LinkSourceID, MainItem.Property, MainItem.Description, SecData.NtSecDescPrimary, MainItem.ItemID, MainItem.ExecutionFlag, LinkTarget.Intermediate, LinkTarget.Property, LinkTarget.Description, MainItem.[SnapshotDataID] FROM Catalog MainItem LEFT OUTER JOIN SecData ON MainItem.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog LinkTarget with (INDEX = PK_CATALOG) on MainItem.LinkSourceID = LinkTarget.ItemID WHERE MainItem.Path = @Path GO GRANT EXECUTE ON [dbo].[GetCompiledDefinition] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetReportForExecution]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetReportForExecution] GO -- gets either the intermediate format or snapshot from cache CREATE PROCEDURE [dbo].[GetReportForExecution] @Path nvarchar (425), @ParamsHash int, @AuthType int AS DECLARE @now AS datetime SET @now = GETDATE() IF ( NOT EXISTS ( SELECT * FROM Catalog AS C INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON C.ItemID = EC.ReportID INNER JOIN ReportServerTempDB.dbo.SnapshotData AS SN ON EC.SnapshotDataID = SN.SnapshotDataID WHERE C.Path = @Path AND EC.AbsoluteExpiration > @now AND SN.ParamsHash = @ParamsHash ) ) BEGIN -- no cache SELECT Cat.Type, Cat.LinkSourceID, Cat2.Path, Cat.Property, Cat.Description, SecData.NtSecDescPrimary, Cat.ItemID, CAST (0 AS BIT), -- not found, Cat.Intermediate, Cat.ExecutionFlag, SD.SnapshotDataID, SD.DependsOnUser, Cat.ExecutionTime, (SELECT Schedule.NextRunTime FROM Schedule WITH (XLOCK) INNER JOIN ReportSchedule ON Schedule.ScheduleID = ReportSchedule.ScheduleID WHERE ReportSchedule.ReportID = Cat.ItemID AND ReportSchedule.ReportAction = 1), -- update snapshot (SELECT Schedule.ScheduleID FROM Schedule INNER JOIN ReportSchedule ON Schedule.ScheduleID = ReportSchedule.ScheduleID WHERE ReportSchedule.ReportID = Cat.ItemID AND ReportSchedule.ReportAction = 1), -- update snapshot (SELECT CachePolicy.ExpirationFlags FROM CachePolicy WHERE CachePolicy.ReportID = Cat.ItemID), Cat2.Intermediate FROM Catalog AS Cat LEFT OUTER JOIN SecData ON Cat.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog AS Cat2 on Cat.LinkSourceID = Cat2.ItemID LEFT OUTER JOIN SnapshotData AS SD ON Cat.SnapshotDataID = SD.SnapshotDataID WHERE Cat.Path = @Path END ELSE BEGIN -- use cache SELECT TOP 1 Cat.Type, Cat.LinkSourceID, Cat2.Path, Cat.Property, Cat.Description, SecData.NtSecDescPrimary, Cat.ItemID, CAST (1 AS BIT), -- found, SN.SnapshotDataID, SN.DependsOnUser, SN.EffectiveParams, SN.CreatedDate, EC.AbsoluteExpiration, (SELECT CachePolicy.ExpirationFlags FROM CachePolicy WHERE CachePolicy.ReportID = Cat.ItemID), (SELECT Schedule.ScheduleID FROM Schedule WITH (XLOCK) INNER JOIN ReportSchedule ON Schedule.ScheduleID = ReportSchedule.ScheduleID WHERE ReportSchedule.ReportID = Cat.ItemID AND ReportSchedule.ReportAction = 1), -- update snapshot SN.QueryParams FROM Catalog AS Cat INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON Cat.ItemID = EC.ReportID INNER JOIN ReportServerTempDB.dbo.SnapshotData AS SN ON EC.SnapshotDataID = SN.SnapshotDataID LEFT OUTER JOIN SecData ON Cat.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog AS Cat2 on Cat.LinkSourceID = Cat2.ItemID WHERE Cat.Path = @Path AND AbsoluteExpiration > @now AND SN.ParamsHash = @ParamsHash ORDER BY SN.CreatedDate DESC END GO GRANT EXECUTE ON [dbo].[GetReportForExecution] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetReportParametersForExecution]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetReportParametersForExecution] GO -- gets either the intermediate format or snapshot from cache CREATE PROCEDURE [dbo].[GetReportParametersForExecution] @Path nvarchar (425), @HistoryID DateTime = NULL, @AuthType int AS SELECT C.[ItemID], C.[Type], C.[ExecutionFlag], [SecData].[NtSecDescPrimary], C.[Parameter], C.[Intermediate], C.[SnapshotDataID], [History].[SnapshotDataID], L.[Intermediate], C.[LinkSourceID], C.[ExecutionTime] FROM [Catalog] AS C LEFT OUTER JOIN [SecData] ON C.[PolicyID] = [SecData].[PolicyID] AND [SecData].AuthType = @AuthType LEFT OUTER JOIN [History] ON ( C.[ItemID] = [History].[ReportID] AND [History].[SnapshotDate] = @HistoryID ) LEFT OUTER JOIN [Catalog] AS L ON C.[LinkSourceID] = L.[ItemID] WHERE C.[Path] = @Path GO GRANT EXECUTE ON [dbo].[GetReportParametersForExecution] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[MoveObject]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[MoveObject] GO CREATE PROCEDURE [dbo].[MoveObject] @OldPath nvarchar (425), @OldPrefix nvarchar (850), @NewName nvarchar (425), @NewPath nvarchar (425), @NewParentID uniqueidentifier, @RenameOnly as bit, @MaxPathLength as int AS DECLARE @LongPath nvarchar(425) SET @LongPath = (SELECT TOP 1 Path FROM Catalog WHERE LEN(Path)-LEN(@OldPath)+LEN(@NewPath) > @MaxPathLength AND Path LIKE @OldPrefix ESCAPE '*') IF @LongPath IS NOT NULL BEGIN SELECT @LongPath RETURN END IF @RenameOnly = 0 -- if this a full-blown move, not just a rename BEGIN -- adjust policies on the top item that gets moved DECLARE @OldInheritedPolicyID as uniqueidentifier SELECT @OldInheritedPolicyID = (SELECT PolicyID FROM Catalog with (XLOCK) WHERE Path = @OldPath AND PolicyRoot = 0) IF (@OldInheritedPolicyID IS NOT NULL) BEGIN -- this was not a policy root, change it to inherit from target folder DECLARE @NewPolicyID as uniqueidentifier SELECT @NewPolicyID = (SELECT PolicyID FROM Catalog with (XLOCK) WHERE ItemID = @NewParentID) -- update item and children that shared the old policy UPDATE Catalog SET PolicyID = @NewPolicyID WHERE Path = @OldPath UPDATE Catalog SET PolicyID = @NewPolicyID WHERE Path LIKE @OldPrefix ESCAPE '*' AND Catalog.PolicyID = @OldInheritedPolicyID END END -- Update item that gets moved (Path, Name, and ParentId) update Catalog set Name = @NewName, Path = @NewPath, ParentID = @NewParentID where Path = @OldPath -- Update all its children (Path only, Names and ParentIds stay the same) update Catalog set Path = STUFF(Path, 1, LEN(@OldPath), @NewPath ) where Path like @OldPrefix escape '*' GO GRANT EXECUTE ON [dbo].[MoveObject] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ObjectExists]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ObjectExists] GO CREATE PROCEDURE [dbo].[ObjectExists] @Path nvarchar (425), @AuthType int AS SELECT Type, ItemID, SnapshotLimit, NtSecDescPrimary, ExecutionFlag, Intermediate, [LinkSourceID] FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[ObjectExists] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetAllProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetAllProperties] GO CREATE PROCEDURE [dbo].[SetAllProperties] @Path nvarchar (425), @Property ntext, @Description ntext = NULL, @Hidden bit = NULL, @ModifiedBySid varbinary (85) = NULL, @ModifiedByName nvarchar(260), @AuthType int, @ModifiedDate DateTime AS DECLARE @ModifiedByID uniqueidentifier EXEC GetUserID @ModifiedBySid, @ModifiedByName, @AuthType, @ModifiedByID OUTPUT UPDATE Catalog SET Property = @Property, Description = @Description, Hidden = @Hidden, ModifiedByID = @ModifiedByID, ModifiedDate = @ModifiedDate WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[SetAllProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FlushReportFromCache]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FlushReportFromCache] GO CREATE PROCEDURE [dbo].[FlushReportFromCache] @Path as nvarchar(425) AS UPDATE SN SET SN.PermanentRefcount = SN.PermanentRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON SN.SnapshotDataID = EC.SnapshotDataID INNER JOIN Catalog AS C ON EC.ReportID = C.ItemID WHERE C.Path = @Path DELETE EC FROM ReportServerTempDB.dbo.ExecutionCache AS EC INNER JOIN Catalog ON EC.ReportID = Catalog.ItemID WHERE Catalog.Path = @Path GO GRANT EXECUTE ON [dbo].[FlushReportFromCache] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetParameters] GO CREATE PROCEDURE [dbo].[SetParameters] @Path nvarchar (425), @Parameter ntext AS UPDATE Catalog SET [Parameter] = @Parameter WHERE Path = @Path EXEC FlushReportFromCache @Path GO GRANT EXECUTE ON [dbo].[SetParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetObjectContent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetObjectContent] GO CREATE PROCEDURE [dbo].[SetObjectContent] @Path nvarchar (425), @Type int, @Content image = NULL, @Intermediate uniqueidentifier = NULL, @Parameter ntext = NULL, @LinkSourceID uniqueidentifier = NULL, @MimeType nvarchar (260) = NULL AS DECLARE @OldIntermediate as uniqueidentifier SET @OldIntermediate = (SELECT Intermediate FROM Catalog WITH (XLOCK) WHERE Path = @Path) UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 WHERE SnapshotData.SnapshotDataID = @OldIntermediate UPDATE Catalog SET Type=@Type, Content = @Content, Intermediate = @Intermediate, [Parameter] = @Parameter, LinkSourceID = @LinkSourceID, MimeType = @MimeType WHERE Path = @Path UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount + 1, TransientRefcount = TransientRefcount - 1 WHERE SnapshotData.SnapshotDataID = @Intermediate EXEC FlushReportFromCache @Path GO GRANT EXECUTE ON [dbo].[SetObjectContent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetLastModified]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetLastModified] GO CREATE PROCEDURE [dbo].[SetLastModified] @Path nvarchar (425), @ModifiedBySid varbinary (85) = NULL, @ModifiedByName nvarchar(260), @AuthType int, @ModifiedDate DateTime AS DECLARE @ModifiedByID uniqueidentifier EXEC GetUserID @ModifiedBySid, @ModifiedByName, @AuthType, @ModifiedByID OUTPUT UPDATE Catalog SET ModifiedByID = @ModifiedByID, ModifiedDate = @ModifiedDate WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[SetLastModified] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetNameById]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetNameById] GO CREATE PROCEDURE [dbo].[GetNameById] @ItemID uniqueidentifier AS SELECT Path FROM Catalog WHERE ItemID = @ItemID GO GRANT EXECUTE ON [dbo].[GetNameById] TO RSExecRole GO -------------------------------------------------- ------------- Data source procedures to store user names and passwords if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddDataSource] GO CREATE PROCEDURE [dbo].[AddDataSource] @DSID [uniqueidentifier], @ItemID [uniqueidentifier] = NULL, -- null for future suport dynamic delivery @SubscriptionID [uniqueidentifier] = NULL, @Name [nvarchar] (260) = NULL, -- only for scoped data sources, MUST be NULL for standalone!!! @Extension [nvarchar] (260) = NULL, @LinkID [uniqueidentifier] = NULL, -- link id is trusted, if it is provided - we use it @LinkPath [nvarchar] (425) = NULL, -- if LinkId is not provided we try to look up LinkPath @CredentialRetrieval [int], @Prompt [ntext] = NULL, @ConnectionString [image] = NULL, @OriginalConnectionString [image] = NULL, @OriginalConnectStringExpressionBased [bit] = NULL, @UserName [image] = NULL, @Password [image] = NULL, @Flags [int], @AuthType [int], @Version [int] AS DECLARE @ActualLinkID uniqueidentifier SET @ActualLinkID = NULL IF (@LinkID is NULL) AND (@LinkPath is not NULL) BEGIN SELECT Type, ItemID, NtSecDescPrimary FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @LinkPath SET @ActualLinkID = (SELECT ItemID FROM Catalog WHERE Path = @LinkPath) END ELSE BEGIN SET @ActualLinkID = @LinkID END INSERT INTO DataSource ([DSID], [ItemID], [SubscriptionID], [Name], [Extension], [Link], [CredentialRetrieval], [Prompt], [ConnectionString], [OriginalConnectionString], [OriginalConnectStringExpressionBased], [UserName], [Password], [Flags], [Version]) VALUES (@DSID, @ItemID, @SubscriptionID, @Name, @Extension, @ActualLinkID, @CredentialRetrieval, @Prompt, @ConnectionString, @OriginalConnectionString, @OriginalConnectStringExpressionBased, @UserName, @Password, @Flags, @Version) GO GRANT EXECUTE ON [dbo].[AddDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDataSources]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDataSources] GO CREATE PROCEDURE [dbo].[GetDataSources] @ItemID [uniqueidentifier], @AuthType int AS SELECT -- select data sources and their links (if they exist) DS.[DSID], -- 0 DS.[ItemID], -- 1 DS.[Name], -- 2 DS.[Extension], -- 3 DS.[Link], -- 4 DS.[CredentialRetrieval], -- 5 DS.[Prompt], -- 6 DS.[ConnectionString], -- 7 DS.[OriginalConnectionString], -- 8 DS.[UserName], -- 9 DS.[Password], -- 10 DS.[Flags], -- 11 DSL.[DSID], -- 12 DSL.[ItemID], -- 13 DSL.[Name], -- 14 DSL.[Extension], -- 15 DSL.[Link], -- 16 DSL.[CredentialRetrieval], -- 17 DSL.[Prompt], -- 18 DSL.[ConnectionString], -- 19 DSL.[UserName], -- 20 DSL.[Password], -- 21 DSL.[Flags], -- 22 C.Path, -- 23 SD.NtSecDescPrimary, -- 24 DS.[OriginalConnectStringExpressionBased], -- 25 DS.[Version], -- 26 DSL.[Version], -- 27 (SELECT 1 WHERE EXISTS (SELECT * from [ModelItemPolicy] AS MIP WHERE C.[ItemID] = MIP.[CatalogItemID])) -- 28 FROM [DataSource] AS DS LEFT OUTER JOIN ([DataSource] AS DSL INNER JOIN [Catalog] AS C ON DSL.[ItemID] = C.[ItemID] LEFT OUTER JOIN [SecData] AS SD ON C.[PolicyID] = SD.[PolicyID] AND SD.AuthType = @AuthType) ON DS.[Link] = DSL.[ItemID] WHERE DS.[ItemID] = @ItemID or DS.[SubscriptionID] = @ItemID GO GRANT EXECUTE ON [dbo].[GetDataSources] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteDataSources]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteDataSources] GO CREATE PROCEDURE [dbo].[DeleteDataSources] @ItemID [uniqueidentifier] AS DELETE FROM [DataSource] WHERE [ItemID] = @ItemID or [SubscriptionID] = @ItemID GO GRANT EXECUTE ON [dbo].[DeleteDataSources] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ChangeStateOfDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ChangeStateOfDataSource] GO CREATE PROCEDURE [dbo].[ChangeStateOfDataSource] @ItemID [uniqueidentifier], @Enable bit AS IF @Enable != 0 BEGIN UPDATE [DataSource] SET [Flags] = [Flags] | 1 WHERE [ItemID] = @ItemID END ELSE BEGIN UPDATE [DataSource] SET [Flags] = [Flags] & 0x7FFFFFFE WHERE [ItemID] = @ItemID END GO GRANT EXECUTE ON [dbo].[ChangeStateOfDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindItemsByDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindItemsByDataSource] GO CREATE PROCEDURE [dbo].[FindItemsByDataSource] @ItemID uniqueidentifier, @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.UserName, SUSER_SNAME(MU.Sid), MU.UserName, C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType INNER JOIN DataSource AS DS ON C.ItemID = DS.ItemID WHERE DS.Link = @ItemID GO GRANT EXECUTE ON [dbo].[FindItemsByDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CopyExecutionSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CopyExecutionSnapshot] GO CREATE PROCEDURE [dbo].[CopyExecutionSnapshot] @SourceReportID uniqueidentifier, @TargetReportID uniqueidentifier, @ReservedUntilUTC datetime AS DECLARE @SourceSnapshotDataID uniqueidentifier SET @SourceSnapshotDataID = (SELECT SnapshotDataID FROM Catalog WHERE ItemID = @SourceReportID) DECLARE @TargetSnapshotDataID uniqueidentifier SET @TargetSnapshotDataID = newid() DECLARE @ChunkID uniqueidentifier IF @SourceSnapshotDataID IS NOT NULL BEGIN -- We need to copy entries in SnapshotData and ChunkData tables. INSERT INTO SnapshotData (SnapshotDataID, CreatedDate, ParamsHash, QueryParams, EffectiveParams, Description, PermanentRefcount, TransientRefcount, ExpirationDate) SELECT @TargetSnapshotDataID, SD.CreatedDate, SD.ParamsHash, SD.QueryParams, SD.EffectiveParams, SD.Description, 1, 0, @ReservedUntilUTC FROM SnapshotData as SD WHERE SD.SnapshotDataID = @SourceSnapshotDataID INSERT INTO ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, ChunkFlags, Content, Version) SELECT newid(), @TargetSnapshotDataID, CD.ChunkName, CD.ChunkType, CD.ChunkFlags, CD.Content, CD.Version FROM ChunkData as CD WHERE CD.SnapshotDataID = @SourceSnapshotDataID UPDATE Target SET Target.SnapshotDataID = @TargetSnapshotDataID, Target.ExecutionTime = Source.ExecutionTime FROM Catalog Target, Catalog Source WHERE Source.ItemID = @SourceReportID AND Target.ItemID = @TargetReportID END GO GRANT EXECUTE ON [dbo].[CopyExecutionSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateRole] GO CREATE PROCEDURE [dbo].[CreateRole] @RoleID as uniqueidentifier, @RoleName as nvarchar(260), @Description as nvarchar(512) = null, @TaskMask as nvarchar(32), @RoleFlags as tinyint AS INSERT INTO Roles (RoleID, RoleName, Description, TaskMask, RoleFlags) VALUES (@RoleID, @RoleName, @Description, @TaskMask, @RoleFlags) GO GRANT EXECUTE ON [dbo].[CreateRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetRoles]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetRoles] GO CREATE PROCEDURE [dbo].[GetRoles] @RoleFlags as tinyint = NULL AS SELECT RoleName, Description, TaskMask FROM Roles WHERE (@RoleFlags is NULL) OR (RoleFlags = @RoleFlags) GO GRANT EXECUTE ON [dbo].[GetRoles] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteRole] GO -- Delete all policies associated with this role CREATE PROCEDURE [dbo].[DeleteRole] @RoleName nvarchar(260) AS -- if you call this, you must delete/reconstruct all policies associated with this role DELETE FROM Roles WHERE RoleName = @RoleName GO GRANT EXECUTE ON [dbo].[DeleteRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadRoleProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadRoleProperties] GO CREATE PROCEDURE [dbo].[ReadRoleProperties] @RoleName as nvarchar(260) AS SELECT Description, TaskMask, RoleFlags FROM Roles WHERE RoleName = @RoleName GO GRANT EXECUTE ON [dbo].[ReadRoleProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetRoleProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetRoleProperties] GO CREATE PROCEDURE [dbo].[SetRoleProperties] @RoleName as nvarchar(260), @Description as nvarchar(512) = NULL, @TaskMask as nvarchar(32), @RoleFlags as tinyint AS DECLARE @ExistingRoleFlags as tinyint SET @ExistingRoleFlags = (SELECT RoleFlags FROM Roles WHERE RoleName = @RoleName) IF @ExistingRoleFlags IS NULL BEGIN RETURN END IF @ExistingRoleFlags <> @RoleFlags BEGIN RAISERROR ('Bad role flags', 16, 1) END UPDATE Roles SET Description = @Description, TaskMask = @TaskMask, RoleFlags = @RoleFlags WHERE RoleName = @RoleName GO GRANT EXECUTE ON [dbo].[SetRoleProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPoliciesForRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPoliciesForRole] GO CREATE PROCEDURE [dbo].[GetPoliciesForRole] @RoleName as nvarchar(260), @AuthType as int AS SELECT Policies.PolicyID, SecData.XmlDescription, Policies.PolicyFlag, Catalog.Type, Catalog.Path, ModelItemPolicy.CatalogItemID, ModelItemPolicy.ModelItemID, RelatedRoles.RoleID, RelatedRoles.RoleName, RelatedRoles.TaskMask, RelatedRoles.RoleFlags FROM Roles INNER JOIN PolicyUserRole ON Roles.RoleID = PolicyUserRole.RoleID INNER JOIN Policies ON PolicyUserRole.PolicyID = Policies.PolicyID INNER JOIN PolicyUserRole AS RelatedPolicyUserRole ON Policies.PolicyID = RelatedPolicyUserRole.PolicyID INNER JOIN Roles AS RelatedRoles ON RelatedPolicyUserRole.RoleID = RelatedRoles.RoleID LEFT OUTER JOIN SecData ON Policies.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog ON Policies.PolicyID = Catalog.PolicyID AND Catalog.PolicyRoot = 1 LEFT OUTER JOIN ModelItemPolicy ON Policies.PolicyID = ModelItemPolicy.PolicyID WHERE Roles.RoleName = @RoleName ORDER BY Policies.PolicyID GO GRANT EXECUTE ON [dbo].[GetPoliciesForRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdatePolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdatePolicy] GO CREATE PROCEDURE [dbo].[UpdatePolicy] @PolicyID as uniqueidentifier, @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @AuthType int AS UPDATE SecData SET NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND SecData.AuthType = @AuthType GO GRANT EXECUTE ON [dbo].[UpdatePolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetPolicy] GO -- this assumes the item exists in the catalog CREATE PROCEDURE [dbo].[SetPolicy] @ItemName as nvarchar(425), @ItemNameLike as nvarchar(850), @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @XmlPolicy as ntext, @AuthType int, @PolicyID uniqueidentifier OUTPUT AS SELECT @PolicyID = (SELECT PolicyID FROM Catalog WHERE Path = @ItemName AND PolicyRoot = 1) IF (@PolicyID IS NULL) BEGIN -- this is not a policy root SET @PolicyID = newid() INSERT INTO Policies (PolicyID, PolicyFlag) VALUES (@PolicyID, 0) INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) DECLARE @OldPolicyID as uniqueidentifier SELECT @OldPolicyID = (SELECT PolicyID FROM Catalog WHERE Path = @ItemName) -- update item and children that shared the old policy UPDATE Catalog SET PolicyID = @PolicyID, PolicyRoot = 1 WHERE Path = @ItemName UPDATE Catalog SET PolicyID = @PolicyID WHERE Path LIKE @ItemNameLike ESCAPE '*' AND Catalog.PolicyID = @OldPolicyID END ELSE BEGIN UPDATE Policies SET PolicyFlag = 0 WHERE Policies.PolicyID = @PolicyID DECLARE @SecDataID as uniqueidentifier SELECT @SecDataID = (SELECT SecDataID FROM SecData WHERE PolicyID = @PolicyID and AuthType = @AuthType) IF (@SecDataID IS NULL) BEGIN -- insert new sec desc's INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription ,NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN -- update existing sec desc's UPDATE SecData SET XmlDescription = @XmlPolicy, NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND AuthType = @AuthType END END DELETE FROM PolicyUserRole WHERE PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[SetPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSystemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSystemPolicy] GO -- update the system policy CREATE PROCEDURE [dbo].[SetSystemPolicy] @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @XmlPolicy as ntext, @AuthType as int, @PolicyID uniqueidentifier OUTPUT AS SELECT @PolicyID = (SELECT PolicyID FROM Policies WHERE PolicyFlag = 1) IF (@PolicyID IS NULL) BEGIN SET @PolicyID = newid() INSERT INTO Policies (PolicyID, PolicyFlag) VALUES (@PolicyID, 1) INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN DECLARE @SecDataID as uniqueidentifier SELECT @SecDataID = (SELECT SecDataID FROM SecData WHERE PolicyID = @PolicyID and AuthType = @AuthType) IF (@SecDataID IS NULL) BEGIN -- insert new sec desc's INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN -- update existing sec desc's UPDATE SecData SET XmlDescription = @XmlPolicy, NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND AuthType = @AuthType END END DELETE FROM PolicyUserRole WHERE PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[SetSystemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetModelItemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetModelItemPolicy] GO -- update the system policy CREATE PROCEDURE [dbo].[SetModelItemPolicy] @CatalogItemID as uniqueidentifier, @ModelItemID as nvarchar(425), @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @XmlPolicy as ntext, @AuthType as int, @PolicyID uniqueidentifier OUTPUT AS SELECT @PolicyID = (SELECT PolicyID FROM ModelItemPolicy WHERE CatalogItemID = @CatalogItemID AND ModelItemID = @ModelItemID ) IF (@PolicyID IS NULL) BEGIN SET @PolicyID = newid() INSERT INTO Policies (PolicyID, PolicyFlag) VALUES (@PolicyID, 2) INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) INSERT INTO ModelItemPolicy (ID, CatalogItemID, ModelItemID, PolicyID) VALUES (newid(), @CatalogItemID, @ModelItemID, @PolicyID) END ELSE BEGIN DECLARE @SecDataID as uniqueidentifier SELECT @SecDataID = (SELECT SecDataID FROM SecData WHERE PolicyID = @PolicyID and AuthType = @AuthType) IF (@SecDataID IS NULL) BEGIN -- insert new sec desc's INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN -- update existing sec desc's UPDATE SecData SET XmlDescription = @XmlPolicy, NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND AuthType = @AuthType END END DELETE FROM PolicyUserRole WHERE PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[SetModelItemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdatePolicyPrincipal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdatePolicyPrincipal] GO CREATE PROCEDURE [dbo].[UpdatePolicyPrincipal] @PolicyID uniqueidentifier, @PrincipalSid varbinary(85) = NULL, @PrincipalName nvarchar(260), @PrincipalAuthType int, @RoleName nvarchar(260), @PrincipalID uniqueidentifier OUTPUT, @RoleID uniqueidentifier OUTPUT AS EXEC GetPrincipalID @PrincipalSid , @PrincipalName, @PrincipalAuthType, @PrincipalID OUTPUT SELECT @RoleID = (SELECT RoleID FROM Roles WHERE RoleName = @RoleName) INSERT INTO PolicyUserRole (ID, RoleID, UserID, PolicyID) VALUES (newid(), @RoleID, @PrincipalID, @PolicyID) GO GRANT EXECUTE ON [dbo].[UpdatePolicyPrincipal] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdatePolicyRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdatePolicyRole] GO CREATE PROCEDURE [dbo].[UpdatePolicyRole] @PolicyID uniqueidentifier, @PrincipalID uniqueidentifier, @RoleName nvarchar(260), @RoleID uniqueidentifier OUTPUT AS SELECT @RoleID = (SELECT RoleID FROM Roles WHERE RoleName = @RoleName) INSERT INTO PolicyUserRole (ID, RoleID, UserID, PolicyID) VALUES (newid(), @RoleID, @PrincipalID, @PolicyID) GO GRANT EXECUTE ON [dbo].[UpdatePolicyRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPolicy] GO CREATE PROCEDURE [dbo].[GetPolicy] @ItemName as nvarchar(425), @AuthType int AS SELECT SecData.XmlDescription, Catalog.PolicyRoot , SecData.NtSecDescPrimary, Catalog.Type FROM Catalog INNER JOIN Policies ON Catalog.PolicyID = Policies.PolicyID LEFT OUTER JOIN SecData ON Policies.PolicyID = SecData.PolicyID AND AuthType = @AuthType WHERE Catalog.Path = @ItemName AND PolicyFlag = 0 GO GRANT EXECUTE ON [dbo].[GetPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSystemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSystemPolicy] GO CREATE PROCEDURE [dbo].[GetSystemPolicy] @AuthType int AS SELECT SecData.NtSecDescPrimary, SecData.XmlDescription FROM Policies LEFT OUTER JOIN SecData ON Policies.PolicyID = SecData.PolicyID AND AuthType = @AuthType WHERE PolicyFlag = 1 GO GRANT EXECUTE ON [dbo].[GetSystemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeletePolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeletePolicy] GO CREATE PROCEDURE [dbo].[DeletePolicy] @ItemName as nvarchar(425) AS DECLARE @OldPolicyID uniqueidentifier SELECT @OldPolicyID = (SELECT PolicyID FROM Catalog WHERE Catalog.Path = @ItemName) UPDATE Catalog SET PolicyID = (SELECT Parent.PolicyID FROM Catalog Parent, Catalog WHERE Parent.ItemID = Catalog.ParentID AND Catalog.Path = @ItemName), PolicyRoot = 0 WHERE Catalog.PolicyID = @OldPolicyID DELETE Policies FROM Policies WHERE Policies.PolicyID = @OldPolicyID GO GRANT EXECUTE ON [dbo].[DeletePolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateSession]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateSession] GO -- Writes or updates session record CREATE PROCEDURE [dbo].[CreateSession] @SessionID as varchar(32), @CompiledDefinition as uniqueidentifier = NULL, @SnapshotDataID as uniqueidentifier = NULL, @IsPermanentSnapshot as bit = NULL, @ReportPath as nvarchar(440) = NULL, @Timeout as int, @AutoRefreshSeconds as int = NULL, @DataSourceInfo as image = NULL, @OwnerName as nvarchar (260), @OwnerSid as varbinary (85) = NULL, @AuthType as int, @EffectiveParams as ntext = NULL, @HistoryDate as datetime = NULL, @PageHeight as float = NULL, @PageWidth as float = NULL, @TopMargin as float = NULL, @BottomMargin as float = NULL, @LeftMargin as float = NULL, @RightMargin as float = NULL, @ExecutionType as smallint = NULL AS UPDATE PS SET PS.RefCount = 1 FROM ReportServerTempDB.dbo.PersistedStream as PS WHERE PS.SessionID = @SessionID UPDATE SN SET TransientRefcount = TransientRefcount + 1 FROM SnapshotData AS SN WHERE SN.SnapshotDataID = @SnapshotDataID UPDATE SN SET TransientRefcount = TransientRefcount + 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN WHERE SN.SnapshotDataID = @SnapshotDataID DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT DECLARE @now datetime SET @now = GETDATE() INSERT INTO ReportServerTempDB.dbo.SessionData ( SessionID, CompiledDefinition, SnapshotDataID, IsPermanentSnapshot, ReportPath, Timeout, AutoRefreshSeconds, Expiration, DataSourceInfo, OwnerID, EffectiveParams, CreationTime, HistoryDate, PageHeight, PageWidth, TopMargin, BottomMargin, LeftMargin, RightMargin, ExecutionType ) VALUES ( @SessionID, @CompiledDefinition, @SnapshotDataID, @IsPermanentSnapshot, @ReportPath, @Timeout, @AutoRefreshSeconds, DATEADD(s, @Timeout, @now), @DataSourceInfo, @OwnerID, @EffectiveParams, @now, @HistoryDate, @PageHeight, @PageWidth, @TopMargin, @BottomMargin, @LeftMargin, @RightMargin, @ExecutionType ) GO GRANT EXECUTE ON [dbo].[CreateSession] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteModelItemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteModelItemPolicy] GO CREATE PROCEDURE [dbo].[DeleteModelItemPolicy] @CatalogItemID as uniqueidentifier, @ModelItemID as nvarchar(425) AS DECLARE @PolicyID uniqueidentifier SELECT @PolicyID = (SELECT PolicyID FROM ModelItemPolicy WHERE CatalogItemID = @CatalogItemID AND ModelItemID = @ModelItemID) DELETE Policies FROM Policies WHERE Policies.PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[DeleteModelItemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteAllModelItemPolicies]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteAllModelItemPolicies] GO CREATE PROCEDURE [dbo].[DeleteAllModelItemPolicies] @Path as nvarchar(450) AS DELETE Policies FROM Policies AS P INNER JOIN ModelItemPolicy AS MIP ON P.PolicyID = MIP.PolicyID INNER JOIN Catalog AS C ON MIP.CatalogItemID = C.ItemID WHERE C.[Path] = @Path GO GRANT EXECUTE ON [dbo].[DeleteAllModelItemPolicies] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelItemInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelItemInfo] GO CREATE PROCEDURE [dbo].[GetModelItemInfo] @Path nvarchar (425), @AuthType int AS SELECT C.[ItemID], C.[Type], C.[ModifiedDate], C.[Description], SD.[NtSecDescPrimary] FROM [Catalog] AS C LEFT OUTER JOIN [SecData] AS SD ON C.[PolicyID] = SD.[PolicyID] AND SD.[AuthType] = @AuthType WHERE C.[Path] = @Path SELECT MIP.[ModelItemID], SD.[NtSecDescPrimary], SD.[XmlDescription] FROM [Catalog] AS C INNER JOIN [ModelItemPolicy] AS MIP ON C.[ItemID] = MIP.[CatalogItemID] LEFT OUTER JOIN [SecData] AS SD ON MIP.[PolicyID] = SD.[PolicyID] WHERE C.[Path] = @Path GO GRANT EXECUTE ON [dbo].[GetModelItemInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelDefinition]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelDefinition] GO CREATE PROCEDURE [dbo].[GetModelDefinition] @CatalogItemID as uniqueidentifier AS SELECT C.[Content] FROM [Catalog] AS C WHERE C.[ItemID] = @CatalogItemID GO GRANT EXECUTE ON [dbo].[GetModelDefinition] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddModelPerspective]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddModelPerspective] GO CREATE PROCEDURE [dbo].[AddModelPerspective] @ModelID as uniqueidentifier, @PerspectiveID as ntext, @PerspectiveName as ntext = null, @PerspectiveDescription as ntext = null AS INSERT INTO [ModelPerspective] ([ID], [ModelID], [PerspectiveID], [PerspectiveName], [PerspectiveDescription]) VALUES (newid(), @ModelID, @PerspectiveID, @PerspectiveName, @PerspectiveDescription) GO GRANT EXECUTE ON [dbo].[AddModelPerspective] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteModelPerspectives]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteModelPerspectives] GO CREATE PROCEDURE [dbo].[DeleteModelPerspectives] @ModelID as uniqueidentifier AS DELETE FROM [ModelPerspective] WHERE [ModelID] = @ModelID GO GRANT EXECUTE ON [dbo].[DeleteModelPerspectives] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelsAndPerspectives]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelsAndPerspectives] GO CREATE PROCEDURE [dbo].[GetModelsAndPerspectives] @AuthType int AS SELECT C.[PolicyID], SD.[NtSecDescPrimary], C.[ItemID], C.[Path], C.[Description], P.[PerspectiveID], P.[PerspectiveName], P.[PerspectiveDescription] FROM [Catalog] as C LEFT OUTER JOIN [ModelPerspective] as P ON C.[ItemID] = P.[ModelID] LEFT OUTER JOIN [SecData] AS SD ON C.[PolicyID] = SD.[PolicyID] AND SD.[AuthType] = @AuthType WHERE C.[Type] = 6 -- Model ORDER BY C.[Path] GO GRANT EXECUTE ON [dbo].[GetModelsAndPerspectives] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelPerspectives]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelPerspectives] GO CREATE PROCEDURE [dbo].[GetModelPerspectives] @Path nvarchar (425), @AuthType int AS SELECT C.[Type], SD.[NtSecDescPrimary], C.[Description] FROM [Catalog] as C LEFT OUTER JOIN [SecData] AS SD ON C.[PolicyID] = SD.[PolicyID] AND SD.[AuthType] = @AuthType WHERE [Path] = @Path SELECT P.[PerspectiveID], P.[PerspectiveName], P.[PerspectiveDescription] FROM [Catalog] as C INNER JOIN [ModelPerspective] as P ON C.[ItemID] = P.[ModelID] WHERE [Path] = @Path GO GRANT EXECUTE ON [dbo].[GetModelPerspectives] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DereferenceSessionSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DereferenceSessionSnapshot] GO CREATE PROCEDURE [dbo].[DereferenceSessionSnapshot] @SessionID as varchar(32), @OwnerID as uniqueidentifier AS UPDATE SN SET TransientRefcount = TransientRefcount - 1 FROM SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.SessionData AS SE ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID UPDATE SN SET TransientRefcount = TransientRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.SessionData AS SE ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[DereferenceSessionSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSessionData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSessionData] GO -- Writes or updates session record CREATE PROCEDURE [dbo].[SetSessionData] @SessionID as varchar(32), @ReportPath as nvarchar(440), @HistoryDate as datetime = NULL, @Timeout as int, @AutoRefreshSeconds as int = NULL, @EffectiveParams ntext = NULL, @OwnerSid as varbinary (85) = NULL, @OwnerName as nvarchar (260), @AuthType as int, @ShowHideInfo as image = NULL, @DataSourceInfo as image = NULL, @SnapshotDataID as uniqueidentifier = NULL, @IsPermanentSnapshot as bit = NULL, @SnapshotTimeoutSeconds as int = NULL, @HasInteractivity as bit, @SnapshotExpirationDate as datetime = NULL, @ExecutionType smallint = NULL AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT DECLARE @now datetime SET @now = GETDATE() -- is there a session for the same report ? DECLARE @OldSnapshotDataID uniqueidentifier DECLARE @OldIsPermanentSnapshot bit DECLARE @OldSessionID varchar(32) SELECT @OldSessionID = SessionID, @OldSnapshotDataID = SnapshotDataID, @OldIsPermanentSnapshot = IsPermanentSnapshot FROM ReportServerTempDB.dbo.SessionData WITH (XLOCK) WHERE SessionID = @SessionID IF @OldSessionID IS NOT NULL BEGIN -- Yes, update it IF @OldSnapshotDataID != @SnapshotDataID or @SnapshotDataID is NULL BEGIN EXEC DereferenceSessionSnapshot @SessionID, @OwnerID END UPDATE ReportServerTempDB.dbo.SessionData SET SnapshotDataID = @SnapshotDataID, IsPermanentSnapshot = @IsPermanentSnapshot, Timeout = @Timeout, AutoRefreshSeconds = @AutoRefreshSeconds, SnapshotExpirationDate = @SnapshotExpirationDate, -- we want database session to expire later than in-memory session Expiration = DATEADD(s, @Timeout+10, @now), ShowHideInfo = @ShowHideInfo, DataSourceInfo = @DataSourceInfo, ExecutionType = @ExecutionType -- EffectiveParams = @EffectiveParams, -- no need to update user params as they are always same -- ReportPath = @ReportPath -- OwnerID = @OwnerID WHERE SessionID = @SessionID -- update expiration date on a snapshot that we reference IF @IsPermanentSnapshot != 0 BEGIN UPDATE SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutSeconds, @now) WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutSeconds, @now) WHERE SnapshotDataID = @SnapshotDataID END END ELSE BEGIN -- no, insert it UPDATE PS SET PS.RefCount = 1 FROM ReportServerTempDB.dbo.PersistedStream as PS WHERE PS.SessionID = @SessionID INSERT INTO ReportServerTempDB.dbo.SessionData (SessionID, SnapshotDataID, IsPermanentSnapshot, ReportPath, EffectiveParams, Timeout, AutoRefreshSeconds, Expiration, ShowHideInfo, DataSourceInfo, OwnerID, CreationTime, HasInteractivity, SnapshotExpirationDate, HistoryDate, ExecutionType) VALUES (@SessionID, @SnapshotDataID, @IsPermanentSnapshot, @ReportPath, @EffectiveParams, @Timeout, @AutoRefreshSeconds, DATEADD(s, @Timeout, @now), @ShowHideInfo, @DataSourceInfo, @OwnerID, @now, @HasInteractivity, @SnapshotExpirationDate, @HistoryDate, @ExecutionType) END GO GRANT EXECUTE ON [dbo].[SetSessionData] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteLockSession]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteLockSession] GO CREATE PROCEDURE [dbo].[WriteLockSession] @SessionID as varchar(32) AS INSERT INTO ReportServerTempDB.dbo.SessionLock WITH (ROWLOCK) (SessionID) VALUES (@SessionID) GO GRANT EXECUTE ON [dbo].[WriteLockSession] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CheckSessionLock]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CheckSessionLock] GO CREATE PROCEDURE [dbo].[CheckSessionLock] @SessionID as varchar(32) AS DECLARE @Selected nvarchar(32) SELECT @Selected=SessionID FROM ReportServerTempDB.dbo.SessionLock WITH (ROWLOCK) WHERE SessionID = @SessionID GO GRANT EXECUTE ON [dbo].[CheckSessionLock] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadLockSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadLockSnapshot] GO CREATE PROCEDURE [dbo].[ReadLockSnapshot] @SnapshotDataID as uniqueidentifier AS SELECT SnapshotDataID FROM SnapshotData WITH (REPEATABLEREAD, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID GO GRANT EXECUTE ON [dbo].[ReadLockSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSessionData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSessionData] GO -- Get record from session data, update session and snapshot CREATE PROCEDURE [dbo].[GetSessionData] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @SnapshotTimeoutMinutes as int AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT DECLARE @now as datetime SET @now = GETDATE() DECLARE @DBSessionID varchar(32) DECLARE @SnapshotDataID uniqueidentifier DECLARE @IsPermanentSnapshot bit EXEC CheckSessionLock @SessionID = @SessionID SELECT @DBSessionID = SE.SessionID, @SnapshotDataID = SE.SnapshotDataID, @IsPermanentSnapshot = SE.IsPermanentSnapshot FROM ReportServerTempDB.dbo.SessionData AS SE WITH (XLOCK) WHERE SE.OwnerID = @OwnerID AND SE.SessionID = @SessionID AND SE.Expiration > @now -- We need this update to keep session around while we process it. -- TODO: This assumes that it will be processed within the session timeout. UPDATE SE SET Expiration = DATEADD(s, Timeout, @now) FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @DBSessionID -- Update snapshot expiration to prevent early deletion -- If session uses snapshot, it is already refcounted. However, if session lasts for too long, -- snapshot may expire. Therefore, every time we touch snapshot we should change expiration. IF (@DBSessionID IS NOT NULL) BEGIN -- We return something only if session is present IF @IsPermanentSnapshot != 0 BEGIN -- If session has snapshot and it is permanent SELECT SN.SnapshotDataID, SE.ShowHideInfo, SE.DataSourceInfo, SN.Description, SE.EffectiveParams, SN.CreatedDate, SE.IsPermanentSnapshot, SE.CreationTime, SE.HasInteractivity, SE.Timeout, SE.SnapshotExpirationDate, SE.ReportPath, SE.HistoryDate, SE.CompiledDefinition, SN.PageCount, SN.HasDocMap, SE.Expiration, SN.EffectiveParams, SE.PageHeight, SE.PageWidth, SE.TopMargin, SE.BottomMargin, SE.LeftMargin, SE.RightMargin, SE.AutoRefreshSeconds, SE.ExecutionType FROM ReportServerTempDB.dbo.SessionData AS SE INNER JOIN SnapshotData AS SN ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @DBSessionID UPDATE SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutMinutes, @now) WHERE SnapshotDataID = @SnapshotDataID END ELSE IF @IsPermanentSnapshot = 0 BEGIN -- If session has snapshot and it is temporary SELECT SN.SnapshotDataID, SE.ShowHideInfo, SE.DataSourceInfo, SN.Description, SE.EffectiveParams, SN.CreatedDate, SE.IsPermanentSnapshot, SE.CreationTime, SE.HasInteractivity, SE.Timeout, SE.SnapshotExpirationDate, SE.ReportPath, SE.HistoryDate, SE.CompiledDefinition, SN.PageCount, SN.HasDocMap, SE.Expiration, SN.EffectiveParams, SE.PageHeight, SE.PageWidth, SE.TopMargin, SE.BottomMargin, SE.LeftMargin, SE.RightMargin, SE.AutoRefreshSeconds, SE.ExecutionType FROM ReportServerTempDB.dbo.SessionData AS SE INNER JOIN ReportServerTempDB.dbo.SnapshotData AS SN ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @DBSessionID UPDATE ReportServerTempDB.dbo.SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutMinutes, @now) WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN -- If session doesn't have snapshot SELECT null, SE.ShowHideInfo, SE.DataSourceInfo, null, SE.EffectiveParams, null, SE.IsPermanentSnapshot, SE.CreationTime, SE.HasInteractivity, SE.Timeout, SE.SnapshotExpirationDate, SE.ReportPath, SE.HistoryDate, SE.CompiledDefinition, null, null, SE.Expiration, null, SE.PageHeight, SE.PageWidth, SE.TopMargin, SE.BottomMargin, SE.LeftMargin, SE.RightMargin, SE.AutoRefreshSeconds, SE.ExecutionType FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @DBSessionID END END GO GRANT EXECUTE ON [dbo].[GetSessionData] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapshotFromHistory]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapshotFromHistory] GO CREATE PROCEDURE [dbo].[GetSnapshotFromHistory] @Path nvarchar (425), @SnapshotDate datetime, @AuthType int AS SELECT Catalog.ItemID, Catalog.Type, SnapshotData.SnapshotDataID, SnapshotData.DependsOnUser, SnapshotData.Description, SecData.NtSecDescPrimary, Catalog.[Property] FROM SnapshotData INNER JOIN History ON History.SnapshotDataID = SnapshotData.SnapshotDataID INNER JOIN Catalog ON History.ReportID = Catalog.ItemID LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Catalog.Path = @Path AND History.SnapshotDate = @SnapshotDate GO GRANT EXECUTE ON [dbo].[GetSnapshotFromHistory] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredSessions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredSessions] GO CREATE PROCEDURE [dbo].[CleanExpiredSessions] @SessionsCleaned int OUTPUT AS SET DEADLOCK_PRIORITY LOW DECLARE @now as datetime SET @now = GETDATE() CREATE TABLE #tempSession (SessionID varchar(32) COLLATE Latin1_General_CI_AS_KS_WS, SnapshotDataID uniqueidentifier, CompiledDefinition uniqueidentifier) INSERT INTO #tempSession SELECT TOP 20 SessionID, SnapshotDataID, CompiledDefinition FROM ReportServerTempDB.dbo.SessionData WITH (XLOCK) WHERE Expiration < @now SET @SessionsCleaned = @@ROWCOUNT IF @SessionsCleaned = 0 RETURN -- Mark persisted streams for this session to be deleted UPDATE PS SET RefCount = 0, ExpirationDate = GETDATE() FROM ReportServerTempDB.dbo.PersistedStream AS PS INNER JOIN #tempSession on PS.SessionID = #tempsession.SessionID DELETE SE FROM ReportServerTempDB.dbo.SessionData AS SE INNER JOIN #tempSession on SE.SessionID = #tempsession.SessionID UPDATE SN SET TransientRefcount = TransientRefcount-1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN #tempSession AS SE ON SN.SnapshotDataID = SE.CompiledDefinition UPDATE SN SET TransientRefcount = TransientRefcount- (SELECT COUNT(*) FROM #tempSession AS SE1 WHERE SE1.SnapshotDataID = SN.SnapshotDataID) FROM SnapshotData AS SN INNER JOIN #tempSession AS SE ON SN.SnapshotDataID = SE.SnapshotDataID UPDATE SN SET TransientRefcount = TransientRefcount- (SELECT COUNT(*) FROM #tempSession AS SE1 WHERE SE1.SnapshotDataID = SN.SnapshotDataID) FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN #tempSession AS SE ON SN.SnapshotDataID = SE.SnapshotDataID GO GRANT EXECUTE ON [dbo].[CleanExpiredSessions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredCache]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredCache] GO CREATE PROCEDURE [dbo].[CleanExpiredCache] AS DECLARE @now as datetime SET @now = DATEADD(minute, -1, GETDATE()) UPDATE SN SET PermanentRefcount = PermanentRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON SN.SnapshotDataID = EC.SnapshotDataID WHERE EC.AbsoluteExpiration < @now DELETE EC FROM ReportServerTempDB.dbo.ExecutionCache AS EC WHERE EC.AbsoluteExpiration < @now GO GRANT EXECUTE ON [dbo].[CleanExpiredCache] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSessionCredentials]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSessionCredentials] GO CREATE PROCEDURE [dbo].[SetSessionCredentials] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @DataSourceInfo as image = NULL, @Expiration as datetime, @EffectiveParams as ntext = NULL AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT EXEC DereferenceSessionSnapshot @SessionID, @OwnerID UPDATE SE SET SE.DataSourceInfo = @DataSourceInfo, SE.SnapshotDataID = null, SE.IsPermanentSnapshot = null, SE.SnapshotExpirationDate = null, SE.ShowHideInfo = null, SE.HasInteractivity = null, SE.AutoRefreshSeconds = null, SE.Expiration = @Expiration, SE.EffectiveParams = @EffectiveParams FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[SetSessionCredentials] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSessionParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSessionParameters] GO CREATE PROCEDURE [dbo].[SetSessionParameters] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @EffectiveParams as ntext = NULL AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT UPDATE SE SET SE.EffectiveParams = @EffectiveParams FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[SetSessionParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ClearSessionSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ClearSessionSnapshot] GO CREATE PROCEDURE [dbo].[ClearSessionSnapshot] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @Expiration as datetime AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT EXEC DereferenceSessionSnapshot @SessionID, @OwnerID UPDATE SE SET SE.SnapshotDataID = null, SE.IsPermanentSnapshot = null, SE.SnapshotExpirationDate = null, SE.ShowHideInfo = null, SE.HasInteractivity = null, SE.AutoRefreshSeconds = null, SE.Expiration = @Expiration FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[ClearSessionSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RemoveReportFromSession]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RemoveReportFromSession] GO CREATE PROCEDURE [dbo].[RemoveReportFromSession] @SessionID as varchar(32), @ReportPath as nvarchar(440), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT EXEC DereferenceSessionSnapshot @SessionID, @OwnerID DELETE SE FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.ReportPath = @ReportPath AND SE.OwnerID = @OwnerID -- Delete any persisted streams associated with this session UPDATE PS SET PS.RefCount = 0, PS.ExpirationDate = GETDATE() FROM ReportServerTempDB.dbo.PersistedStream AS PS WHERE PS.SessionID = @SessionID GO GRANT EXECUTE ON [dbo].[RemoveReportFromSession] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanBrokenSnapshots]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanBrokenSnapshots] GO CREATE PROCEDURE [dbo].[CleanBrokenSnapshots] @Machine nvarchar(512), @SnapshotsCleaned int OUTPUT, @ChunksCleaned int OUTPUT, @TempSnapshotID uniqueidentifier OUTPUT AS SET DEADLOCK_PRIORITY LOW DECLARE @now AS datetime SELECT @now = GETDATE() CREATE TABLE #tempSnapshot (SnapshotDataID uniqueidentifier) INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM SnapshotData WITH (NOLOCK) where SnapshotData.PermanentRefcount <= 0 AND ExpirationDate < @now SET @SnapshotsCleaned = @@ROWCOUNT DELETE ChunkData FROM ChunkData INNER JOIN #tempSnapshot ON ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @@ROWCOUNT DELETE SnapshotData FROM SnapshotData INNER JOIN #tempSnapshot ON SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID TRUNCATE TABLE #tempSnapshot INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM ReportServerTempDB.dbo.SnapshotData WITH (NOLOCK) where ReportServerTempDB.dbo.SnapshotData.PermanentRefcount <= 0 AND ReportServerTempDB.dbo.SnapshotData.ExpirationDate < @now AND ReportServerTempDB.dbo.SnapshotData.Machine = @Machine SET @SnapshotsCleaned = @SnapshotsCleaned + @@ROWCOUNT SELECT @TempSnapshotID = (SELECT SnapshotDataID FROM #tempSnapshot) DELETE ReportServerTempDB.dbo.ChunkData FROM ReportServerTempDB.dbo.ChunkData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @ChunksCleaned + @@ROWCOUNT DELETE ReportServerTempDB.dbo.SnapshotData FROM ReportServerTempDB.dbo.SnapshotData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID GO GRANT EXECUTE ON [dbo].[CleanBrokenSnapshots] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanOrphanedSnapshots]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanOrphanedSnapshots] GO CREATE PROCEDURE [dbo].[CleanOrphanedSnapshots] @Machine nvarchar(512), @SnapshotsCleaned int OUTPUT, @ChunksCleaned int OUTPUT, @TempSnapshotID uniqueidentifier OUTPUT AS SET DEADLOCK_PRIORITY LOW CREATE TABLE #tempSnapshot (SnapshotDataID uniqueidentifier) INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM SnapshotData WITH (NOLOCK) where SnapshotData.PermanentRefcount = 0 AND SnapshotData.TransientRefcount = 0 SET @SnapshotsCleaned = @@ROWCOUNT DELETE ChunkData FROM ChunkData INNER JOIN #tempSnapshot ON ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @@ROWCOUNT DELETE SnapshotData FROM SnapshotData INNER JOIN #tempSnapshot ON SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID TRUNCATE TABLE #tempSnapshot INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM ReportServerTempDB.dbo.SnapshotData WITH (NOLOCK) where ReportServerTempDB.dbo.SnapshotData.PermanentRefcount = 0 AND ReportServerTempDB.dbo.SnapshotData.TransientRefcount = 0 AND ReportServerTempDB.dbo.SnapshotData.Machine = @Machine SET @SnapshotsCleaned = @SnapshotsCleaned + @@ROWCOUNT SELECT @TempSnapshotID = (SELECT SnapshotDataID FROM #tempSnapshot) DELETE ReportServerTempDB.dbo.ChunkData FROM ReportServerTempDB.dbo.ChunkData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @ChunksCleaned + @@ROWCOUNT DELETE ReportServerTempDB.dbo.SnapshotData FROM ReportServerTempDB.dbo.SnapshotData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID GO GRANT EXECUTE ON [dbo].[CleanOrphanedSnapshots] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetCacheOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetCacheOptions] GO CREATE PROCEDURE [dbo].[SetCacheOptions] @Path as nvarchar(425), @CacheReport as bit, @ExpirationFlags as int, @CacheExpiration as int = NULL AS DECLARE @CachePolicyID as uniqueidentifier SELECT @CachePolicyID = (SELECT CachePolicyID FROM CachePolicy with (XLOCK) INNER JOIN Catalog ON Catalog.ItemID = CachePolicy.ReportID WHERE Catalog.Path = @Path) IF @CachePolicyID IS NULL -- no policy exists BEGIN IF @CacheReport = 1 -- create a new one BEGIN INSERT INTO CachePolicy (CachePolicyID, ReportID, ExpirationFlags, CacheExpiration) (SELECT NEWID(), ItemID, @ExpirationFlags, @CacheExpiration FROM Catalog WHERE Catalog.Path = @Path) END -- ELSE if it has no policy and we want to remove its policy do nothing END ELSE -- existing policy BEGIN IF @CacheReport = 1 BEGIN UPDATE CachePolicy SET ExpirationFlags = @ExpirationFlags, CacheExpiration = @CacheExpiration WHERE CachePolicyID = @CachePolicyID EXEC FlushReportFromCache @Path END ELSE BEGIN DELETE FROM CachePolicy WHERE CachePolicyID = @CachePolicyID EXEC FlushReportFromCache @Path END END GO GRANT EXECUTE ON [dbo].[SetCacheOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCacheOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetCacheOptions] GO CREATE PROCEDURE [dbo].[GetCacheOptions] @Path as nvarchar(425) AS SELECT ExpirationFlags, CacheExpiration, S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type] FROM CachePolicy INNER JOIN Catalog ON Catalog.ItemID = CachePolicy.ReportID LEFT outer join reportschedule rs on catalog.itemid = rs.reportid and rs.reportaction = 3 LEFT OUTER JOIN [Schedule] S ON S.ScheduleID = rs.ScheduleID LEFT OUTER JOIN [Users] Owner on Owner.UserID = S.[CreatedById] WHERE Catalog.Path = @Path GO GRANT EXECUTE ON [dbo].[GetCacheOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddReportToCache]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddReportToCache] GO CREATE PROCEDURE [dbo].[AddReportToCache] @ReportID as uniqueidentifier, @ExecutionDate datetime, @SnapshotDataID uniqueidentifier, @ExpirationDate datetime OUTPUT, @ScheduleID uniqueidentifier OUTPUT AS DECLARE @ExpirationFlags as int DECLARE @Timeout as int SET @ExpirationDate = NULL SET @ScheduleID = NULL SET @ExpirationFlags = (SELECT ExpirationFlags FROM CachePolicy WHERE ReportID = @ReportID) IF @ExpirationFlags = 1 -- timeout based BEGIN SET @Timeout = (SELECT CacheExpiration FROM CachePolicy WHERE ReportID = @ReportID) SET @ExpirationDate = DATEADD(n, @Timeout, @ExecutionDate) END ELSE IF @ExpirationFlags = 2 -- schedule based BEGIN SET @ScheduleID = (SELECT s.ScheduleID FROM Schedule s INNER JOIN ReportSchedule rs on rs.ScheduleID = s.ScheduleID and rs.ReportAction = 3 WHERE rs.ReportID = @ReportID) SET @ExpirationDate = (SELECT Schedule.NextRunTime FROM Schedule with (XLOCK) WHERE Schedule.ScheduleID = @ScheduleID) END ELSE BEGIN RAISERROR('Invalid cache flags', 16, 1) END -- and to the report cache INSERT INTO ReportServerTempDB.dbo.ExecutionCache (ExecutionCacheID, ReportID, ExpirationFlags, AbsoluteExpiration, RelativeExpiration, SnapshotDataID) VALUES (newid(), @ReportID, @ExpirationFlags, @ExpirationDate, @Timeout, @SnapshotDataID ) UPDATE ReportServerTempDB.dbo.SnapshotData SET PermanentRefcount = PermanentRefcount + 1 WHERE SnapshotDataID = @SnapshotDataID; GO GRANT EXECUTE ON [dbo].[AddReportToCache] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetExecutionOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetExecutionOptions] GO CREATE PROCEDURE [dbo].[GetExecutionOptions] @Path nvarchar(425) AS SELECT ExecutionFlag, S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type] FROM Catalog LEFT OUTER JOIN ReportSchedule ON Catalog.ItemID = ReportSchedule.ReportID AND ReportSchedule.ReportAction = 1 LEFT OUTER JOIN [Schedule] S ON S.ScheduleID = ReportSchedule.ScheduleID LEFT OUTER JOIN [Users] Owner on Owner.UserID = S.[CreatedById] WHERE Catalog.Path = @Path GO GRANT EXECUTE ON [dbo].[GetExecutionOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetExecutionOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetExecutionOptions] GO CREATE PROCEDURE [dbo].[SetExecutionOptions] @Path as nvarchar(425), @ExecutionFlag as int, @ExecutionChanged as bit = 0 AS IF @ExecutionChanged = 0 BEGIN UPDATE Catalog SET ExecutionFlag = @ExecutionFlag WHERE Catalog.Path = @Path END ELSE BEGIN IF (@ExecutionFlag & 3) = 2 BEGIN -- set it to snapshot, flush cache EXEC FlushReportFromCache @Path DELETE CachePolicy FROM CachePolicy INNER JOIN Catalog ON CachePolicy.ReportID = Catalog.ItemID WHERE Catalog.Path = @Path END -- now clean existing snapshot and execution time if any UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 FROM SnapshotData INNER JOIN Catalog ON SnapshotData.SnapshotDataID = Catalog.SnapshotDataID WHERE Catalog.Path = @Path UPDATE Catalog SET ExecutionFlag = @ExecutionFlag, SnapshotDataID = NULL, ExecutionTime = NULL WHERE Catalog.Path = @Path END GO GRANT EXECUTE ON [dbo].[SetExecutionOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSnapshot] GO CREATE PROCEDURE [dbo].[UpdateSnapshot] @Path as nvarchar(425), @SnapshotDataID as uniqueidentifier, @executionDate as datetime AS DECLARE @OldSnapshotDataID uniqueidentifier SET @OldSnapshotDataID = (SELECT SnapshotDataID FROM Catalog WITH (XLOCK) WHERE Catalog.Path = @Path) -- update reference count in snapshot table UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount-1 WHERE SnapshotData.SnapshotDataID = @OldSnapshotDataID -- update catalog to point to the new execution snapshot UPDATE Catalog SET SnapshotDataID = @SnapshotDataID, ExecutionTime = @executionDate WHERE Catalog.Path = @Path UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount+1, TransientRefcount = TransientRefcount-1 WHERE SnapshotData.SnapshotDataID = @SnapshotDataID GO GRANT EXECUTE ON [dbo].[UpdateSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateChunkAndGetPointer]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateChunkAndGetPointer] GO CREATE PROCEDURE [dbo].[CreateChunkAndGetPointer] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int, @MimeType nvarchar(260) = NULL, @Version smallint, @Content image, @ChunkFlags tinyint = NULL, @ChunkPointer binary(16) OUTPUT AS DECLARE @ChunkID uniqueidentifier SET @ChunkID = NEWID() IF @IsPermanentSnapshot != 0 BEGIN DELETE ChunkData WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType INSERT INTO ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) VALUES (@ChunkID, @SnapshotDataID, @ChunkName, @ChunkType, @MimeType, @Version, @ChunkFlags, @Content) SELECT @ChunkPointer = TEXTPTR(Content) FROM ChunkData WHERE ChunkData.ChunkID = @ChunkID END ELSE BEGIN DELETE ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType INSERT INTO ReportServerTempDB.dbo.ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) VALUES (@ChunkID, @SnapshotDataID, @ChunkName, @ChunkType, @MimeType, @Version, @ChunkFlags, @Content) SELECT @ChunkPointer = TEXTPTR(Content) FROM ReportServerTempDB.dbo.ChunkData AS CH WHERE CH.ChunkID = @ChunkID END GO GRANT EXECUTE ON [dbo].[CreateChunkAndGetPointer] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteChunkPortion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteChunkPortion] GO CREATE PROCEDURE [dbo].[WriteChunkPortion] @ChunkPointer binary(16), @IsPermanentSnapshot bit, @DataIndex int = NULL, @DeleteLength int = NULL, @Content image AS IF @IsPermanentSnapshot != 0 BEGIN UPDATETEXT ChunkData.Content @ChunkPointer @DataIndex @DeleteLength @Content END ELSE BEGIN UPDATETEXT ReportServerTempDB.dbo.ChunkData.Content @ChunkPointer @DataIndex @DeleteLength @Content END GO GRANT EXECUTE ON [dbo].[WriteChunkPortion] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetChunkPointerAndLength]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetChunkPointerAndLength] GO CREATE PROCEDURE [dbo].[GetChunkPointerAndLength] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int AS IF @IsPermanentSnapshot != 0 BEGIN SELECT TEXTPTR(Content), DATALENGTH(Content), MimeType, ChunkFlags, Version FROM ChunkData AS CH WITH (HOLDLOCK, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END ELSE BEGIN SELECT TEXTPTR(Content), DATALENGTH(Content), MimeType, ChunkFlags, Version FROM ReportServerTempDB.dbo.ChunkData AS CH WITH (HOLDLOCK, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END GO GRANT EXECUTE ON [dbo].[GetChunkPointerAndLength] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetChunkInformation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetChunkInformation] GO CREATE PROCEDURE [dbo].[GetChunkInformation] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int AS IF @IsPermanentSnapshot != 0 BEGIN SELECT MimeType FROM ChunkData AS CH WITH (HOLDLOCK, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END ELSE BEGIN SELECT MimeType FROM ReportServerTempDB.dbo.ChunkData AS CH WITH (HOLDLOCK, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END GO GRANT EXECUTE ON [dbo].[GetChunkInformation] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadChunkPortion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadChunkPortion] GO CREATE PROCEDURE [dbo].[ReadChunkPortion] @ChunkPointer binary(16), @IsPermanentSnapshot bit, @DataIndex int, @Length int AS IF @IsPermanentSnapshot != 0 BEGIN READTEXT ChunkData.Content @ChunkPointer @DataIndex @Length END ELSE BEGIN READTEXT ReportServerTempDB.dbo.ChunkData.Content @ChunkPointer @DataIndex @Length END GO GRANT EXECUTE ON [dbo].[ReadChunkPortion] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CopyChunksOfType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CopyChunksOfType] GO CREATE PROCEDURE [dbo].[CopyChunksOfType] @FromSnapshotID uniqueidentifier, @FromIsPermanent bit, @ToSnapshotID uniqueidentifier, @ToIsPermanent bit, @ChunkType int AS IF @FromIsPermanent != 0 AND @ToIsPermanent = 0 BEGIN INSERT INTO ReportServerTempDB.dbo.ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) SELECT newid(), @ToSnapshotID, S.ChunkName, S.ChunkType, S.MimeType, S.Version, S.ChunkFlags, S.Content FROM ChunkData AS S WHERE S.SnapshotDataID = @FromSnapshotID AND S.ChunkType = @ChunkType AND NOT EXISTS( SELECT T.ChunkName FROM ReportServerTempDB.dbo.ChunkData AS T -- exclude the ones in the target WHERE T.ChunkName = S.ChunkName AND T.ChunkType = S.ChunkType AND T.SnapshotDataID = @ToSnapshotID) END ELSE IF @FromIsPermanent = 0 AND @ToIsPermanent = 0 BEGIN INSERT INTO ReportServerTempDB.dbo.ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) SELECT newid(), @ToSnapshotID, S.ChunkName, S.ChunkType, S.MimeType, S.Version, S.ChunkFlags, S.Content FROM ReportServerTempDB.dbo.ChunkData AS S WHERE S.SnapshotDataID = @FromSnapshotID AND S.ChunkType = @ChunkType AND NOT EXISTS( SELECT T.ChunkName FROM ReportServerTempDB.dbo.ChunkData AS T -- exclude the ones in the target WHERE T.ChunkName = S.ChunkName AND T.ChunkType = S.ChunkType AND T.SnapshotDataID = @ToSnapshotID) END ELSE IF @FromIsPermanent != 0 AND @ToIsPermanent != 0 BEGIN INSERT INTO ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) SELECT newid(), @ToSnapshotID, S.ChunkName, S.ChunkType, S.MimeType, S.Version, S.ChunkFlags, S.Content FROM ChunkData AS S WHERE S.SnapshotDataID = @FromSnapshotID AND S.ChunkType = @ChunkType AND NOT EXISTS( SELECT T.ChunkName FROM ChunkData AS T -- exclude the ones in the target WHERE T.ChunkName = S.ChunkName AND T.ChunkType = S.ChunkType AND T.SnapshotDataID = @ToSnapshotID) END ELSE BEGIN RAISERROR('Unsupported chunk copy', 16, 1) END GO GRANT EXECUTE ON [dbo].[CopyChunksOfType] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteSnapshotAndChunks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteSnapshotAndChunks] GO CREATE PROCEDURE [dbo].[DeleteSnapshotAndChunks] @SnapshotID uniqueidentifier, @IsPermanentSnapshot bit AS IF @IsPermanentSnapshot != 0 BEGIN DELETE ChunkData WHERE ChunkData.SnapshotDataID = @SnapshotID DELETE SnapshotData WHERE SnapshotData.SnapshotDataID = @SnapshotID END ELSE BEGIN DELETE ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotID DELETE ReportServerTempDB.dbo.SnapshotData WHERE SnapshotDataID = @SnapshotID END GO GRANT EXECUTE ON [dbo].[DeleteSnapshotAndChunks] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteOneChunk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteOneChunk] GO CREATE PROCEDURE [dbo].[DeleteOneChunk] @SnapshotID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int AS IF @IsPermanentSnapshot != 0 BEGIN DELETE ChunkData WHERE SnapshotDataID = @SnapshotID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END ELSE BEGIN DELETE ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END GO GRANT EXECUTE ON [dbo].[DeleteOneChunk] TO RSExecRole GO -------------------------------------------------- ------------- Persisted stream SPs if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeletePersistedStreams]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeletePersistedStreams] GO CREATE PROCEDURE [dbo].[DeletePersistedStreams] @SessionID varchar(32) AS delete ReportServerTempDB.dbo.PersistedStream from (select top 1 * from ReportServerTempDB.dbo.PersistedStream PS2 where PS2.SessionID = @SessionID) as e1 where e1.SessionID = ReportServerTempDB.dbo.PersistedStream.[SessionID] and e1.[Index] = ReportServerTempDB.dbo.PersistedStream.[Index] GO GRANT EXECUTE ON [dbo].[DeletePersistedStreams] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteExpiredPersistedStreams]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteExpiredPersistedStreams] GO CREATE PROCEDURE [dbo].[DeleteExpiredPersistedStreams] AS SET DEADLOCK_PRIORITY LOW DELETE ReportServerTempDB.dbo.PersistedStream FROM (SELECT TOP 1 * FROM ReportServerTempDB.dbo.PersistedStream PS2 WHERE PS2.RefCount = 0 AND GETDATE() > PS2.ExpirationDate) AS e1 WHERE e1.SessionID = ReportServerTempDB.dbo.PersistedStream.[SessionID] AND e1.[Index] = ReportServerTempDB.dbo.PersistedStream.[Index] GO GRANT EXECUTE ON [dbo].[DeleteExpiredPersistedStreams] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeletePersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeletePersistedStream] GO CREATE PROCEDURE [dbo].[DeletePersistedStream] @SessionID varchar(32), @Index int AS delete from ReportServerTempDB.dbo.PersistedStream where SessionID = @SessionID and [Index] = @Index GO GRANT EXECUTE ON [dbo].[DeletePersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddPersistedStream] GO CREATE PROCEDURE [dbo].[AddPersistedStream] @SessionID varchar(32), @Index int AS DECLARE @RefCount int DECLARE @id varchar(32) DECLARE @ExpirationDate datetime set @RefCount = 0 set @ExpirationDate = DATEADD(day, 2, GETDATE()) set @id = (select SessionID from ReportServerTempDB.dbo.SessionData where SessionID = @SessionID) if @id is not null begin set @RefCount = 1 end INSERT INTO ReportServerTempDB.dbo.PersistedStream (SessionID, [Index], [RefCount], [ExpirationDate]) VALUES (@SessionID, @Index, @RefCount, @ExpirationDate) GO GRANT EXECUTE ON [dbo].[AddPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[LockPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[LockPersistedStream] GO CREATE PROCEDURE [dbo].[LockPersistedStream] @SessionID varchar(32), @Index int AS SELECT [Index] FROM ReportServerTempDB.dbo.PersistedStream WITH (XLOCK) WHERE SessionID = @SessionID AND [Index] = @Index GO GRANT EXECUTE ON [dbo].[LockPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteFirstPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteFirstPortionPersistedStream] GO CREATE PROCEDURE [dbo].[WriteFirstPortionPersistedStream] @SessionID varchar(32), @Index int, @Name nvarchar(260) = NULL, @MimeType nvarchar(260) = NULL, @Extension nvarchar(260) = NULL, @Encoding nvarchar(260) = NULL, @Content image AS UPDATE ReportServerTempDB.dbo.PersistedStream set Content = @Content, [Name] = @Name, MimeType = @MimeType, Extension = @Extension WHERE SessionID = @SessionID AND [Index] = @Index SELECT TEXTPTR(Content) FROM ReportServerTempDB.dbo.PersistedStream WHERE SessionID = @SessionID AND [Index] = @Index GO GRANT EXECUTE ON [dbo].[WriteFirstPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteNextPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteNextPortionPersistedStream] GO CREATE PROCEDURE [dbo].[WriteNextPortionPersistedStream] @DataPointer binary(16), @DataIndex int, @DeleteLength int, @Content image AS UPDATETEXT ReportServerTempDB.dbo.PersistedStream.Content @DataPointer @DataIndex @DeleteLength @Content GO GRANT EXECUTE ON [dbo].[WriteNextPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetFirstPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetFirstPortionPersistedStream] GO CREATE PROCEDURE [dbo].[GetFirstPortionPersistedStream] @SessionID varchar(32) AS SELECT TOP 1 TEXTPTR(P.Content), DATALENGTH(P.Content), P.[Index], P.[Name], P.MimeType, P.Extension, P.Encoding, P.Error FROM ReportServerTempDB.dbo.PersistedStream P WITH (XLOCK) WHERE P.SessionID = @SessionID GO GRANT EXECUTE ON [dbo].[GetFirstPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetPersistedStreamError]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetPersistedStreamError] GO CREATE PROCEDURE [dbo].[SetPersistedStreamError] @SessionID varchar(32), @Index int, @AllRows bit, @Error nvarchar(512) AS if @AllRows = 0 BEGIN UPDATE ReportServerTempDB.dbo.PersistedStream SET Error = @Error WHERE SessionID = @SessionID and [Index] = @Index END ELSE BEGIN UPDATE ReportServerTempDB.dbo.PersistedStream SET Error = @Error WHERE SessionID = @SessionID END GO GRANT EXECUTE ON [dbo].[SetPersistedStreamError] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetNextPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetNextPortionPersistedStream] GO CREATE PROCEDURE [dbo].[GetNextPortionPersistedStream] @DataPointer binary(16), @DataIndex int, @Length int AS READTEXT ReportServerTempDB.dbo.PersistedStream.Content @DataPointer @DataIndex @Length GO GRANT EXECUTE ON [dbo].[GetNextPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapshotChunks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapshotChunks] GO CREATE PROCEDURE [dbo].[GetSnapshotChunks] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit AS IF @IsPermanentSnapshot != 0 BEGIN SELECT ChunkName, ChunkType, ChunkFlags, MimeType, Version, datalength(Content) FROM ChunkData WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN SELECT ChunkName, ChunkType, ChunkFlags, MimeType, Version, datalength(Content) FROM ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[GetSnapshotChunks] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetDrillthroughReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetDrillthroughReports] GO CREATE PROCEDURE [dbo].[SetDrillthroughReports] @ReportID uniqueidentifier, @ModelID uniqueidentifier, @ModelItemID nvarchar(425), @Type tinyint AS INSERT INTO ModelDrill (ModelDrillID, ModelID, ReportID, ModelItemID, [Type]) VALUES (newid(), @ModelID, @ReportID, @ModelItemID, @Type) GO GRANT EXECUTE ON [dbo].[SetDrillthroughReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteDrillthroughReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteDrillthroughReports] GO CREATE PROCEDURE [dbo].[DeleteDrillthroughReports] @ModelID uniqueidentifier, @ModelItemID nvarchar(425) AS DELETE ModelDrill WHERE ModelID = @ModelID and ModelItemID = @ModelItemID GO GRANT EXECUTE ON [dbo].[DeleteDrillthroughReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDrillthroughReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDrillthroughReports] GO CREATE PROCEDURE [dbo].[GetDrillthroughReports] @ModelID uniqueidentifier, @ModelItemID nvarchar(425) AS SELECT ModelDrill.Type, Catalog.Path FROM ModelDrill INNER JOIN Catalog ON ModelDrill.ReportID = Catalog.ItemID WHERE ModelID = @ModelID AND ModelItemID = @ModelItemID GO GRANT EXECUTE ON [dbo].[GetDrillthroughReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDrillthroughReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDrillthroughReport] GO CREATE PROCEDURE [dbo].[GetDrillthroughReport] @ModelPath nvarchar(425), @ModelItemID nvarchar(425), @Type tinyint AS SELECT CatRep.Path FROM ModelDrill INNER JOIN Catalog CatMod ON ModelDrill.ModelID = CatMod.ItemID INNER JOIN Catalog CatRep ON ModelDrill.ReportID = CatRep.ItemID WHERE CatMod.Path = @ModelPath AND ModelItemID = @ModelItemID AND ModelDrill.[Type] = @Type GO GRANT EXECUTE ON [dbo].[GetDrillthroughReport] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUpgradeItems]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUpgradeItems] GO CREATE PROCEDURE [dbo].[GetUpgradeItems] AS SELECT [Item], [Status] FROM [UpgradeInfo] GO GRANT EXECUTE ON [dbo].[GetUpgradeItems] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetUpgradeItemStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetUpgradeItemStatus] GO CREATE PROCEDURE [dbo].[SetUpgradeItemStatus] @ItemName nvarchar(260), @Status nvarchar(512) AS UPDATE [UpgradeInfo] SET [Status] = @Status WHERE [Item] = @ItemName GO GRANT EXECUTE ON [dbo].[SetUpgradeItemStatus] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPolicyRoots]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPolicyRoots] GO CREATE PROCEDURE [dbo].[GetPolicyRoots] AS SELECT [Path], [Type] FROM [Catalog] WHERE [PolicyRoot] = 1 GO GRANT EXECUTE ON [dbo].[GetPolicyRoots] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDataSourceForUpgrade]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDataSourceForUpgrade] GO CREATE PROCEDURE [dbo].[GetDataSourceForUpgrade] @CurrentVersion int AS SELECT [DSID] FROM [DataSource] WHERE [Version] != @CurrentVersion GO GRANT EXECUTE ON [dbo].[GetDataSourceForUpgrade] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSubscriptionsForUpgrade]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSubscriptionsForUpgrade] GO CREATE PROCEDURE [dbo].[GetSubscriptionsForUpgrade] @CurrentVersion int AS SELECT [SubscriptionID] FROM [Subscriptions] WHERE [Version] != @CurrentVersion GO GRANT EXECUTE ON [dbo].[GetSubscriptionsForUpgrade] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[StoreServerParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[StoreServerParameters] GO CREATE PROCEDURE [dbo].[StoreServerParameters] @ServerParametersID nvarchar(32), @Path nvarchar(425), @CurrentDate datetime, @Timeout int, @Expiration datetime, @ParametersValues image, @ParentParametersID nvarchar(32) = NULL AS DECLARE @ExistingServerParametersID as nvarchar(32) SET @ExistingServerParametersID = (SELECT ServerParametersID from [dbo].[ServerParametersInstance] WHERE ServerParametersID = @ServerParametersID) IF @ExistingServerParametersID IS NULL -- new row BEGIN INSERT INTO [dbo].[ServerParametersInstance] (ServerParametersID, ParentID, Path, CreateDate, ModifiedDate, Timeout, Expiration, ParametersValues) VALUES (@ServerParametersID, @ParentParametersID, @Path, @CurrentDate, @CurrentDate, @Timeout, @Expiration, @ParametersValues) END ELSE BEGIN UPDATE [dbo].[ServerParametersInstance] SET Timeout = @Timeout, Expiration = @Expiration, ParametersValues = @ParametersValues, ModifiedDate = @CurrentDate, Path = @Path, ParentID = @ParentParametersID WHERE ServerParametersID = @ServerParametersID END GO GRANT EXECUTE ON [dbo].[StoreServerParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetServerParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetServerParameters] GO CREATE PROCEDURE [dbo].[GetServerParameters] @ServerParametersID nvarchar(32) AS DECLARE @now as DATETIME SET @now = GETDATE() SELECT Child.Path, Child.ParametersValues, Parent.ParametersValues FROM [dbo].[ServerParametersInstance] Child LEFT OUTER JOIN [dbo].[ServerParametersInstance] Parent ON Child.ParentID = Parent.ServerParametersID WHERE Child.ServerParametersID = @ServerParametersID AND Child.Expiration > @now GO GRANT EXECUTE ON [dbo].[GetServerParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredServerParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredServerParameters] GO CREATE PROCEDURE [dbo].[CleanExpiredServerParameters] @ParametersCleaned INT OUTPUT AS DECLARE @now as DATETIME SET @now = GETDATE() DELETE FROM [dbo].[ServerParametersInstance] WHERE ServerParametersID IN ( SELECT TOP 20 ServerParametersID FROM [dbo].[ServerParametersInstance] WHERE Expiration < @now ) SET @ParametersCleaned = @@ROWCOUNT GO GRANT EXECUTE ON [dbo].[CleanExpiredServerParameters] TO RSExecRole GO -- END STORED PROCEDURES -------------------------------------------------- ------------- Initial population -------------------------------------------------- INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'MyReportsRole', N'My Reports' ) INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'EnableMyReports', 'False' ) INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'UseSessionCookies', 'true' ) INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'SessionTimeout', '600' ) -- 10 min INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'SystemSnapshotLimit', '-1' ) INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'SystemReportTimeout', '1800' ) -- 30 min INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'SiteName', 'SQL Server Reporting Services' ) INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'EnableExecutionLogging', 'True' ) INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'ExecutionLogDaysKept', '60' ) INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'SnapshotCompression', 'SQL' ) INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'EnableIntegratedSecurity', 'true' ) INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'ExternalImagesTimeout', '600' ) -- 10 min INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'StoredParametersThreshold', '1500' ) INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'StoredParametersLifetime', '180' ) -- days INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'EnableReportDesignClientDownload', 'True' ) INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'EnableClientPrinting', 'True' ) INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'EnableRemoteErrors', 'False' ) GO DECLARE @NewItemID uniqueidentifier DECLARE @Now DateTime DECLARE @NewPolicyID uniqueidentifier SET @NewItemID = newid() SET @Now = GETDATE() -- Create builtin roles DECLARE @RoleIDPublisher uniqueidentifier SET @RoleIDPublisher = newid() EXEC [dbo].[CreateRole] @RoleID = @RoleIDPublisher, @RoleName = N'Publisher', @Description = N'Publish reports and linked reports to the Report Server.', @TaskMask = '0101010100001010', @RoleFlags = 0 /* ConfigureAccess =0, CreateLinkedReports =1, x ViewReports =2, ManageReports =3, x ViewResources =4, ManageResources =5, x ViewFolders =6, ManageFolders =7, x ManageSnapshots =8, Subscribe =9, ManageAnySubscription =10, ViewDatasources =11, ManageDatasources =12,x ViewModels =13, ManageModels =14, x ConsumeReports =15 */ DECLARE @RoleIDBrowser uniqueidentifier SET @RoleIDBrowser = newid() EXEC [dbo].[CreateRole] @RoleID = @RoleIDBrowser, @RoleName = N'Browser', -- This string is localized. Changing it here requires a change in setupmanagement.dll @Description = N'View folders, reports and subscribe to reports.', -- This string is localized. Changing it here requires a change in setupmanagement.dll @TaskMask = '0010101001000100', @RoleFlags = 0 /* ConfigureAccess =0, CreateLinkedReports =1, ViewReports =2, x ManageReports =3, ViewResources =4, x ManageResources =5, ViewFolders =6, x ManageFolders =7, ManageSnapshots =8, Subscribe =9, x ManageAnySubscription =10 ViewDatasources =11, ManageDatasources =12, ViewModels =13,x ManageModels =14 , ConsumeReports =15 */ DECLARE @RoleIDContentManager uniqueidentifier SET @RoleIDContentManager = newid() EXEC [dbo].[CreateRole] @RoleID = @RoleIDContentManager, @RoleName = N'Content Manager', -- This string is localized. Changing it here requires a change in setupmanagement.dll @Description = N'Manage content in the Report Server. This includes folders, reports and resources.', -- This string is localized. Changing it here requires a change in setupmanagement.dll @TaskMask = '1111111111111111', @RoleFlags = 0 /* ConfigureAccess =0, x CreateLinkedReports =1, x ViewReports =2, x ManageReports =3, x ViewResources =4, x ManageResources =5, x ViewFolders =6, x ManageFolders =7, x ManageSnapshots =8, x Subscribe =9, x ManageAnySubscription =10,x ViewDatasources =11,x ManageDatasources =12,x ViewModels =13,x ManageModels =14,x ConsumeReports =15,x */ DECLARE @RoleIDReportConsumer uniqueidentifier SET @RoleIDReportConsumer = newid() EXEC [dbo].[CreateRole] @RoleID = @RoleIDReportConsumer, @RoleName = N'Report Builder', -- This string is localized. Changing it here requires a change in setupmanagement.dll @Description = N'May view report definitions.', -- This string is localized. Changing it here requires a change in setupmanagement.dll @TaskMask = '0010101001000101', @RoleFlags = 0 /* ConfigureAccess =0, CreateLinkedReports =1, ViewReports =2, ManageReports =3, ViewResources =4, ManageResources =5, ViewFolders =6, ManageFolders =7, ManageSnapshots =8, Subscribe =9, ManageAnySubscription =10, ViewDatasources =11, ManageDatasources =12, ViewModels =13, ManageModels =14, ConsumeReports =15 x */ DECLARE @RoleIDMyReports uniqueidentifier SET @RoleIDMyReports = newid() EXEC [dbo].[CreateRole] @RoleID = @RoleIDMyReports, @RoleName = N'My Reports', -- This string is localized. Changing it here requires a change in setupmanagement.dll @Description = N'Publish reports and linked reports; manage folders, reports and resources in a users My Reports folder.', -- This string is localized. Changing it here requires a change in setupmanagement.dll @TaskMask = '0111111111011000', @RoleFlags = 0 /* ConfigureAccess =0, PublishLinkedReport =1, X ViewReports =2, X ManageReports =3, X ViewResources =4, X ManageResources =5, X ViewFolders =6, X ManageFolders =7, X ManageSnapshots =8, X Subscribe =9, X ManageAllSubscriptions =10, ViewDatasources =11,X ManageDatasources =12 X ViewModels =13, ManageModels =14, ConsumeReports =15 */ DECLARE @RoleIDAdministrator uniqueidentifier SET @RoleIDAdministrator = newid() EXEC [dbo].[CreateRole] @RoleID = @RoleIDAdministrator, @RoleName = N'System Administrator', -- This string is localized. Changing it here requires a change in setupmanagement.dll @Description = N'View and modify system role assignments, system role definitions, system properties, and shared schedules.', -- This string is localized. Changing it here requires a change in setupmanagement.dll @TaskMask = '110101011', @RoleFlags = 1 --system role /* ManageRoles = 0, x ManageSystemSecurity = 1, x ViewSystemProperties = 2, ManageSystemProperties = 3, x ViewSharedSchedules = 4, ManageSharedSchedules = 5, x GenerateEvents = 6, ManageJobs = 7, x ExecuteReportDefinitions = 8 x */ DECLARE @RoleIDSysBrowser uniqueidentifier SET @RoleIDSysBrowser = newid() EXEC [dbo].[CreateRole] @RoleID = @RoleIDSysBrowser, @RoleName = N'System User', -- This string is localized. Changing it here requires a change in setupmanagement.dll @Description = N'View system properties and shared schedules.', -- This string is localized. Changing it here requires a change in setupmanagement.dll @TaskMask = '001010001', @RoleFlags = 1 --system role /* ManageRoles = 0, ManageSystemSecurity = 1, ViewSystemProperties = 2, x ManageSystemProperties = 3, ViewSharedSchedules = 4, x ManageSharedSchedules = 5, GenerateEvents = 6, ManageJobs = 7, ExecuteReportDefinitions = 8 x */ DECLARE @RoleIDModelItemBrowser uniqueidentifier SET @RoleIDModelItemBrowser = newid() EXEC [dbo].[CreateRole] @RoleID = @RoleIDModelItemBrowser, @RoleName = N'Model Item Browser', -- This string is localized. Changing it here requires a change in setupmanagement.dll @Description = N'Allows users to view models items in a particular model.', -- This string is localized. Changing it here requires a change in setupmanagement.dll @TaskMask = '1', @RoleFlags = 2 -- Model item role /*Create policies*/ SET @NewPolicyID = newid() INSERT INTO [dbo].[Policies] ( [PolicyID], [PolicyFlag]) VALUES ( @NewPolicyID, 0) INSERT INTO [dbo].[SecData] ( [SecDataID], [PolicyID], [XmlDescription], [NtSecDescPrimary], [AuthType]) VALUES ( newid(), @NewPolicyID, -- The xml string is localized. Changing the group user name or role name fields required a change in setupmanagement.dll N'<Policies><Policy><GroupUserName>Builtin\Administrators</GroupUserName><GroupUserId>AQIAAAAAAAUgAAAAIAIAAA==</GroupUserId><Roles><Role><Name>Content Manager</Name></Role></Roles></Policy></Policies>' , 0x06050054000000020100048034000000440000000000000014000000020020000100000000041800FF00060001020000000000052000000020020000010200000000000520000000200200000102000000000005200000002002000054000000030100048034000000440000000000000014000000020020000100000000041800FFFF3F00010200000000000520000000200200000102000000000005200000002002000001020000000000052000000020020000540000000401000480340000004400000000000000140000000200200001000000000418001D000000010200000000000520000000200200000102000000000005200000002002000001020000000000052000000020020000540000000501000480340000004400000000000000140000000200200001000000000418001F000600010200000000000520000000200200000102000000000005200000002002000001020000000000052000000020020000540000000601000480340000004400000000000000140000000200200001000000000418001F00060001020000000000052000000020020000010200000000000520000000200200000102000000000005200000002002000054000000070100048034000000440000000000000014000000020020000100000000041800FF010600010200000000000520000000200200000102000000000005200000002002000001020000000000052000000020020000, 1) DECLARE @SystemPolicyID uniqueidentifier SET @SystemPolicyID = newid() INSERT INTO [dbo].[Policies] ( [PolicyID], [PolicyFlag]) VALUES ( @SystemPolicyID, 1) INSERT INTO [dbo].[SecData] ( [SecDataID], [PolicyID], [XmlDescription], [NtSecDescPrimary], [AuthType]) VALUES ( newid(), @SystemPolicyID, -- The xml string is localized. Changing the group user name or role name fields required a change in setupmanagement.dll N'<Policies><Policy><GroupUserName>Builtin\Administrators</GroupUserName><GroupUserId>AQIAAAAAAAUgAAAAIAIAAA==</GroupUserId><Roles><Role><Name>System Administrator</Name></Role></Roles></Policy></Policies>', 0x01050054000000010100048034000000440000000000000014000000020020000100000000041800BF3F0600010200000000000520000000200200000102000000000005200000002002000001020000000000052000000020020000, 1) -- Create builtin principals DECLARE @EveryoneID as uniqueidentifier -- The xml string is localized. Changing the group user name or role name fields required a change in setupmanagement.dll EXEC [dbo].[GetPrincipalID] 0x010100000000000100000000, N'Everyone', 1, @EveryoneID OUTPUT DECLARE @AdminID as uniqueidentifier -- The xml string is localized. Changing the group user name or role name fields required a change in setupmanagement.dll EXEC [dbo].[GetPrincipalID] 0x01020000000000052000000020020000, N'Builtin\Administrators' , 1, @AdminID OUTPUT -- create role-policy-principal relationships INSERT INTO [dbo].[PolicyUserRole] ([ID], [RoleID], [UserID], [PolicyID]) VALUES (newid(), @RoleIDBrowser, @EveryoneID, @NewPolicyID) INSERT INTO [dbo].[PolicyUserRole] ([ID], [RoleID], [UserID], [PolicyID]) VALUES (newid(), @RoleIDContentManager, @AdminID, @NewPolicyID) INSERT INTO [dbo].[PolicyUserRole] ([ID], [RoleID], [UserID], [PolicyID]) VALUES (newid(), @RoleIDAdministrator, @AdminID, @SystemPolicyID) INSERT INTO [dbo].[PolicyUserRole] ([ID], [RoleID], [UserID], [PolicyID]) VALUES (newid(), @RoleIDSysBrowser, @EveryoneID, @SystemPolicyID) EXEC [dbo].[CreateObject] @ItemID = @NewItemID, @Name = '', @Path = '', @ParentID = NULL, @Type = 1, @Content = null, @Intermediate = null, @LinkSourceID = null, @Property = null, @Description = null, @CreatedBySid = 0x010100000000000512000000, -- local system @CreatedByName = N'NT AUTHORITY\SYSTEM', @AuthType = 1, @CreationDate = @Now, @MimeType = null, @SnapshotLimit = null, @PolicyRoot = 1, @PolicyID = @NewPolicyID GO -------------------------------------------------- ------------- Master and MSDB rights -------------------------------------------------- USE master GO GRANT EXECUTE ON master.dbo.xp_sqlagent_notify TO RSExecRole GO GRANT EXECUTE ON master.dbo.xp_sqlagent_enum_jobs TO RSExecRole GO GRANT EXECUTE ON master.dbo.xp_sqlagent_is_starting TO RSExecRole GO USE msdb GO -- Permissions for SQL Agent SP's GRANT EXECUTE ON msdb.dbo.sp_help_category TO RSExecRole GO GRANT EXECUTE ON msdb.dbo.sp_add_category TO RSExecRole GO GRANT EXECUTE ON msdb.dbo.sp_add_job TO RSExecRole GO GRANT EXECUTE ON msdb.dbo.sp_add_jobserver TO RSExecRole GO GRANT EXECUTE ON msdb.dbo.sp_add_jobstep TO RSExecRole GO GRANT EXECUTE ON msdb.dbo.sp_add_jobschedule TO RSExecRole GO GRANT EXECUTE ON msdb.dbo.sp_help_job TO RSExecRole GO GRANT EXECUTE ON msdb.dbo.sp_delete_job TO RSExecRole GO GRANT EXECUTE ON msdb.dbo.sp_help_jobschedule TO RSExecRole GO GRANT EXECUTE ON msdb.dbo.sp_verify_job_identifiers TO RSExecRole GO GRANT SELECT ON msdb.dbo.sysjobs TO RSExecRole GO GRANT SELECT ON msdb.dbo.syscategories TO RSExecRole GO -- Yukon Requires that the user is in the SQLAgentOperatorRole if exists (select * from sysusers where issqlrole = 1 and name = N'SQLAgentOperatorRole') BEGIN EXEC msdb.dbo.sp_addrolemember N'SQLAgentOperatorRole', N'RSExecRole' END PA-- standard script to set the database version, can be used both the catalog database and the tempdb database -- the idea is to first drop the existing stored procedure and then create a new on with the correct database version -- and give the RSExecRole permissions to execute it. The correct database version replaces the DBVERSIONTOKEN place holder -- during the build script finalization in the DatabaseMgr.cpp code. ------------- DBVersion ------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDBVersion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDBVersion] GO CREATE PROCEDURE [dbo].[GetDBVersion] @DBVersion nvarchar(32) OUTPUT AS set @DBVersion = 'DBVERSIONTOKEN' GO GRANT EXECUTE ON [dbo].[GetDBVersion] TO RSExecRole GO PAHKCR { NoRemove CLSID { ForceRemove {7832DD88-C63A-45BA-BEA4-86635F4303ED} { InprocServer32 = s '%MODULE%' { val ThreadingModel = s 'Both' } } } } -- !!! This assumes the database is created and the user is either a dbo or is added to the RSExecRole -- !!! Please run setup to create the database, users, role !!! if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDBVersion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDBVersion] GO CREATE PROCEDURE [dbo].[GetDBVersion] @DBVersion nvarchar(32) OUTPUT AS set @DBVersion = 'T.0.8.40' GO GRANT EXECUTE ON [dbo].[GetDBVersion] TO RSExecRole GO ------------------------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SessionLock]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[SessionLock] GO CREATE TABLE [dbo].[SessionLock] ( [SessionID] varchar(32) NOT NULL ) GO GRANT SELECT, INSERT, UPDATE, DELETE, REFERENCES ON [dbo].[SessionLock] TO RSExecRole GO CREATE UNIQUE CLUSTERED INDEX [IDX_SessionLock] ON [dbo].[SessionLock]([SessionID]) GO ------------------------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SessionData]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[SessionData] GO CREATE TABLE [dbo].[SessionData] ( [SessionID] varchar(32) NOT NULL, [CompiledDefinition] uniqueidentifier NULL, -- when session starts from definition, this holds compiled definition snapshot id [SnapshotDataID] uniqueidentifier NULL, [IsPermanentSnapshot] bit NULL, [ReportPath] nvarchar(424) NULL, -- Report Path is empty string ("") when session starts from definition [Timeout] int NOT NULL, [AutoRefreshSeconds] int NULL, -- How often data should be refreshed [Expiration] datetime NOT NULL, [ShowHideInfo] image NULL, [DataSourceInfo] image NULL, [OwnerID] uniqueidentifier NOT NULL, [EffectiveParams] ntext NULL, [CreationTime] DateTime NOT NULL, [HasInteractivity] bit NULL, [SnapshotExpirationDate] datetime NULL, -- when this snapshot expires - cache or exec snapshot [HistoryDate] datetime NULL, -- if this is not null, session was started from history [PageHeight] float NULL, -- page properties are only populated for temporary reports. [PageWidth] float NULL, [TopMargin] float NULL, [BottomMargin] float NULL, [LeftMargin] float NULL, [RightMargin] float NULL, [ExecutionType] smallint NULL ) GO EXEC sp_tableoption N'[dbo].[SessionData]', 'text in row', 'ON' GO GRANT SELECT, INSERT, UPDATE, DELETE, REFERENCES ON [dbo].[SessionData] TO RSExecRole GO CREATE UNIQUE CLUSTERED INDEX [IDX_SessionData] ON [dbo].[SessionData]([SessionID]) GO CREATE INDEX [IX_SessionCleanup] ON [dbo].[SessionData]([Expiration]) GO CREATE INDEX [IX_SessionSnapshotID] ON [dbo].[SessionData]([SnapshotDataID]) GO ------------------------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ExecutionCache]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[ExecutionCache] GO CREATE TABLE [dbo].[ExecutionCache] ( [ExecutionCacheID] uniqueidentifier NOT NULL, [ReportID] uniqueidentifier NOT NULL, [ExpirationFlags] int NOT NULL, [AbsoluteExpiration] datetime NULL, [RelativeExpiration] int NULL, [SnapshotDataID] uniqueidentifier NOT NULL ) GO GRANT SELECT, INSERT, UPDATE, DELETE, REFERENCES ON [dbo].[ExecutionCache] TO RSExecRole GO ALTER TABLE [dbo].[ExecutionCache] ADD CONSTRAINT [PK_ExecutionCache] PRIMARY KEY NONCLUSTERED ( [ExecutionCacheID] ) GO CREATE UNIQUE CLUSTERED INDEX [IX_ExecutionCache] ON [dbo].[ExecutionCache] ([AbsoluteExpiration] DESC, [ReportID], [SnapshotDataID]) GO ------------------------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SnapshotData]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[SnapshotData] GO CREATE TABLE [dbo].[SnapshotData] ( [SnapshotDataID] uniqueidentifier NOT NULL, [CreatedDate] datetime NOT NULL, [ParamsHash] int NULL, -- Hash of values of parameters that are used in query [QueryParams] ntext NULL, -- Values of parameters that are used in query [EffectiveParams] ntext NULL, -- Full set of effective parameters [Description] nvarchar(512) NULL, [DependsOnUser] bit NULL, [PermanentRefcount] int NOT NULL, -- this counts only permanent references, NOT SESSIONS!!! [TransientRefcount] int NOT NULL, -- this is to count sessions, may be more than expected [ExpirationDate] datetime NOT NULL, -- Expired snapshots should be erased regardless of TransiendRefcount [PageCount] int NULL, [HasDocMap] bit NULL, [Machine] nvarchar(512) NOT NULL ) GO EXEC sp_tableoption N'[dbo].[SnapshotData]', 'text in row', 'ON' GO GRANT SELECT, INSERT, UPDATE, DELETE, REFERENCES ON [dbo].[SnapshotData] TO RSExecRole GO ALTER TABLE [dbo].[SnapshotData] ADD CONSTRAINT [PK_SnapshotData] PRIMARY KEY CLUSTERED ( [SnapshotDataID] ) GO CREATE INDEX [IX_SnapshotCleaning] ON [dbo].[SnapshotData]([PermanentRefcount], [TransientRefcount]) GO CREATE INDEX [IS_SnapshotExpiration] ON [dbo].[SnapshotData]([PermanentRefcount], [ExpirationDate]) GO ------------------------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ChunkData]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[ChunkData] GO CREATE TABLE [dbo].[ChunkData] ( [ChunkID] uniqueidentifier NOT NULL, [SnapshotDataID] uniqueidentifier NOT NULL, [ChunkFlags] tinyint NULL, [ChunkName] nvarchar(260), -- Name of the chunk [ChunkType] int, -- internal type of the chunk [Version] smallint NULL, -- version of the chunk [MimeType] nvarchar(260), -- mime type of the content of the chunk [Content] image -- content of the chunk ) GO GRANT SELECT, INSERT, UPDATE, DELETE, REFERENCES ON [dbo].[ChunkData] TO RSExecRole GO ALTER TABLE [dbo].[ChunkData] WITH NOCHECK ADD CONSTRAINT [PK_ChunkData] PRIMARY KEY NONCLUSTERED ( [ChunkID] ) ON [PRIMARY] GO CREATE UNIQUE CLUSTERED INDEX [IX_ChunkData] ON [dbo].[ChunkData]([SnapshotDataID], [ChunkType], [ChunkName]) ON [PRIMARY] GO ------------------------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[PersistedStream]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[PersistedStream] GO CREATE TABLE [dbo].[PersistedStream] ( [SessionID] varchar(32) NOT NULL, [Index] int NOT NULL, [Content] image NULL, [Name] nvarchar(260) NULL, [MimeType] nvarchar(260) NULL, [Extension] nvarchar(260) NULL, [Encoding] nvarchar(260) NULL, [Error] nvarchar(512) NULL, [RefCount] int NOT NULL, [ExpirationDate] datetime NOT NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO GRANT SELECT, INSERT, UPDATE, DELETE, REFERENCES ON [dbo].[PersistedStream] TO RSExecRole GO ALTER TABLE [dbo].[PersistedStream] ADD CONSTRAINT [PK_PersistedStream] PRIMARY KEY CLUSTERED ( [SessionID], [Index] ) ON [PRIMARY] GO PA-- Because we actually shipped Katmai CTP5 with these stored procedures (and they are not needed) we need -- to include the following fragements from the Yukon to Katmai script. -------------------------------------- -- Begin necessary Yukon to Katmai upgrades -------------------------------------- -------------------------------------- -- C.0.8.54 to C.0.9.00 -------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CopyExecutionSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CopyExecutionSnapshot] GO -------------------------------------- -- C.0.9.14 to C.0.9.15 -------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadLockSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadLockSnapshot] GO -------------------------------------- --- End of necessary Yukon to Katmai upgrades -------------------------------------- -------------------------------------- -- C.0.9.18 to C.0.9.32 -------------------------------------- -- IO optimization for segmented chunks SET ANSI_NULLS ON GO SET ANSI_PADDING ON GO SET ANSI_WARNINGS ON GO SET ARITHABORT ON GO SET CONCAT_NULL_YIELDS_NULL ON GO SET NUMERIC_ROUNDABORT OFF GO SET QUOTED_IDENTIFIER ON GO -- ensure we are atleast in SQL Server 2005 compat level declare @compatlevel tinyint select top 1 @compatlevel = compatibility_level from sys.databases d where d.database_id = DB_ID() if( @compatlevel < 90 ) begin declare @dbname sysname select @dbname = DB_NAME() exec sp_dbcmptlevel @dbname, 90 end GO -- Perform the entire migration as a single transaction begin tran GO if exists ( select * from sys.indexes idx where object_id = object_id('SegmentedChunk') and idx.name = 'PK_SnapshotChunkMapping' ) and exists ( select * from sys.columns c where c.object_id = object_id('Segment') and c.name = 'LogicalByteCount' ) and not exists ( select * from sys.columns c where c.object_id = object_id('Segment') and c.name = 'ActualByteCount' ) begin alter table SegmentedChunk add SegmentedChunkId bigint identity(1,1) not null alter table SegmentedChunk with nocheck add constraint [DF_SegmentedChunk_ChunkId] default newsequentialid() for ChunkId alter table SegmentedChunk drop constraint [PK_SnapshotChunkMapping] alter table SegmentedChunk with nocheck add constraint [PK_SegmentedChunk] primary key clustered (SegmentedChunkId) alter table SegmentedChunk alter column Version smallint not null alter table SegmentedChunk alter column ChunkFlags tinyint not null create unique nonclustered index [UNIQ_SnapshotChunkMapping] on [dbo].[SegmentedChunk] ([SnapshotDataId], [ChunkType], [ChunkName]) include ([ChunkFlags], [ChunkId]) alter table Segment add ActualByteCount as convert(int, datalength(Content)) persisted alter table Segment with nocheck add constraint [DF_Segment_SegmentId] default newsequentialid() for SegmentId create nonclustered index [IX_SegmentMetadata] on [dbo].[Segment] ([SegmentId]) include ([LogicalByteCount], [ActualByteCount]) end GO commit GO -------------------------------------- -- T.0.9.18 to T.0.9.32 -------------------------------------- -- IO optimization for segmented chunks SET ANSI_NULLS ON GO SET ANSI_PADDING ON GO SET ANSI_WARNINGS ON GO SET ARITHABORT ON GO SET CONCAT_NULL_YIELDS_NULL ON GO SET NUMERIC_ROUNDABORT OFF GO SET QUOTED_IDENTIFIER ON GO -- ensure we are atleast in SQL Server 2005 compat level declare @compatlevel tinyint select top 1 @compatlevel = compatibility_level from sys.databases d where d.database_id = DB_ID() if( @compatlevel < 90 ) begin declare @dbname sysname select @dbname = DB_NAME() exec sp_dbcmptlevel @dbname, 90 end GO -- Perform the entire migration as a single transaction begin tran GO if exists ( select * from sys.indexes idx where object_id = object_id('SegmentedChunk') and idx.name = 'PK_SnapshotChunkMapping' ) and exists ( select * from sys.columns c where c.object_id = object_id('Segment') and c.name = 'LogicalByteCount' ) and not exists ( select * from sys.columns c where c.object_id = object_id('Segment') and c.name = 'ActualByteCount' ) begin alter table SegmentedChunk add SegmentedChunkId bigint identity(1,1) not null alter table SegmentedChunk with nocheck add constraint [DF_SegmentedChunk_ChunkId] default newsequentialid() for ChunkId alter table SegmentedChunk drop constraint [PK_SnapshotChunkMapping] alter table SegmentedChunk with nocheck add constraint [PK_SegmentedChunk] primary key clustered (SegmentedChunkId) alter table SegmentedChunk alter column Version smallint not null alter table SegmentedChunk alter column ChunkFlags tinyint not null create unique nonclustered index [UNIQ_SnapshotChunkMapping] on [dbo].[SegmentedChunk] ([SnapshotDataId], [ChunkType], [ChunkName]) include ([ChunkFlags], [ChunkId]) exec sp_rename 'SegmentedChunk.IX_ChunkId_SnapshotDataId', 'UNIQ_ChunkId_SnapshotDataId', 'INDEX' alter table Segment add ActualByteCount as convert(int, datalength(Content)) persisted alter table Segment with nocheck add constraint [DF_Segment_SegmentId] default newsequentialid() for SegmentId create nonclustered index [IX_SegmentMetadata] on [dbo].[Segment] ([SegmentId]) include ([LogicalByteCount], [ActualByteCount]) end GO commit GO -------------------------------------- -- C.0.9.34 to C.0.9.35 -------------------------------------- -- Modifications to cleanup to remove new segmented chunk data as part of CleanOrphanedSnapshot -- plus other cleanup optimizations. -- drop cascade operation on SegmentedChunk table. we need to keep track -- of the chunks which get deleted so CleanOrphanedSnapshots can enumerate -- mappings/segments which need to be cleaned. IF EXISTS ( SELECT 1 FROM sys.foreign_keys fk WHERE fk.name = 'FK_SnapshotChunkMappingSnapshotDataId' AND fk.parent_object_id = object_id('SegmentedChunk') ) BEGIN ALTER TABLE SegmentedChunk DROP CONSTRAINT FK_SnapshotChunkMappingSnapshotDataId ; END ; GO -------------------------------------- -- C.0.9.35 to C.0.9.36 -------------------------------------- -- No schema changes -------------------------------------- -- C.0.9.36 to C.0.9.37 -------------------------------------- begin ALTER TABLE [dbo].[ExecutionLogStorage] ALTER COLUMN [Status] nvarchar(40) NOT NULL ; end; GO -------------------------------------- -- C.0.9.37 to C.0.9.38 -------------------------------------- -- No schema changes -------------------------------------- -- C.0.9.38 to C.0.9.39 -------------------------------------- -- Add Rdce execution type to ExecutionLog2 view if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ExecutionLog2]') and OBJECTPROPERTY(id, N'IsView') = 1) begin drop view [dbo].[ExecutionLog2] end GO CREATE VIEW [dbo].[ExecutionLog2] AS SELECT InstanceName, COALESCE(C.Path, 'Unknown') AS ReportPath, UserName, ExecutionId, CASE(RequestType) WHEN 0 THEN 'Interactive' WHEN 1 THEN 'Subscription' ELSE 'Unknown' END AS RequestType, -- SubscriptionId, Format, Parameters, CASE(ReportAction) WHEN 1 THEN 'Render' WHEN 2 THEN 'BookmarkNavigation' WHEN 3 THEN 'DocumentMapNavigation' WHEN 4 THEN 'DrillThrough' WHEN 5 THEN 'FindString' WHEN 6 THEN 'GetDocumentMap' WHEN 7 THEN 'Toggle' WHEN 8 THEN 'Sort' ELSE 'Unknown' END AS ReportAction, TimeStart, TimeEnd, TimeDataRetrieval, TimeProcessing, TimeRendering, CASE(Source) WHEN 1 THEN 'Live' WHEN 2 THEN 'Cache' WHEN 3 THEN 'Snapshot' WHEN 4 THEN 'History' WHEN 5 THEN 'AdHoc' WHEN 6 THEN 'Session' WHEN 7 THEN 'Rdce' ELSE 'Unknown' END AS Source, Status, ByteCount, [RowCount], AdditionalInfo FROM ExecutionLogStorage EL WITH(NOLOCK) LEFT OUTER JOIN Catalog C WITH(NOLOCK) ON (EL.ReportID = C.ItemID) GO GRANT SELECT, REFERENCES ON [dbo].[ExecutionLog2] TO RSExecRole GO -------------------------------------- -- C.0.9.39 to C.0.9.40 -------------------------------------- -- No schema changes -------------------------------------- -- C.0.9.40 to C.0.9.41 -------------------------------------- -- No schema changes -------------------------------------- -- C.0.9.42 to C.0.9.43 -------------------------------------- begin transaction GO if not exists ( select 1 from sys.columns c where c.object_id = object_id('ChunkSegmentMapping') and c.name = 'LogicalByteCount' ) begin alter table ChunkSegmentMapping add LogicalByteCount int not null constraint [TEMP_CNSTR_CSM_LogicalByteCount] default (-1) alter table ChunkSegmentMapping add ActualByteCount int not null constraint [TEMP_CNSTR_CSM_ActualByteCount] default (-1) end GO if exists ( select 1 from sys.columns c where c.object_id = object_id('Segment') and c.name = 'LogicalByteCount' ) begin exec sp_executesql N'update ChunkSegmentMapping set LogicalByteCount = S.LogicalByteCount, ActualByteCount = S.ActualByteCount from Segment S where ChunkSegmentMapping.SegmentId = S.SegmentId' end GO if exists ( select 1 from sys.columns c where c.object_id = object_id('Segment') and c.name = 'LogicalByteCount' ) begin alter table ChunkSegmentMapping drop constraint [TEMP_CNSTR_CSM_LogicalByteCount] alter table ChunkSegmentMapping drop constraint [TEMP_CNSTR_CSM_ActualByteCount] alter table Segment drop constraint Positive_LogicalByteCount alter table ChunkSegmentMapping with check add constraint [Positive_LogicalByteCount] check ([LogicalByteCount] >= 0) alter table ChunkSegmentMapping with check add constraint [Positive_ActualByteCount] check ([ActualByteCount] >= 0) alter table ChunkSegmentMapping drop constraint [UNIQ_ChunkId_StartByte] create unique nonclustered index [UNIQ_ChunkId_StartByte] on ChunkSegmentMapping (ChunkId ASC, StartByte ASC) include (ActualByteCount, LogicalByteCount) drop index IX_SegmentMetadata on Segment alter table Segment drop column LogicalByteCount alter table Segment drop column ActualByteCount create unique nonclustered index IX_SegmentMetadata on Segment(SegmentId) end GO commit GO -------------------------------------- -- C.0.9.43 to C.0.9.44 -------------------------------------- declare @sql nvarchar(max) declare @dfname nvarchar(max) select @dfname = df.name from sys.default_constraints df join sys.columns c on(df.parent_object_id = c.object_id and df.parent_column_id = c.column_id) where df.parent_object_id = object_id('SegmentedChunk') and c.name = 'ChunkId' if (@dfname is not null) begin select @sql = N'alter table SegmentedChunk drop constraint ' select @sql = @sql + QUOTENAME(@dfname) exec sp_executesql @sql end alter table SegmentedChunk with nocheck add constraint [DF_SegmentedChunk_ChunkId] default newsequentialid() for ChunkId GO declare @sql nvarchar(max) declare @dfname nvarchar(max) select @dfname = df.name from sys.default_constraints df join sys.columns c on(df.parent_object_id = c.object_id and df.parent_column_id = c.column_id) where df.parent_object_id = object_id('Segment') and c.name = 'SegmentId' if (@dfname is not null) begin select @sql = N'alter table Segment drop constraint ' select @sql = @sql + QUOTENAME(@dfname) exec sp_executesql @sql end alter table Segment with nocheck add constraint [DF_Segment_SegmentId] default newsequentialid() for SegmentId GO -- remove unique constraint on SegmentedChunk (ChunkId, SnapshotDataId). -- this constraint is no longer valid that chunks can be shared across database boundary -- since two chunks with the same logical ChunkID can be created (for example, two execution -- snapshots using the compiled definition chunk) if exists ( select * from sys.indexes ix where ix.name = 'UNIQ_ChunkId_SnapshotDataId' and ix.object_id = object_id('SegmentedChunk') ) begin drop index [UNIQ_ChunkId_SnapshotDataId] on [SegmentedChunk] end GO if exists ( select * from sys.indexes ix where ix.name = 'IX_ChunkId_SnapshotDataId' and ix.object_id = object_id('SegmentedChunk') ) begin drop index [IX_ChunkId_SnapshotDataId] on [SegmentedChunk] end GO create nonclustered index [IX_ChunkId_SnapshotDataId] on [SegmentedChunk]( [ChunkId], [SnapshotDataId] ) GO if not exists ( select * from [dbo].[ConfigurationInfo] where [Name] = 'ReportBuilderLaunchURL' ) begin INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'ReportBuilderLaunchURL', '' ) end GO -------------------------------------- -- C.0.9.44 to C.0.9.45 -------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAndHoldLockActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAndHoldLockActiveSubscription] GO -------------------------------------- -- T.0.9.34 to T.0.9.35 -------------------------------------- -- include [Machine] in index as non-key column to allow searching for orphaned snapshots query -- to be completely covered by this index. CREATE INDEX [IX_SnapshotCleaning] ON [dbo].[SnapshotData]([PermanentRefcount], [TransientRefcount]) INCLUDE ([Machine]) WITH (DROP_EXISTING = ON) GO -------------------------------------- -- T.0.9.35 to T.0.9.36 -------------------------------------- -- No schema changes -------------------------------------- -- T.0.9.36 to T.0.9.37 -------------------------------------- -- No schema changes -------------------------------------- -- T.0.9.37 to T.0.9.38 -------------------------------------- -- No schema changes -------------------------------------- -- T.0.9.38 to T.0.9.39 -------------------------------------- -- No schema changes -------------------------------------- -- T.0.9.39 to T.0.9.40 -------------------------------------- -- No schema changes -------------------------------------- -- T.0.9.40 to T.0.9.41 -------------------------------------- -- No schema changes -------------------------------------- -- T.0.9.42 to T.0.9.43 -------------------------------------- begin transaction GO if not exists ( select 1 from sys.columns c where c.object_id = object_id('ChunkSegmentMapping') and c.name = 'LogicalByteCount' ) begin alter table ChunkSegmentMapping add LogicalByteCount int not null constraint [TEMP_CNSTR_CSM_LogicalByteCount] default (-1) alter table ChunkSegmentMapping add ActualByteCount int not null constraint [TEMP_CNSTR_CSM_ActualByteCount] default (-1) end GO if exists ( select 1 from sys.columns c where c.object_id = object_id('Segment') and c.name = 'LogicalByteCount' ) begin exec sp_executesql N'update ChunkSegmentMapping set LogicalByteCount = S.LogicalByteCount, ActualByteCount = S.ActualByteCount from Segment S where ChunkSegmentMapping.SegmentId = S.SegmentId' end GO if exists ( select 1 from sys.columns c where c.object_id = object_id('Segment') and c.name = 'LogicalByteCount' ) begin alter table ChunkSegmentMapping drop constraint [TEMP_CNSTR_CSM_LogicalByteCount] alter table ChunkSegmentMapping drop constraint [TEMP_CNSTR_CSM_ActualByteCount] alter table Segment drop constraint Positive_LogicalByteCount alter table ChunkSegmentMapping with check add constraint [Positive_LogicalByteCount] check ([LogicalByteCount] >= 0) alter table ChunkSegmentMapping with check add constraint [Positive_ActualByteCount] check ([ActualByteCount] >= 0) alter table ChunkSegmentMapping drop constraint [UNIQ_ChunkId_StartByte] create unique nonclustered index [UNIQ_ChunkId_StartByte] on ChunkSegmentMapping (ChunkId ASC, StartByte ASC) include (ActualByteCount, LogicalByteCount) drop index IX_SegmentMetadata on Segment alter table Segment drop column LogicalByteCount alter table Segment drop column ActualByteCount create unique nonclustered index IX_SegmentMetadata on Segment(SegmentId) end GO commit GO -------------------------------------- -- T.0.9.43 to T.0.9.44 -------------------------------------- declare @sql nvarchar(max) declare @dfname nvarchar(max) select @dfname = df.name from sys.default_constraints df join sys.columns c on(df.parent_object_id = c.object_id and df.parent_column_id = c.column_id) where df.parent_object_id = object_id('SegmentedChunk') and c.name = 'ChunkId' if (@dfname is not null) begin select @sql = N'alter table SegmentedChunk drop constraint ' select @sql = @sql + QUOTENAME(@dfname) exec sp_executesql @sql end alter table SegmentedChunk with nocheck add constraint [DF_SegmentedChunk_ChunkId] default newsequentialid() for ChunkId GO declare @sql nvarchar(max) declare @dfname nvarchar(max) select @dfname = df.name from sys.default_constraints df join sys.columns c on(df.parent_object_id = c.object_id and df.parent_column_id = c.column_id) where df.parent_object_id = object_id('Segment') and c.name = 'SegmentId' if (@dfname is not null) begin select @sql = N'alter table Segment drop constraint ' select @sql = @sql + QUOTENAME(@dfname) exec sp_executesql @sql end alter table Segment with nocheck add constraint [DF_Segment_SegmentId] default newsequentialid() for SegmentId GO -- remove unique constraint on SegmentedChunk (ChunkId, SnapshotDataId). -- this constraint is no longer valid that chunks can be shared across database boundary -- since two chunks with the same logical ChunkID can be created (for example, two execution -- snapshots using the compiled definition chunk) if exists ( select * from sys.indexes ix where ix.name = 'UNIQ_ChunkId_SnapshotDataId' and ix.object_id = object_id('SegmentedChunk') ) begin drop index [UNIQ_ChunkId_SnapshotDataId] on [SegmentedChunk] end GO if exists ( select * from sys.indexes ix where ix.name = 'IX_ChunkId_SnapshotDataId' and ix.object_id = object_id('SegmentedChunk') ) begin drop index [IX_ChunkId_SnapshotDataId] on [SegmentedChunk] end GO create nonclustered index [IX_ChunkId_SnapshotDataId] on [SegmentedChunk]( [ChunkId], [SnapshotDataId] ) GOPA -------------------------------------- -- Remove old web service keys that are not needed for RS 2005 -------------------------------------- delete from Keys where Client = 0 -------------------------------------- -- C.0.6.54 to C.0.7.0 -------------------------------------- --No updates in tables, but need to delete some stored procedures -------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AcceptKey]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AcceptKey] GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindObjectsGeneral]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindObjectsGeneral] GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindReportsByDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindReportsByDataSource] GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetRSKey]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetRSKey] GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetDataSource] GO -------------------------------------- -- C.0.7.0 to C.0.7.1 -------------------------------------- --No updates in tables -------------------------------------- -- C.0.8.0 to C.0.8.2 -------------------------------------- -- No updates in tables -------------------------------------- -- C.0.7.1 to C.0.7.3 -------------------------------------- if (select count(*) from dbo.syscolumns where id = object_id('ChunkData') and name = 'Version') = 0 begin ALTER TABLE [dbo].[ChunkData] ADD [Version] smallint NULL end GO -------------------------------------- -- C.0.7.3 to C.0.7.4 -------------------------------------- if (select count(*) from dbo.syscolumns where id = object_id('SnapshotData') and name = 'PageCount') = 0 begin ALTER TABLE [dbo].[SnapshotData] ADD [PageCount] int NULL end GO -------------------------------------- -- C.0.7.4 to C.0.7.5 -------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_PoliciesPolicyID]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1) ALTER TABLE [dbo].[ModelItemPolicy] DROP CONSTRAINT FK_PoliciesPolicyID GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ModelItemPolicy]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[ModelItemPolicy] GO CREATE TABLE [dbo].[ModelItemPolicy] ( [ID] uniqueidentifier NOT NULL, [CatalogItemID] uniqueidentifier NOT NULL, [ModelItemID] nvarchar(3850) NOT NULL, [PolicyID] uniqueidentifier NOT NULL ) ON [PRIMARY] GO GRANT SELECT, UPDATE, INSERT, DELETE, REFERENCES ON [dbo].[ModelItemPolicy] TO RSExecRole GO ALTER TABLE [dbo].[ModelItemPolicy] WITH NOCHECK ADD CONSTRAINT [PK_ModelItemPolicy] PRIMARY KEY NONCLUSTERED ( [ID] ) ON [PRIMARY] GO CREATE UNIQUE CLUSTERED INDEX [IX_ModelItemPolicy] ON [dbo].[ModelItemPolicy] ([CatalogItemID]) ON [PRIMARY] GO ALTER TABLE [dbo].[ModelItemPolicy] WITH NOCHECK ADD CONSTRAINT [FK_PoliciesPolicyID] FOREIGN KEY ( [PolicyID] ) REFERENCES [dbo].[Policies] ( [PolicyID] ) ON DELETE CASCADE GO if not exists (select * from [dbo].[Roles] where [RoleName] = N'Model Item Browser') BEGIN DECLARE @RoleIDModelItemBrowser uniqueidentifier SET @RoleIDModelItemBrowser = newid() EXEC [dbo].[CreateRole] @RoleID = @RoleIDModelItemBrowser, @RoleName = N'Model Item Browser', -- This string is localized. Changing it here requires a change in setupmanagement.dll @Description = N'Allows users to view models items in a particular model.', -- This string is localized. Changing it here requires a change in setupmanagement.dll @TaskMask = '1', @RoleFlags = 2 -- Model item role END GO if not exists (select * from [dbo].[Roles] where [RoleName] = N'Report Builder') BEGIN DECLARE @RoleIDReportConsumer uniqueidentifier SET @RoleIDReportConsumer = newid() EXEC [dbo].[CreateRole] @RoleID = @RoleIDReportConsumer, @RoleName = N'Report Builder', -- This string is localized. Changing it here requires a change in setupmanagement.dll @Description = N'May view report definitions.', -- This string is localized. Changing it here requires a change in setupmanagement.dll @TaskMask = '0010101001000101', @RoleFlags = 0 END GO -------------------------------------- -- C.0.7.5 to C.0.8.0 -------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_ModelDrillModel]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1) ALTER TABLE [dbo].[ModelDrill] DROP CONSTRAINT [FK_ModelDrillModel] GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_ModelDrillReport]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1) ALTER TABLE [dbo].[ModelDrill] DROP CONSTRAINT [FK_ModelDrillReport] GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ModelDrill]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[ModelDrill] GO CREATE TABLE [dbo].[ModelDrill] ( [ModelDrillID] [uniqueidentifier] NOT NULL, [ModelID] [uniqueidentifier] NOT NULL, [ReportID] [uniqueidentifier] NOT NULL, [ModelItemID] nvarchar(3850) NOT NULL, [Type] tinyint NOT NULL ) ON [PRIMARY] GO GRANT SELECT, UPDATE, INSERT, DELETE, REFERENCES ON [dbo].[ModelDrill] TO RSExecRole GO ALTER TABLE [dbo].[ModelDrill] WITH NOCHECK ADD CONSTRAINT [PK_ModelDrill] PRIMARY KEY NONCLUSTERED ( [ModelDrillID] ) ON [PRIMARY] GO CREATE UNIQUE CLUSTERED INDEX [IX_ModelDrillModelID] ON [dbo].[ModelDrill]([ModelID]) ON [PRIMARY] GO ALTER TABLE [dbo].[ModelDrill] WITH NOCHECK ADD CONSTRAINT [FK_ModelDrillModel] FOREIGN KEY ( [ModelID] ) REFERENCES [dbo].[Catalog] ( [ItemID] ) ON DELETE CASCADE GO ALTER TABLE [dbo].[ModelDrill] WITH NOCHECK ADD CONSTRAINT [FK_ModelDrillReport] FOREIGN KEY ( [ReportID] ) REFERENCES [dbo].[Catalog] ( [ItemID] ) GO if (select count(*) from dbo.syscolumns where id = object_id('SnapshotData') and name = 'HasDocMap') = 0 begin ALTER TABLE SnapshotData ADD HasDocMap bit NULL end GO -------------------------------------- -- C.0.8.0 to C.0.8.2 -------------------------------------- -- No updates in tables -------------------------------------- -- C.0.8.2 to C.0.8.3 -------------------------------------- -- No updates in tables -------------------------------------- -- C.0.8.3 to C.0.8.4 -------------------------------------- if (select count(*) from dbo.syscolumns where id = object_id('SnapshotData') and name = 'QueryParams') = 0 begin ALTER TABLE [dbo].[SnapshotData] ADD [QueryParams] ntext end GO UPDATE [dbo].[SnapshotData] SET [ParamsHash]=0 -- New algorithm for the hash GO -------------------------------------- -- C.0.8.5 to C.0.8.6 -------------------------------------- if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpgradeInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) begin CREATE TABLE [dbo].[UpgradeInfo] ( [Item] nvarchar(260) NOT NULL, [Status] nvarchar(512) NULL ) ON [PRIMARY] ALTER TABLE [dbo].[UpgradeInfo] ADD CONSTRAINT [PK_UpgradeInfo] PRIMARY KEY CLUSTERED ( Item ) ON [PRIMARY] end GO -- Set that we need to upgrade the security descriptors if not exists (select * from [dbo].[UpgradeInfo] where [Item] = N'UpgradedSecurityDesc') begin INSERT INTO [dbo].[UpgradeInfo]([Item], [Status]) VALUES ('UpgradedSecurityDesc', 'False') end GO -------------------------------------- -- C.0.8.6 to C.0.8.7 -------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_ModelPerspectiveModel]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1) ALTER TABLE [dbo].[ModelPerspective] DROP CONSTRAINT [FK_ModelPerspectiveModel] GO if exists (select * from dbo.sysobjects where name = N'ModelPerspective' and type = N'U') drop table [dbo].[ModelPerspective] GO CREATE TABLE [dbo].[ModelPerspective] ( [ID] uniqueidentifier NOT NULL, [ModelID] uniqueidentifier NOT NULL, [PerspectiveID] ntext NOT NULL, -- this is nvarchar(3850), but doesn't fit in row [PerspectiveName] ntext NULL, [PerspectiveDescription] ntext NULL ) ON [PRIMARY] GO if OBJECTPROPERTY(object_id('ModelPerspective'), 'TableTextInRowLimit') = 0 begin EXEC sp_tableoption N'[dbo].[ModelPerspective]', 'text in row', 'ON' end GO CREATE CLUSTERED INDEX [IX_ModelPerspective] ON [dbo].[ModelPerspective]([ModelID]) ON [PRIMARY] GO ALTER TABLE [dbo].[ModelPerspective] WITH NOCHECK ADD CONSTRAINT [FK_ModelPerspectiveModel] FOREIGN KEY ( [ModelID] ) REFERENCES [dbo].[Catalog] ( [ItemID] ) ON DELETE CASCADE GO -------------------------------------- -- C.0.8.7 to C.0.8.8 -------------------------------------- -- adjusted tables and procs so that they are always in dbo -------------------------------------- -- C.0.8.8 to C.0.8.9 -------------------------------------- -- No change in tables -------------------------------------- -- C.0.8.9 to C.0.8.10 -------------------------------------- if (select count(*) from dbo.syscolumns where id = object_id('DataSource') and name = 'OriginalConnectionString') = 0 begin ALTER TABLE [dbo].[DataSource] ADD [OriginalConnectionString] image end GO UPDATE [dbo].[DataSource] SET [OriginalConnectionString] = [ConnectionString] GO -------------------------------------- -- C.0.8.10 to C.0.8.11 -------------------------------------- -- No change in tables -------------------------------------- -- C.0.8.11 to C.0.8.12 -------------------------------------- if (select count(*) from dbo.syscolumns where id = object_id('DataSource') and name = 'OriginalConnectStringExpressionBased') = 0 begin ALTER TABLE [dbo].[DataSource] ADD [OriginalConnectStringExpressionBased] bit end GO -------------------------------------- -- C.0.8.12 to C.0.8.13 -------------------------------------- -- No change in tables -------------------------------------- -- C.0.8.12 to C.0.8.14 -------------------------------------- if exists (select * from dbo.sysindexes where [name]='IX_ModelDrillModelID') begin DROP INDEX [dbo].[ModelDrill].[IX_ModelDrillModelID] end GO CREATE UNIQUE CLUSTERED INDEX [IX_ModelDrillModelID] ON [dbo].[ModelDrill]([ModelID],[ReportID],[ModelDrillID]) ON [PRIMARY] GO -------------------------------------- -- C.0.8.14 to C.0.8.16 -------------------------------------- DELETE FROM [dbo].[Keys] WHERE [Client]=0 GO if (select count(*) from dbo.syscolumns where id = object_id('Keys') and name = 'InstanceID') > 0 begin ALTER TABLE [dbo].[Keys] DROP CONSTRAINT [PK_Keys] ALTER TABLE [dbo].[Keys] ADD [InstallationID] uniqueidentifier NULL, [MachineName] nvarchar(256) NULL, [InstanceName] nvarchar(32) NULL exec('UPDATE [dbo].[Keys] SET [InstallationID] = [InstanceID]') ALTER TABLE [dbo].[Keys] ALTER COLUMN [InstallationID] uniqueidentifier NOT NULL ALTER TABLE [dbo].[Keys] DROP COLUMN [InstanceID] ALTER TABLE [dbo].[Keys] WITH NOCHECK ADD CONSTRAINT [PK_Keys] PRIMARY KEY CLUSTERED ( [InstallationID], [Client] ) ON [PRIMARY] end GO -------------------------------------- -- C.0.8.16 to C.0.8.17 -------------------------------------- -- No change in tables -------------------------------------- -- C.0.8.17 to C.0.8.18 -------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ServerParametersInstance]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[ServerParametersInstance] GO CREATE TABLE [dbo].[ServerParametersInstance] ( [ServerParametersID] nvarchar(32) NOT NULL, [CreateDate] datetime NOT NULL, [ModifiedDate] datetime NOT NULL, [Timeout] int NOT NULL, [Expiration] datetime NOT NULL, [ParametersValues] image NOT NULL ) ON [PRIMARY] GO ALTER TABLE [dbo].[ServerParametersInstance] ADD CONSTRAINT [PK_ServerParametersInstance] PRIMARY KEY CLUSTERED ( [ServerParametersID] ) GO CREATE INDEX [IX_ServerParametersInstanceExpiration] ON [dbo].[ServerParametersInstance]([Expiration] DESC) ON [PRIMARY] GO if OBJECTPROPERTY(object_id('ServerParametersInstance'), 'TableTextInRowLimit') = 0 begin EXEC sp_tableoption N'[dbo].[ServerParametersInstance]', 'text in row', 'ON' end GO if not exists (select * from [dbo].[ConfigurationInfo] where [Name] = N'StoredParametersThreshold') begin INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'StoredParametersThreshold', '1500' ) end GO if not exists (select * from [dbo].[ConfigurationInfo] where [Name] = N'StoredParametersLifetime') begin INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'StoredParametersLifetime', '180' ) -- days end GO -------------------------------------- -- C.0.8.18 to C.0.8.19 -------------------------------------- if not exists (select * from [dbo].[ConfigurationInfo] where [Name] = N'EnableReportDesignClientDownload') begin INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'EnableReportDesignClientDownload', 'True' ) end GO -------------------------------------- -- C.0.8.19 to C.0.8.20 -------------------------------------- if not exists (select * from [dbo].[ConfigurationInfo] where [Name] = N'EnableClientPrinting') begin INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'EnableClientPrinting', 'True' ) end GO -------------------------------------- -- C.0.8.20 to C.0.8.21 -------------------------------------- if (select count(*) from dbo.syscolumns where id = object_id('DataSource') and name = 'Version') = 0 begin ALTER TABLE [dbo].[DataSource] ADD [Version] [int] NOT NULL DEFAULT 1 end GO if (select count(*) from dbo.syscolumns where id = object_id('Subscriptions') and name = 'Version') = 0 begin ALTER TABLE [dbo].[Subscriptions] ADD [Version] [int] NOT NULL DEFAULT 1 end GO if (select count(*) from dbo.syscolumns where id = object_id('Notifications') and name = 'Version') = 0 begin ALTER TABLE [dbo].[Notifications] ADD [Version] [int] NOT NULL DEFAULT 1 end GO --INSERT INTO [dbo].[UpgradeInfo]([Item], [Status]) VALUES ('UpgradeConnectionEncryption-1-2', 'False') --GO -------------------------------------- -- C.0.8.21 to C.0.8.22 -------------------------------------- -- No change in tables -------------------------------------- -- C.0.8.22 to C.0.8.23 -------------------------------------- -- No change in tables -------------------------------------- -- C.0.8.23 to C.0.8.24 -------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ServerParametersInstance]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[ServerParametersInstance] GO CREATE TABLE [dbo].[ServerParametersInstance] ( [ServerParametersID] nvarchar(32) NOT NULL, [Path] [nvarchar] (425) NOT NULL, [CreateDate] datetime NOT NULL, [ModifiedDate] datetime NOT NULL, [Timeout] int NOT NULL, [Expiration] datetime NOT NULL, [ParametersValues] image NOT NULL ) ON [PRIMARY] GO ALTER TABLE [dbo].[ServerParametersInstance] ADD CONSTRAINT [PK_ServerParametersInstance] PRIMARY KEY CLUSTERED ( [ServerParametersID] ) GO CREATE INDEX [IX_ServerParametersInstanceExpiration] ON [dbo].[ServerParametersInstance]([Expiration] DESC) ON [PRIMARY] GO if OBJECTPROPERTY(object_id('ServerParametersInstance'), 'TableTextInRowLimit') = 0 begin EXEC sp_tableoption N'[dbo].[ServerParametersInstance]', 'text in row', 'ON' end GO -------------------------------------- -- C.0.8.24 to C.0.8.25 -------------------------------------- if not exists (select * from [dbo].[ConfigurationInfo] where [Name] = N'EnableRemoteErrors') begin INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'EnableRemoteErrors', 'False' ) end GO -------------------------------------- -- C.0.8.25 to C.0.8.26 -------------------------------------- -- No change in tables -------------------------------------- -- C.0.8.26 to C.0.8.27 -------------------------------------- -- No change in tables -------------------------------------- -- C.0.8.27 to C.0.8.28 -------------------------------------- -- No change in tables -------------------------------------- -- C.0.8.28 to C.0.8.29 -------------------------------------- -- No change in tables -------------------------------------- -- C.0.8.29 to C.0.8.30 -------------------------------------- ALTER TABLE [dbo].[ModelDrill] ALTER COLUMN [ModelItemID] nvarchar(425) NOT NULL GO DROP INDEX [dbo].[ModelItemPolicy].[IX_ModelItemPolicy] GO ALTER TABLE [dbo].[ModelItemPolicy] ALTER COLUMN [ModelItemID] nvarchar(425); GO CREATE CLUSTERED INDEX [IX_ModelItemPolicy] ON [dbo].[ModelItemPolicy]([CatalogItemID], [ModelItemID]) ON [PRIMARY] GO -------------------------------------- -- C.0.8.30 to C.0.8.31 -------------------------------------- -- No change in tables -------------------------------------- -- C.0.8.31 to C.0.8.32 -------------------------------------- -- No change in tables -------------------------------------- -- C.0.8.33 to C.0.8.34 -------------------------------------- -- No change in tables -------------------------------------- -- C.0.8.34 to C.0.8.35 -------------------------------------- -- No change in tables -------------------------------------- -- C.0.8.35 to C.0.8.36 -------------------------------------- -- No change in tables -------------------------------------- -- C.0.8.36 to C.0.8.37 -------------------------------------- if not exists (select * from [dbo].[UpgradeInfo] where [Item] = N'UpgradeConnectionEncryption') begin INSERT INTO [dbo].[UpgradeInfo]([Item], [Status]) VALUES ('UpgradeConnectionEncryption', 'False') end GO -------------------------------------- -- C.0.8.37 to C.0.8.38 -------------------------------------- -- Dropped explicit collation on Subscription table. -- Collation is the same as db, no need to change anything here. -------------------------------------- -- C.0.8.37 to C.0.8.39 -------------------------------------- if (select count(*) from dbo.syscolumns where id = object_id('ServerParametersInstance') and name = 'ParentID') = 0 begin ALTER TABLE [dbo].[ServerParametersInstance] ADD [ParentID] nvarchar(32) NULL end GO -------------------------------------- -- C.0.8.39 to C.0.8.40 -------------------------------------- -- No change in tables -- !!! This assumes the database is created and the user is either a dbo or is added to the RSExecRole -- !!! Please run setup to create the database, users, role !!! -------------------------------------- -- T.0.7.1 to T.0.7.3 -------------------------------------- if (select count(*) from dbo.syscolumns where id = object_id('ChunkData') and name = 'Version') = 0 begin ALTER TABLE [dbo].[ChunkData] ADD [Version] smallint NULL end GO -------------------------------------- -- T.0.7.3 to T.0.7.4 -------------------------------------- if (select count(*) from dbo.syscolumns where id = object_id('SessionData') and name = 'SnapshotDataID') = 1 begin ALTER TABLE [dbo].[SessionData] ALTER Column [SnapshotDataID] uniqueidentifier NULL end GO if (select count(*) from dbo.syscolumns where id = object_id('SessionData') and name = 'IsPermanentSnapshot') = 1 begin ALTER TABLE [dbo].[SessionData] ALTER Column [IsPermanentSnapshot] bit NULL end GO if (select count(*) from dbo.syscolumns where id = object_id('SessionData') and name = 'ReportPath') = 1 begin ALTER TABLE [dbo].[SessionData] ALTER Column [ReportPath] nvarchar(424) NULL end GO if (select count(*) from dbo.syscolumns where id = object_id('SessionData') and name = 'HasInteractivity') = 1 begin ALTER TABLE [dbo].[SessionData] ALTER Column [HasInteractivity] bit NULL end GO if exists (select * from dbo.sysindexes where [name]='IDX_SessionData') begin DROP INDEX [dbo].[SessionData].[IDX_SessionData] end GO if (select count(*) from dbo.syscolumns where id = object_id('SessionData') and name = 'ParamsHash') = 1 begin ALTER TABLE [dbo].[SessionData] DROP Column [ParamsHash] end GO if (select count(*) from dbo.syscolumns where id = object_id('SessionData') and name = 'UserParams') = 1 begin ALTER TABLE [dbo].[SessionData] DROP Column [UserParams] end GO if (select count(*) from dbo.syscolumns where id = object_id('SessionData') and name = 'EffectiveParams') = 0 begin ALTER TABLE [dbo].[SessionData] ADD [EffectiveParams] ntext NULL end GO if (select count(*) from dbo.syscolumns where id = object_id('SnapshotData') and name = 'PageCount') = 0 begin ALTER TABLE [dbo].[SnapshotData] ADD [PageCount] int NULL end GO if (select count(*) from dbo.sysindexes where [name]='IDX_SessionData') = 0 begin CREATE UNIQUE CLUSTERED INDEX [IDX_SessionData] ON [dbo].[SessionData]([SessionID]) end GO -------------------------------------- -- T.0.7.5 to T.0.7.6 -------------------------------------- if (select count(*) from dbo.syscolumns where id = object_id('SessionData') and name = 'CompiledDefinition') = 0 begin ALTER TABLE [dbo].[SessionData] ADD [CompiledDefinition] uniqueidentifier NULL end GO if (select count(*) from dbo.syscolumns where id = object_id('SessionData') and name = 'HistoryDate') = 0 begin ALTER TABLE [dbo].[SessionData] ADD [HistoryDate] datetime NULL end GO if (select count(*) from dbo.syscolumns where id = object_id('SnapshotData') and name = 'HasDocMap') = 0 begin ALTER TABLE [dbo].[SnapshotData] ADD [HasDocMap] bit NULL end GO -------------------------------------- -- T.0.8.0 to T.0.8.2 -------------------------------------- -- No updates in tables -------------------------------------- -- T.0.8.2 to T.0.8.3 -------------------------------------- -- No updates in tables -------------------------------------- -- T.0.8.3 to T.0.8.4 -------------------------------------- -- No updates in tables -------------------------------------- -- T.0.8.4 to T.0.8.5 -------------------------------------- if OBJECTPROPERTY(object_id('ExecutionCache'), 'TableTextInRowLimit') > 0 begin EXEC sp_tableoption N'[dbo].[ExecutionCache]', 'text in row', 'OFF' end GO if (select count(*) from dbo.syscolumns where id = object_id('ExecutionCache') and name = 'EffectiveParameters') = 1 begin ALTER TABLE [dbo].[ExecutionCache] DROP COLUMN [EffectiveParameters] end GO if (select count(*) from dbo.syscolumns where id = object_id('SnapshotData') and name = 'QueryParams') = 0 begin ALTER TABLE [dbo].[SnapshotData] ADD [QueryParams] ntext end GO UPDATE [dbo].[SnapshotData] SET [ParamsHash]=0 -- New algorithm for the hash GO -------------------------------------- -- T.0.8.5 to T.0.8.6 -------------------------------------- -- No updates in tables -------------------------------------- -- T.0.8.7 to T.0.8.8 -------------------------------------- -- adjusted tables and procs so that they are always in dbo -------------------------------------- -- T.0.8.8 to T.0.8.9 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.9 to T.0.8.10 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.10 to T.0.8.11 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.11 to T.0.8.12 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.12 to T.0.8.13 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.12 to T.0.8.14 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.16 to T.0.8.17 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.17 to T.0.8.18 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.18 to T.0.8.19 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.19 to T.0.8.20 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.21 to T.0.8.22 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.22 to T.0.8.23 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.22 to T.0.8.23 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.24 to T.0.8.25 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.25 to T.0.8.26 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.26 to T.0.8.27 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.27 to T.0.8.28 -------------------------------------- if (select count(*) from dbo.syscolumns where id = object_id('SessionData') and name in ('PageHeight', 'PageWidth', 'TopMargin', 'BottomMargin', 'LeftMargin', 'RightMargin')) = 0 begin ALTER TABLE [dbo].[SessionData] ADD [PageHeight] float NULL, [PageWidth] float NULL, [TopMargin] float NULL, [BottomMargin] float NULL, [LeftMargin] float NULL, [RightMargin] float NULL end GO -------------------------------------- -- T.0.8.28 to T.0.8.29 -------------------------------------- --No change in tables -------------------------------------- -- T.0.8.29 to T.0.8.30 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.30 to T.0.8.31 -------------------------------------- if (select count(*) from dbo.syscolumns where id = object_id('SessionData') and name = 'AutoRefreshSeconds') = 0 begin ALTER TABLE [dbo].[SessionData] ADD [AutoRefreshSeconds] int NULL end GO -------------------------------------- -- T.0.8.31 to T.0.8.32 -------------------------------------- if (select count(*) from dbo.syscolumns where id = object_id('PersistedStream') and name in ('RefCount', 'ExpirationDate')) = 0 begin ALTER TABLE dbo.PersistedStream ADD RefCount int NOT NULL CONSTRAINT DF_PersistedStream_RefCount DEFAULT 0, ExpirationDate datetime NOT NULL CONSTRAINT DF_PersistedStream_ExpirationDate DEFAULT DATEADD(day, 2, GETDATE()) end GO -------------------------------------- -- T.0.8.33 to T.0.8.34 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.34 to T.0.8.35 -------------------------------------- if (select count(*) from dbo.syscolumns where id = object_id('SessionData') and name = 'ExecutionType') = 0 begin ALTER TABLE [dbo].[SessionData] ADD [ExecutionType] smallint NULL end GO -------------------------------------- -- T.0.8.35 to T.0.8.36 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.36 to T.0.8.37 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.37 to T.0.8.38 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.38 to T.0.8.39 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.39 to T.0.8.40 -------------------------------------- -- No change in tables-- START STORED PROCEDURES if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetKeysForInstallation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetKeysForInstallation] GO CREATE PROCEDURE [dbo].[SetKeysForInstallation] @InstallationID uniqueidentifier, @SymmetricKey image = NULL, @PublicKey image AS update [dbo].[Keys] set [SymmetricKey] = @SymmetricKey, [PublicKey] = @PublicKey where [InstallationID] = @InstallationID and [Client] = 1 GO GRANT EXECUTE ON [dbo].[SetKeysForInstallation] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAnnouncedKey]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAnnouncedKey] GO CREATE PROCEDURE [dbo].[GetAnnouncedKey] @InstallationID uniqueidentifier AS select PublicKey, MachineName, InstanceName from Keys where InstallationID = @InstallationID and Client = 1 GO GRANT EXECUTE ON [dbo].[GetAnnouncedKey] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AnnounceOrGetKey]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AnnounceOrGetKey] GO CREATE PROCEDURE [dbo].[AnnounceOrGetKey] @MachineName nvarchar(256), @InstanceName nvarchar(32), @InstallationID uniqueidentifier, @PublicKey image, @NumAnnouncedServices int OUTPUT AS -- Acquire lock IF NOT EXISTS (SELECT * FROM [dbo].[Keys] WITH(XLOCK) WHERE [Client] < 0) BEGIN RAISERROR('Keys lock row not found', 16, 1) RETURN END -- Get the number of services that have already announced their presence SELECT @NumAnnouncedServices = count(*) FROM [dbo].[Keys] WHERE [Client] = 1 DECLARE @StoredInstallationID uniqueidentifier DECLARE @StoredInstanceName nvarchar(32) SELECT @StoredInstallationID = [InstallationID], @StoredInstanceName = [InstanceName] FROM [dbo].[Keys] WHERE [InstallationID] = @InstallationID AND [Client] = 1 IF @StoredInstallationID IS NULL -- no record present BEGIN INSERT INTO [dbo].[Keys] ([MachineName], [InstanceName], [InstallationID], [Client], [PublicKey], [SymmetricKey]) VALUES (@MachineName, @InstanceName, @InstallationID, 1, @PublicKey, null) END ELSE BEGIN IF @StoredInstanceName IS NULL BEGIN UPDATE [dbo].[Keys] SET [InstanceName] = @InstanceName WHERE [InstallationID] = @InstallationID AND [Client] = 1 END END SELECT [MachineName], [SymmetricKey], [PublicKey] FROM [Keys] WHERE [InstallationID] = @InstallationID and [Client] = 1 GO GRANT EXECUTE ON [dbo].[AnnounceOrGetKey] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetMachineName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetMachineName] GO CREATE PROCEDURE [dbo].[SetMachineName] @MachineName nvarchar(256), @InstallationID uniqueidentifier AS UPDATE [dbo].[Keys] SET MachineName = @MachineName WHERE [InstallationID] = @InstallationID and [Client] = 1 GO GRANT EXECUTE ON [dbo].[SetMachineName] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListInstallations]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListInstallations] GO CREATE PROCEDURE [dbo].[ListInstallations] AS SELECT [MachineName], [InstanceName], [InstallationID], CASE WHEN [SymmetricKey] IS null THEN 0 ELSE 1 END FROM [dbo].[Keys] WHERE [Client] = 1 GO GRANT EXECUTE ON [dbo].[ListInstallations] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListInfoForReencryption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListInfoForReencryption] GO CREATE PROCEDURE [dbo].[ListInfoForReencryption] AS SELECT [DSID] FROM [dbo].[DataSource] WITH (XLOCK, TABLOCK) SELECT [SubscriptionID] FROM [dbo].[Subscriptions] WITH (XLOCK, TABLOCK) SELECT [InstallationID], [PublicKey] FROM [dbo].[Keys] WITH (XLOCK, TABLOCK) WHERE [Client] = 1 AND ([SymmetricKey] IS NOT NULL) GO GRANT EXECUTE ON [dbo].[ListInfoForReencryption] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDatasourceInfoForReencryption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDatasourceInfoForReencryption] GO CREATE PROCEDURE [dbo].[GetDatasourceInfoForReencryption] @DSID as uniqueidentifier AS SELECT [ConnectionString], [OriginalConnectionString], [UserName], [Password], [CredentialRetrieval], [Version] FROM [dbo].[DataSource] WHERE [DSID] = @DSID GO GRANT EXECUTE ON [dbo].[GetDatasourceInfoForReencryption] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetReencryptedDatasourceInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetReencryptedDatasourceInfo] GO CREATE PROCEDURE [dbo].[SetReencryptedDatasourceInfo] @DSID uniqueidentifier, @ConnectionString image = NULL, @OriginalConnectionString image = NULL, @UserName image = NULL, @Password image = NULL, @CredentialRetrieval int, @Version int AS UPDATE [dbo].[DataSource] SET [ConnectionString] = @ConnectionString, [OriginalConnectionString] = @OriginalConnectionString, [UserName] = @UserName, [Password] = @Password, [CredentialRetrieval] = @CredentialRetrieval, [Version] = @Version WHERE [DSID] = @DSID GO GRANT EXECUTE ON [dbo].[SetReencryptedDatasourceInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSubscriptionInfoForReencryption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSubscriptionInfoForReencryption] GO CREATE PROCEDURE [dbo].[GetSubscriptionInfoForReencryption] @SubscriptionID as uniqueidentifier AS SELECT [DeliveryExtension], [ExtensionSettings], [Version] FROM [dbo].[Subscriptions] WHERE [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetSubscriptionInfoForReencryption] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetReencryptedSubscriptionInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetReencryptedSubscriptionInfo] GO CREATE PROCEDURE [dbo].[SetReencryptedSubscriptionInfo] @SubscriptionID as uniqueidentifier, @ExtensionSettings as ntext = NULL, @Version as int AS UPDATE [dbo].[Subscriptions] SET [ExtensionSettings] = @ExtensionSettings, [Version] = @Version WHERE [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[SetReencryptedSubscriptionInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteEncryptedContent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteEncryptedContent] GO CREATE PROCEDURE [dbo].[DeleteEncryptedContent] AS -- Remove the encryption keys delete from keys where client >= 0 -- Remove the encrypted content update datasource set CredentialRetrieval = 1, -- CredentialRetrieval.Prompt ConnectionString = null, OriginalConnectionString = null, UserName = null, Password = null GO GRANT EXECUTE ON [dbo].[DeleteEncryptedContent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteKey]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteKey] GO CREATE PROCEDURE [dbo].[DeleteKey] @InstallationID uniqueidentifier AS if (@InstallationID = '00000000-0000-0000-0000-000000000000') RAISERROR('Cannot delete reserved key', 16, 1) -- Remove the encryption keys delete from keys where InstallationID = @InstallationID and Client = 1 GO GRANT EXECUTE ON [dbo].[DeleteKey] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAllConfigurationInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAllConfigurationInfo] GO CREATE PROCEDURE [dbo].[GetAllConfigurationInfo] AS SELECT [Name], [Value] FROM [ConfigurationInfo] GO GRANT EXECUTE ON [dbo].[GetAllConfigurationInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetOneConfigurationInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetOneConfigurationInfo] GO CREATE PROCEDURE [dbo].[GetOneConfigurationInfo] @Name nvarchar (260) AS SELECT [Value] FROM [ConfigurationInfo] WHERE [Name] = @Name GO GRANT EXECUTE ON [dbo].[GetOneConfigurationInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetConfigurationInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetConfigurationInfo] GO CREATE PROCEDURE [dbo].[SetConfigurationInfo] @Name nvarchar (260), @Value ntext AS DELETE FROM [ConfigurationInfo] WHERE [Name] = @Name IF @Value is not null BEGIN INSERT INTO ConfigurationInfo VALUES ( newid(), @Name, @Value ) END GO GRANT EXECUTE ON [dbo].[SetConfigurationInfo] TO RSExecRole if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddEvent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddEvent] GO CREATE PROCEDURE [dbo].[AddEvent] @EventType nvarchar (260), @EventData nvarchar (260) AS insert into [Event] ([EventID], [EventType], [EventData], [TimeEntered], [ProcessStart], [BatchID]) values (NewID(), @EventType, @EventData, GETUTCDATE(), NULL, NULL) GO GRANT EXECUTE ON [dbo].[AddEvent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteEvent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteEvent] GO CREATE PROCEDURE [dbo].[DeleteEvent] @ID uniqueidentifier AS delete from [Event] where [EventID] = @ID GO GRANT EXECUTE ON [dbo].[DeleteEvent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanEventRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanEventRecords] GO CREATE PROCEDURE [dbo].[CleanEventRecords] @MaxAgeMinutes int AS -- Reset all notifications which have been add over n minutes ago Update [Event] set [ProcessStart] = NULL, [ProcessHeartbeat] = NULL where [EventID] in ( SELECT [EventID] FROM [Event] WHERE [ProcessHeartbeat] < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) ) GO GRANT EXECUTE ON [dbo].[CleanEventRecords] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddExecutionLogEntry]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddExecutionLogEntry] GO CREATE PROCEDURE [dbo].[AddExecutionLogEntry] @InstanceName nvarchar(38), @Report nvarchar(260), @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @RequestType bit, @Format nvarchar(26), @Parameters ntext, @TimeStart DateTime, @TimeEnd DateTime, @TimeDataRetrieval int, @TimeProcessing int, @TimeRendering int, @Source tinyint, @Status nvarchar(32), @ByteCount bigint, @RowCount bigint AS -- Unless is is specifically 'False', it's true if exists (select * from ConfigurationInfo where [Name] = 'EnableExecutionLogging' and [Value] like 'False') begin return end Declare @ReportID uniqueidentifier select @ReportID = ItemID from Catalog with (nolock) where Path = @Report insert into ExecutionLog (InstanceName, ReportID, UserName, RequestType, [Format], Parameters, TimeStart, TimeEnd, TimeDataRetrieval, TimeProcessing, TimeRendering, Source, Status, ByteCount, [RowCount]) Values (@InstanceName, @ReportID, @UserName, @RequestType, @Format, @Parameters, @TimeStart, @TimeEnd, @TimeDataRetrieval, @TimeProcessing, @TimeRendering, @Source, @Status, @ByteCount, @RowCount) GO GRANT EXECUTE ON [dbo].[AddExecutionLogEntry] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ExpireExecutionLogEntries]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ExpireExecutionLogEntries] GO CREATE PROCEDURE [dbo].[ExpireExecutionLogEntries] AS -- -1 means no expiration if exists (select * from ConfigurationInfo where [Name] = 'ExecutionLogDaysKept' and CAST(CAST(Value as nvarchar) as integer) = -1) begin return end delete from ExecutionLog where DateDiff(day, TimeStart, getdate()) >= (select CAST(CAST(Value as nvarchar) as integer) from ConfigurationInfo where [Name] = 'ExecutionLogDaysKept') GO GRANT EXECUTE ON [dbo].[ExpireExecutionLogEntries] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUserIDBySid]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUserIDBySid] GO -- looks up any user name by its SID, if not it creates a regular user CREATE PROCEDURE [dbo].[GetUserIDBySid] @UserSid varbinary(85), @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS SELECT @UserID = (SELECT UserID FROM Users WHERE Sid = @UserSid AND AuthType = @AuthType) IF @UserID IS NULL BEGIN SET @UserID = newid() INSERT INTO Users (UserID, Sid, UserType, AuthType, UserName) VALUES (@UserID, @UserSid, 0, @AuthType, @UserName) END GO GRANT EXECUTE ON [dbo].[GetUserIDBySid] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUserIDByName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUserIDByName] GO -- looks up any user name by its User Name, if not it creates a regular user CREATE PROCEDURE [dbo].[GetUserIDByName] @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS SELECT @UserID = (SELECT UserID FROM Users WHERE UserName = @UserName AND AuthType = @AuthType) IF @UserID IS NULL BEGIN SET @UserID = newid() INSERT INTO Users (UserID, Sid, UserType, AuthType, UserName) VALUES (@UserID, NULL, 0, @AuthType, @UserName) END GO GRANT EXECUTE ON [dbo].[GetUserIDByName] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUserID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUserID] GO -- looks up any user name, if not it creates a regular user - uses Sid CREATE PROCEDURE [dbo].[GetUserID] @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS IF @AuthType = 1 -- Windows BEGIN EXEC GetUserIDBySid @UserSid, @UserName, @AuthType, @UserID OUTPUT END ELSE BEGIN EXEC GetUserIDByName @UserName, @AuthType, @UserID OUTPUT END GO GRANT EXECUTE ON [dbo].[GetUserID] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPrincipalID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPrincipalID] GO -- looks up a principal, if not there looks up regular users and turns them into principals -- if not, it creates a principal CREATE PROCEDURE [dbo].[GetPrincipalID] @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS -- windows auth IF @AuthType = 1 BEGIN -- is this a principal? SELECT @UserID = (SELECT UserID FROM Users WHERE Sid = @UserSid AND UserType = 1 AND AuthType = @AuthType) END ELSE BEGIN -- is this a principal? SELECT @UserID = (SELECT UserID FROM Users WHERE UserName = @UserName AND UserType = 1 AND AuthType = @AuthType) END IF @UserID IS NULL BEGIN IF @AuthType = 1 -- Windows BEGIN -- Is this a regular user SELECT @UserID = (SELECT UserID FROM Users WHERE Sid = @UserSid AND UserType = 0 AND AuthType = @AuthType) END ELSE BEGIN -- Is this a regular user SELECT @UserID = (SELECT UserID FROM Users WHERE UserName = @UserName AND UserType = 0 AND AuthType = @AuthType) END -- No, create a new principal IF @UserID IS NULL BEGIN SET @UserID = newid() INSERT INTO Users (UserID, Sid, UserType, AuthType, UserName) VALUES (@UserID, @UserSid, 1, @AuthType, @UserName) END ELSE BEGIN UPDATE Users SET UserType = 1 WHERE UserID = @UserID END END GO GRANT EXECUTE ON [dbo].[GetPrincipalID] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateSubscription] GO CREATE PROCEDURE [dbo].[CreateSubscription] @id uniqueidentifier, @Locale nvarchar (128), @Report_Name nvarchar (425), @OwnerSid varbinary (85) = NULL, @OwnerName nvarchar(260), @OwnerAuthType int, @DeliveryExtension nvarchar (260) = NULL, @InactiveFlags int, @ExtensionSettings ntext = NULL, @ModifiedBySid varbinary (85) = NULL, @ModifiedByName nvarchar(260), @ModifiedByAuthType int, @ModifiedDate datetime, @Description nvarchar(512) = NULL, @LastStatus nvarchar(260) = NULL, @EventType nvarchar(260), @MatchData ntext = NULL, @Parameters ntext = NULL, @DataSettings ntext = NULL, @Version int AS -- Create a subscription with the given data. The name must match a name in the -- Catalog table and it must be a report type (2) or linked report (4) DECLARE @Report_OID uniqueidentifier DECLARE @OwnerID uniqueidentifier DECLARE @ModifiedByID uniqueidentifier DECLARE @TempDeliveryID uniqueidentifier --Get the report id for this subscription select @Report_OID = (select [ItemID] from [Catalog] where [Catalog].[Path] = @Report_Name and ([Catalog].[Type] = 2 or [Catalog].[Type] = 4)) EXEC GetUserID @OwnerSid, @OwnerName, @OwnerAuthType, @OwnerID OUTPUT EXEC GetUserID @ModifiedBySid, @ModifiedByName, @ModifiedByAuthType, @ModifiedByID OUTPUT if (@Report_OID is NULL) begin RAISERROR('Report Not Found', 16, 1) return end Insert into Subscriptions ( [SubscriptionID], [OwnerID], [Report_OID], [Locale], [DeliveryExtension], [InactiveFlags], [ExtensionSettings], [ModifiedByID], [ModifiedDate], [Description], [LastStatus], [EventType], [MatchData], [LastRunTime], [Parameters], [DataSettings], [Version] ) values (@id, @OwnerID, @Report_OID, @Locale, @DeliveryExtension, @InactiveFlags, @ExtensionSettings, @ModifiedByID, @ModifiedDate, @Description, @LastStatus, @EventType, @MatchData, NULL, @Parameters, @DataSettings, @Version) GO GRANT EXECUTE ON [dbo].[CreateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeliveryRemovedInactivateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeliveryRemovedInactivateSubscription] GO CREATE PROCEDURE [dbo].[DeliveryRemovedInactivateSubscription] @DeliveryExtension nvarchar(260), @Status nvarchar(260) AS update Subscriptions set [DeliveryExtension] = '', [InactiveFlags] = [InactiveFlags] | 1, -- Delivery Provider Removed Flag == 1 [LastStatus] = @Status where [DeliveryExtension] = @DeliveryExtension GO GRANT EXECUTE ON [dbo].[DeliveryRemovedInactivateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteSubscription] GO CREATE PROCEDURE [dbo].[DeleteSubscription] @SubscriptionID uniqueidentifier AS -- Delete the given subscription delete from [Subscriptions] where [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[DeleteSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSubscription] GO CREATE PROCEDURE [dbo].[GetSubscription] @SubscriptionID uniqueidentifier, @AuthType int AS -- Grab all of the-- subscription properties given a id select S.[SubscriptionID], S.[Report_OID], S.[Locale], S.[InactiveFlags], S.[DeliveryExtension], S.[ExtensionSettings], SUSER_SNAME(Modified.[Sid]), Modified.[UserName], S.[ModifiedDate], S.[Description], S.[LastStatus], S.[EventType], S.[MatchData], S.[Parameters], S.[DataSettings], A.[TotalNotifications], A.[TotalSuccesses], A.[TotalFailures], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], CAT.[Path], S.[LastRunTime], CAT.[Type], SD.NtSecDescPrimary, S.[Version] from [Subscriptions] S inner join [Catalog] CAT on S.[Report_OID] = CAT.[ItemID] inner join [Users] Owner on S.OwnerID = Owner.UserID inner join [Users] Modified on S.ModifiedByID = Modified.UserID left outer join [SecData] SD on CAT.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType left outer join [ActiveSubscriptions] A with (NOLOCK) on S.[SubscriptionID] = A.[SubscriptionID] where S.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListSubscriptionsUsingDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListSubscriptionsUsingDataSource] GO CREATE PROCEDURE [dbo].[ListSubscriptionsUsingDataSource] @DataSourceName nvarchar(450), @AuthType int AS select S.[SubscriptionID], S.[Report_OID], S.[Locale], S.[InactiveFlags], S.[DeliveryExtension], S.[ExtensionSettings], SUSER_SNAME(Modified.[Sid]), Modified.[UserName], S.[ModifiedDate], S.[Description], S.[LastStatus], S.[EventType], S.[MatchData], S.[Parameters], S.[DataSettings], A.[TotalNotifications], A.[TotalSuccesses], A.[TotalFailures], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], CAT.[Path], S.[LastRunTime], CAT.[Type], SD.NtSecDescPrimary, S.[Version] from [DataSource] DS inner join Catalog C on C.ItemID = DS.Link inner join Subscriptions S on S.[SubscriptionID] = DS.[SubscriptionID] inner join [Catalog] CAT on S.[Report_OID] = CAT.[ItemID] inner join [Users] Owner on S.OwnerID = Owner.UserID inner join [Users] Modified on S.ModifiedByID = Modified.UserID left join [SecData] SD on SD.[PolicyID] = CAT.[PolicyID] AND SD.AuthType = @AuthType left outer join [ActiveSubscriptions] A with (NOLOCK) on S.[SubscriptionID] = A.[SubscriptionID] where C.Path = @DataSourceName GO GRANT EXECUTE ON [dbo].[ListSubscriptionsUsingDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSubscriptionStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSubscriptionStatus] GO CREATE PROCEDURE [dbo].[UpdateSubscriptionStatus] @SubscriptionID uniqueidentifier, @Status nvarchar(260) AS update Subscriptions set [LastStatus] = @Status where [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[UpdateSubscriptionStatus] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSubscription] GO CREATE PROCEDURE [dbo].[UpdateSubscription] @id uniqueidentifier, @Locale nvarchar(260), @OwnerSid varbinary(85) = NULL, @OwnerName nvarchar(260), @OwnerAuthType int, @DeliveryExtension nvarchar(260), @InactiveFlags int, @ExtensionSettings ntext = NULL, @ModifiedBySid varbinary(85) = NULL, @ModifiedByName nvarchar(260), @ModifiedByAuthType int, @ModifiedDate datetime, @Description nvarchar(512) = NULL, @LastStatus nvarchar(260) = NULL, @EventType nvarchar(260), @MatchData ntext = NULL, @Parameters ntext = NULL, @DataSettings ntext = NULL, @Version int AS -- Update a subscription's information. DECLARE @ModifiedByID uniqueidentifier DECLARE @OwnerID uniqueidentifier EXEC GetUserID @ModifiedBySid, @OwnerName,@OwnerAuthType, @ModifiedByID OUTPUT EXEC GetUserID @OwnerSid, @ModifiedByName, @ModifiedByAuthType, @OwnerID OUTPUT -- Make sure there is a valid provider update Subscriptions set [DeliveryExtension] = @DeliveryExtension, [Locale] = @Locale, [OwnerID] = @OwnerID, [InactiveFlags] = @InactiveFlags, [ExtensionSettings] = @ExtensionSettings, [ModifiedByID] = @ModifiedByID, [ModifiedDate] = @ModifiedDate, [Description] = @Description, [LastStatus] = @LastStatus, [EventType] = @EventType, [MatchData] = @MatchData, [Parameters] = @Parameters, [DataSettings] = @DataSettings, [Version] = @Version where [SubscriptionID] = @id GO GRANT EXECUTE ON [dbo].[UpdateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[InvalidateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[InvalidateSubscription] GO CREATE PROCEDURE [dbo].[InvalidateSubscription] @SubscriptionID uniqueidentifier, @Flags int, @LastStatus nvarchar(260) AS -- Mark all subscriptions for this report as inactive for the given flags update Subscriptions set [InactiveFlags] = S.[InactiveFlags] | @Flags, [LastStatus] = @LastStatus from Subscriptions S where SubscriptionID = @SubscriptionID GO GRANT EXECUTE ON [dbo].[InvalidateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanNotificationRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanNotificationRecords] GO CREATE PROCEDURE [dbo].[CleanNotificationRecords] @MaxAgeMinutes int AS -- Reset all notifications which have been add over n minutes ago Update [Notifications] set [ProcessStart] = NULL, [ProcessHeartbeat] = NULL, [Attempt] = 1 where [NotificationID] in ( SELECT [NotificationID] FROM [Notifications] WHERE [ProcessHeartbeat] < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) and [Attempt] is NULL ) Update [Notifications] set [ProcessStart] = NULL, [ProcessHeartbeat] = NULL, [Attempt] = [Attempt] + 1 where [NotificationID] in ( SELECT [NotificationID] FROM [Notifications] WHERE [ProcessHeartbeat] < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) and [Attempt] is not NULL ) GO GRANT EXECUTE ON [dbo].[CleanNotificationRecords] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateSnapShotNotifications]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateSnapShotNotifications] GO CREATE PROCEDURE [dbo].[CreateSnapShotNotifications] @HistoryID uniqueidentifier, @LastRunTime datetime AS update [Subscriptions] set [LastRunTime] = @LastRunTime from History SS inner join [Subscriptions] S on S.[Report_OID] = SS.[ReportID] where SS.[HistoryID] = @HistoryID and S.EventType = 'ReportHistorySnapshotCreated' and InactiveFlags = 0 -- Find all valid subscriptions for the given report and create a new notification row for -- each subscription insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) select NewID(), S.[SubscriptionID], NULL, S.[Report_OID], NULL, S.[ExtensionSettings], S.[Locale], S.[Parameters], GETUTCDATE(), S.[LastRunTime], S.[DeliveryExtension], S.[OwnerID], 0, S.[Version] from [Subscriptions] S with (READPAST) inner join History H on S.[Report_OID] = H.[ReportID] where H.[HistoryID] = @HistoryID and S.EventType = 'ReportHistorySnapshotCreated' and InactiveFlags = 0 and S.[DataSettings] is null -- Create any data driven subscription by creating a data driven event insert into [Event] ( [EventID], [EventType], [EventData], [TimeEntered] ) select NewID(), 'DataDrivenSubscription', S.SubscriptionID, GETUTCDATE() from [Subscriptions] S with (READPAST) inner join History H on S.[Report_OID] = H.[ReportID] where H.[HistoryID] = @HistoryID and S.EventType = 'ReportHistorySnapshotCreated' and InactiveFlags = 0 and S.[DataSettings] is not null GO GRANT EXECUTE ON [dbo].[CreateSnapShotNotifications] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateDataDrivenNotification]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateDataDrivenNotification] GO CREATE PROCEDURE [dbo].[CreateDataDrivenNotification] @SubscriptionID uniqueidentifier, @ActiveationID uniqueidentifier, @ReportID uniqueidentifier, @ExtensionSettings ntext, @Locale nvarchar(128), @Parameters ntext, @LastRunTime datetime, @DeliveryExtension nvarchar(260), @OwnerSid varbinary (85) = null, @OwnerName nvarchar(260), @OwnerAuthType int, @Version int AS declare @OwnerID as uniqueidentifier EXEC GetUserID @OwnerSid,@OwnerName, @OwnerAuthType, @OwnerID OUTPUT -- Insert into the notification table insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) values ( NewID(), @SubscriptionID, @ActiveationID, @ReportID, NULL, @ExtensionSettings, @Locale, @Parameters, GETUTCDATE(), @LastRunTime, @DeliveryExtension, @OwnerID, 1, @Version ) GO GRANT EXECUTE ON [dbo].[CreateDataDrivenNotification] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateNewActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateNewActiveSubscription] GO CREATE PROCEDURE [dbo].[CreateNewActiveSubscription] @ActiveID uniqueidentifier, @SubscriptionID uniqueidentifier AS -- Insert into the activesubscription table insert into [ActiveSubscriptions] ( [ActiveID], [SubscriptionID], [TotalNotifications], [TotalSuccesses], [TotalFailures] ) values ( @ActiveID, @SubscriptionID, NULL, 0, 0 ) GO GRANT EXECUTE ON [dbo].[CreateNewActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateActiveSubscription] GO CREATE PROCEDURE [dbo].[UpdateActiveSubscription] @ActiveID uniqueidentifier, @TotalNotifications int = NULL, @TotalSuccesses int = NULL, @TotalFailures int = NULL AS if @TotalNotifications is not NULL begin update ActiveSubscriptions set TotalNotifications = @TotalNotifications where ActiveID = @ActiveID end if @TotalSuccesses is not NULL begin update ActiveSubscriptions set TotalSuccesses = @TotalSuccesses where ActiveID = @ActiveID end if @TotalFailures is not NULL begin update ActiveSubscriptions set TotalFailures = @TotalFailures where ActiveID = @ActiveID end GO GRANT EXECUTE ON [dbo].[UpdateActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteActiveSubscription] GO CREATE PROCEDURE [dbo].[DeleteActiveSubscription] @ActiveID uniqueidentifier AS delete from ActiveSubscriptions where ActiveID = @ActiveID GO GRANT EXECUTE ON [dbo].[DeleteActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAndHoldLockActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAndHoldLockActiveSubscription] GO CREATE PROCEDURE [dbo].[GetAndHoldLockActiveSubscription] @ActiveID uniqueidentifier AS select TotalNotifications, TotalSuccesses, TotalFailures from ActiveSubscriptions with (XLOCK) where ActiveID = @ActiveID GO GRANT EXECUTE ON [dbo].[GetAndHoldLockActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateCacheUpdateNotifications]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateCacheUpdateNotifications] GO CREATE PROCEDURE [dbo].[CreateCacheUpdateNotifications] @ReportID uniqueidentifier, @LastRunTime datetime AS update [Subscriptions] set [LastRunTime] = @LastRunTime from [Subscriptions] S where S.[Report_OID] = @ReportID and S.EventType = 'SnapshotUpdated' and InactiveFlags = 0 -- Find all valid subscriptions for the given report and create a new notification row for -- each subscription insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) select NewID(), S.[SubscriptionID], NULL, S.[Report_OID], NULL, S.[ExtensionSettings], S.[Locale], S.[Parameters], GETUTCDATE(), S.[LastRunTime], S.[DeliveryExtension], S.[OwnerID], 0, S.[Version] from [Subscriptions] S inner join Catalog C on S.[Report_OID] = C.[ItemID] where C.[ItemID] = @ReportID and S.EventType = 'SnapshotUpdated' and InactiveFlags = 0 and S.[DataSettings] is null -- Create any data driven subscription by creating a data driven event insert into [Event] ( [EventID], [EventType], [EventData], [TimeEntered] ) select NewID(), 'DataDrivenSubscription', S.SubscriptionID, GETUTCDATE() from [Subscriptions] S inner join Catalog C on S.[Report_OID] = C.[ItemID] where C.[ItemID] = @ReportID and S.EventType = 'SnapshotUpdated' and InactiveFlags = 0 and S.[DataSettings] is not null GO GRANT EXECUTE ON [dbo].[CreateCacheUpdateNotifications] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCacheSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetCacheSchedule] GO CREATE PROCEDURE [dbo].[GetCacheSchedule] @ReportID uniqueidentifier AS SELECT S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], RS.ReportAction FROM Schedule S with (XLOCK) inner join ReportSchedule RS on S.ScheduleID = RS.ScheduleID inner join [Users] Owner on S.[CreatedById] = Owner.[UserID] WHERE (RS.ReportAction = 1 or RS.ReportAction = 3) and -- 1 == UpdateCache, 3 == Invalidate cache RS.[ReportID] = @ReportID GO GRANT EXECUTE ON [dbo].[GetCacheSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteNotification]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteNotification] GO CREATE PROCEDURE [dbo].[DeleteNotification] @ID uniqueidentifier AS delete from [Notifications] where [NotificationID] = @ID GO GRANT EXECUTE ON [dbo].[DeleteNotification] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetNotificationAttempt]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetNotificationAttempt] GO CREATE PROCEDURE [dbo].[SetNotificationAttempt] @Attempt int, @SecondsToAdd int, @NotificationID uniqueidentifier AS update [Notifications] set [ProcessStart] = NULL, [Attempt] = @Attempt, [ProcessAfter] = DateAdd(second, @SecondsToAdd, GetUtcDate()) where [NotificationID] = @NotificationID GO GRANT EXECUTE ON [dbo].[SetNotificationAttempt] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateTimeBasedSubscriptionNotification]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateTimeBasedSubscriptionNotification] GO CREATE PROCEDURE [dbo].[CreateTimeBasedSubscriptionNotification] @SubscriptionID uniqueidentifier, @LastRunTime datetime as insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) select NewID(), S.[SubscriptionID], NULL, S.[Report_OID], NULL, S.[ExtensionSettings], S.[Locale], S.[Parameters], GETUTCDATE(), @LastRunTime, S.[DeliveryExtension], S.[OwnerID], 0, S.[Version] from [Subscriptions] S where S.[SubscriptionID] = @SubscriptionID and InactiveFlags = 0 and S.[DataSettings] is null -- Create any data driven subscription by creating a data driven event insert into [Event] ( [EventID], [EventType], [EventData], [TimeEntered] ) select NewID(), 'DataDrivenSubscription', S.SubscriptionID, GETUTCDATE() from [Subscriptions] S where S.[SubscriptionID] = @SubscriptionID and InactiveFlags = 0 and S.[DataSettings] is not null update [Subscriptions] set [LastRunTime] = @LastRunTime where [SubscriptionID] = @SubscriptionID and InactiveFlags = 0 GO GRANT EXECUTE ON [dbo].[CreateTimeBasedSubscriptionNotification] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteTimeBasedSubscriptionSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteTimeBasedSubscriptionSchedule] GO CREATE PROCEDURE [dbo].[DeleteTimeBasedSubscriptionSchedule] @SubscriptionID as uniqueidentifier as delete ReportSchedule from ReportSchedule RS inner join Subscriptions S on S.[SubscriptionID] = RS.[SubscriptionID] where S.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[DeleteTimeBasedSubscriptionSchedule] TO RSExecRole GO -------------------------------------------------- ------------- Provider Info if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListUsedDeliveryProviders]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListUsedDeliveryProviders] GO CREATE PROCEDURE [dbo].[ListUsedDeliveryProviders] AS select distinct [DeliveryExtension] from Subscriptions where [DeliveryExtension] <> '' GO GRANT EXECUTE ON [dbo].[ListUsedDeliveryProviders] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id('[dbo].[AddBatchRecord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddBatchRecord] GO CREATE PROCEDURE [dbo].[AddBatchRecord] @BatchID uniqueidentifier, @UserName nvarchar(260), @Action varchar(32), @Item nvarchar(425) = NULL, @Parent nvarchar(425) = NULL, @Param nvarchar(425) = NULL, @BoolParam bit = NULL, @Content image = NULL, @Properties ntext = NULL AS IF @Action='BatchStart' BEGIN INSERT INTO [Batch] (BatchID, AddedOn, [Action], Item, Parent, Param, BoolParam, Content, Properties) VALUES (@BatchID, GETUTCDATE(), @Action, @UserName, @Parent, @Param, @BoolParam, @Content, @Properties) END ELSE BEGIN IF EXISTS (SELECT * FROM Batch WHERE BatchID = @BatchID AND [Action] = 'BatchStart' AND Item = @UserName) BEGIN INSERT INTO [Batch] (BatchID, AddedOn, [Action], Item, Parent, Param, BoolParam, Content, Properties) VALUES (@BatchID, GETUTCDATE(), @Action, @Item, @Parent, @Param, @BoolParam, @Content, @Properties) END ELSE BEGIN RAISERROR( 'Batch does not exist', 16, 1 ) END END GO GRANT EXECUTE ON [dbo].[AddBatchRecord] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[GetBatchRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetBatchRecords] GO CREATE PROCEDURE [dbo].[GetBatchRecords] @BatchID uniqueidentifier AS SELECT [Action], Item, Parent, Param, BoolParam, Content, Properties FROM [Batch] WHERE BatchID = @BatchID ORDER BY AddedOn GO GRANT EXECUTE ON [dbo].[GetBatchRecords] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteBatchRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteBatchRecords] GO CREATE PROCEDURE [dbo].[DeleteBatchRecords] @BatchID uniqueidentifier AS DELETE FROM [Batch] WHERE BatchID = @BatchID GO GRANT EXECUTE ON [dbo].[DeleteBatchRecords] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanBatchRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanBatchRecords] GO CREATE PROCEDURE [dbo].[CleanBatchRecords] @MaxAgeMinutes int AS DELETE FROM [Batch] where BatchID in ( SELECT BatchID FROM [Batch] WHERE AddedOn < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) ) GO GRANT EXECUTE ON [dbo].[CleanBatchRecords] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanOrphanedPolicies]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanOrphanedPolicies] GO -- Cleaning orphan policies CREATE PROCEDURE [dbo].[CleanOrphanedPolicies] AS DELETE [Policies] WHERE [Policies].[PolicyFlag] = 0 AND NOT EXISTS (SELECT ItemID FROM [Catalog] WHERE [Catalog].[PolicyID] = [Policies].[PolicyID]) DELETE [Policies] FROM [Policies] INNER JOIN [ModelItemPolicy] ON [ModelItemPolicy].[PolicyID] = [Policies].[PolicyID] WHERE NOT EXISTS (SELECT ItemID FROM [Catalog] WHERE [Catalog].[ItemID] = [ModelItemPolicy].[CatalogItemID]) GO GRANT EXECUTE ON [dbo].[CleanOrphanedPolicies] TO RSExecRole GO -------------------------------------------------- ------------- Snapshot manipulation if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[IncreaseTransientSnapshotRefcount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[IncreaseTransientSnapshotRefcount] GO CREATE PROCEDURE [dbo].[IncreaseTransientSnapshotRefcount] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @ExpirationMinutes as int AS DECLARE @soon AS datetime SET @soon = DATEADD(n, @ExpirationMinutes, GETDATE()) if @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET ExpirationDate = @soon, TransientRefcount = TransientRefcount + 1 WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET ExpirationDate = @soon, TransientRefcount = TransientRefcount + 1 WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[IncreaseTransientSnapshotRefcount] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DecreaseTransientSnapshotRefcount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DecreaseTransientSnapshotRefcount] GO CREATE PROCEDURE [dbo].[DecreaseTransientSnapshotRefcount] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS if @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET TransientRefcount = TransientRefcount - 1 WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET TransientRefcount = TransientRefcount - 1 WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[DecreaseTransientSnapshotRefcount] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[MarkSnapshotAsDependentOnUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[MarkSnapshotAsDependentOnUser] GO CREATE PROCEDURE [dbo].[MarkSnapshotAsDependentOnUser] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS if @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET DependsOnUser = 1 WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET DependsOnUser = 1 WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[MarkSnapshotAsDependentOnUser] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSnapshotChunksVersion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSnapshotChunksVersion] GO CREATE PROCEDURE [dbo].[SetSnapshotChunksVersion] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @Version as smallint AS if @IsPermanentSnapshot = 1 BEGIN if @Version > 0 BEGIN UPDATE ChunkData SET Version = @Version WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ChunkData SET Version = Version WHERE SnapshotDataID = @SnapshotDataID END END ELSE BEGIN if @Version > 0 BEGIN UPDATE ReportServerTempDB.dbo.ChunkData SET Version = @Version WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.ChunkData SET Version = Version WHERE SnapshotDataID = @SnapshotDataID END END GO GRANT EXECUTE ON [dbo].[SetSnapshotChunksVersion] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[LockSnapshotForUpgrade]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[LockSnapshotForUpgrade] GO CREATE PROCEDURE [dbo].[LockSnapshotForUpgrade] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS if @IsPermanentSnapshot = 1 BEGIN SELECT ChunkName from ChunkData with (XLOCK) WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN SELECT ChunkName from ReportServerTempDB.dbo.ChunkData with (XLOCK) WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[LockSnapshotForUpgrade] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[InsertUnreferencedSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[InsertUnreferencedSnapshot] GO CREATE PROCEDURE [dbo].[InsertUnreferencedSnapshot] @ReportID as uniqueidentifier = NULL, @EffectiveParams as ntext = NULL, @QueryParams as ntext = NULL, @ParamsHash as int = NULL, @CreatedDate as datetime, @Description as nvarchar(512) = NULL, @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @SnapshotTimeoutMinutes as int, @Machine as nvarchar(512) = NULL AS DECLARE @now datetime SET @now = GETDATE() IF @IsPermanentSnapshot = 1 BEGIN INSERT INTO SnapshotData (SnapshotDataID, CreatedDate, EffectiveParams, QueryParams, ParamsHash, Description, PermanentRefcount, TransientRefcount, ExpirationDate) VALUES (@SnapshotDataID, @CreatedDate, @EffectiveParams, @QueryParams, @ParamsHash, @Description, 0, 1, DATEADD(n, @SnapshotTimeoutMinutes, @now)) END ELSE BEGIN INSERT INTO ReportServerTempDB.dbo.SnapshotData (SnapshotDataID, CreatedDate, EffectiveParams, QueryParams, ParamsHash, Description, PermanentRefcount, TransientRefcount, ExpirationDate, Machine) VALUES (@SnapshotDataID, @CreatedDate, @EffectiveParams, @QueryParams, @ParamsHash, @Description, 0, 1, DATEADD(n, @SnapshotTimeoutMinutes, @now), @Machine) END GO GRANT EXECuTE ON [dbo].[InsertUnreferencedSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[PromoteSnapshotInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[PromoteSnapshotInfo] GO CREATE PROCEDURE [dbo].[PromoteSnapshotInfo] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @PageCount as int, @HasDocMap as bit AS IF @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET PageCount = @PageCount, HasDocMap = @HasDocMap WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET PageCount = @PageCount, HasDocMap = @HasDocMap WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[PromoteSnapshotInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapshotPromotedInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapshotPromotedInfo] GO CREATE PROCEDURE [dbo].[GetSnapshotPromotedInfo] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS IF @IsPermanentSnapshot = 1 BEGIN SELECT PageCount, HasDocMap FROM SnapshotData WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN SELECT PageCount, HasDocMap FROM ReportServerTempDB.dbo.SnapshotData WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[GetSnapshotPromotedInfo] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[AddHistoryRecord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddHistoryRecord] GO -- add new record to History table CREATE PROCEDURE [dbo].[AddHistoryRecord] @HistoryID uniqueidentifier, @ReportID uniqueidentifier, @SnapshotDate datetime, @SnapshotDataID uniqueidentifier, @SnapshotTransientRefcountChange int AS INSERT INTO History (HistoryID, ReportID, SnapshotDataID, SnapshotDate) VALUES (@HistoryID, @ReportID, @SnapshotDataID, @SnapshotDate) IF @@ERROR = 0 BEGIN UPDATE SnapshotData -- Snapshots, when created, have transient refcount set to 1. Here create permanent reference -- here so we need to increase permanent refcount and decrease transient refcount. However, -- if it was already referenced by the execution snapshot, transient refcount was already -- decreased. Hence, there's a parameter @SnapshotTransientRefcountChange that is 0 or -1. SET PermanentRefcount = PermanentRefcount + 1, TransientRefcount = TransientRefcount + @SnapshotTransientRefcountChange WHERE SnapshotData.SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[AddHistoryRecord] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[SetHistoryLimit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetHistoryLimit] GO CREATE PROCEDURE [dbo].[SetHistoryLimit] @Path nvarchar (425), @SnapshotLimit int = NULL AS UPDATE Catalog SET SnapshotLimit=@SnapshotLimit WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[SetHistoryLimit] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[ListHistory]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListHistory] GO -- list all historical snapshots for a specific report CREATE PROCEDURE [dbo].[ListHistory] @ReportID uniqueidentifier AS SELECT S.SnapshotDate, (SELECT SUM(DATALENGTH( CD.Content ) ) FROM ChunkData AS CD WHERE CD.SnapshotDataID = S.SnapshotDataID ) FROM History AS S -- skipping intermediate table SnapshotData WHERE S.ReportID = @ReportID GO GRANT EXECUTE ON [dbo].[ListHistory] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanHistoryForReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanHistoryForReport] GO -- delete snapshots exceeding # of snapshots. won't work if @SnapshotLimit = 0 CREATE PROCEDURE [dbo].[CleanHistoryForReport] @SnapshotLimit int, @ReportID uniqueidentifier AS DECLARE @cmd varchar(2000) SET @cmd = 'DELETE FROM History WHERE ReportID = ''' + cast(@ReportID as varchar(40) ) + ''' and SnapshotDate < (SELECT MIN(SnapshotDate) FROM (SELECT TOP ' + CAST(@SnapshotLimit as varchar(20)) + ' SnapshotDate FROM History WHERE ReportID = ''' + cast(@ReportID as varchar(40) ) + ''' ORDER BY SnapshotDate DESC ) AS TopSnapshots )' EXEC( @cmd ) GO GRANT EXECUTE ON [dbo].[CleanHistoryForReport] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanAllHistories]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanAllHistories] GO -- delete snapshots exceeding # of snapshots for the whole system CREATE PROCEDURE [dbo].[CleanAllHistories] @SnapshotLimit int AS DECLARE @cmd varchar(2000) SET @cmd = 'DELETE FROM History WHERE HistoryID in (SELECT HistoryID FROM History JOIN Catalog AS ReportJoinSnapshot ON ItemID = ReportID WHERE SnapshotLimit is NULL and SnapshotDate < (SELECT MIN(SnapshotDate) FROM (SELECT TOP ' + CAST(@SnapshotLimit as varchar(20)) + ' SnapshotDate FROM History AS InnerSnapshot WHERE InnerSnapshot.ReportID = ReportJoinSnapshot.ItemID ORDER BY SnapshotDate DESC ) AS TopSnapshots ) )' EXEC( @cmd ) GO GRANT EXECUTE ON [dbo].[CleanAllHistories] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteHistoryRecord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteHistoryRecord] GO -- delete one historical snapshot CREATE PROCEDURE [dbo].[DeleteHistoryRecord] @ReportID uniqueidentifier, @SnapshotDate DateTime AS DELETE FROM History WHERE ReportID = @ReportID AND SnapshotDate = @SnapshotDate GO GRANT EXECUTE ON [dbo].[DeleteHistoryRecord] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteAllHistoryForReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteAllHistoryForReport] GO -- delete all snapshots for a report CREATE PROCEDURE [dbo].[DeleteAllHistoryForReport] @ReportID uniqueidentifier AS DELETE FROM History WHERE HistoryID in (SELECT HistoryID FROM History JOIN Catalog on ItemID = ReportID WHERE ReportID = @ReportID ) GO GRANT EXECUTE ON [dbo].[DeleteAllHistoryForReport] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteHistoriesWithNoPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteHistoriesWithNoPolicy] GO -- delete all snapshots for all reports that inherit system History policy CREATE PROCEDURE [dbo].[DeleteHistoriesWithNoPolicy] AS DELETE FROM History WHERE HistoryID in (SELECT HistoryID FROM History JOIN Catalog on ItemID = ReportID WHERE SnapshotLimit is null ) GO GRANT EXECUTE ON [dbo].[DeleteHistoriesWithNoPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Get_sqlagent_job_status]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[Get_sqlagent_job_status] GO CREATE PROCEDURE [dbo].[Get_sqlagent_job_status] -- Individual job parameters @job_id UNIQUEIDENTIFIER = NULL, -- If provided will only return info about this job -- Note: Only @job_id or @job_name needs to be provided @job_name sysname = NULL, -- If provided will only return info about this job @owner_login_name sysname = NULL -- If provided will only return jobs for this owner AS BEGIN DECLARE @retval INT DECLARE @job_owner_sid VARBINARY(85) DECLARE @is_sysadmin INT SET NOCOUNT ON -- Remove any leading/trailing spaces from parameters (except @owner_login_name) SELECT @job_name = LTRIM(RTRIM(@job_name)) -- Turn [nullable] empty string parameters into NULLs IF (@job_name = N'') SELECT @job_name = NULL -- Verify the job if supplied. This also checks if the caller has rights to view the job IF ((@job_id IS NOT NULL) OR (@job_name IS NOT NULL)) BEGIN EXECUTE @retval = msdb..sp_verify_job_identifiers '@job_name', '@job_id', @job_name OUTPUT, @job_id OUTPUT IF (@retval <> 0) RETURN(1) -- Failure END -- If the login name isn't given, set it to the job owner or the current caller IF(@owner_login_name IS NULL) BEGIN SET @owner_login_name = (SELECT SUSER_SNAME(sj.owner_sid) FROM msdb.dbo.sysjobs sj where sj.job_id = @job_id) SET @is_sysadmin = ISNULL(IS_SRVROLEMEMBER(N'sysadmin', @owner_login_name), 0) END ELSE BEGIN -- Check owner IF (SUSER_SID(@owner_login_name) IS NULL) BEGIN RAISERROR(14262, -1, -1, '@owner_login_name', @owner_login_name) RETURN(1) -- Failure END --only allow sysadmin types to specify the owner IF ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1) AND (ISNULL(IS_MEMBER(N'SQLAgentAdminRole'), 0) = 1) AND (SUSER_SNAME() <> @owner_login_name)) BEGIN --TODO: RAISERROR(14525, -1, -1) RETURN(1) -- Failure END SET @is_sysadmin = 0 END IF (@job_id IS NOT NULL) BEGIN -- Individual job... EXECUTE @retval = master.dbo.xp_sqlagent_enum_jobs @is_sysadmin, @owner_login_name, @job_id IF (@retval <> 0) RETURN(1) -- Failure END ELSE BEGIN -- Set of jobs... EXECUTE @retval = master.dbo.xp_sqlagent_enum_jobs @is_sysadmin, @owner_login_name IF (@retval <> 0) RETURN(1) -- Failure END RETURN(0) -- Success END GO GRANT EXECUTE ON [dbo].[Get_sqlagent_job_status] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateTask] GO CREATE PROCEDURE [dbo].[CreateTask] @ScheduleID uniqueidentifier, @Name nvarchar (260), @StartDate datetime, @Flags int, @NextRunTime datetime = NULL, @LastRunTime datetime = NULL, @EndDate datetime = NULL, @RecurrenceType int = NULL, @MinutesInterval int = NULL, @DaysInterval int = NULL, @WeeksInterval int = NULL, @DaysOfWeek int = NULL, @DaysOfMonth int = NULL, @Month int = NULL, @MonthlyWeek int = NULL, @State int = NULL, @LastRunStatus nvarchar (260) = NULL, @ScheduledRunTimeout int = NULL, @UserSid varbinary (85) = null, @UserName nvarchar(260), @AuthType int, @EventType nvarchar (260), @EventData nvarchar (260), @Type int AS DECLARE @UserID uniqueidentifier EXEC GetUserID @UserSid, @UserName, @AuthType, @UserID OUTPUT -- Create a task with the given data. Insert into Schedule ( [ScheduleID], [Name], [StartDate], [Flags], [NextRunTime], [LastRunTime], [EndDate], [RecurrenceType], [MinutesInterval], [DaysInterval], [WeeksInterval], [DaysOfWeek], [DaysOfMonth], [Month], [MonthlyWeek], [State], [LastRunStatus], [ScheduledRunTimeout], [CreatedById], [EventType], [EventData], [Type] ) values (@ScheduleID, @Name, @StartDate, @Flags, @NextRunTime, @LastRunTime, @EndDate, @RecurrenceType, @MinutesInterval, @DaysInterval, @WeeksInterval, @DaysOfWeek, @DaysOfMonth, @Month, @MonthlyWeek, @State, @LastRunStatus, @ScheduledRunTimeout, @UserID, @EventType, @EventData, @Type) GO GRANT EXECUTE ON [dbo].[CreateTask] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateTask] GO CREATE PROCEDURE [dbo].[UpdateTask] @ScheduleID uniqueidentifier, @Name nvarchar (260), @StartDate datetime, @Flags int, @NextRunTime datetime = NULL, @LastRunTime datetime = NULL, @EndDate datetime = NULL, @RecurrenceType int = NULL, @MinutesInterval int = NULL, @DaysInterval int = NULL, @WeeksInterval int = NULL, @DaysOfWeek int = NULL, @DaysOfMonth int = NULL, @Month int = NULL, @MonthlyWeek int = NULL, @State int = NULL, @LastRunStatus nvarchar (260) = NULL, @ScheduledRunTimeout int = NULL AS -- Update a tasks values. ScheduleID and Report information can not be updated Update Schedule set [StartDate] = @StartDate, [Name] = @Name, [Flags] = @Flags, [NextRunTime] = @NextRunTime, [LastRunTime] = @LastRunTime, [EndDate] = @EndDate, [RecurrenceType] = @RecurrenceType, [MinutesInterval] = @MinutesInterval, [DaysInterval] = @DaysInterval, [WeeksInterval] = @WeeksInterval, [DaysOfWeek] = @DaysOfWeek, [DaysOfMonth] = @DaysOfMonth, [Month] = @Month, [MonthlyWeek] = @MonthlyWeek, [State] = @State, [LastRunStatus] = @LastRunStatus, [ScheduledRunTimeout] = @ScheduledRunTimeout where [ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[UpdateTask] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateScheduleNextRunTime]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateScheduleNextRunTime] GO CREATE PROCEDURE [dbo].[UpdateScheduleNextRunTime] @ScheduleID as uniqueidentifier, @NextRunTime as datetime as update Schedule set [NextRunTime] = @NextRunTime where [ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[UpdateScheduleNextRunTime] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListScheduledReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListScheduledReports] GO CREATE PROCEDURE [dbo].[ListScheduledReports] @ScheduleID uniqueidentifier, @AuthType int AS -- List all reports for a schedule select RS.[ReportAction], RS.[ScheduleID], RS.[ReportID], RS.[SubscriptionID], C.[Path], C.[Name], C.[Description], C.[ModifiedDate], SUSER_SNAME(U.[Sid]), U.[UserName], DATALENGTH( C.Content ), C.ExecutionTime, S.[Type], SD.[NtSecDescPrimary] from [ReportSchedule] RS Inner join [Catalog] C on RS.[ReportID] = C.[ItemID] left outer join [SecData] SD on SD.[PolicyID] = C.[PolicyID] AND SD.AuthType = @AuthType Inner join [Schedule] S on RS.[ScheduleID] = S.[ScheduleID] Inner join [Users] U on C.[ModifiedByID] = U.UserID where RS.[ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[ListScheduledReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListTasks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListTasks] GO CREATE PROCEDURE [dbo].[ListTasks] AS select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], (select count(*) from ReportSchedule where ReportSchedule.ScheduleID = S.ScheduleID) from [Schedule] S inner join [Users] Owner on S.[CreatedById] = Owner.UserID where S.[Type] = 0 -- Type 0 is shared schedules GO GRANT EXECUTE ON [dbo].[ListTasks] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListTasksForMaintenance]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListTasksForMaintenance] GO CREATE PROCEDURE [dbo].[ListTasksForMaintenance] AS declare @date datetime set @date = GETUTCDATE() update [Schedule] set [ConsistancyCheck] = @date from ( SELECT TOP 20 [ScheduleID] FROM [Schedule] WITH(UPDLOCK) WHERE [ConsistancyCheck] is NULL ) AS t1 WHERE [Schedule].[ScheduleID] = t1.[ScheduleID] select top 20 S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type] from [Schedule] S where [ConsistancyCheck] = @date GO GRANT EXECUTE ON [dbo].[ListTasksForMaintenance] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ClearScheduleConsistancyFlags]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ClearScheduleConsistancyFlags] GO CREATE PROCEDURE [dbo].[ClearScheduleConsistancyFlags] AS update [Schedule] with (tablock, xlock) set [ConsistancyCheck] = NULL GO GRANT EXECUTE ON [dbo].[ClearScheduleConsistancyFlags] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAReportsReportAction]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAReportsReportAction] GO CREATE PROCEDURE [dbo].[GetAReportsReportAction] @ReportID uniqueidentifier, @ReportAction int AS select RS.[ReportAction], RS.[ScheduleID], RS.[ReportID], RS.[SubscriptionID], C.[Path] from [ReportSchedule] RS Inner join [Catalog] C on RS.[ReportID] = C.[ItemID] where C.ItemID = @ReportID and RS.[ReportAction] = @ReportAction GO GRANT EXECUTE ON [dbo].[GetAReportsReportAction] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetTimeBasedSubscriptionReportAction]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetTimeBasedSubscriptionReportAction] GO CREATE PROCEDURE [dbo].[GetTimeBasedSubscriptionReportAction] @SubscriptionID uniqueidentifier AS select RS.[ReportAction], RS.[ScheduleID], RS.[ReportID], RS.[SubscriptionID], C.[Path] from [ReportSchedule] RS Inner join [Catalog] C on RS.[ReportID] = C.[ItemID] where RS.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetTimeBasedSubscriptionReportAction] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetTaskProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetTaskProperties] GO CREATE PROCEDURE [dbo].[GetTaskProperties] @ScheduleID uniqueidentifier AS -- Grab all of a tasks properties given a task id select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], SUSER_SNAME(Owner.[Sid]), Owner.[UserName] from [Schedule] S with (XLOCK) Inner join [Users] Owner on S.[CreatedById] = Owner.UserID where S.[ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[GetTaskProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteTask] GO CREATE PROCEDURE [dbo].[DeleteTask] @ScheduleID uniqueidentifier AS -- Delete the task with the given task id DELETE FROM Schedule WHERE [ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[DeleteTask] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSchedulesReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSchedulesReports] GO CREATE PROCEDURE [dbo].[GetSchedulesReports] @ID uniqueidentifier AS select C.Path from ReportSchedule RS inner join Catalog C on (C.ItemID = RS.ReportID) where ScheduleID = @ID GO GRANT EXECUTE ON [dbo].[GetSchedulesReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddReportSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddReportSchedule] GO CREATE PROCEDURE [dbo].[AddReportSchedule] @ScheduleID uniqueidentifier, @ReportID uniqueidentifier, @SubscriptionID uniqueidentifier = NULL, @Action int AS Insert into ReportSchedule ([ScheduleID], [ReportID], [SubscriptionID], [ReportAction]) values (@ScheduleID, @ReportID, @SubscriptionID, @Action) GO GRANT EXECUTE ON [dbo].[AddReportSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteReportSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteReportSchedule] GO CREATE PROCEDURE [dbo].[DeleteReportSchedule] @ScheduleID uniqueidentifier, @ReportID uniqueidentifier, @SubscriptionID uniqueidentifier = NULL, @ReportAction int AS IF @SubscriptionID is NULL BEGIN delete from ReportSchedule where ScheduleID = @ScheduleID and ReportID = @ReportID and ReportAction = @ReportAction END ELSE BEGIN delete from ReportSchedule where ScheduleID = @ScheduleID and ReportID = @ReportID and ReportAction = @ReportAction and SubscriptionID = @SubscriptionID END GO GRANT EXECUTE ON [dbo].[DeleteReportSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapShotSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapShotSchedule] GO CREATE PROCEDURE [dbo].[GetSnapShotSchedule] @ReportID uniqueidentifier AS select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], SUSER_SNAME(Owner.[Sid]), Owner.[UserName] from Schedule S with (XLOCK) inner join ReportSchedule RS on S.ScheduleID = RS.ScheduleID inner join [Users] Owner on S.[CreatedById] = Owner.[UserID] where RS.ReportAction = 2 and -- 2 == create snapshot RS.ReportID = @ReportID GO GRANT EXECUTE ON [dbo].[GetSnapShotSchedule] TO RSExecRole GO -------------------------------------------------- ------------- Time based subscriptions if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateTimeBasedSubscriptionSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateTimeBasedSubscriptionSchedule] GO CREATE PROCEDURE [dbo].[CreateTimeBasedSubscriptionSchedule] @SubscriptionID as uniqueidentifier, @ScheduleID uniqueidentifier, @Schedule_Name nvarchar (260), @Report_Name nvarchar (425), @StartDate datetime, @Flags int, @NextRunTime datetime = NULL, @LastRunTime datetime = NULL, @EndDate datetime = NULL, @RecurrenceType int = NULL, @MinutesInterval int = NULL, @DaysInterval int = NULL, @WeeksInterval int = NULL, @DaysOfWeek int = NULL, @DaysOfMonth int = NULL, @Month int = NULL, @MonthlyWeek int = NULL, @State int = NULL, @LastRunStatus nvarchar (260) = NULL, @ScheduledRunTimeout int = NULL, @UserSid varbinary (85) = NULL, @UserName nvarchar(260), @AuthType int, @EventType nvarchar (260), @EventData nvarchar (260) AS EXEC CreateTask @ScheduleID, @Schedule_Name, @StartDate, @Flags, @NextRunTime, @LastRunTime, @EndDate, @RecurrenceType, @MinutesInterval, @DaysInterval, @WeeksInterval, @DaysOfWeek, @DaysOfMonth, @Month, @MonthlyWeek, @State, @LastRunStatus, @ScheduledRunTimeout, @UserSid, @UserName, @AuthType, @EventType, @EventData, 1 -- scoped type -- add a row to the reportSchedule table declare @Report_OID uniqueidentifier select @Report_OID = (select [ItemID] from [Catalog] with (HOLDLOCK) where [Catalog].[Path] = @Report_Name and ([Catalog].[Type] = 2 or [Catalog].[Type] = 4)) EXEC AddReportSchedule @ScheduleID, @Report_OID, @SubscriptionID, 4 -- TimedSubscription action GO GRANT EXECUTE ON [dbo].[CreateTimeBasedSubscriptionSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetTimeBasedSubscriptionSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetTimeBasedSubscriptionSchedule] GO CREATE PROCEDURE [dbo].[GetTimeBasedSubscriptionSchedule] @SubscriptionID as uniqueidentifier AS select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], SUSER_SNAME(Owner.[Sid]), Owner.[UserName] from [ReportSchedule] R inner join Schedule S with (XLOCK) on R.[ScheduleID] = S.[ScheduleID] Inner join [Users] Owner on S.[CreatedById] = Owner.UserID where R.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetTimeBasedSubscriptionSchedule] TO RSExecRole GO -------------------------------------------------- ------------- Running Jobs if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddRunningJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddRunningJob] GO CREATE PROCEDURE [dbo].[AddRunningJob] @JobID as nvarchar(32), @StartDate as datetime, @ComputerName as nvarchar(32), @RequestName as nvarchar(425), @RequestPath as nvarchar(425), @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @Description as ntext = NULL, @Timeout as int, @JobAction as smallint, @JobType as smallint, @JobStatus as smallint AS DECLARE @UserID uniqueidentifier EXEC GetUserID @UserSid, @UserName, @AuthType, @UserID OUTPUT INSERT INTO RunningJobs (JobID, StartDate, ComputerName, RequestName, RequestPath, UserID, Description, Timeout, JobAction, JobType, JobStatus ) VALUES (@JobID, @StartDate, @ComputerName, @RequestName, @RequestPath, @UserID, @Description, @Timeout, @JobAction, @JobType, @JobStatus) GO GRANT EXECUTE ON [dbo].[AddRunningJob] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RemoveRunningJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RemoveRunningJob] GO CREATE PROCEDURE [dbo].[RemoveRunningJob] @JobID as nvarchar(32) AS DELETE FROM RunningJobs WHERE JobID = @JobID GO GRANT EXECUTE ON [dbo].[RemoveRunningJob] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateRunningJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateRunningJob] GO CREATE PROCEDURE [dbo].[UpdateRunningJob] @JobID as nvarchar(32), @JobStatus as smallint AS UPDATE RunningJobs SET JobStatus = @JobStatus WHERE JobID = @JobID GO GRANT EXECUTE ON [dbo].[UpdateRunningJob] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetMyRunningJobs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetMyRunningJobs] GO CREATE PROCEDURE [dbo].[GetMyRunningJobs] @ComputerName as nvarchar(32), @JobType as smallint AS SELECT JobID, StartDate, ComputerName, RequestName, RequestPath, SUSER_SNAME(Users.[Sid]), Users.[UserName], Description, Timeout, JobAction, JobType, JobStatus FROM RunningJobs INNER JOIN Users ON RunningJobs.UserID = Users.UserID WHERE ComputerName = @ComputerName AND JobType = @JobType GO GRANT EXECUTE ON [dbo].[GetMyRunningJobs] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListRunningJobs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListRunningJobs] GO CREATE PROCEDURE [dbo].[ListRunningJobs] AS SELECT JobID, StartDate, ComputerName, RequestName, RequestPath, SUSER_SNAME(Users.[Sid]), Users.[UserName], Description, Timeout, JobAction, JobType, JobStatus FROM RunningJobs INNER JOIN Users ON RunningJobs.UserID = Users.UserID GO GRANT EXECUTE ON [dbo].[ListRunningJobs] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredJobs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredJobs] GO CREATE PROCEDURE [dbo].[CleanExpiredJobs] AS DELETE FROM RunningJobs WHERE DATEADD(s, Timeout, StartDate) < GETDATE() GO GRANT EXECUTE ON [dbo].[CleanExpiredJobs] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateObject]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateObject] GO -- This SP should never be called with a policy ID unless it is guarenteed that -- the parent will not be deleted before the insert (such as while running this script) CREATE PROCEDURE [dbo].[CreateObject] @ItemID uniqueidentifier, @Name nvarchar (425), @Path nvarchar (425), @ParentID uniqueidentifier, @Type int, @Content image = NULL, @Intermediate uniqueidentifier = NULL, @LinkSourceID uniqueidentifier = NULL, @Property ntext = NULL, @Parameter ntext = NULL, @Description ntext = NULL, @Hidden bit = NULL, @CreatedBySid varbinary(85) = NULL, @CreatedByName nvarchar(260), @AuthType int, @CreationDate datetime, @MimeType nvarchar (260) = NULL, @SnapshotLimit int = NULL, @PolicyRoot int = 0, @PolicyID uniqueidentifier = NULL, @ExecutionFlag int = 1 -- allow live execution, don't keep history AS DECLARE @CreatedByID uniqueidentifier EXEC GetUserID @CreatedBySid, @CreatedByName, @AuthType, @CreatedByID OUTPUT UPDATE Catalog with (XLOCK) SET ModifiedByID = @CreatedByID, ModifiedDate = @CreationDate WHERE ItemID = @ParentID -- If no policyID, use the parent's IF @PolicyID is NULL BEGIN SET @PolicyID = (SELECT PolicyID FROM [dbo].[Catalog] WHERE Catalog.ItemID = @ParentID) END -- If there is no policy ID then we are guarenteed not to have a parent IF @PolicyID is NULL BEGIN RAISERROR ('Parent Not Found', 16, 1) return END INSERT INTO Catalog (ItemID, Path, Name, ParentID, Type, Content, Intermediate, LinkSourceID, Property, Description, Hidden, CreatedByID, CreationDate, ModifiedByID, ModifiedDate, MimeType, SnapshotLimit, [Parameter], PolicyID, PolicyRoot, ExecutionFlag ) VALUES (@ItemID, @Path, @Name, @ParentID, @Type, @Content, @Intermediate, @LinkSourceID, @Property, @Description, @Hidden, @CreatedByID, @CreationDate, @CreatedByID, @CreationDate, @MimeType, @SnapshotLimit, @Parameter, @PolicyID, @PolicyRoot , @ExecutionFlag) IF @Intermediate IS NOT NULL AND @@ERROR = 0 BEGIN UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount + 1, TransientRefcount = TransientRefcount - 1 WHERE SnapshotData.SnapshotDataID = @Intermediate END GO GRANT EXECUTE ON [dbo].[CreateObject] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteObject]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteObject] GO CREATE PROCEDURE [dbo].[DeleteObject] @Path nvarchar (425), @Prefix nvarchar (850) AS -- Remove reference for intermediate formats UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 FROM Catalog AS R WITH (XLOCK) INNER JOIN [SnapshotData] AS SD ON R.Intermediate = SD.SnapshotDataID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Remove reference for execution snapshots UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 FROM Catalog AS R WITH (XLOCK) INNER JOIN [SnapshotData] AS SD ON R.SnapshotDataID = SD.SnapshotDataID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Remove history for deleted reports and linked report DELETE History FROM [Catalog] AS R INNER JOIN [History] AS S ON R.ItemID = S.ReportID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Remove model drill reports DELETE ModelDrill FROM [Catalog] AS C INNER JOIN [ModelDrill] AS M ON C.ItemID = M.ReportID WHERE (C.Path = @Path OR C.Path LIKE @Prefix ESCAPE '*') -- Adjust data sources UPDATE [DataSource] SET [Flags] = [Flags] & 0x7FFFFFFD, -- broken link [Link] = NULL FROM [Catalog] AS C INNER JOIN [DataSource] AS DS ON C.[ItemID] = DS.[Link] WHERE (C.Path = @Path OR C.Path LIKE @Prefix ESCAPE '*') -- Clean all data sources DELETE [DataSource] FROM [Catalog] AS R INNER JOIN [DataSource] AS DS ON R.[ItemID] = DS.[ItemID] WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Update linked reports UPDATE LR SET LR.LinkSourceID = NULL FROM [Catalog] AS R INNER JOIN [Catalog] AS LR ON R.ItemID = LR.LinkSourceID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') AND (LR.Path NOT LIKE @Prefix ESCAPE '*') -- Remove references for cache entries UPDATE SN SET PermanentRefcount = PermanentRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC on SN.SnapshotDataID = EC.SnapshotDataID INNER JOIN Catalog AS C ON EC.ReportID = C.ItemID WHERE (Path = @Path OR Path LIKE @Prefix ESCAPE '*') -- Clean cache entries for items to be deleted DELETE EC FROM ReportServerTempDB.dbo.ExecutionCache AS EC INNER JOIN Catalog AS C ON EC.ReportID = C.ItemID WHERE (Path = @Path OR Path LIKE @Prefix ESCAPE '*') -- Finally delete items DELETE FROM [Catalog] WHERE (Path = @Path OR Path LIKE @Prefix ESCAPE '*') EXEC CleanOrphanedPolicies GO GRANT EXECUTE ON [dbo].[DeleteObject] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindObjectsNonRecursive]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindObjectsNonRecursive] GO CREATE PROCEDURE [dbo].[FindObjectsNonRecursive] @Path nvarchar (425), @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.[UserName], SUSER_SNAME(MU.Sid), MU.[UserName], C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Catalog AS P ON C.ParentID = P.ItemID INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE P.Path = @Path GO GRANT EXECUTE ON [dbo].[FindObjectsNonRecursive] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindObjectsRecursive]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindObjectsRecursive] GO CREATE PROCEDURE [dbo].[FindObjectsRecursive] @Prefix nvarchar (850), @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.UserName, SUSER_SNAME(MU.Sid), MU.UserName, C.MimeType, C.ExecutionTime, C.Hidden from Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE C.Path LIKE @Prefix ESCAPE '*' GO GRANT EXECUTE ON [dbo].[FindObjectsRecursive] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindObjectsByLink]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindObjectsByLink] GO CREATE PROCEDURE [dbo].[FindObjectsByLink] @Link uniqueidentifier, @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.UserName, SUSER_SNAME(MU.Sid), MU.UserName, C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE C.LinkSourceID = @Link GO GRANT EXECUTE ON [dbo].[FindObjectsByLink] TO RSExecRole GO -------------------------------------------------- ------------- Procedures used to update linked reports if exists (select * from sysobjects where id = object_id('[dbo].[GetIDPairsByLink]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetIDPairsByLink] GO CREATE PROCEDURE [dbo].[GetIDPairsByLink] @Link uniqueidentifier AS SELECT LinkSourceID, ItemID FROM Catalog WHERE LinkSourceID = @Link GO GRANT EXECUTE ON [dbo].[GetIDPairsByLink] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[GetChildrenBeforeDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetChildrenBeforeDelete] GO CREATE PROCEDURE [dbo].[GetChildrenBeforeDelete] @Prefix nvarchar (850), @AuthType int AS SELECT C.PolicyID, C.Type, SD.NtSecDescPrimary FROM Catalog AS C LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE C.Path LIKE @Prefix ESCAPE '*' -- return children only, not item itself GO GRANT EXECUTE ON [dbo].[GetChildrenBeforeDelete] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAllProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAllProperties] GO CREATE PROCEDURE [dbo].[GetAllProperties] @Path nvarchar (425), @AuthType int AS select Property, Description, Type, DATALENGTH( Content ), ItemID, SUSER_SNAME(C.Sid), C.UserName, CreationDate, SUSER_SNAME(M.Sid), M.UserName, ModifiedDate, MimeType, ExecutionTime, NtSecDescPrimary, [LinkSourceID], Hidden, ExecutionFlag, SnapshotLimit FROM Catalog INNER JOIN Users C ON Catalog.CreatedByID = C.UserID INNER JOIN Users M ON Catalog.ModifiedByID = M.UserID LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[GetAllProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetParameters] GO CREATE PROCEDURE [dbo].[GetParameters] @Path nvarchar (425), @AuthType int AS SELECT Type, [Parameter], ItemID, SecData.NtSecDescPrimary, [LinkSourceID], [ExecutionFlag] FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[GetParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetObjectContent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetObjectContent] GO CREATE PROCEDURE [dbo].[GetObjectContent] @Path nvarchar (425), @AuthType int AS SELECT Type, Content, LinkSourceID, MimeType, SecData.NtSecDescPrimary, ItemID FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[GetObjectContent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCompiledDefinition]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetCompiledDefinition] GO -- used to create snapshots CREATE PROCEDURE [dbo].[GetCompiledDefinition] @Path nvarchar (425), @AuthType int AS SELECT MainItem.Type, MainItem.Intermediate, MainItem.LinkSourceID, MainItem.Property, MainItem.Description, SecData.NtSecDescPrimary, MainItem.ItemID, MainItem.ExecutionFlag, LinkTarget.Intermediate, LinkTarget.Property, LinkTarget.Description, MainItem.[SnapshotDataID] FROM Catalog MainItem LEFT OUTER JOIN SecData ON MainItem.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog LinkTarget with (INDEX = PK_CATALOG) on MainItem.LinkSourceID = LinkTarget.ItemID WHERE MainItem.Path = @Path GO GRANT EXECUTE ON [dbo].[GetCompiledDefinition] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetReportForExecution]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetReportForExecution] GO -- gets either the intermediate format or snapshot from cache CREATE PROCEDURE [dbo].[GetReportForExecution] @Path nvarchar (425), @ParamsHash int, @AuthType int AS DECLARE @now AS datetime SET @now = GETDATE() IF ( NOT EXISTS ( SELECT * FROM Catalog AS C INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON C.ItemID = EC.ReportID INNER JOIN ReportServerTempDB.dbo.SnapshotData AS SN ON EC.SnapshotDataID = SN.SnapshotDataID WHERE C.Path = @Path AND EC.AbsoluteExpiration > @now AND SN.ParamsHash = @ParamsHash ) ) BEGIN -- no cache SELECT Cat.Type, Cat.LinkSourceID, Cat2.Path, Cat.Property, Cat.Description, SecData.NtSecDescPrimary, Cat.ItemID, CAST (0 AS BIT), -- not found, Cat.Intermediate, Cat.ExecutionFlag, SD.SnapshotDataID, SD.DependsOnUser, Cat.ExecutionTime, (SELECT Schedule.NextRunTime FROM Schedule WITH (XLOCK) INNER JOIN ReportSchedule ON Schedule.ScheduleID = ReportSchedule.ScheduleID WHERE ReportSchedule.ReportID = Cat.ItemID AND ReportSchedule.ReportAction = 1), -- update snapshot (SELECT Schedule.ScheduleID FROM Schedule INNER JOIN ReportSchedule ON Schedule.ScheduleID = ReportSchedule.ScheduleID WHERE ReportSchedule.ReportID = Cat.ItemID AND ReportSchedule.ReportAction = 1), -- update snapshot (SELECT CachePolicy.ExpirationFlags FROM CachePolicy WHERE CachePolicy.ReportID = Cat.ItemID), Cat2.Intermediate FROM Catalog AS Cat LEFT OUTER JOIN SecData ON Cat.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog AS Cat2 on Cat.LinkSourceID = Cat2.ItemID LEFT OUTER JOIN SnapshotData AS SD ON Cat.SnapshotDataID = SD.SnapshotDataID WHERE Cat.Path = @Path END ELSE BEGIN -- use cache SELECT TOP 1 Cat.Type, Cat.LinkSourceID, Cat2.Path, Cat.Property, Cat.Description, SecData.NtSecDescPrimary, Cat.ItemID, CAST (1 AS BIT), -- found, SN.SnapshotDataID, SN.DependsOnUser, SN.EffectiveParams, SN.CreatedDate, EC.AbsoluteExpiration, (SELECT CachePolicy.ExpirationFlags FROM CachePolicy WHERE CachePolicy.ReportID = Cat.ItemID), (SELECT Schedule.ScheduleID FROM Schedule WITH (XLOCK) INNER JOIN ReportSchedule ON Schedule.ScheduleID = ReportSchedule.ScheduleID WHERE ReportSchedule.ReportID = Cat.ItemID AND ReportSchedule.ReportAction = 1), -- update snapshot SN.QueryParams FROM Catalog AS Cat INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON Cat.ItemID = EC.ReportID INNER JOIN ReportServerTempDB.dbo.SnapshotData AS SN ON EC.SnapshotDataID = SN.SnapshotDataID LEFT OUTER JOIN SecData ON Cat.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog AS Cat2 on Cat.LinkSourceID = Cat2.ItemID WHERE Cat.Path = @Path AND AbsoluteExpiration > @now AND SN.ParamsHash = @ParamsHash ORDER BY SN.CreatedDate DESC END GO GRANT EXECUTE ON [dbo].[GetReportForExecution] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetReportParametersForExecution]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetReportParametersForExecution] GO -- gets either the intermediate format or snapshot from cache CREATE PROCEDURE [dbo].[GetReportParametersForExecution] @Path nvarchar (425), @HistoryID DateTime = NULL, @AuthType int AS SELECT C.[ItemID], C.[Type], C.[ExecutionFlag], [SecData].[NtSecDescPrimary], C.[Parameter], C.[Intermediate], C.[SnapshotDataID], [History].[SnapshotDataID], L.[Intermediate], C.[LinkSourceID], C.[ExecutionTime] FROM [Catalog] AS C LEFT OUTER JOIN [SecData] ON C.[PolicyID] = [SecData].[PolicyID] AND [SecData].AuthType = @AuthType LEFT OUTER JOIN [History] ON ( C.[ItemID] = [History].[ReportID] AND [History].[SnapshotDate] = @HistoryID ) LEFT OUTER JOIN [Catalog] AS L ON C.[LinkSourceID] = L.[ItemID] WHERE C.[Path] = @Path GO GRANT EXECUTE ON [dbo].[GetReportParametersForExecution] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[MoveObject]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[MoveObject] GO CREATE PROCEDURE [dbo].[MoveObject] @OldPath nvarchar (425), @OldPrefix nvarchar (850), @NewName nvarchar (425), @NewPath nvarchar (425), @NewParentID uniqueidentifier, @RenameOnly as bit, @MaxPathLength as int AS DECLARE @LongPath nvarchar(425) SET @LongPath = (SELECT TOP 1 Path FROM Catalog WHERE LEN(Path)-LEN(@OldPath)+LEN(@NewPath) > @MaxPathLength AND Path LIKE @OldPrefix ESCAPE '*') IF @LongPath IS NOT NULL BEGIN SELECT @LongPath RETURN END IF @RenameOnly = 0 -- if this a full-blown move, not just a rename BEGIN -- adjust policies on the top item that gets moved DECLARE @OldInheritedPolicyID as uniqueidentifier SELECT @OldInheritedPolicyID = (SELECT PolicyID FROM Catalog with (XLOCK) WHERE Path = @OldPath AND PolicyRoot = 0) IF (@OldInheritedPolicyID IS NOT NULL) BEGIN -- this was not a policy root, change it to inherit from target folder DECLARE @NewPolicyID as uniqueidentifier SELECT @NewPolicyID = (SELECT PolicyID FROM Catalog with (XLOCK) WHERE ItemID = @NewParentID) -- update item and children that shared the old policy UPDATE Catalog SET PolicyID = @NewPolicyID WHERE Path = @OldPath UPDATE Catalog SET PolicyID = @NewPolicyID WHERE Path LIKE @OldPrefix ESCAPE '*' AND Catalog.PolicyID = @OldInheritedPolicyID END END -- Update item that gets moved (Path, Name, and ParentId) update Catalog set Name = @NewName, Path = @NewPath, ParentID = @NewParentID where Path = @OldPath -- Update all its children (Path only, Names and ParentIds stay the same) update Catalog set Path = STUFF(Path, 1, LEN(@OldPath), @NewPath ) where Path like @OldPrefix escape '*' GO GRANT EXECUTE ON [dbo].[MoveObject] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ObjectExists]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ObjectExists] GO CREATE PROCEDURE [dbo].[ObjectExists] @Path nvarchar (425), @AuthType int AS SELECT Type, ItemID, SnapshotLimit, NtSecDescPrimary, ExecutionFlag, Intermediate, [LinkSourceID] FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[ObjectExists] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetAllProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetAllProperties] GO CREATE PROCEDURE [dbo].[SetAllProperties] @Path nvarchar (425), @Property ntext, @Description ntext = NULL, @Hidden bit = NULL, @ModifiedBySid varbinary (85) = NULL, @ModifiedByName nvarchar(260), @AuthType int, @ModifiedDate DateTime AS DECLARE @ModifiedByID uniqueidentifier EXEC GetUserID @ModifiedBySid, @ModifiedByName, @AuthType, @ModifiedByID OUTPUT UPDATE Catalog SET Property = @Property, Description = @Description, Hidden = @Hidden, ModifiedByID = @ModifiedByID, ModifiedDate = @ModifiedDate WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[SetAllProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FlushReportFromCache]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FlushReportFromCache] GO CREATE PROCEDURE [dbo].[FlushReportFromCache] @Path as nvarchar(425) AS UPDATE SN SET SN.PermanentRefcount = SN.PermanentRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON SN.SnapshotDataID = EC.SnapshotDataID INNER JOIN Catalog AS C ON EC.ReportID = C.ItemID WHERE C.Path = @Path DELETE EC FROM ReportServerTempDB.dbo.ExecutionCache AS EC INNER JOIN Catalog ON EC.ReportID = Catalog.ItemID WHERE Catalog.Path = @Path GO GRANT EXECUTE ON [dbo].[FlushReportFromCache] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetParameters] GO CREATE PROCEDURE [dbo].[SetParameters] @Path nvarchar (425), @Parameter ntext AS UPDATE Catalog SET [Parameter] = @Parameter WHERE Path = @Path EXEC FlushReportFromCache @Path GO GRANT EXECUTE ON [dbo].[SetParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetObjectContent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetObjectContent] GO CREATE PROCEDURE [dbo].[SetObjectContent] @Path nvarchar (425), @Type int, @Content image = NULL, @Intermediate uniqueidentifier = NULL, @Parameter ntext = NULL, @LinkSourceID uniqueidentifier = NULL, @MimeType nvarchar (260) = NULL AS DECLARE @OldIntermediate as uniqueidentifier SET @OldIntermediate = (SELECT Intermediate FROM Catalog WITH (XLOCK) WHERE Path = @Path) UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 WHERE SnapshotData.SnapshotDataID = @OldIntermediate UPDATE Catalog SET Type=@Type, Content = @Content, Intermediate = @Intermediate, [Parameter] = @Parameter, LinkSourceID = @LinkSourceID, MimeType = @MimeType WHERE Path = @Path UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount + 1, TransientRefcount = TransientRefcount - 1 WHERE SnapshotData.SnapshotDataID = @Intermediate EXEC FlushReportFromCache @Path GO GRANT EXECUTE ON [dbo].[SetObjectContent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetLastModified]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetLastModified] GO CREATE PROCEDURE [dbo].[SetLastModified] @Path nvarchar (425), @ModifiedBySid varbinary (85) = NULL, @ModifiedByName nvarchar(260), @AuthType int, @ModifiedDate DateTime AS DECLARE @ModifiedByID uniqueidentifier EXEC GetUserID @ModifiedBySid, @ModifiedByName, @AuthType, @ModifiedByID OUTPUT UPDATE Catalog SET ModifiedByID = @ModifiedByID, ModifiedDate = @ModifiedDate WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[SetLastModified] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetNameById]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetNameById] GO CREATE PROCEDURE [dbo].[GetNameById] @ItemID uniqueidentifier AS SELECT Path FROM Catalog WHERE ItemID = @ItemID GO GRANT EXECUTE ON [dbo].[GetNameById] TO RSExecRole GO -------------------------------------------------- ------------- Data source procedures to store user names and passwords if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddDataSource] GO CREATE PROCEDURE [dbo].[AddDataSource] @DSID [uniqueidentifier], @ItemID [uniqueidentifier] = NULL, -- null for future suport dynamic delivery @SubscriptionID [uniqueidentifier] = NULL, @Name [nvarchar] (260) = NULL, -- only for scoped data sources, MUST be NULL for standalone!!! @Extension [nvarchar] (260) = NULL, @LinkID [uniqueidentifier] = NULL, -- link id is trusted, if it is provided - we use it @LinkPath [nvarchar] (425) = NULL, -- if LinkId is not provided we try to look up LinkPath @CredentialRetrieval [int], @Prompt [ntext] = NULL, @ConnectionString [image] = NULL, @OriginalConnectionString [image] = NULL, @OriginalConnectStringExpressionBased [bit] = NULL, @UserName [image] = NULL, @Password [image] = NULL, @Flags [int], @AuthType [int], @Version [int] AS DECLARE @ActualLinkID uniqueidentifier SET @ActualLinkID = NULL IF (@LinkID is NULL) AND (@LinkPath is not NULL) BEGIN SELECT Type, ItemID, NtSecDescPrimary FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @LinkPath SET @ActualLinkID = (SELECT ItemID FROM Catalog WHERE Path = @LinkPath) END ELSE BEGIN SET @ActualLinkID = @LinkID END INSERT INTO DataSource ([DSID], [ItemID], [SubscriptionID], [Name], [Extension], [Link], [CredentialRetrieval], [Prompt], [ConnectionString], [OriginalConnectionString], [OriginalConnectStringExpressionBased], [UserName], [Password], [Flags], [Version]) VALUES (@DSID, @ItemID, @SubscriptionID, @Name, @Extension, @ActualLinkID, @CredentialRetrieval, @Prompt, @ConnectionString, @OriginalConnectionString, @OriginalConnectStringExpressionBased, @UserName, @Password, @Flags, @Version) GO GRANT EXECUTE ON [dbo].[AddDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDataSources]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDataSources] GO CREATE PROCEDURE [dbo].[GetDataSources] @ItemID [uniqueidentifier], @AuthType int AS SELECT -- select data sources and their links (if they exist) DS.[DSID], -- 0 DS.[ItemID], -- 1 DS.[Name], -- 2 DS.[Extension], -- 3 DS.[Link], -- 4 DS.[CredentialRetrieval], -- 5 DS.[Prompt], -- 6 DS.[ConnectionString], -- 7 DS.[OriginalConnectionString], -- 8 DS.[UserName], -- 9 DS.[Password], -- 10 DS.[Flags], -- 11 DSL.[DSID], -- 12 DSL.[ItemID], -- 13 DSL.[Name], -- 14 DSL.[Extension], -- 15 DSL.[Link], -- 16 DSL.[CredentialRetrieval], -- 17 DSL.[Prompt], -- 18 DSL.[ConnectionString], -- 19 DSL.[UserName], -- 20 DSL.[Password], -- 21 DSL.[Flags], -- 22 C.Path, -- 23 SD.NtSecDescPrimary, -- 24 DS.[OriginalConnectStringExpressionBased], -- 25 DS.[Version], -- 26 DSL.[Version], -- 27 (SELECT 1 WHERE EXISTS (SELECT * from [ModelItemPolicy] AS MIP WHERE C.[ItemID] = MIP.[CatalogItemID])) -- 28 FROM [DataSource] AS DS LEFT OUTER JOIN ([DataSource] AS DSL INNER JOIN [Catalog] AS C ON DSL.[ItemID] = C.[ItemID] LEFT OUTER JOIN [SecData] AS SD ON C.[PolicyID] = SD.[PolicyID] AND SD.AuthType = @AuthType) ON DS.[Link] = DSL.[ItemID] WHERE DS.[ItemID] = @ItemID or DS.[SubscriptionID] = @ItemID GO GRANT EXECUTE ON [dbo].[GetDataSources] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteDataSources]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteDataSources] GO CREATE PROCEDURE [dbo].[DeleteDataSources] @ItemID [uniqueidentifier] AS DELETE FROM [DataSource] WHERE [ItemID] = @ItemID or [SubscriptionID] = @ItemID GO GRANT EXECUTE ON [dbo].[DeleteDataSources] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ChangeStateOfDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ChangeStateOfDataSource] GO CREATE PROCEDURE [dbo].[ChangeStateOfDataSource] @ItemID [uniqueidentifier], @Enable bit AS IF @Enable != 0 BEGIN UPDATE [DataSource] SET [Flags] = [Flags] | 1 WHERE [ItemID] = @ItemID END ELSE BEGIN UPDATE [DataSource] SET [Flags] = [Flags] & 0x7FFFFFFE WHERE [ItemID] = @ItemID END GO GRANT EXECUTE ON [dbo].[ChangeStateOfDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindItemsByDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindItemsByDataSource] GO CREATE PROCEDURE [dbo].[FindItemsByDataSource] @ItemID uniqueidentifier, @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.UserName, SUSER_SNAME(MU.Sid), MU.UserName, C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType INNER JOIN DataSource AS DS ON C.ItemID = DS.ItemID WHERE DS.Link = @ItemID GO GRANT EXECUTE ON [dbo].[FindItemsByDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CopyExecutionSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CopyExecutionSnapshot] GO CREATE PROCEDURE [dbo].[CopyExecutionSnapshot] @SourceReportID uniqueidentifier, @TargetReportID uniqueidentifier, @ReservedUntilUTC datetime AS DECLARE @SourceSnapshotDataID uniqueidentifier SET @SourceSnapshotDataID = (SELECT SnapshotDataID FROM Catalog WHERE ItemID = @SourceReportID) DECLARE @TargetSnapshotDataID uniqueidentifier SET @TargetSnapshotDataID = newid() DECLARE @ChunkID uniqueidentifier IF @SourceSnapshotDataID IS NOT NULL BEGIN -- We need to copy entries in SnapshotData and ChunkData tables. INSERT INTO SnapshotData (SnapshotDataID, CreatedDate, ParamsHash, QueryParams, EffectiveParams, Description, PermanentRefcount, TransientRefcount, ExpirationDate) SELECT @TargetSnapshotDataID, SD.CreatedDate, SD.ParamsHash, SD.QueryParams, SD.EffectiveParams, SD.Description, 1, 0, @ReservedUntilUTC FROM SnapshotData as SD WHERE SD.SnapshotDataID = @SourceSnapshotDataID INSERT INTO ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, ChunkFlags, Content, Version) SELECT newid(), @TargetSnapshotDataID, CD.ChunkName, CD.ChunkType, CD.ChunkFlags, CD.Content, CD.Version FROM ChunkData as CD WHERE CD.SnapshotDataID = @SourceSnapshotDataID UPDATE Target SET Target.SnapshotDataID = @TargetSnapshotDataID, Target.ExecutionTime = Source.ExecutionTime FROM Catalog Target, Catalog Source WHERE Source.ItemID = @SourceReportID AND Target.ItemID = @TargetReportID END GO GRANT EXECUTE ON [dbo].[CopyExecutionSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateRole] GO CREATE PROCEDURE [dbo].[CreateRole] @RoleID as uniqueidentifier, @RoleName as nvarchar(260), @Description as nvarchar(512) = null, @TaskMask as nvarchar(32), @RoleFlags as tinyint AS INSERT INTO Roles (RoleID, RoleName, Description, TaskMask, RoleFlags) VALUES (@RoleID, @RoleName, @Description, @TaskMask, @RoleFlags) GO GRANT EXECUTE ON [dbo].[CreateRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetRoles]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetRoles] GO CREATE PROCEDURE [dbo].[GetRoles] @RoleFlags as tinyint = NULL AS SELECT RoleName, Description, TaskMask FROM Roles WHERE (@RoleFlags is NULL) OR (RoleFlags = @RoleFlags) GO GRANT EXECUTE ON [dbo].[GetRoles] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteRole] GO -- Delete all policies associated with this role CREATE PROCEDURE [dbo].[DeleteRole] @RoleName nvarchar(260) AS -- if you call this, you must delete/reconstruct all policies associated with this role DELETE FROM Roles WHERE RoleName = @RoleName GO GRANT EXECUTE ON [dbo].[DeleteRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadRoleProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadRoleProperties] GO CREATE PROCEDURE [dbo].[ReadRoleProperties] @RoleName as nvarchar(260) AS SELECT Description, TaskMask, RoleFlags FROM Roles WHERE RoleName = @RoleName GO GRANT EXECUTE ON [dbo].[ReadRoleProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetRoleProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetRoleProperties] GO CREATE PROCEDURE [dbo].[SetRoleProperties] @RoleName as nvarchar(260), @Description as nvarchar(512) = NULL, @TaskMask as nvarchar(32), @RoleFlags as tinyint AS DECLARE @ExistingRoleFlags as tinyint SET @ExistingRoleFlags = (SELECT RoleFlags FROM Roles WHERE RoleName = @RoleName) IF @ExistingRoleFlags IS NULL BEGIN RETURN END IF @ExistingRoleFlags <> @RoleFlags BEGIN RAISERROR ('Bad role flags', 16, 1) END UPDATE Roles SET Description = @Description, TaskMask = @TaskMask, RoleFlags = @RoleFlags WHERE RoleName = @RoleName GO GRANT EXECUTE ON [dbo].[SetRoleProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPoliciesForRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPoliciesForRole] GO CREATE PROCEDURE [dbo].[GetPoliciesForRole] @RoleName as nvarchar(260), @AuthType as int AS SELECT Policies.PolicyID, SecData.XmlDescription, Policies.PolicyFlag, Catalog.Type, Catalog.Path, ModelItemPolicy.CatalogItemID, ModelItemPolicy.ModelItemID, RelatedRoles.RoleID, RelatedRoles.RoleName, RelatedRoles.TaskMask, RelatedRoles.RoleFlags FROM Roles INNER JOIN PolicyUserRole ON Roles.RoleID = PolicyUserRole.RoleID INNER JOIN Policies ON PolicyUserRole.PolicyID = Policies.PolicyID INNER JOIN PolicyUserRole AS RelatedPolicyUserRole ON Policies.PolicyID = RelatedPolicyUserRole.PolicyID INNER JOIN Roles AS RelatedRoles ON RelatedPolicyUserRole.RoleID = RelatedRoles.RoleID LEFT OUTER JOIN SecData ON Policies.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog ON Policies.PolicyID = Catalog.PolicyID AND Catalog.PolicyRoot = 1 LEFT OUTER JOIN ModelItemPolicy ON Policies.PolicyID = ModelItemPolicy.PolicyID WHERE Roles.RoleName = @RoleName ORDER BY Policies.PolicyID GO GRANT EXECUTE ON [dbo].[GetPoliciesForRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdatePolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdatePolicy] GO CREATE PROCEDURE [dbo].[UpdatePolicy] @PolicyID as uniqueidentifier, @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @AuthType int AS UPDATE SecData SET NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND SecData.AuthType = @AuthType GO GRANT EXECUTE ON [dbo].[UpdatePolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetPolicy] GO -- this assumes the item exists in the catalog CREATE PROCEDURE [dbo].[SetPolicy] @ItemName as nvarchar(425), @ItemNameLike as nvarchar(850), @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @XmlPolicy as ntext, @AuthType int, @PolicyID uniqueidentifier OUTPUT AS SELECT @PolicyID = (SELECT PolicyID FROM Catalog WHERE Path = @ItemName AND PolicyRoot = 1) IF (@PolicyID IS NULL) BEGIN -- this is not a policy root SET @PolicyID = newid() INSERT INTO Policies (PolicyID, PolicyFlag) VALUES (@PolicyID, 0) INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) DECLARE @OldPolicyID as uniqueidentifier SELECT @OldPolicyID = (SELECT PolicyID FROM Catalog WHERE Path = @ItemName) -- update item and children that shared the old policy UPDATE Catalog SET PolicyID = @PolicyID, PolicyRoot = 1 WHERE Path = @ItemName UPDATE Catalog SET PolicyID = @PolicyID WHERE Path LIKE @ItemNameLike ESCAPE '*' AND Catalog.PolicyID = @OldPolicyID END ELSE BEGIN UPDATE Policies SET PolicyFlag = 0 WHERE Policies.PolicyID = @PolicyID DECLARE @SecDataID as uniqueidentifier SELECT @SecDataID = (SELECT SecDataID FROM SecData WHERE PolicyID = @PolicyID and AuthType = @AuthType) IF (@SecDataID IS NULL) BEGIN -- insert new sec desc's INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription ,NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN -- update existing sec desc's UPDATE SecData SET XmlDescription = @XmlPolicy, NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND AuthType = @AuthType END END DELETE FROM PolicyUserRole WHERE PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[SetPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSystemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSystemPolicy] GO -- update the system policy CREATE PROCEDURE [dbo].[SetSystemPolicy] @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @XmlPolicy as ntext, @AuthType as int, @PolicyID uniqueidentifier OUTPUT AS SELECT @PolicyID = (SELECT PolicyID FROM Policies WHERE PolicyFlag = 1) IF (@PolicyID IS NULL) BEGIN SET @PolicyID = newid() INSERT INTO Policies (PolicyID, PolicyFlag) VALUES (@PolicyID, 1) INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN DECLARE @SecDataID as uniqueidentifier SELECT @SecDataID = (SELECT SecDataID FROM SecData WHERE PolicyID = @PolicyID and AuthType = @AuthType) IF (@SecDataID IS NULL) BEGIN -- insert new sec desc's INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN -- update existing sec desc's UPDATE SecData SET XmlDescription = @XmlPolicy, NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND AuthType = @AuthType END END DELETE FROM PolicyUserRole WHERE PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[SetSystemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetModelItemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetModelItemPolicy] GO -- update the system policy CREATE PROCEDURE [dbo].[SetModelItemPolicy] @CatalogItemID as uniqueidentifier, @ModelItemID as nvarchar(425), @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @XmlPolicy as ntext, @AuthType as int, @PolicyID uniqueidentifier OUTPUT AS SELECT @PolicyID = (SELECT PolicyID FROM ModelItemPolicy WHERE CatalogItemID = @CatalogItemID AND ModelItemID = @ModelItemID ) IF (@PolicyID IS NULL) BEGIN SET @PolicyID = newid() INSERT INTO Policies (PolicyID, PolicyFlag) VALUES (@PolicyID, 2) INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) INSERT INTO ModelItemPolicy (ID, CatalogItemID, ModelItemID, PolicyID) VALUES (newid(), @CatalogItemID, @ModelItemID, @PolicyID) END ELSE BEGIN DECLARE @SecDataID as uniqueidentifier SELECT @SecDataID = (SELECT SecDataID FROM SecData WHERE PolicyID = @PolicyID and AuthType = @AuthType) IF (@SecDataID IS NULL) BEGIN -- insert new sec desc's INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN -- update existing sec desc's UPDATE SecData SET XmlDescription = @XmlPolicy, NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND AuthType = @AuthType END END DELETE FROM PolicyUserRole WHERE PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[SetModelItemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdatePolicyPrincipal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdatePolicyPrincipal] GO CREATE PROCEDURE [dbo].[UpdatePolicyPrincipal] @PolicyID uniqueidentifier, @PrincipalSid varbinary(85) = NULL, @PrincipalName nvarchar(260), @PrincipalAuthType int, @RoleName nvarchar(260), @PrincipalID uniqueidentifier OUTPUT, @RoleID uniqueidentifier OUTPUT AS EXEC GetPrincipalID @PrincipalSid , @PrincipalName, @PrincipalAuthType, @PrincipalID OUTPUT SELECT @RoleID = (SELECT RoleID FROM Roles WHERE RoleName = @RoleName) INSERT INTO PolicyUserRole (ID, RoleID, UserID, PolicyID) VALUES (newid(), @RoleID, @PrincipalID, @PolicyID) GO GRANT EXECUTE ON [dbo].[UpdatePolicyPrincipal] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdatePolicyRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdatePolicyRole] GO CREATE PROCEDURE [dbo].[UpdatePolicyRole] @PolicyID uniqueidentifier, @PrincipalID uniqueidentifier, @RoleName nvarchar(260), @RoleID uniqueidentifier OUTPUT AS SELECT @RoleID = (SELECT RoleID FROM Roles WHERE RoleName = @RoleName) INSERT INTO PolicyUserRole (ID, RoleID, UserID, PolicyID) VALUES (newid(), @RoleID, @PrincipalID, @PolicyID) GO GRANT EXECUTE ON [dbo].[UpdatePolicyRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPolicy] GO CREATE PROCEDURE [dbo].[GetPolicy] @ItemName as nvarchar(425), @AuthType int AS SELECT SecData.XmlDescription, Catalog.PolicyRoot , SecData.NtSecDescPrimary, Catalog.Type FROM Catalog INNER JOIN Policies ON Catalog.PolicyID = Policies.PolicyID LEFT OUTER JOIN SecData ON Policies.PolicyID = SecData.PolicyID AND AuthType = @AuthType WHERE Catalog.Path = @ItemName AND PolicyFlag = 0 GO GRANT EXECUTE ON [dbo].[GetPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSystemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSystemPolicy] GO CREATE PROCEDURE [dbo].[GetSystemPolicy] @AuthType int AS SELECT SecData.NtSecDescPrimary, SecData.XmlDescription FROM Policies LEFT OUTER JOIN SecData ON Policies.PolicyID = SecData.PolicyID AND AuthType = @AuthType WHERE PolicyFlag = 1 GO GRANT EXECUTE ON [dbo].[GetSystemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeletePolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeletePolicy] GO CREATE PROCEDURE [dbo].[DeletePolicy] @ItemName as nvarchar(425) AS DECLARE @OldPolicyID uniqueidentifier SELECT @OldPolicyID = (SELECT PolicyID FROM Catalog WHERE Catalog.Path = @ItemName) UPDATE Catalog SET PolicyID = (SELECT Parent.PolicyID FROM Catalog Parent, Catalog WHERE Parent.ItemID = Catalog.ParentID AND Catalog.Path = @ItemName), PolicyRoot = 0 WHERE Catalog.PolicyID = @OldPolicyID DELETE Policies FROM Policies WHERE Policies.PolicyID = @OldPolicyID GO GRANT EXECUTE ON [dbo].[DeletePolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateSession]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateSession] GO -- Writes or updates session record CREATE PROCEDURE [dbo].[CreateSession] @SessionID as varchar(32), @CompiledDefinition as uniqueidentifier = NULL, @SnapshotDataID as uniqueidentifier = NULL, @IsPermanentSnapshot as bit = NULL, @ReportPath as nvarchar(440) = NULL, @Timeout as int, @AutoRefreshSeconds as int = NULL, @DataSourceInfo as image = NULL, @OwnerName as nvarchar (260), @OwnerSid as varbinary (85) = NULL, @AuthType as int, @EffectiveParams as ntext = NULL, @HistoryDate as datetime = NULL, @PageHeight as float = NULL, @PageWidth as float = NULL, @TopMargin as float = NULL, @BottomMargin as float = NULL, @LeftMargin as float = NULL, @RightMargin as float = NULL, @ExecutionType as smallint = NULL AS UPDATE PS SET PS.RefCount = 1 FROM ReportServerTempDB.dbo.PersistedStream as PS WHERE PS.SessionID = @SessionID UPDATE SN SET TransientRefcount = TransientRefcount + 1 FROM SnapshotData AS SN WHERE SN.SnapshotDataID = @SnapshotDataID UPDATE SN SET TransientRefcount = TransientRefcount + 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN WHERE SN.SnapshotDataID = @SnapshotDataID DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT DECLARE @now datetime SET @now = GETDATE() INSERT INTO ReportServerTempDB.dbo.SessionData ( SessionID, CompiledDefinition, SnapshotDataID, IsPermanentSnapshot, ReportPath, Timeout, AutoRefreshSeconds, Expiration, DataSourceInfo, OwnerID, EffectiveParams, CreationTime, HistoryDate, PageHeight, PageWidth, TopMargin, BottomMargin, LeftMargin, RightMargin, ExecutionType ) VALUES ( @SessionID, @CompiledDefinition, @SnapshotDataID, @IsPermanentSnapshot, @ReportPath, @Timeout, @AutoRefreshSeconds, DATEADD(s, @Timeout, @now), @DataSourceInfo, @OwnerID, @EffectiveParams, @now, @HistoryDate, @PageHeight, @PageWidth, @TopMargin, @BottomMargin, @LeftMargin, @RightMargin, @ExecutionType ) GO GRANT EXECUTE ON [dbo].[CreateSession] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteModelItemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteModelItemPolicy] GO CREATE PROCEDURE [dbo].[DeleteModelItemPolicy] @CatalogItemID as uniqueidentifier, @ModelItemID as nvarchar(425) AS DECLARE @PolicyID uniqueidentifier SELECT @PolicyID = (SELECT PolicyID FROM ModelItemPolicy WHERE CatalogItemID = @CatalogItemID AND ModelItemID = @ModelItemID) DELETE Policies FROM Policies WHERE Policies.PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[DeleteModelItemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteAllModelItemPolicies]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteAllModelItemPolicies] GO CREATE PROCEDURE [dbo].[DeleteAllModelItemPolicies] @Path as nvarchar(450) AS DELETE Policies FROM Policies AS P INNER JOIN ModelItemPolicy AS MIP ON P.PolicyID = MIP.PolicyID INNER JOIN Catalog AS C ON MIP.CatalogItemID = C.ItemID WHERE C.[Path] = @Path GO GRANT EXECUTE ON [dbo].[DeleteAllModelItemPolicies] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelItemInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelItemInfo] GO CREATE PROCEDURE [dbo].[GetModelItemInfo] @Path nvarchar (425), @AuthType int AS SELECT C.[ItemID], C.[Type], C.[ModifiedDate], C.[Description], SD.[NtSecDescPrimary] FROM [Catalog] AS C LEFT OUTER JOIN [SecData] AS SD ON C.[PolicyID] = SD.[PolicyID] AND SD.[AuthType] = @AuthType WHERE C.[Path] = @Path SELECT MIP.[ModelItemID], SD.[NtSecDescPrimary], SD.[XmlDescription] FROM [Catalog] AS C INNER JOIN [ModelItemPolicy] AS MIP ON C.[ItemID] = MIP.[CatalogItemID] LEFT OUTER JOIN [SecData] AS SD ON MIP.[PolicyID] = SD.[PolicyID] WHERE C.[Path] = @Path GO GRANT EXECUTE ON [dbo].[GetModelItemInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelDefinition]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelDefinition] GO CREATE PROCEDURE [dbo].[GetModelDefinition] @CatalogItemID as uniqueidentifier AS SELECT C.[Content] FROM [Catalog] AS C WHERE C.[ItemID] = @CatalogItemID GO GRANT EXECUTE ON [dbo].[GetModelDefinition] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddModelPerspective]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddModelPerspective] GO CREATE PROCEDURE [dbo].[AddModelPerspective] @ModelID as uniqueidentifier, @PerspectiveID as ntext, @PerspectiveName as ntext = null, @PerspectiveDescription as ntext = null AS INSERT INTO [ModelPerspective] ([ID], [ModelID], [PerspectiveID], [PerspectiveName], [PerspectiveDescription]) VALUES (newid(), @ModelID, @PerspectiveID, @PerspectiveName, @PerspectiveDescription) GO GRANT EXECUTE ON [dbo].[AddModelPerspective] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteModelPerspectives]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteModelPerspectives] GO CREATE PROCEDURE [dbo].[DeleteModelPerspectives] @ModelID as uniqueidentifier AS DELETE FROM [ModelPerspective] WHERE [ModelID] = @ModelID GO GRANT EXECUTE ON [dbo].[DeleteModelPerspectives] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelsAndPerspectives]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelsAndPerspectives] GO CREATE PROCEDURE [dbo].[GetModelsAndPerspectives] @AuthType int AS SELECT C.[PolicyID], SD.[NtSecDescPrimary], C.[ItemID], C.[Path], C.[Description], P.[PerspectiveID], P.[PerspectiveName], P.[PerspectiveDescription] FROM [Catalog] as C LEFT OUTER JOIN [ModelPerspective] as P ON C.[ItemID] = P.[ModelID] LEFT OUTER JOIN [SecData] AS SD ON C.[PolicyID] = SD.[PolicyID] AND SD.[AuthType] = @AuthType WHERE C.[Type] = 6 -- Model ORDER BY C.[Path] GO GRANT EXECUTE ON [dbo].[GetModelsAndPerspectives] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelPerspectives]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelPerspectives] GO CREATE PROCEDURE [dbo].[GetModelPerspectives] @Path nvarchar (425), @AuthType int AS SELECT C.[Type], SD.[NtSecDescPrimary], C.[Description] FROM [Catalog] as C LEFT OUTER JOIN [SecData] AS SD ON C.[PolicyID] = SD.[PolicyID] AND SD.[AuthType] = @AuthType WHERE [Path] = @Path SELECT P.[PerspectiveID], P.[PerspectiveName], P.[PerspectiveDescription] FROM [Catalog] as C INNER JOIN [ModelPerspective] as P ON C.[ItemID] = P.[ModelID] WHERE [Path] = @Path GO GRANT EXECUTE ON [dbo].[GetModelPerspectives] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DereferenceSessionSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DereferenceSessionSnapshot] GO CREATE PROCEDURE [dbo].[DereferenceSessionSnapshot] @SessionID as varchar(32), @OwnerID as uniqueidentifier AS UPDATE SN SET TransientRefcount = TransientRefcount - 1 FROM SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.SessionData AS SE ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID UPDATE SN SET TransientRefcount = TransientRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.SessionData AS SE ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[DereferenceSessionSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSessionData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSessionData] GO -- Writes or updates session record CREATE PROCEDURE [dbo].[SetSessionData] @SessionID as varchar(32), @ReportPath as nvarchar(440), @HistoryDate as datetime = NULL, @Timeout as int, @AutoRefreshSeconds as int = NULL, @EffectiveParams ntext = NULL, @OwnerSid as varbinary (85) = NULL, @OwnerName as nvarchar (260), @AuthType as int, @ShowHideInfo as image = NULL, @DataSourceInfo as image = NULL, @SnapshotDataID as uniqueidentifier = NULL, @IsPermanentSnapshot as bit = NULL, @SnapshotTimeoutSeconds as int = NULL, @HasInteractivity as bit, @SnapshotExpirationDate as datetime = NULL, @ExecutionType smallint = NULL AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT DECLARE @now datetime SET @now = GETDATE() -- is there a session for the same report ? DECLARE @OldSnapshotDataID uniqueidentifier DECLARE @OldIsPermanentSnapshot bit DECLARE @OldSessionID varchar(32) SELECT @OldSessionID = SessionID, @OldSnapshotDataID = SnapshotDataID, @OldIsPermanentSnapshot = IsPermanentSnapshot FROM ReportServerTempDB.dbo.SessionData WITH (XLOCK) WHERE SessionID = @SessionID IF @OldSessionID IS NOT NULL BEGIN -- Yes, update it IF @OldSnapshotDataID != @SnapshotDataID or @SnapshotDataID is NULL BEGIN EXEC DereferenceSessionSnapshot @SessionID, @OwnerID END UPDATE ReportServerTempDB.dbo.SessionData SET SnapshotDataID = @SnapshotDataID, IsPermanentSnapshot = @IsPermanentSnapshot, Timeout = @Timeout, AutoRefreshSeconds = @AutoRefreshSeconds, SnapshotExpirationDate = @SnapshotExpirationDate, -- we want database session to expire later than in-memory session Expiration = DATEADD(s, @Timeout+10, @now), ShowHideInfo = @ShowHideInfo, DataSourceInfo = @DataSourceInfo, ExecutionType = @ExecutionType -- EffectiveParams = @EffectiveParams, -- no need to update user params as they are always same -- ReportPath = @ReportPath -- OwnerID = @OwnerID WHERE SessionID = @SessionID -- update expiration date on a snapshot that we reference IF @IsPermanentSnapshot != 0 BEGIN UPDATE SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutSeconds, @now) WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutSeconds, @now) WHERE SnapshotDataID = @SnapshotDataID END END ELSE BEGIN -- no, insert it UPDATE PS SET PS.RefCount = 1 FROM ReportServerTempDB.dbo.PersistedStream as PS WHERE PS.SessionID = @SessionID INSERT INTO ReportServerTempDB.dbo.SessionData (SessionID, SnapshotDataID, IsPermanentSnapshot, ReportPath, EffectiveParams, Timeout, AutoRefreshSeconds, Expiration, ShowHideInfo, DataSourceInfo, OwnerID, CreationTime, HasInteractivity, SnapshotExpirationDate, HistoryDate, ExecutionType) VALUES (@SessionID, @SnapshotDataID, @IsPermanentSnapshot, @ReportPath, @EffectiveParams, @Timeout, @AutoRefreshSeconds, DATEADD(s, @Timeout, @now), @ShowHideInfo, @DataSourceInfo, @OwnerID, @now, @HasInteractivity, @SnapshotExpirationDate, @HistoryDate, @ExecutionType) END GO GRANT EXECUTE ON [dbo].[SetSessionData] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteLockSession]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteLockSession] GO CREATE PROCEDURE [dbo].[WriteLockSession] @SessionID as varchar(32) AS INSERT INTO ReportServerTempDB.dbo.SessionLock WITH (ROWLOCK) (SessionID) VALUES (@SessionID) GO GRANT EXECUTE ON [dbo].[WriteLockSession] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CheckSessionLock]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CheckSessionLock] GO CREATE PROCEDURE [dbo].[CheckSessionLock] @SessionID as varchar(32) AS DECLARE @Selected nvarchar(32) SELECT @Selected=SessionID FROM ReportServerTempDB.dbo.SessionLock WITH (ROWLOCK) WHERE SessionID = @SessionID GO GRANT EXECUTE ON [dbo].[CheckSessionLock] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadLockSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadLockSnapshot] GO CREATE PROCEDURE [dbo].[ReadLockSnapshot] @SnapshotDataID as uniqueidentifier AS SELECT SnapshotDataID FROM SnapshotData WITH (REPEATABLEREAD, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID GO GRANT EXECUTE ON [dbo].[ReadLockSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSessionData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSessionData] GO -- Get record from session data, update session and snapshot CREATE PROCEDURE [dbo].[GetSessionData] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @SnapshotTimeoutMinutes as int AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT DECLARE @now as datetime SET @now = GETDATE() DECLARE @DBSessionID varchar(32) DECLARE @SnapshotDataID uniqueidentifier DECLARE @IsPermanentSnapshot bit EXEC CheckSessionLock @SessionID = @SessionID SELECT @DBSessionID = SE.SessionID, @SnapshotDataID = SE.SnapshotDataID, @IsPermanentSnapshot = SE.IsPermanentSnapshot FROM ReportServerTempDB.dbo.SessionData AS SE WITH (XLOCK) WHERE SE.OwnerID = @OwnerID AND SE.SessionID = @SessionID AND SE.Expiration > @now -- We need this update to keep session around while we process it. -- TODO: This assumes that it will be processed within the session timeout. UPDATE SE SET Expiration = DATEADD(s, Timeout, @now) FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @DBSessionID -- Update snapshot expiration to prevent early deletion -- If session uses snapshot, it is already refcounted. However, if session lasts for too long, -- snapshot may expire. Therefore, every time we touch snapshot we should change expiration. IF (@DBSessionID IS NOT NULL) BEGIN -- We return something only if session is present IF @IsPermanentSnapshot != 0 BEGIN -- If session has snapshot and it is permanent SELECT SN.SnapshotDataID, SE.ShowHideInfo, SE.DataSourceInfo, SN.Description, SE.EffectiveParams, SN.CreatedDate, SE.IsPermanentSnapshot, SE.CreationTime, SE.HasInteractivity, SE.Timeout, SE.SnapshotExpirationDate, SE.ReportPath, SE.HistoryDate, SE.CompiledDefinition, SN.PageCount, SN.HasDocMap, SE.Expiration, SN.EffectiveParams, SE.PageHeight, SE.PageWidth, SE.TopMargin, SE.BottomMargin, SE.LeftMargin, SE.RightMargin, SE.AutoRefreshSeconds, SE.ExecutionType FROM ReportServerTempDB.dbo.SessionData AS SE INNER JOIN SnapshotData AS SN ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @DBSessionID UPDATE SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutMinutes, @now) WHERE SnapshotDataID = @SnapshotDataID END ELSE IF @IsPermanentSnapshot = 0 BEGIN -- If session has snapshot and it is temporary SELECT SN.SnapshotDataID, SE.ShowHideInfo, SE.DataSourceInfo, SN.Description, SE.EffectiveParams, SN.CreatedDate, SE.IsPermanentSnapshot, SE.CreationTime, SE.HasInteractivity, SE.Timeout, SE.SnapshotExpirationDate, SE.ReportPath, SE.HistoryDate, SE.CompiledDefinition, SN.PageCount, SN.HasDocMap, SE.Expiration, SN.EffectiveParams, SE.PageHeight, SE.PageWidth, SE.TopMargin, SE.BottomMargin, SE.LeftMargin, SE.RightMargin, SE.AutoRefreshSeconds, SE.ExecutionType FROM ReportServerTempDB.dbo.SessionData AS SE INNER JOIN ReportServerTempDB.dbo.SnapshotData AS SN ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @DBSessionID UPDATE ReportServerTempDB.dbo.SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutMinutes, @now) WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN -- If session doesn't have snapshot SELECT null, SE.ShowHideInfo, SE.DataSourceInfo, null, SE.EffectiveParams, null, SE.IsPermanentSnapshot, SE.CreationTime, SE.HasInteractivity, SE.Timeout, SE.SnapshotExpirationDate, SE.ReportPath, SE.HistoryDate, SE.CompiledDefinition, null, null, SE.Expiration, null, SE.PageHeight, SE.PageWidth, SE.TopMargin, SE.BottomMargin, SE.LeftMargin, SE.RightMargin, SE.AutoRefreshSeconds, SE.ExecutionType FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @DBSessionID END END GO GRANT EXECUTE ON [dbo].[GetSessionData] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapshotFromHistory]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapshotFromHistory] GO CREATE PROCEDURE [dbo].[GetSnapshotFromHistory] @Path nvarchar (425), @SnapshotDate datetime, @AuthType int AS SELECT Catalog.ItemID, Catalog.Type, SnapshotData.SnapshotDataID, SnapshotData.DependsOnUser, SnapshotData.Description, SecData.NtSecDescPrimary, Catalog.[Property] FROM SnapshotData INNER JOIN History ON History.SnapshotDataID = SnapshotData.SnapshotDataID INNER JOIN Catalog ON History.ReportID = Catalog.ItemID LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Catalog.Path = @Path AND History.SnapshotDate = @SnapshotDate GO GRANT EXECUTE ON [dbo].[GetSnapshotFromHistory] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredSessions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredSessions] GO CREATE PROCEDURE [dbo].[CleanExpiredSessions] @SessionsCleaned int OUTPUT AS SET DEADLOCK_PRIORITY LOW DECLARE @now as datetime SET @now = GETDATE() CREATE TABLE #tempSession (SessionID varchar(32) COLLATE Latin1_General_CI_AS_KS_WS, SnapshotDataID uniqueidentifier, CompiledDefinition uniqueidentifier) INSERT INTO #tempSession SELECT TOP 20 SessionID, SnapshotDataID, CompiledDefinition FROM ReportServerTempDB.dbo.SessionData WITH (XLOCK) WHERE Expiration < @now SET @SessionsCleaned = @@ROWCOUNT IF @SessionsCleaned = 0 RETURN -- Mark persisted streams for this session to be deleted UPDATE PS SET RefCount = 0, ExpirationDate = GETDATE() FROM ReportServerTempDB.dbo.PersistedStream AS PS INNER JOIN #tempSession on PS.SessionID = #tempsession.SessionID DELETE SE FROM ReportServerTempDB.dbo.SessionData AS SE INNER JOIN #tempSession on SE.SessionID = #tempsession.SessionID UPDATE SN SET TransientRefcount = TransientRefcount-1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN #tempSession AS SE ON SN.SnapshotDataID = SE.CompiledDefinition UPDATE SN SET TransientRefcount = TransientRefcount- (SELECT COUNT(*) FROM #tempSession AS SE1 WHERE SE1.SnapshotDataID = SN.SnapshotDataID) FROM SnapshotData AS SN INNER JOIN #tempSession AS SE ON SN.SnapshotDataID = SE.SnapshotDataID UPDATE SN SET TransientRefcount = TransientRefcount- (SELECT COUNT(*) FROM #tempSession AS SE1 WHERE SE1.SnapshotDataID = SN.SnapshotDataID) FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN #tempSession AS SE ON SN.SnapshotDataID = SE.SnapshotDataID GO GRANT EXECUTE ON [dbo].[CleanExpiredSessions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredCache]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredCache] GO CREATE PROCEDURE [dbo].[CleanExpiredCache] AS DECLARE @now as datetime SET @now = DATEADD(minute, -1, GETDATE()) UPDATE SN SET PermanentRefcount = PermanentRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON SN.SnapshotDataID = EC.SnapshotDataID WHERE EC.AbsoluteExpiration < @now DELETE EC FROM ReportServerTempDB.dbo.ExecutionCache AS EC WHERE EC.AbsoluteExpiration < @now GO GRANT EXECUTE ON [dbo].[CleanExpiredCache] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSessionCredentials]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSessionCredentials] GO CREATE PROCEDURE [dbo].[SetSessionCredentials] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @DataSourceInfo as image = NULL, @Expiration as datetime, @EffectiveParams as ntext = NULL AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT EXEC DereferenceSessionSnapshot @SessionID, @OwnerID UPDATE SE SET SE.DataSourceInfo = @DataSourceInfo, SE.SnapshotDataID = null, SE.IsPermanentSnapshot = null, SE.SnapshotExpirationDate = null, SE.ShowHideInfo = null, SE.HasInteractivity = null, SE.AutoRefreshSeconds = null, SE.Expiration = @Expiration, SE.EffectiveParams = @EffectiveParams FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[SetSessionCredentials] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSessionParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSessionParameters] GO CREATE PROCEDURE [dbo].[SetSessionParameters] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @EffectiveParams as ntext = NULL AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT UPDATE SE SET SE.EffectiveParams = @EffectiveParams FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[SetSessionParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ClearSessionSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ClearSessionSnapshot] GO CREATE PROCEDURE [dbo].[ClearSessionSnapshot] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @Expiration as datetime AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT EXEC DereferenceSessionSnapshot @SessionID, @OwnerID UPDATE SE SET SE.SnapshotDataID = null, SE.IsPermanentSnapshot = null, SE.SnapshotExpirationDate = null, SE.ShowHideInfo = null, SE.HasInteractivity = null, SE.AutoRefreshSeconds = null, SE.Expiration = @Expiration FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[ClearSessionSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RemoveReportFromSession]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RemoveReportFromSession] GO CREATE PROCEDURE [dbo].[RemoveReportFromSession] @SessionID as varchar(32), @ReportPath as nvarchar(440), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT EXEC DereferenceSessionSnapshot @SessionID, @OwnerID DELETE SE FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.ReportPath = @ReportPath AND SE.OwnerID = @OwnerID -- Delete any persisted streams associated with this session UPDATE PS SET PS.RefCount = 0, PS.ExpirationDate = GETDATE() FROM ReportServerTempDB.dbo.PersistedStream AS PS WHERE PS.SessionID = @SessionID GO GRANT EXECUTE ON [dbo].[RemoveReportFromSession] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanBrokenSnapshots]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanBrokenSnapshots] GO CREATE PROCEDURE [dbo].[CleanBrokenSnapshots] @Machine nvarchar(512), @SnapshotsCleaned int OUTPUT, @ChunksCleaned int OUTPUT, @TempSnapshotID uniqueidentifier OUTPUT AS SET DEADLOCK_PRIORITY LOW DECLARE @now AS datetime SELECT @now = GETDATE() CREATE TABLE #tempSnapshot (SnapshotDataID uniqueidentifier) INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM SnapshotData WITH (NOLOCK) where SnapshotData.PermanentRefcount <= 0 AND ExpirationDate < @now SET @SnapshotsCleaned = @@ROWCOUNT DELETE ChunkData FROM ChunkData INNER JOIN #tempSnapshot ON ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @@ROWCOUNT DELETE SnapshotData FROM SnapshotData INNER JOIN #tempSnapshot ON SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID TRUNCATE TABLE #tempSnapshot INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM ReportServerTempDB.dbo.SnapshotData WITH (NOLOCK) where ReportServerTempDB.dbo.SnapshotData.PermanentRefcount <= 0 AND ReportServerTempDB.dbo.SnapshotData.ExpirationDate < @now AND ReportServerTempDB.dbo.SnapshotData.Machine = @Machine SET @SnapshotsCleaned = @SnapshotsCleaned + @@ROWCOUNT SELECT @TempSnapshotID = (SELECT SnapshotDataID FROM #tempSnapshot) DELETE ReportServerTempDB.dbo.ChunkData FROM ReportServerTempDB.dbo.ChunkData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @ChunksCleaned + @@ROWCOUNT DELETE ReportServerTempDB.dbo.SnapshotData FROM ReportServerTempDB.dbo.SnapshotData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID GO GRANT EXECUTE ON [dbo].[CleanBrokenSnapshots] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanOrphanedSnapshots]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanOrphanedSnapshots] GO CREATE PROCEDURE [dbo].[CleanOrphanedSnapshots] @Machine nvarchar(512), @SnapshotsCleaned int OUTPUT, @ChunksCleaned int OUTPUT, @TempSnapshotID uniqueidentifier OUTPUT AS SET DEADLOCK_PRIORITY LOW CREATE TABLE #tempSnapshot (SnapshotDataID uniqueidentifier) INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM SnapshotData WITH (NOLOCK) where SnapshotData.PermanentRefcount = 0 AND SnapshotData.TransientRefcount = 0 SET @SnapshotsCleaned = @@ROWCOUNT DELETE ChunkData FROM ChunkData INNER JOIN #tempSnapshot ON ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @@ROWCOUNT DELETE SnapshotData FROM SnapshotData INNER JOIN #tempSnapshot ON SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID TRUNCATE TABLE #tempSnapshot INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM ReportServerTempDB.dbo.SnapshotData WITH (NOLOCK) where ReportServerTempDB.dbo.SnapshotData.PermanentRefcount = 0 AND ReportServerTempDB.dbo.SnapshotData.TransientRefcount = 0 AND ReportServerTempDB.dbo.SnapshotData.Machine = @Machine SET @SnapshotsCleaned = @SnapshotsCleaned + @@ROWCOUNT SELECT @TempSnapshotID = (SELECT SnapshotDataID FROM #tempSnapshot) DELETE ReportServerTempDB.dbo.ChunkData FROM ReportServerTempDB.dbo.ChunkData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @ChunksCleaned + @@ROWCOUNT DELETE ReportServerTempDB.dbo.SnapshotData FROM ReportServerTempDB.dbo.SnapshotData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID GO GRANT EXECUTE ON [dbo].[CleanOrphanedSnapshots] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetCacheOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetCacheOptions] GO CREATE PROCEDURE [dbo].[SetCacheOptions] @Path as nvarchar(425), @CacheReport as bit, @ExpirationFlags as int, @CacheExpiration as int = NULL AS DECLARE @CachePolicyID as uniqueidentifier SELECT @CachePolicyID = (SELECT CachePolicyID FROM CachePolicy with (XLOCK) INNER JOIN Catalog ON Catalog.ItemID = CachePolicy.ReportID WHERE Catalog.Path = @Path) IF @CachePolicyID IS NULL -- no policy exists BEGIN IF @CacheReport = 1 -- create a new one BEGIN INSERT INTO CachePolicy (CachePolicyID, ReportID, ExpirationFlags, CacheExpiration) (SELECT NEWID(), ItemID, @ExpirationFlags, @CacheExpiration FROM Catalog WHERE Catalog.Path = @Path) END -- ELSE if it has no policy and we want to remove its policy do nothing END ELSE -- existing policy BEGIN IF @CacheReport = 1 BEGIN UPDATE CachePolicy SET ExpirationFlags = @ExpirationFlags, CacheExpiration = @CacheExpiration WHERE CachePolicyID = @CachePolicyID EXEC FlushReportFromCache @Path END ELSE BEGIN DELETE FROM CachePolicy WHERE CachePolicyID = @CachePolicyID EXEC FlushReportFromCache @Path END END GO GRANT EXECUTE ON [dbo].[SetCacheOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCacheOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetCacheOptions] GO CREATE PROCEDURE [dbo].[GetCacheOptions] @Path as nvarchar(425) AS SELECT ExpirationFlags, CacheExpiration, S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type] FROM CachePolicy INNER JOIN Catalog ON Catalog.ItemID = CachePolicy.ReportID LEFT outer join reportschedule rs on catalog.itemid = rs.reportid and rs.reportaction = 3 LEFT OUTER JOIN [Schedule] S ON S.ScheduleID = rs.ScheduleID LEFT OUTER JOIN [Users] Owner on Owner.UserID = S.[CreatedById] WHERE Catalog.Path = @Path GO GRANT EXECUTE ON [dbo].[GetCacheOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddReportToCache]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddReportToCache] GO CREATE PROCEDURE [dbo].[AddReportToCache] @ReportID as uniqueidentifier, @ExecutionDate datetime, @SnapshotDataID uniqueidentifier, @ExpirationDate datetime OUTPUT, @ScheduleID uniqueidentifier OUTPUT AS DECLARE @ExpirationFlags as int DECLARE @Timeout as int SET @ExpirationDate = NULL SET @ScheduleID = NULL SET @ExpirationFlags = (SELECT ExpirationFlags FROM CachePolicy WHERE ReportID = @ReportID) IF @ExpirationFlags = 1 -- timeout based BEGIN SET @Timeout = (SELECT CacheExpiration FROM CachePolicy WHERE ReportID = @ReportID) SET @ExpirationDate = DATEADD(n, @Timeout, @ExecutionDate) END ELSE IF @ExpirationFlags = 2 -- schedule based BEGIN SET @ScheduleID = (SELECT s.ScheduleID FROM Schedule s INNER JOIN ReportSchedule rs on rs.ScheduleID = s.ScheduleID and rs.ReportAction = 3 WHERE rs.ReportID = @ReportID) SET @ExpirationDate = (SELECT Schedule.NextRunTime FROM Schedule with (XLOCK) WHERE Schedule.ScheduleID = @ScheduleID) END ELSE BEGIN RAISERROR('Invalid cache flags', 16, 1) END -- and to the report cache INSERT INTO ReportServerTempDB.dbo.ExecutionCache (ExecutionCacheID, ReportID, ExpirationFlags, AbsoluteExpiration, RelativeExpiration, SnapshotDataID) VALUES (newid(), @ReportID, @ExpirationFlags, @ExpirationDate, @Timeout, @SnapshotDataID ) UPDATE ReportServerTempDB.dbo.SnapshotData SET PermanentRefcount = PermanentRefcount + 1 WHERE SnapshotDataID = @SnapshotDataID; GO GRANT EXECUTE ON [dbo].[AddReportToCache] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetExecutionOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetExecutionOptions] GO CREATE PROCEDURE [dbo].[GetExecutionOptions] @Path nvarchar(425) AS SELECT ExecutionFlag, S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type] FROM Catalog LEFT OUTER JOIN ReportSchedule ON Catalog.ItemID = ReportSchedule.ReportID AND ReportSchedule.ReportAction = 1 LEFT OUTER JOIN [Schedule] S ON S.ScheduleID = ReportSchedule.ScheduleID LEFT OUTER JOIN [Users] Owner on Owner.UserID = S.[CreatedById] WHERE Catalog.Path = @Path GO GRANT EXECUTE ON [dbo].[GetExecutionOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetExecutionOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetExecutionOptions] GO CREATE PROCEDURE [dbo].[SetExecutionOptions] @Path as nvarchar(425), @ExecutionFlag as int, @ExecutionChanged as bit = 0 AS IF @ExecutionChanged = 0 BEGIN UPDATE Catalog SET ExecutionFlag = @ExecutionFlag WHERE Catalog.Path = @Path END ELSE BEGIN IF (@ExecutionFlag & 3) = 2 BEGIN -- set it to snapshot, flush cache EXEC FlushReportFromCache @Path DELETE CachePolicy FROM CachePolicy INNER JOIN Catalog ON CachePolicy.ReportID = Catalog.ItemID WHERE Catalog.Path = @Path END -- now clean existing snapshot and execution time if any UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 FROM SnapshotData INNER JOIN Catalog ON SnapshotData.SnapshotDataID = Catalog.SnapshotDataID WHERE Catalog.Path = @Path UPDATE Catalog SET ExecutionFlag = @ExecutionFlag, SnapshotDataID = NULL, ExecutionTime = NULL WHERE Catalog.Path = @Path END GO GRANT EXECUTE ON [dbo].[SetExecutionOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSnapshot] GO CREATE PROCEDURE [dbo].[UpdateSnapshot] @Path as nvarchar(425), @SnapshotDataID as uniqueidentifier, @executionDate as datetime AS DECLARE @OldSnapshotDataID uniqueidentifier SET @OldSnapshotDataID = (SELECT SnapshotDataID FROM Catalog WITH (XLOCK) WHERE Catalog.Path = @Path) -- update reference count in snapshot table UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount-1 WHERE SnapshotData.SnapshotDataID = @OldSnapshotDataID -- update catalog to point to the new execution snapshot UPDATE Catalog SET SnapshotDataID = @SnapshotDataID, ExecutionTime = @executionDate WHERE Catalog.Path = @Path UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount+1, TransientRefcount = TransientRefcount-1 WHERE SnapshotData.SnapshotDataID = @SnapshotDataID GO GRANT EXECUTE ON [dbo].[UpdateSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateChunkAndGetPointer]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateChunkAndGetPointer] GO CREATE PROCEDURE [dbo].[CreateChunkAndGetPointer] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int, @MimeType nvarchar(260) = NULL, @Version smallint, @Content image, @ChunkFlags tinyint = NULL, @ChunkPointer binary(16) OUTPUT AS DECLARE @ChunkID uniqueidentifier SET @ChunkID = NEWID() IF @IsPermanentSnapshot != 0 BEGIN DELETE ChunkData WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType INSERT INTO ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) VALUES (@ChunkID, @SnapshotDataID, @ChunkName, @ChunkType, @MimeType, @Version, @ChunkFlags, @Content) SELECT @ChunkPointer = TEXTPTR(Content) FROM ChunkData WHERE ChunkData.ChunkID = @ChunkID END ELSE BEGIN DELETE ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType INSERT INTO ReportServerTempDB.dbo.ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) VALUES (@ChunkID, @SnapshotDataID, @ChunkName, @ChunkType, @MimeType, @Version, @ChunkFlags, @Content) SELECT @ChunkPointer = TEXTPTR(Content) FROM ReportServerTempDB.dbo.ChunkData AS CH WHERE CH.ChunkID = @ChunkID END GO GRANT EXECUTE ON [dbo].[CreateChunkAndGetPointer] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteChunkPortion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteChunkPortion] GO CREATE PROCEDURE [dbo].[WriteChunkPortion] @ChunkPointer binary(16), @IsPermanentSnapshot bit, @DataIndex int = NULL, @DeleteLength int = NULL, @Content image AS IF @IsPermanentSnapshot != 0 BEGIN UPDATETEXT ChunkData.Content @ChunkPointer @DataIndex @DeleteLength @Content END ELSE BEGIN UPDATETEXT ReportServerTempDB.dbo.ChunkData.Content @ChunkPointer @DataIndex @DeleteLength @Content END GO GRANT EXECUTE ON [dbo].[WriteChunkPortion] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetChunkPointerAndLength]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetChunkPointerAndLength] GO CREATE PROCEDURE [dbo].[GetChunkPointerAndLength] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int AS IF @IsPermanentSnapshot != 0 BEGIN SELECT TEXTPTR(Content), DATALENGTH(Content), MimeType, ChunkFlags, Version FROM ChunkData AS CH WITH (HOLDLOCK, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END ELSE BEGIN SELECT TEXTPTR(Content), DATALENGTH(Content), MimeType, ChunkFlags, Version FROM ReportServerTempDB.dbo.ChunkData AS CH WITH (HOLDLOCK, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END GO GRANT EXECUTE ON [dbo].[GetChunkPointerAndLength] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetChunkInformation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetChunkInformation] GO CREATE PROCEDURE [dbo].[GetChunkInformation] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int AS IF @IsPermanentSnapshot != 0 BEGIN SELECT MimeType FROM ChunkData AS CH WITH (HOLDLOCK, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END ELSE BEGIN SELECT MimeType FROM ReportServerTempDB.dbo.ChunkData AS CH WITH (HOLDLOCK, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END GO GRANT EXECUTE ON [dbo].[GetChunkInformation] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadChunkPortion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadChunkPortion] GO CREATE PROCEDURE [dbo].[ReadChunkPortion] @ChunkPointer binary(16), @IsPermanentSnapshot bit, @DataIndex int, @Length int AS IF @IsPermanentSnapshot != 0 BEGIN READTEXT ChunkData.Content @ChunkPointer @DataIndex @Length END ELSE BEGIN READTEXT ReportServerTempDB.dbo.ChunkData.Content @ChunkPointer @DataIndex @Length END GO GRANT EXECUTE ON [dbo].[ReadChunkPortion] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CopyChunksOfType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CopyChunksOfType] GO CREATE PROCEDURE [dbo].[CopyChunksOfType] @FromSnapshotID uniqueidentifier, @FromIsPermanent bit, @ToSnapshotID uniqueidentifier, @ToIsPermanent bit, @ChunkType int AS IF @FromIsPermanent != 0 AND @ToIsPermanent = 0 BEGIN INSERT INTO ReportServerTempDB.dbo.ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) SELECT newid(), @ToSnapshotID, S.ChunkName, S.ChunkType, S.MimeType, S.Version, S.ChunkFlags, S.Content FROM ChunkData AS S WHERE S.SnapshotDataID = @FromSnapshotID AND S.ChunkType = @ChunkType AND NOT EXISTS( SELECT T.ChunkName FROM ReportServerTempDB.dbo.ChunkData AS T -- exclude the ones in the target WHERE T.ChunkName = S.ChunkName AND T.ChunkType = S.ChunkType AND T.SnapshotDataID = @ToSnapshotID) END ELSE IF @FromIsPermanent = 0 AND @ToIsPermanent = 0 BEGIN INSERT INTO ReportServerTempDB.dbo.ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) SELECT newid(), @ToSnapshotID, S.ChunkName, S.ChunkType, S.MimeType, S.Version, S.ChunkFlags, S.Content FROM ReportServerTempDB.dbo.ChunkData AS S WHERE S.SnapshotDataID = @FromSnapshotID AND S.ChunkType = @ChunkType AND NOT EXISTS( SELECT T.ChunkName FROM ReportServerTempDB.dbo.ChunkData AS T -- exclude the ones in the target WHERE T.ChunkName = S.ChunkName AND T.ChunkType = S.ChunkType AND T.SnapshotDataID = @ToSnapshotID) END ELSE IF @FromIsPermanent != 0 AND @ToIsPermanent != 0 BEGIN INSERT INTO ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) SELECT newid(), @ToSnapshotID, S.ChunkName, S.ChunkType, S.MimeType, S.Version, S.ChunkFlags, S.Content FROM ChunkData AS S WHERE S.SnapshotDataID = @FromSnapshotID AND S.ChunkType = @ChunkType AND NOT EXISTS( SELECT T.ChunkName FROM ChunkData AS T -- exclude the ones in the target WHERE T.ChunkName = S.ChunkName AND T.ChunkType = S.ChunkType AND T.SnapshotDataID = @ToSnapshotID) END ELSE BEGIN RAISERROR('Unsupported chunk copy', 16, 1) END GO GRANT EXECUTE ON [dbo].[CopyChunksOfType] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteSnapshotAndChunks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteSnapshotAndChunks] GO CREATE PROCEDURE [dbo].[DeleteSnapshotAndChunks] @SnapshotID uniqueidentifier, @IsPermanentSnapshot bit AS IF @IsPermanentSnapshot != 0 BEGIN DELETE ChunkData WHERE ChunkData.SnapshotDataID = @SnapshotID DELETE SnapshotData WHERE SnapshotData.SnapshotDataID = @SnapshotID END ELSE BEGIN DELETE ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotID DELETE ReportServerTempDB.dbo.SnapshotData WHERE SnapshotDataID = @SnapshotID END GO GRANT EXECUTE ON [dbo].[DeleteSnapshotAndChunks] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteOneChunk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteOneChunk] GO CREATE PROCEDURE [dbo].[DeleteOneChunk] @SnapshotID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int AS IF @IsPermanentSnapshot != 0 BEGIN DELETE ChunkData WHERE SnapshotDataID = @SnapshotID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END ELSE BEGIN DELETE ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END GO GRANT EXECUTE ON [dbo].[DeleteOneChunk] TO RSExecRole GO -------------------------------------------------- ------------- Persisted stream SPs if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeletePersistedStreams]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeletePersistedStreams] GO CREATE PROCEDURE [dbo].[DeletePersistedStreams] @SessionID varchar(32) AS delete ReportServerTempDB.dbo.PersistedStream from (select top 1 * from ReportServerTempDB.dbo.PersistedStream PS2 where PS2.SessionID = @SessionID) as e1 where e1.SessionID = ReportServerTempDB.dbo.PersistedStream.[SessionID] and e1.[Index] = ReportServerTempDB.dbo.PersistedStream.[Index] GO GRANT EXECUTE ON [dbo].[DeletePersistedStreams] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteExpiredPersistedStreams]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteExpiredPersistedStreams] GO CREATE PROCEDURE [dbo].[DeleteExpiredPersistedStreams] AS SET DEADLOCK_PRIORITY LOW DELETE ReportServerTempDB.dbo.PersistedStream FROM (SELECT TOP 1 * FROM ReportServerTempDB.dbo.PersistedStream PS2 WHERE PS2.RefCount = 0 AND GETDATE() > PS2.ExpirationDate) AS e1 WHERE e1.SessionID = ReportServerTempDB.dbo.PersistedStream.[SessionID] AND e1.[Index] = ReportServerTempDB.dbo.PersistedStream.[Index] GO GRANT EXECUTE ON [dbo].[DeleteExpiredPersistedStreams] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeletePersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeletePersistedStream] GO CREATE PROCEDURE [dbo].[DeletePersistedStream] @SessionID varchar(32), @Index int AS delete from ReportServerTempDB.dbo.PersistedStream where SessionID = @SessionID and [Index] = @Index GO GRANT EXECUTE ON [dbo].[DeletePersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddPersistedStream] GO CREATE PROCEDURE [dbo].[AddPersistedStream] @SessionID varchar(32), @Index int AS DECLARE @RefCount int DECLARE @id varchar(32) DECLARE @ExpirationDate datetime set @RefCount = 0 set @ExpirationDate = DATEADD(day, 2, GETDATE()) set @id = (select SessionID from ReportServerTempDB.dbo.SessionData where SessionID = @SessionID) if @id is not null begin set @RefCount = 1 end INSERT INTO ReportServerTempDB.dbo.PersistedStream (SessionID, [Index], [RefCount], [ExpirationDate]) VALUES (@SessionID, @Index, @RefCount, @ExpirationDate) GO GRANT EXECUTE ON [dbo].[AddPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[LockPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[LockPersistedStream] GO CREATE PROCEDURE [dbo].[LockPersistedStream] @SessionID varchar(32), @Index int AS SELECT [Index] FROM ReportServerTempDB.dbo.PersistedStream WITH (XLOCK) WHERE SessionID = @SessionID AND [Index] = @Index GO GRANT EXECUTE ON [dbo].[LockPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteFirstPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteFirstPortionPersistedStream] GO CREATE PROCEDURE [dbo].[WriteFirstPortionPersistedStream] @SessionID varchar(32), @Index int, @Name nvarchar(260) = NULL, @MimeType nvarchar(260) = NULL, @Extension nvarchar(260) = NULL, @Encoding nvarchar(260) = NULL, @Content image AS UPDATE ReportServerTempDB.dbo.PersistedStream set Content = @Content, [Name] = @Name, MimeType = @MimeType, Extension = @Extension WHERE SessionID = @SessionID AND [Index] = @Index SELECT TEXTPTR(Content) FROM ReportServerTempDB.dbo.PersistedStream WHERE SessionID = @SessionID AND [Index] = @Index GO GRANT EXECUTE ON [dbo].[WriteFirstPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteNextPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteNextPortionPersistedStream] GO CREATE PROCEDURE [dbo].[WriteNextPortionPersistedStream] @DataPointer binary(16), @DataIndex int, @DeleteLength int, @Content image AS UPDATETEXT ReportServerTempDB.dbo.PersistedStream.Content @DataPointer @DataIndex @DeleteLength @Content GO GRANT EXECUTE ON [dbo].[WriteNextPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetFirstPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetFirstPortionPersistedStream] GO CREATE PROCEDURE [dbo].[GetFirstPortionPersistedStream] @SessionID varchar(32) AS SELECT TOP 1 TEXTPTR(P.Content), DATALENGTH(P.Content), P.[Index], P.[Name], P.MimeType, P.Extension, P.Encoding, P.Error FROM ReportServerTempDB.dbo.PersistedStream P WITH (XLOCK) WHERE P.SessionID = @SessionID GO GRANT EXECUTE ON [dbo].[GetFirstPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetPersistedStreamError]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetPersistedStreamError] GO CREATE PROCEDURE [dbo].[SetPersistedStreamError] @SessionID varchar(32), @Index int, @AllRows bit, @Error nvarchar(512) AS if @AllRows = 0 BEGIN UPDATE ReportServerTempDB.dbo.PersistedStream SET Error = @Error WHERE SessionID = @SessionID and [Index] = @Index END ELSE BEGIN UPDATE ReportServerTempDB.dbo.PersistedStream SET Error = @Error WHERE SessionID = @SessionID END GO GRANT EXECUTE ON [dbo].[SetPersistedStreamError] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetNextPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetNextPortionPersistedStream] GO CREATE PROCEDURE [dbo].[GetNextPortionPersistedStream] @DataPointer binary(16), @DataIndex int, @Length int AS READTEXT ReportServerTempDB.dbo.PersistedStream.Content @DataPointer @DataIndex @Length GO GRANT EXECUTE ON [dbo].[GetNextPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapshotChunks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapshotChunks] GO CREATE PROCEDURE [dbo].[GetSnapshotChunks] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit AS IF @IsPermanentSnapshot != 0 BEGIN SELECT ChunkName, ChunkType, ChunkFlags, MimeType, Version, datalength(Content) FROM ChunkData WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN SELECT ChunkName, ChunkType, ChunkFlags, MimeType, Version, datalength(Content) FROM ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[GetSnapshotChunks] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetDrillthroughReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetDrillthroughReports] GO CREATE PROCEDURE [dbo].[SetDrillthroughReports] @ReportID uniqueidentifier, @ModelID uniqueidentifier, @ModelItemID nvarchar(425), @Type tinyint AS INSERT INTO ModelDrill (ModelDrillID, ModelID, ReportID, ModelItemID, [Type]) VALUES (newid(), @ModelID, @ReportID, @ModelItemID, @Type) GO GRANT EXECUTE ON [dbo].[SetDrillthroughReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteDrillthroughReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteDrillthroughReports] GO CREATE PROCEDURE [dbo].[DeleteDrillthroughReports] @ModelID uniqueidentifier, @ModelItemID nvarchar(425) AS DELETE ModelDrill WHERE ModelID = @ModelID and ModelItemID = @ModelItemID GO GRANT EXECUTE ON [dbo].[DeleteDrillthroughReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDrillthroughReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDrillthroughReports] GO CREATE PROCEDURE [dbo].[GetDrillthroughReports] @ModelID uniqueidentifier, @ModelItemID nvarchar(425) AS SELECT ModelDrill.Type, Catalog.Path FROM ModelDrill INNER JOIN Catalog ON ModelDrill.ReportID = Catalog.ItemID WHERE ModelID = @ModelID AND ModelItemID = @ModelItemID GO GRANT EXECUTE ON [dbo].[GetDrillthroughReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDrillthroughReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDrillthroughReport] GO CREATE PROCEDURE [dbo].[GetDrillthroughReport] @ModelPath nvarchar(425), @ModelItemID nvarchar(425), @Type tinyint AS SELECT CatRep.Path FROM ModelDrill INNER JOIN Catalog CatMod ON ModelDrill.ModelID = CatMod.ItemID INNER JOIN Catalog CatRep ON ModelDrill.ReportID = CatRep.ItemID WHERE CatMod.Path = @ModelPath AND ModelItemID = @ModelItemID AND ModelDrill.[Type] = @Type GO GRANT EXECUTE ON [dbo].[GetDrillthroughReport] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUpgradeItems]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUpgradeItems] GO CREATE PROCEDURE [dbo].[GetUpgradeItems] AS SELECT [Item], [Status] FROM [UpgradeInfo] GO GRANT EXECUTE ON [dbo].[GetUpgradeItems] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetUpgradeItemStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetUpgradeItemStatus] GO CREATE PROCEDURE [dbo].[SetUpgradeItemStatus] @ItemName nvarchar(260), @Status nvarchar(512) AS UPDATE [UpgradeInfo] SET [Status] = @Status WHERE [Item] = @ItemName GO GRANT EXECUTE ON [dbo].[SetUpgradeItemStatus] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPolicyRoots]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPolicyRoots] GO CREATE PROCEDURE [dbo].[GetPolicyRoots] AS SELECT [Path], [Type] FROM [Catalog] WHERE [PolicyRoot] = 1 GO GRANT EXECUTE ON [dbo].[GetPolicyRoots] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDataSourceForUpgrade]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDataSourceForUpgrade] GO CREATE PROCEDURE [dbo].[GetDataSourceForUpgrade] @CurrentVersion int AS SELECT [DSID] FROM [DataSource] WHERE [Version] != @CurrentVersion GO GRANT EXECUTE ON [dbo].[GetDataSourceForUpgrade] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSubscriptionsForUpgrade]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSubscriptionsForUpgrade] GO CREATE PROCEDURE [dbo].[GetSubscriptionsForUpgrade] @CurrentVersion int AS SELECT [SubscriptionID] FROM [Subscriptions] WHERE [Version] != @CurrentVersion GO GRANT EXECUTE ON [dbo].[GetSubscriptionsForUpgrade] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[StoreServerParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[StoreServerParameters] GO CREATE PROCEDURE [dbo].[StoreServerParameters] @ServerParametersID nvarchar(32), @Path nvarchar(425), @CurrentDate datetime, @Timeout int, @Expiration datetime, @ParametersValues image, @ParentParametersID nvarchar(32) = NULL AS DECLARE @ExistingServerParametersID as nvarchar(32) SET @ExistingServerParametersID = (SELECT ServerParametersID from [dbo].[ServerParametersInstance] WHERE ServerParametersID = @ServerParametersID) IF @ExistingServerParametersID IS NULL -- new row BEGIN INSERT INTO [dbo].[ServerParametersInstance] (ServerParametersID, ParentID, Path, CreateDate, ModifiedDate, Timeout, Expiration, ParametersValues) VALUES (@ServerParametersID, @ParentParametersID, @Path, @CurrentDate, @CurrentDate, @Timeout, @Expiration, @ParametersValues) END ELSE BEGIN UPDATE [dbo].[ServerParametersInstance] SET Timeout = @Timeout, Expiration = @Expiration, ParametersValues = @ParametersValues, ModifiedDate = @CurrentDate, Path = @Path, ParentID = @ParentParametersID WHERE ServerParametersID = @ServerParametersID END GO GRANT EXECUTE ON [dbo].[StoreServerParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetServerParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetServerParameters] GO CREATE PROCEDURE [dbo].[GetServerParameters] @ServerParametersID nvarchar(32) AS DECLARE @now as DATETIME SET @now = GETDATE() SELECT Child.Path, Child.ParametersValues, Parent.ParametersValues FROM [dbo].[ServerParametersInstance] Child LEFT OUTER JOIN [dbo].[ServerParametersInstance] Parent ON Child.ParentID = Parent.ServerParametersID WHERE Child.ServerParametersID = @ServerParametersID AND Child.Expiration > @now GO GRANT EXECUTE ON [dbo].[GetServerParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredServerParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredServerParameters] GO CREATE PROCEDURE [dbo].[CleanExpiredServerParameters] @ParametersCleaned INT OUTPUT AS DECLARE @now as DATETIME SET @now = GETDATE() DELETE FROM [dbo].[ServerParametersInstance] WHERE ServerParametersID IN ( SELECT TOP 20 ServerParametersID FROM [dbo].[ServerParametersInstance] WHERE Expiration < @now ) SET @ParametersCleaned = @@ROWCOUNT GO GRANT EXECUTE ON [dbo].[CleanExpiredServerParameters] TO RSExecRole GO -- END STORED PROCEDURES -- START STORED PROCEDURES if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetKeysForInstallation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetKeysForInstallation] GO CREATE PROCEDURE [dbo].[SetKeysForInstallation] @InstallationID uniqueidentifier, @SymmetricKey image = NULL, @PublicKey image AS update [dbo].[Keys] set [SymmetricKey] = @SymmetricKey, [PublicKey] = @PublicKey where [InstallationID] = @InstallationID and [Client] = 1 GO GRANT EXECUTE ON [dbo].[SetKeysForInstallation] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAnnouncedKey]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAnnouncedKey] GO CREATE PROCEDURE [dbo].[GetAnnouncedKey] @InstallationID uniqueidentifier AS select PublicKey, MachineName, InstanceName from Keys where InstallationID = @InstallationID and Client = 1 GO GRANT EXECUTE ON [dbo].[GetAnnouncedKey] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AnnounceOrGetKey]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AnnounceOrGetKey] GO CREATE PROCEDURE [dbo].[AnnounceOrGetKey] @MachineName nvarchar(256), @InstanceName nvarchar(32), @InstallationID uniqueidentifier, @PublicKey image, @NumAnnouncedServices int OUTPUT AS -- Acquire lock IF NOT EXISTS (SELECT * FROM [dbo].[Keys] WITH(XLOCK) WHERE [Client] < 0) BEGIN RAISERROR('Keys lock row not found', 16, 1) RETURN END -- Get the number of services that have already announced their presence SELECT @NumAnnouncedServices = count(*) FROM [dbo].[Keys] WHERE [Client] = 1 DECLARE @StoredInstallationID uniqueidentifier DECLARE @StoredInstanceName nvarchar(32) SELECT @StoredInstallationID = [InstallationID], @StoredInstanceName = [InstanceName] FROM [dbo].[Keys] WHERE [InstallationID] = @InstallationID AND [Client] = 1 IF @StoredInstallationID IS NULL -- no record present BEGIN INSERT INTO [dbo].[Keys] ([MachineName], [InstanceName], [InstallationID], [Client], [PublicKey], [SymmetricKey]) VALUES (@MachineName, @InstanceName, @InstallationID, 1, @PublicKey, null) END ELSE BEGIN IF @StoredInstanceName IS NULL BEGIN UPDATE [dbo].[Keys] SET [InstanceName] = @InstanceName WHERE [InstallationID] = @InstallationID AND [Client] = 1 END END SELECT [MachineName], [SymmetricKey], [PublicKey] FROM [Keys] WHERE [InstallationID] = @InstallationID and [Client] = 1 GO GRANT EXECUTE ON [dbo].[AnnounceOrGetKey] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetMachineName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetMachineName] GO CREATE PROCEDURE [dbo].[SetMachineName] @MachineName nvarchar(256), @InstallationID uniqueidentifier AS UPDATE [dbo].[Keys] SET MachineName = @MachineName WHERE [InstallationID] = @InstallationID and [Client] = 1 GO GRANT EXECUTE ON [dbo].[SetMachineName] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListInstallations]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListInstallations] GO CREATE PROCEDURE [dbo].[ListInstallations] AS SELECT [MachineName], [InstanceName], [InstallationID], CASE WHEN [SymmetricKey] IS null THEN 0 ELSE 1 END FROM [dbo].[Keys] WHERE [Client] = 1 GO GRANT EXECUTE ON [dbo].[ListInstallations] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListInfoForReencryption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListInfoForReencryption] GO CREATE PROCEDURE [dbo].[ListInfoForReencryption] AS SELECT [DSID] FROM [dbo].[DataSource] WITH (XLOCK, TABLOCK) SELECT [SubscriptionID] FROM [dbo].[Subscriptions] WITH (XLOCK, TABLOCK) SELECT [InstallationID], [PublicKey] FROM [dbo].[Keys] WITH (XLOCK, TABLOCK) WHERE [Client] = 1 AND ([SymmetricKey] IS NOT NULL) GO GRANT EXECUTE ON [dbo].[ListInfoForReencryption] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDatasourceInfoForReencryption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDatasourceInfoForReencryption] GO CREATE PROCEDURE [dbo].[GetDatasourceInfoForReencryption] @DSID as uniqueidentifier AS SELECT [ConnectionString], [OriginalConnectionString], [UserName], [Password], [CredentialRetrieval], [Version] FROM [dbo].[DataSource] WHERE [DSID] = @DSID GO GRANT EXECUTE ON [dbo].[GetDatasourceInfoForReencryption] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetReencryptedDatasourceInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetReencryptedDatasourceInfo] GO CREATE PROCEDURE [dbo].[SetReencryptedDatasourceInfo] @DSID uniqueidentifier, @ConnectionString image = NULL, @OriginalConnectionString image = NULL, @UserName image = NULL, @Password image = NULL, @CredentialRetrieval int, @Version int AS UPDATE [dbo].[DataSource] SET [ConnectionString] = @ConnectionString, [OriginalConnectionString] = @OriginalConnectionString, [UserName] = @UserName, [Password] = @Password, [CredentialRetrieval] = @CredentialRetrieval, [Version] = @Version WHERE [DSID] = @DSID GO GRANT EXECUTE ON [dbo].[SetReencryptedDatasourceInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSubscriptionInfoForReencryption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSubscriptionInfoForReencryption] GO CREATE PROCEDURE [dbo].[GetSubscriptionInfoForReencryption] @SubscriptionID as uniqueidentifier AS SELECT [DeliveryExtension], [ExtensionSettings], [Version] FROM [dbo].[Subscriptions] WHERE [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetSubscriptionInfoForReencryption] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetReencryptedSubscriptionInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetReencryptedSubscriptionInfo] GO CREATE PROCEDURE [dbo].[SetReencryptedSubscriptionInfo] @SubscriptionID as uniqueidentifier, @ExtensionSettings as ntext = NULL, @Version as int AS UPDATE [dbo].[Subscriptions] SET [ExtensionSettings] = @ExtensionSettings, [Version] = @Version WHERE [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[SetReencryptedSubscriptionInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteEncryptedContent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteEncryptedContent] GO CREATE PROCEDURE [dbo].[DeleteEncryptedContent] AS -- Remove the encryption keys delete from keys where client >= 0 -- Remove the encrypted content update datasource set CredentialRetrieval = 1, -- CredentialRetrieval.Prompt ConnectionString = null, OriginalConnectionString = null, UserName = null, Password = null GO GRANT EXECUTE ON [dbo].[DeleteEncryptedContent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteKey]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteKey] GO CREATE PROCEDURE [dbo].[DeleteKey] @InstallationID uniqueidentifier AS if (@InstallationID = '00000000-0000-0000-0000-000000000000') RAISERROR('Cannot delete reserved key', 16, 1) -- Remove the encryption keys delete from keys where InstallationID = @InstallationID and Client = 1 GO GRANT EXECUTE ON [dbo].[DeleteKey] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAllConfigurationInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAllConfigurationInfo] GO CREATE PROCEDURE [dbo].[GetAllConfigurationInfo] AS SELECT [Name], [Value] FROM [ConfigurationInfo] GO GRANT EXECUTE ON [dbo].[GetAllConfigurationInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetOneConfigurationInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetOneConfigurationInfo] GO CREATE PROCEDURE [dbo].[GetOneConfigurationInfo] @Name nvarchar (260) AS SELECT [Value] FROM [ConfigurationInfo] WHERE [Name] = @Name GO GRANT EXECUTE ON [dbo].[GetOneConfigurationInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetConfigurationInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetConfigurationInfo] GO CREATE PROCEDURE [dbo].[SetConfigurationInfo] @Name nvarchar (260), @Value ntext AS DELETE FROM [ConfigurationInfo] WHERE [Name] = @Name IF @Value is not null BEGIN INSERT INTO ConfigurationInfo VALUES ( newid(), @Name, @Value ) END GO GRANT EXECUTE ON [dbo].[SetConfigurationInfo] TO RSExecRole if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddEvent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddEvent] GO CREATE PROCEDURE [dbo].[AddEvent] @EventType nvarchar (260), @EventData nvarchar (260) AS insert into [Event] ([EventID], [EventType], [EventData], [TimeEntered], [ProcessStart], [BatchID]) values (NewID(), @EventType, @EventData, GETUTCDATE(), NULL, NULL) GO GRANT EXECUTE ON [dbo].[AddEvent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteEvent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteEvent] GO CREATE PROCEDURE [dbo].[DeleteEvent] @ID uniqueidentifier AS delete from [Event] where [EventID] = @ID GO GRANT EXECUTE ON [dbo].[DeleteEvent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanEventRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanEventRecords] GO CREATE PROCEDURE [dbo].[CleanEventRecords] @MaxAgeMinutes int AS -- Reset all notifications which have been add over n minutes ago Update [Event] set [ProcessStart] = NULL, [ProcessHeartbeat] = NULL where [EventID] in ( SELECT [EventID] FROM [Event] WHERE [ProcessHeartbeat] < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) ) GO GRANT EXECUTE ON [dbo].[CleanEventRecords] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddExecutionLogEntry]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddExecutionLogEntry] GO CREATE PROCEDURE [dbo].[AddExecutionLogEntry] @InstanceName nvarchar(38), @Report nvarchar(260), @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @RequestType bit, @Format nvarchar(26), @Parameters ntext, @TimeStart DateTime, @TimeEnd DateTime, @TimeDataRetrieval int, @TimeProcessing int, @TimeRendering int, @Source tinyint, @Status nvarchar(32), @ByteCount bigint, @RowCount bigint AS -- Unless is is specifically 'False', it's true if exists (select * from ConfigurationInfo where [Name] = 'EnableExecutionLogging' and [Value] like 'False') begin return end Declare @ReportID uniqueidentifier select @ReportID = ItemID from Catalog with (nolock) where Path = @Report insert into ExecutionLog (InstanceName, ReportID, UserName, RequestType, [Format], Parameters, TimeStart, TimeEnd, TimeDataRetrieval, TimeProcessing, TimeRendering, Source, Status, ByteCount, [RowCount]) Values (@InstanceName, @ReportID, @UserName, @RequestType, @Format, @Parameters, @TimeStart, @TimeEnd, @TimeDataRetrieval, @TimeProcessing, @TimeRendering, @Source, @Status, @ByteCount, @RowCount) GO GRANT EXECUTE ON [dbo].[AddExecutionLogEntry] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ExpireExecutionLogEntries]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ExpireExecutionLogEntries] GO CREATE PROCEDURE [dbo].[ExpireExecutionLogEntries] AS -- -1 means no expiration if exists (select * from ConfigurationInfo where [Name] = 'ExecutionLogDaysKept' and CAST(CAST(Value as nvarchar) as integer) = -1) begin return end delete from ExecutionLog where DateDiff(day, TimeStart, getdate()) >= (select CAST(CAST(Value as nvarchar) as integer) from ConfigurationInfo where [Name] = 'ExecutionLogDaysKept') GO GRANT EXECUTE ON [dbo].[ExpireExecutionLogEntries] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUserIDBySid]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUserIDBySid] GO -- looks up any user name by its SID, if not it creates a regular user CREATE PROCEDURE [dbo].[GetUserIDBySid] @UserSid varbinary(85), @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS SELECT @UserID = (SELECT UserID FROM Users WHERE Sid = @UserSid AND AuthType = @AuthType) IF @UserID IS NULL BEGIN SET @UserID = newid() INSERT INTO Users (UserID, Sid, UserType, AuthType, UserName) VALUES (@UserID, @UserSid, 0, @AuthType, @UserName) END GO GRANT EXECUTE ON [dbo].[GetUserIDBySid] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUserIDByName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUserIDByName] GO -- looks up any user name by its User Name, if not it creates a regular user CREATE PROCEDURE [dbo].[GetUserIDByName] @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS SELECT @UserID = (SELECT UserID FROM Users WHERE UserName = @UserName AND AuthType = @AuthType) IF @UserID IS NULL BEGIN SET @UserID = newid() INSERT INTO Users (UserID, Sid, UserType, AuthType, UserName) VALUES (@UserID, NULL, 0, @AuthType, @UserName) END GO GRANT EXECUTE ON [dbo].[GetUserIDByName] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUserID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUserID] GO -- looks up any user name, if not it creates a regular user - uses Sid CREATE PROCEDURE [dbo].[GetUserID] @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS IF @AuthType = 1 -- Windows BEGIN EXEC GetUserIDBySid @UserSid, @UserName, @AuthType, @UserID OUTPUT END ELSE BEGIN EXEC GetUserIDByName @UserName, @AuthType, @UserID OUTPUT END GO GRANT EXECUTE ON [dbo].[GetUserID] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPrincipalID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPrincipalID] GO -- looks up a principal, if not there looks up regular users and turns them into principals -- if not, it creates a principal CREATE PROCEDURE [dbo].[GetPrincipalID] @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS -- windows auth IF @AuthType = 1 BEGIN -- is this a principal? SELECT @UserID = (SELECT UserID FROM Users WHERE Sid = @UserSid AND UserType = 1 AND AuthType = @AuthType) END ELSE BEGIN -- is this a principal? SELECT @UserID = (SELECT UserID FROM Users WHERE UserName = @UserName AND UserType = 1 AND AuthType = @AuthType) END IF @UserID IS NULL BEGIN IF @AuthType = 1 -- Windows BEGIN -- Is this a regular user SELECT @UserID = (SELECT UserID FROM Users WHERE Sid = @UserSid AND UserType = 0 AND AuthType = @AuthType) END ELSE BEGIN -- Is this a regular user SELECT @UserID = (SELECT UserID FROM Users WHERE UserName = @UserName AND UserType = 0 AND AuthType = @AuthType) END -- No, create a new principal IF @UserID IS NULL BEGIN SET @UserID = newid() INSERT INTO Users (UserID, Sid, UserType, AuthType, UserName) VALUES (@UserID, @UserSid, 1, @AuthType, @UserName) END ELSE BEGIN UPDATE Users SET UserType = 1 WHERE UserID = @UserID END END GO GRANT EXECUTE ON [dbo].[GetPrincipalID] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateSubscription] GO CREATE PROCEDURE [dbo].[CreateSubscription] @id uniqueidentifier, @Locale nvarchar (128), @Report_Name nvarchar (425), @OwnerSid varbinary (85) = NULL, @OwnerName nvarchar(260), @OwnerAuthType int, @DeliveryExtension nvarchar (260) = NULL, @InactiveFlags int, @ExtensionSettings ntext = NULL, @ModifiedBySid varbinary (85) = NULL, @ModifiedByName nvarchar(260), @ModifiedByAuthType int, @ModifiedDate datetime, @Description nvarchar(512) = NULL, @LastStatus nvarchar(260) = NULL, @EventType nvarchar(260), @MatchData ntext = NULL, @Parameters ntext = NULL, @DataSettings ntext = NULL, @Version int AS -- Create a subscription with the given data. The name must match a name in the -- Catalog table and it must be a report type (2) or linked report (4) DECLARE @Report_OID uniqueidentifier DECLARE @OwnerID uniqueidentifier DECLARE @ModifiedByID uniqueidentifier DECLARE @TempDeliveryID uniqueidentifier --Get the report id for this subscription select @Report_OID = (select [ItemID] from [Catalog] where [Catalog].[Path] = @Report_Name and ([Catalog].[Type] = 2 or [Catalog].[Type] = 4)) EXEC GetUserID @OwnerSid, @OwnerName, @OwnerAuthType, @OwnerID OUTPUT EXEC GetUserID @ModifiedBySid, @ModifiedByName, @ModifiedByAuthType, @ModifiedByID OUTPUT if (@Report_OID is NULL) begin RAISERROR('Report Not Found', 16, 1) return end Insert into Subscriptions ( [SubscriptionID], [OwnerID], [Report_OID], [Locale], [DeliveryExtension], [InactiveFlags], [ExtensionSettings], [ModifiedByID], [ModifiedDate], [Description], [LastStatus], [EventType], [MatchData], [LastRunTime], [Parameters], [DataSettings], [Version] ) values (@id, @OwnerID, @Report_OID, @Locale, @DeliveryExtension, @InactiveFlags, @ExtensionSettings, @ModifiedByID, @ModifiedDate, @Description, @LastStatus, @EventType, @MatchData, NULL, @Parameters, @DataSettings, @Version) GO GRANT EXECUTE ON [dbo].[CreateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeliveryRemovedInactivateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeliveryRemovedInactivateSubscription] GO CREATE PROCEDURE [dbo].[DeliveryRemovedInactivateSubscription] @DeliveryExtension nvarchar(260), @Status nvarchar(260) AS update Subscriptions set [DeliveryExtension] = '', [InactiveFlags] = [InactiveFlags] | 1, -- Delivery Provider Removed Flag == 1 [LastStatus] = @Status where [DeliveryExtension] = @DeliveryExtension GO GRANT EXECUTE ON [dbo].[DeliveryRemovedInactivateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteSubscription] GO CREATE PROCEDURE [dbo].[DeleteSubscription] @SubscriptionID uniqueidentifier AS -- Delete the given subscription delete from [Subscriptions] where [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[DeleteSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSubscription] GO CREATE PROCEDURE [dbo].[GetSubscription] @SubscriptionID uniqueidentifier, @AuthType int AS -- Grab all of the-- subscription properties given a id select S.[SubscriptionID], S.[Report_OID], S.[Locale], S.[InactiveFlags], S.[DeliveryExtension], S.[ExtensionSettings], SUSER_SNAME(Modified.[Sid]), Modified.[UserName], S.[ModifiedDate], S.[Description], S.[LastStatus], S.[EventType], S.[MatchData], S.[Parameters], S.[DataSettings], A.[TotalNotifications], A.[TotalSuccesses], A.[TotalFailures], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], CAT.[Path], S.[LastRunTime], CAT.[Type], SD.NtSecDescPrimary, S.[Version] from [Subscriptions] S inner join [Catalog] CAT on S.[Report_OID] = CAT.[ItemID] inner join [Users] Owner on S.OwnerID = Owner.UserID inner join [Users] Modified on S.ModifiedByID = Modified.UserID left outer join [SecData] SD on CAT.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType left outer join [ActiveSubscriptions] A with (NOLOCK) on S.[SubscriptionID] = A.[SubscriptionID] where S.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListSubscriptionsUsingDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListSubscriptionsUsingDataSource] GO CREATE PROCEDURE [dbo].[ListSubscriptionsUsingDataSource] @DataSourceName nvarchar(450), @AuthType int AS select S.[SubscriptionID], S.[Report_OID], S.[Locale], S.[InactiveFlags], S.[DeliveryExtension], S.[ExtensionSettings], SUSER_SNAME(Modified.[Sid]), Modified.[UserName], S.[ModifiedDate], S.[Description], S.[LastStatus], S.[EventType], S.[MatchData], S.[Parameters], S.[DataSettings], A.[TotalNotifications], A.[TotalSuccesses], A.[TotalFailures], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], CAT.[Path], S.[LastRunTime], CAT.[Type], SD.NtSecDescPrimary, S.[Version] from [DataSource] DS inner join Catalog C on C.ItemID = DS.Link inner join Subscriptions S on S.[SubscriptionID] = DS.[SubscriptionID] inner join [Catalog] CAT on S.[Report_OID] = CAT.[ItemID] inner join [Users] Owner on S.OwnerID = Owner.UserID inner join [Users] Modified on S.ModifiedByID = Modified.UserID left join [SecData] SD on SD.[PolicyID] = CAT.[PolicyID] AND SD.AuthType = @AuthType left outer join [ActiveSubscriptions] A with (NOLOCK) on S.[SubscriptionID] = A.[SubscriptionID] where C.Path = @DataSourceName GO GRANT EXECUTE ON [dbo].[ListSubscriptionsUsingDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSubscriptionStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSubscriptionStatus] GO CREATE PROCEDURE [dbo].[UpdateSubscriptionStatus] @SubscriptionID uniqueidentifier, @Status nvarchar(260) AS update Subscriptions set [LastStatus] = @Status where [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[UpdateSubscriptionStatus] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSubscription] GO CREATE PROCEDURE [dbo].[UpdateSubscription] @id uniqueidentifier, @Locale nvarchar(260), @OwnerSid varbinary(85) = NULL, @OwnerName nvarchar(260), @OwnerAuthType int, @DeliveryExtension nvarchar(260), @InactiveFlags int, @ExtensionSettings ntext = NULL, @ModifiedBySid varbinary(85) = NULL, @ModifiedByName nvarchar(260), @ModifiedByAuthType int, @ModifiedDate datetime, @Description nvarchar(512) = NULL, @LastStatus nvarchar(260) = NULL, @EventType nvarchar(260), @MatchData ntext = NULL, @Parameters ntext = NULL, @DataSettings ntext = NULL, @Version int AS -- Update a subscription's information. DECLARE @ModifiedByID uniqueidentifier DECLARE @OwnerID uniqueidentifier EXEC GetUserID @ModifiedBySid, @OwnerName,@OwnerAuthType, @ModifiedByID OUTPUT EXEC GetUserID @OwnerSid, @ModifiedByName, @ModifiedByAuthType, @OwnerID OUTPUT -- Make sure there is a valid provider update Subscriptions set [DeliveryExtension] = @DeliveryExtension, [Locale] = @Locale, [OwnerID] = @OwnerID, [InactiveFlags] = @InactiveFlags, [ExtensionSettings] = @ExtensionSettings, [ModifiedByID] = @ModifiedByID, [ModifiedDate] = @ModifiedDate, [Description] = @Description, [LastStatus] = @LastStatus, [EventType] = @EventType, [MatchData] = @MatchData, [Parameters] = @Parameters, [DataSettings] = @DataSettings, [Version] = @Version where [SubscriptionID] = @id GO GRANT EXECUTE ON [dbo].[UpdateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[InvalidateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[InvalidateSubscription] GO CREATE PROCEDURE [dbo].[InvalidateSubscription] @SubscriptionID uniqueidentifier, @Flags int, @LastStatus nvarchar(260) AS -- Mark all subscriptions for this report as inactive for the given flags update Subscriptions set [InactiveFlags] = S.[InactiveFlags] | @Flags, [LastStatus] = @LastStatus from Subscriptions S where SubscriptionID = @SubscriptionID GO GRANT EXECUTE ON [dbo].[InvalidateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanNotificationRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanNotificationRecords] GO CREATE PROCEDURE [dbo].[CleanNotificationRecords] @MaxAgeMinutes int AS -- Reset all notifications which have been add over n minutes ago Update [Notifications] set [ProcessStart] = NULL, [ProcessHeartbeat] = NULL, [Attempt] = 1 where [NotificationID] in ( SELECT [NotificationID] FROM [Notifications] WHERE [ProcessHeartbeat] < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) and [Attempt] is NULL ) Update [Notifications] set [ProcessStart] = NULL, [ProcessHeartbeat] = NULL, [Attempt] = [Attempt] + 1 where [NotificationID] in ( SELECT [NotificationID] FROM [Notifications] WHERE [ProcessHeartbeat] < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) and [Attempt] is not NULL ) GO GRANT EXECUTE ON [dbo].[CleanNotificationRecords] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateSnapShotNotifications]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateSnapShotNotifications] GO CREATE PROCEDURE [dbo].[CreateSnapShotNotifications] @HistoryID uniqueidentifier, @LastRunTime datetime AS update [Subscriptions] set [LastRunTime] = @LastRunTime from History SS inner join [Subscriptions] S on S.[Report_OID] = SS.[ReportID] where SS.[HistoryID] = @HistoryID and S.EventType = 'ReportHistorySnapshotCreated' and InactiveFlags = 0 -- Find all valid subscriptions for the given report and create a new notification row for -- each subscription insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) select NewID(), S.[SubscriptionID], NULL, S.[Report_OID], NULL, S.[ExtensionSettings], S.[Locale], S.[Parameters], GETUTCDATE(), S.[LastRunTime], S.[DeliveryExtension], S.[OwnerID], 0, S.[Version] from [Subscriptions] S with (READPAST) inner join History H on S.[Report_OID] = H.[ReportID] where H.[HistoryID] = @HistoryID and S.EventType = 'ReportHistorySnapshotCreated' and InactiveFlags = 0 and S.[DataSettings] is null -- Create any data driven subscription by creating a data driven event insert into [Event] ( [EventID], [EventType], [EventData], [TimeEntered] ) select NewID(), 'DataDrivenSubscription', S.SubscriptionID, GETUTCDATE() from [Subscriptions] S with (READPAST) inner join History H on S.[Report_OID] = H.[ReportID] where H.[HistoryID] = @HistoryID and S.EventType = 'ReportHistorySnapshotCreated' and InactiveFlags = 0 and S.[DataSettings] is not null GO GRANT EXECUTE ON [dbo].[CreateSnapShotNotifications] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateDataDrivenNotification]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateDataDrivenNotification] GO CREATE PROCEDURE [dbo].[CreateDataDrivenNotification] @SubscriptionID uniqueidentifier, @ActiveationID uniqueidentifier, @ReportID uniqueidentifier, @ExtensionSettings ntext, @Locale nvarchar(128), @Parameters ntext, @LastRunTime datetime, @DeliveryExtension nvarchar(260), @OwnerSid varbinary (85) = null, @OwnerName nvarchar(260), @OwnerAuthType int, @Version int AS declare @OwnerID as uniqueidentifier EXEC GetUserID @OwnerSid,@OwnerName, @OwnerAuthType, @OwnerID OUTPUT -- Insert into the notification table insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) values ( NewID(), @SubscriptionID, @ActiveationID, @ReportID, NULL, @ExtensionSettings, @Locale, @Parameters, GETUTCDATE(), @LastRunTime, @DeliveryExtension, @OwnerID, 1, @Version ) GO GRANT EXECUTE ON [dbo].[CreateDataDrivenNotification] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateNewActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateNewActiveSubscription] GO CREATE PROCEDURE [dbo].[CreateNewActiveSubscription] @ActiveID uniqueidentifier, @SubscriptionID uniqueidentifier AS -- Insert into the activesubscription table insert into [ActiveSubscriptions] ( [ActiveID], [SubscriptionID], [TotalNotifications], [TotalSuccesses], [TotalFailures] ) values ( @ActiveID, @SubscriptionID, NULL, 0, 0 ) GO GRANT EXECUTE ON [dbo].[CreateNewActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateActiveSubscription] GO CREATE PROCEDURE [dbo].[UpdateActiveSubscription] @ActiveID uniqueidentifier, @TotalNotifications int = NULL, @TotalSuccesses int = NULL, @TotalFailures int = NULL AS if @TotalNotifications is not NULL begin update ActiveSubscriptions set TotalNotifications = @TotalNotifications where ActiveID = @ActiveID end if @TotalSuccesses is not NULL begin update ActiveSubscriptions set TotalSuccesses = @TotalSuccesses where ActiveID = @ActiveID end if @TotalFailures is not NULL begin update ActiveSubscriptions set TotalFailures = @TotalFailures where ActiveID = @ActiveID end GO GRANT EXECUTE ON [dbo].[UpdateActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteActiveSubscription] GO CREATE PROCEDURE [dbo].[DeleteActiveSubscription] @ActiveID uniqueidentifier AS delete from ActiveSubscriptions where ActiveID = @ActiveID GO GRANT EXECUTE ON [dbo].[DeleteActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAndHoldLockActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAndHoldLockActiveSubscription] GO CREATE PROCEDURE [dbo].[GetAndHoldLockActiveSubscription] @ActiveID uniqueidentifier AS select TotalNotifications, TotalSuccesses, TotalFailures from ActiveSubscriptions with (XLOCK) where ActiveID = @ActiveID GO GRANT EXECUTE ON [dbo].[GetAndHoldLockActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateCacheUpdateNotifications]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateCacheUpdateNotifications] GO CREATE PROCEDURE [dbo].[CreateCacheUpdateNotifications] @ReportID uniqueidentifier, @LastRunTime datetime AS update [Subscriptions] set [LastRunTime] = @LastRunTime from [Subscriptions] S where S.[Report_OID] = @ReportID and S.EventType = 'SnapshotUpdated' and InactiveFlags = 0 -- Find all valid subscriptions for the given report and create a new notification row for -- each subscription insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) select NewID(), S.[SubscriptionID], NULL, S.[Report_OID], NULL, S.[ExtensionSettings], S.[Locale], S.[Parameters], GETUTCDATE(), S.[LastRunTime], S.[DeliveryExtension], S.[OwnerID], 0, S.[Version] from [Subscriptions] S inner join Catalog C on S.[Report_OID] = C.[ItemID] where C.[ItemID] = @ReportID and S.EventType = 'SnapshotUpdated' and InactiveFlags = 0 and S.[DataSettings] is null -- Create any data driven subscription by creating a data driven event insert into [Event] ( [EventID], [EventType], [EventData], [TimeEntered] ) select NewID(), 'DataDrivenSubscription', S.SubscriptionID, GETUTCDATE() from [Subscriptions] S inner join Catalog C on S.[Report_OID] = C.[ItemID] where C.[ItemID] = @ReportID and S.EventType = 'SnapshotUpdated' and InactiveFlags = 0 and S.[DataSettings] is not null GO GRANT EXECUTE ON [dbo].[CreateCacheUpdateNotifications] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCacheSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetCacheSchedule] GO CREATE PROCEDURE [dbo].[GetCacheSchedule] @ReportID uniqueidentifier AS SELECT S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], RS.ReportAction FROM Schedule S with (XLOCK) inner join ReportSchedule RS on S.ScheduleID = RS.ScheduleID inner join [Users] Owner on S.[CreatedById] = Owner.[UserID] WHERE (RS.ReportAction = 1 or RS.ReportAction = 3) and -- 1 == UpdateCache, 3 == Invalidate cache RS.[ReportID] = @ReportID GO GRANT EXECUTE ON [dbo].[GetCacheSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteNotification]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteNotification] GO CREATE PROCEDURE [dbo].[DeleteNotification] @ID uniqueidentifier AS delete from [Notifications] where [NotificationID] = @ID GO GRANT EXECUTE ON [dbo].[DeleteNotification] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetNotificationAttempt]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetNotificationAttempt] GO CREATE PROCEDURE [dbo].[SetNotificationAttempt] @Attempt int, @SecondsToAdd int, @NotificationID uniqueidentifier AS update [Notifications] set [ProcessStart] = NULL, [Attempt] = @Attempt, [ProcessAfter] = DateAdd(second, @SecondsToAdd, GetUtcDate()) where [NotificationID] = @NotificationID GO GRANT EXECUTE ON [dbo].[SetNotificationAttempt] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateTimeBasedSubscriptionNotification]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateTimeBasedSubscriptionNotification] GO CREATE PROCEDURE [dbo].[CreateTimeBasedSubscriptionNotification] @SubscriptionID uniqueidentifier, @LastRunTime datetime as insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) select NewID(), S.[SubscriptionID], NULL, S.[Report_OID], NULL, S.[ExtensionSettings], S.[Locale], S.[Parameters], GETUTCDATE(), @LastRunTime, S.[DeliveryExtension], S.[OwnerID], 0, S.[Version] from [Subscriptions] S where S.[SubscriptionID] = @SubscriptionID and InactiveFlags = 0 and S.[DataSettings] is null -- Create any data driven subscription by creating a data driven event insert into [Event] ( [EventID], [EventType], [EventData], [TimeEntered] ) select NewID(), 'DataDrivenSubscription', S.SubscriptionID, GETUTCDATE() from [Subscriptions] S where S.[SubscriptionID] = @SubscriptionID and InactiveFlags = 0 and S.[DataSettings] is not null update [Subscriptions] set [LastRunTime] = @LastRunTime where [SubscriptionID] = @SubscriptionID and InactiveFlags = 0 GO GRANT EXECUTE ON [dbo].[CreateTimeBasedSubscriptionNotification] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteTimeBasedSubscriptionSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteTimeBasedSubscriptionSchedule] GO CREATE PROCEDURE [dbo].[DeleteTimeBasedSubscriptionSchedule] @SubscriptionID as uniqueidentifier as delete ReportSchedule from ReportSchedule RS inner join Subscriptions S on S.[SubscriptionID] = RS.[SubscriptionID] where S.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[DeleteTimeBasedSubscriptionSchedule] TO RSExecRole GO -------------------------------------------------- ------------- Provider Info if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListUsedDeliveryProviders]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListUsedDeliveryProviders] GO CREATE PROCEDURE [dbo].[ListUsedDeliveryProviders] AS select distinct [DeliveryExtension] from Subscriptions where [DeliveryExtension] <> '' GO GRANT EXECUTE ON [dbo].[ListUsedDeliveryProviders] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id('[dbo].[AddBatchRecord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddBatchRecord] GO CREATE PROCEDURE [dbo].[AddBatchRecord] @BatchID uniqueidentifier, @UserName nvarchar(260), @Action varchar(32), @Item nvarchar(425) = NULL, @Parent nvarchar(425) = NULL, @Param nvarchar(425) = NULL, @BoolParam bit = NULL, @Content image = NULL, @Properties ntext = NULL AS IF @Action='BatchStart' BEGIN INSERT INTO [Batch] (BatchID, AddedOn, [Action], Item, Parent, Param, BoolParam, Content, Properties) VALUES (@BatchID, GETUTCDATE(), @Action, @UserName, @Parent, @Param, @BoolParam, @Content, @Properties) END ELSE BEGIN IF EXISTS (SELECT * FROM Batch WHERE BatchID = @BatchID AND [Action] = 'BatchStart' AND Item = @UserName) BEGIN INSERT INTO [Batch] (BatchID, AddedOn, [Action], Item, Parent, Param, BoolParam, Content, Properties) VALUES (@BatchID, GETUTCDATE(), @Action, @Item, @Parent, @Param, @BoolParam, @Content, @Properties) END ELSE BEGIN RAISERROR( 'Batch does not exist', 16, 1 ) END END GO GRANT EXECUTE ON [dbo].[AddBatchRecord] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[GetBatchRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetBatchRecords] GO CREATE PROCEDURE [dbo].[GetBatchRecords] @BatchID uniqueidentifier AS SELECT [Action], Item, Parent, Param, BoolParam, Content, Properties FROM [Batch] WHERE BatchID = @BatchID ORDER BY AddedOn GO GRANT EXECUTE ON [dbo].[GetBatchRecords] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteBatchRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteBatchRecords] GO CREATE PROCEDURE [dbo].[DeleteBatchRecords] @BatchID uniqueidentifier AS DELETE FROM [Batch] WHERE BatchID = @BatchID GO GRANT EXECUTE ON [dbo].[DeleteBatchRecords] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanBatchRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanBatchRecords] GO CREATE PROCEDURE [dbo].[CleanBatchRecords] @MaxAgeMinutes int AS DELETE FROM [Batch] where BatchID in ( SELECT BatchID FROM [Batch] WHERE AddedOn < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) ) GO GRANT EXECUTE ON [dbo].[CleanBatchRecords] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanOrphanedPolicies]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanOrphanedPolicies] GO -- Cleaning orphan policies CREATE PROCEDURE [dbo].[CleanOrphanedPolicies] AS DELETE [Policies] WHERE [Policies].[PolicyFlag] = 0 AND NOT EXISTS (SELECT ItemID FROM [Catalog] WHERE [Catalog].[PolicyID] = [Policies].[PolicyID]) DELETE [Policies] FROM [Policies] INNER JOIN [ModelItemPolicy] ON [ModelItemPolicy].[PolicyID] = [Policies].[PolicyID] WHERE NOT EXISTS (SELECT ItemID FROM [Catalog] WHERE [Catalog].[ItemID] = [ModelItemPolicy].[CatalogItemID]) GO GRANT EXECUTE ON [dbo].[CleanOrphanedPolicies] TO RSExecRole GO -------------------------------------------------- ------------- Snapshot manipulation if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[IncreaseTransientSnapshotRefcount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[IncreaseTransientSnapshotRefcount] GO CREATE PROCEDURE [dbo].[IncreaseTransientSnapshotRefcount] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @ExpirationMinutes as int AS DECLARE @soon AS datetime SET @soon = DATEADD(n, @ExpirationMinutes, GETDATE()) if @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET ExpirationDate = @soon, TransientRefcount = TransientRefcount + 1 WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET ExpirationDate = @soon, TransientRefcount = TransientRefcount + 1 WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[IncreaseTransientSnapshotRefcount] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DecreaseTransientSnapshotRefcount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DecreaseTransientSnapshotRefcount] GO CREATE PROCEDURE [dbo].[DecreaseTransientSnapshotRefcount] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS if @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET TransientRefcount = TransientRefcount - 1 WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET TransientRefcount = TransientRefcount - 1 WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[DecreaseTransientSnapshotRefcount] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[MarkSnapshotAsDependentOnUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[MarkSnapshotAsDependentOnUser] GO CREATE PROCEDURE [dbo].[MarkSnapshotAsDependentOnUser] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS if @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET DependsOnUser = 1 WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET DependsOnUser = 1 WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[MarkSnapshotAsDependentOnUser] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSnapshotChunksVersion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSnapshotChunksVersion] GO CREATE PROCEDURE [dbo].[SetSnapshotChunksVersion] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @Version as smallint AS if @IsPermanentSnapshot = 1 BEGIN if @Version > 0 BEGIN UPDATE ChunkData SET Version = @Version WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ChunkData SET Version = Version WHERE SnapshotDataID = @SnapshotDataID END END ELSE BEGIN if @Version > 0 BEGIN UPDATE ReportServerTempDB.dbo.ChunkData SET Version = @Version WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.ChunkData SET Version = Version WHERE SnapshotDataID = @SnapshotDataID END END GO GRANT EXECUTE ON [dbo].[SetSnapshotChunksVersion] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[LockSnapshotForUpgrade]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[LockSnapshotForUpgrade] GO CREATE PROCEDURE [dbo].[LockSnapshotForUpgrade] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS if @IsPermanentSnapshot = 1 BEGIN SELECT ChunkName from ChunkData with (XLOCK) WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN SELECT ChunkName from ReportServerTempDB.dbo.ChunkData with (XLOCK) WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[LockSnapshotForUpgrade] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[InsertUnreferencedSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[InsertUnreferencedSnapshot] GO CREATE PROCEDURE [dbo].[InsertUnreferencedSnapshot] @ReportID as uniqueidentifier = NULL, @EffectiveParams as ntext = NULL, @QueryParams as ntext = NULL, @ParamsHash as int = NULL, @CreatedDate as datetime, @Description as nvarchar(512) = NULL, @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @SnapshotTimeoutMinutes as int, @Machine as nvarchar(512) = NULL AS DECLARE @now datetime SET @now = GETDATE() IF @IsPermanentSnapshot = 1 BEGIN INSERT INTO SnapshotData (SnapshotDataID, CreatedDate, EffectiveParams, QueryParams, ParamsHash, Description, PermanentRefcount, TransientRefcount, ExpirationDate) VALUES (@SnapshotDataID, @CreatedDate, @EffectiveParams, @QueryParams, @ParamsHash, @Description, 0, 1, DATEADD(n, @SnapshotTimeoutMinutes, @now)) END ELSE BEGIN INSERT INTO ReportServerTempDB.dbo.SnapshotData (SnapshotDataID, CreatedDate, EffectiveParams, QueryParams, ParamsHash, Description, PermanentRefcount, TransientRefcount, ExpirationDate, Machine) VALUES (@SnapshotDataID, @CreatedDate, @EffectiveParams, @QueryParams, @ParamsHash, @Description, 0, 1, DATEADD(n, @SnapshotTimeoutMinutes, @now), @Machine) END GO GRANT EXECuTE ON [dbo].[InsertUnreferencedSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[PromoteSnapshotInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[PromoteSnapshotInfo] GO CREATE PROCEDURE [dbo].[PromoteSnapshotInfo] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @PageCount as int, @HasDocMap as bit AS IF @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET PageCount = @PageCount, HasDocMap = @HasDocMap WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET PageCount = @PageCount, HasDocMap = @HasDocMap WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[PromoteSnapshotInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapshotPromotedInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapshotPromotedInfo] GO CREATE PROCEDURE [dbo].[GetSnapshotPromotedInfo] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS IF @IsPermanentSnapshot = 1 BEGIN SELECT PageCount, HasDocMap FROM SnapshotData WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN SELECT PageCount, HasDocMap FROM ReportServerTempDB.dbo.SnapshotData WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[GetSnapshotPromotedInfo] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[AddHistoryRecord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddHistoryRecord] GO -- add new record to History table CREATE PROCEDURE [dbo].[AddHistoryRecord] @HistoryID uniqueidentifier, @ReportID uniqueidentifier, @SnapshotDate datetime, @SnapshotDataID uniqueidentifier, @SnapshotTransientRefcountChange int AS INSERT INTO History (HistoryID, ReportID, SnapshotDataID, SnapshotDate) VALUES (@HistoryID, @ReportID, @SnapshotDataID, @SnapshotDate) IF @@ERROR = 0 BEGIN UPDATE SnapshotData -- Snapshots, when created, have transient refcount set to 1. Here create permanent reference -- here so we need to increase permanent refcount and decrease transient refcount. However, -- if it was already referenced by the execution snapshot, transient refcount was already -- decreased. Hence, there's a parameter @SnapshotTransientRefcountChange that is 0 or -1. SET PermanentRefcount = PermanentRefcount + 1, TransientRefcount = TransientRefcount + @SnapshotTransientRefcountChange WHERE SnapshotData.SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[AddHistoryRecord] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[SetHistoryLimit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetHistoryLimit] GO CREATE PROCEDURE [dbo].[SetHistoryLimit] @Path nvarchar (425), @SnapshotLimit int = NULL AS UPDATE Catalog SET SnapshotLimit=@SnapshotLimit WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[SetHistoryLimit] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[ListHistory]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListHistory] GO -- list all historical snapshots for a specific report CREATE PROCEDURE [dbo].[ListHistory] @ReportID uniqueidentifier AS SELECT S.SnapshotDate, (SELECT SUM(DATALENGTH( CD.Content ) ) FROM ChunkData AS CD WHERE CD.SnapshotDataID = S.SnapshotDataID ) FROM History AS S -- skipping intermediate table SnapshotData WHERE S.ReportID = @ReportID GO GRANT EXECUTE ON [dbo].[ListHistory] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanHistoryForReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanHistoryForReport] GO -- delete snapshots exceeding # of snapshots. won't work if @SnapshotLimit = 0 CREATE PROCEDURE [dbo].[CleanHistoryForReport] @SnapshotLimit int, @ReportID uniqueidentifier AS DECLARE @cmd varchar(2000) SET @cmd = 'DELETE FROM History WHERE ReportID = ''' + cast(@ReportID as varchar(40) ) + ''' and SnapshotDate < (SELECT MIN(SnapshotDate) FROM (SELECT TOP ' + CAST(@SnapshotLimit as varchar(20)) + ' SnapshotDate FROM History WHERE ReportID = ''' + cast(@ReportID as varchar(40) ) + ''' ORDER BY SnapshotDate DESC ) AS TopSnapshots )' EXEC( @cmd ) GO GRANT EXECUTE ON [dbo].[CleanHistoryForReport] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanAllHistories]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanAllHistories] GO -- delete snapshots exceeding # of snapshots for the whole system CREATE PROCEDURE [dbo].[CleanAllHistories] @SnapshotLimit int AS DECLARE @cmd varchar(2000) SET @cmd = 'DELETE FROM History WHERE HistoryID in (SELECT HistoryID FROM History JOIN Catalog AS ReportJoinSnapshot ON ItemID = ReportID WHERE SnapshotLimit is NULL and SnapshotDate < (SELECT MIN(SnapshotDate) FROM (SELECT TOP ' + CAST(@SnapshotLimit as varchar(20)) + ' SnapshotDate FROM History AS InnerSnapshot WHERE InnerSnapshot.ReportID = ReportJoinSnapshot.ItemID ORDER BY SnapshotDate DESC ) AS TopSnapshots ) )' EXEC( @cmd ) GO GRANT EXECUTE ON [dbo].[CleanAllHistories] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteHistoryRecord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteHistoryRecord] GO -- delete one historical snapshot CREATE PROCEDURE [dbo].[DeleteHistoryRecord] @ReportID uniqueidentifier, @SnapshotDate DateTime AS DELETE FROM History WHERE ReportID = @ReportID AND SnapshotDate = @SnapshotDate GO GRANT EXECUTE ON [dbo].[DeleteHistoryRecord] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteAllHistoryForReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteAllHistoryForReport] GO -- delete all snapshots for a report CREATE PROCEDURE [dbo].[DeleteAllHistoryForReport] @ReportID uniqueidentifier AS DELETE FROM History WHERE HistoryID in (SELECT HistoryID FROM History JOIN Catalog on ItemID = ReportID WHERE ReportID = @ReportID ) GO GRANT EXECUTE ON [dbo].[DeleteAllHistoryForReport] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteHistoriesWithNoPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteHistoriesWithNoPolicy] GO -- delete all snapshots for all reports that inherit system History policy CREATE PROCEDURE [dbo].[DeleteHistoriesWithNoPolicy] AS DELETE FROM History WHERE HistoryID in (SELECT HistoryID FROM History JOIN Catalog on ItemID = ReportID WHERE SnapshotLimit is null ) GO GRANT EXECUTE ON [dbo].[DeleteHistoriesWithNoPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Get_sqlagent_job_status]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[Get_sqlagent_job_status] GO CREATE PROCEDURE [dbo].[Get_sqlagent_job_status] -- Individual job parameters @job_id UNIQUEIDENTIFIER = NULL, -- If provided will only return info about this job -- Note: Only @job_id or @job_name needs to be provided @job_name sysname = NULL, -- If provided will only return info about this job @owner_login_name sysname = NULL -- If provided will only return jobs for this owner AS BEGIN DECLARE @retval INT DECLARE @job_owner_sid VARBINARY(85) DECLARE @is_sysadmin INT SET NOCOUNT ON -- Remove any leading/trailing spaces from parameters (except @owner_login_name) SELECT @job_name = LTRIM(RTRIM(@job_name)) -- Turn [nullable] empty string parameters into NULLs IF (@job_name = N'') SELECT @job_name = NULL -- Verify the job if supplied. This also checks if the caller has rights to view the job IF ((@job_id IS NOT NULL) OR (@job_name IS NOT NULL)) BEGIN EXECUTE @retval = msdb..sp_verify_job_identifiers '@job_name', '@job_id', @job_name OUTPUT, @job_id OUTPUT IF (@retval <> 0) RETURN(1) -- Failure END -- If the login name isn't given, set it to the job owner or the current caller IF(@owner_login_name IS NULL) BEGIN SET @owner_login_name = (SELECT SUSER_SNAME(sj.owner_sid) FROM msdb.dbo.sysjobs sj where sj.job_id = @job_id) SET @is_sysadmin = ISNULL(IS_SRVROLEMEMBER(N'sysadmin', @owner_login_name), 0) END ELSE BEGIN -- Check owner IF (SUSER_SID(@owner_login_name) IS NULL) BEGIN RAISERROR(14262, -1, -1, '@owner_login_name', @owner_login_name) RETURN(1) -- Failure END --only allow sysadmin types to specify the owner IF ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1) AND (ISNULL(IS_MEMBER(N'SQLAgentAdminRole'), 0) = 1) AND (SUSER_SNAME() <> @owner_login_name)) BEGIN --TODO: RAISERROR(14525, -1, -1) RETURN(1) -- Failure END SET @is_sysadmin = 0 END IF (@job_id IS NOT NULL) BEGIN -- Individual job... EXECUTE @retval = master.dbo.xp_sqlagent_enum_jobs @is_sysadmin, @owner_login_name, @job_id IF (@retval <> 0) RETURN(1) -- Failure END ELSE BEGIN -- Set of jobs... EXECUTE @retval = master.dbo.xp_sqlagent_enum_jobs @is_sysadmin, @owner_login_name IF (@retval <> 0) RETURN(1) -- Failure END RETURN(0) -- Success END GO GRANT EXECUTE ON [dbo].[Get_sqlagent_job_status] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateTask] GO CREATE PROCEDURE [dbo].[CreateTask] @ScheduleID uniqueidentifier, @Name nvarchar (260), @StartDate datetime, @Flags int, @NextRunTime datetime = NULL, @LastRunTime datetime = NULL, @EndDate datetime = NULL, @RecurrenceType int = NULL, @MinutesInterval int = NULL, @DaysInterval int = NULL, @WeeksInterval int = NULL, @DaysOfWeek int = NULL, @DaysOfMonth int = NULL, @Month int = NULL, @MonthlyWeek int = NULL, @State int = NULL, @LastRunStatus nvarchar (260) = NULL, @ScheduledRunTimeout int = NULL, @UserSid varbinary (85) = null, @UserName nvarchar(260), @AuthType int, @EventType nvarchar (260), @EventData nvarchar (260), @Type int AS DECLARE @UserID uniqueidentifier EXEC GetUserID @UserSid, @UserName, @AuthType, @UserID OUTPUT -- Create a task with the given data. Insert into Schedule ( [ScheduleID], [Name], [StartDate], [Flags], [NextRunTime], [LastRunTime], [EndDate], [RecurrenceType], [MinutesInterval], [DaysInterval], [WeeksInterval], [DaysOfWeek], [DaysOfMonth], [Month], [MonthlyWeek], [State], [LastRunStatus], [ScheduledRunTimeout], [CreatedById], [EventType], [EventData], [Type] ) values (@ScheduleID, @Name, @StartDate, @Flags, @NextRunTime, @LastRunTime, @EndDate, @RecurrenceType, @MinutesInterval, @DaysInterval, @WeeksInterval, @DaysOfWeek, @DaysOfMonth, @Month, @MonthlyWeek, @State, @LastRunStatus, @ScheduledRunTimeout, @UserID, @EventType, @EventData, @Type) GO GRANT EXECUTE ON [dbo].[CreateTask] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateTask] GO CREATE PROCEDURE [dbo].[UpdateTask] @ScheduleID uniqueidentifier, @Name nvarchar (260), @StartDate datetime, @Flags int, @NextRunTime datetime = NULL, @LastRunTime datetime = NULL, @EndDate datetime = NULL, @RecurrenceType int = NULL, @MinutesInterval int = NULL, @DaysInterval int = NULL, @WeeksInterval int = NULL, @DaysOfWeek int = NULL, @DaysOfMonth int = NULL, @Month int = NULL, @MonthlyWeek int = NULL, @State int = NULL, @LastRunStatus nvarchar (260) = NULL, @ScheduledRunTimeout int = NULL AS -- Update a tasks values. ScheduleID and Report information can not be updated Update Schedule set [StartDate] = @StartDate, [Name] = @Name, [Flags] = @Flags, [NextRunTime] = @NextRunTime, [LastRunTime] = @LastRunTime, [EndDate] = @EndDate, [RecurrenceType] = @RecurrenceType, [MinutesInterval] = @MinutesInterval, [DaysInterval] = @DaysInterval, [WeeksInterval] = @WeeksInterval, [DaysOfWeek] = @DaysOfWeek, [DaysOfMonth] = @DaysOfMonth, [Month] = @Month, [MonthlyWeek] = @MonthlyWeek, [State] = @State, [LastRunStatus] = @LastRunStatus, [ScheduledRunTimeout] = @ScheduledRunTimeout where [ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[UpdateTask] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateScheduleNextRunTime]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateScheduleNextRunTime] GO CREATE PROCEDURE [dbo].[UpdateScheduleNextRunTime] @ScheduleID as uniqueidentifier, @NextRunTime as datetime as update Schedule set [NextRunTime] = @NextRunTime where [ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[UpdateScheduleNextRunTime] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListScheduledReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListScheduledReports] GO CREATE PROCEDURE [dbo].[ListScheduledReports] @ScheduleID uniqueidentifier, @AuthType int AS -- List all reports for a schedule select RS.[ReportAction], RS.[ScheduleID], RS.[ReportID], RS.[SubscriptionID], C.[Path], C.[Name], C.[Description], C.[ModifiedDate], SUSER_SNAME(U.[Sid]), U.[UserName], DATALENGTH( C.Content ), C.ExecutionTime, S.[Type], SD.[NtSecDescPrimary] from [ReportSchedule] RS Inner join [Catalog] C on RS.[ReportID] = C.[ItemID] left outer join [SecData] SD on SD.[PolicyID] = C.[PolicyID] AND SD.AuthType = @AuthType Inner join [Schedule] S on RS.[ScheduleID] = S.[ScheduleID] Inner join [Users] U on C.[ModifiedByID] = U.UserID where RS.[ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[ListScheduledReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListTasks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListTasks] GO CREATE PROCEDURE [dbo].[ListTasks] AS select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], (select count(*) from ReportSchedule where ReportSchedule.ScheduleID = S.ScheduleID) from [Schedule] S inner join [Users] Owner on S.[CreatedById] = Owner.UserID where S.[Type] = 0 -- Type 0 is shared schedules GO GRANT EXECUTE ON [dbo].[ListTasks] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListTasksForMaintenance]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListTasksForMaintenance] GO CREATE PROCEDURE [dbo].[ListTasksForMaintenance] AS declare @date datetime set @date = GETUTCDATE() update [Schedule] set [ConsistancyCheck] = @date from ( SELECT TOP 20 [ScheduleID] FROM [Schedule] WITH(UPDLOCK) WHERE [ConsistancyCheck] is NULL ) AS t1 WHERE [Schedule].[ScheduleID] = t1.[ScheduleID] select top 20 S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type] from [Schedule] S where [ConsistancyCheck] = @date GO GRANT EXECUTE ON [dbo].[ListTasksForMaintenance] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ClearScheduleConsistancyFlags]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ClearScheduleConsistancyFlags] GO CREATE PROCEDURE [dbo].[ClearScheduleConsistancyFlags] AS update [Schedule] with (tablock, xlock) set [ConsistancyCheck] = NULL GO GRANT EXECUTE ON [dbo].[ClearScheduleConsistancyFlags] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAReportsReportAction]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAReportsReportAction] GO CREATE PROCEDURE [dbo].[GetAReportsReportAction] @ReportID uniqueidentifier, @ReportAction int AS select RS.[ReportAction], RS.[ScheduleID], RS.[ReportID], RS.[SubscriptionID], C.[Path] from [ReportSchedule] RS Inner join [Catalog] C on RS.[ReportID] = C.[ItemID] where C.ItemID = @ReportID and RS.[ReportAction] = @ReportAction GO GRANT EXECUTE ON [dbo].[GetAReportsReportAction] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetTimeBasedSubscriptionReportAction]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetTimeBasedSubscriptionReportAction] GO CREATE PROCEDURE [dbo].[GetTimeBasedSubscriptionReportAction] @SubscriptionID uniqueidentifier AS select RS.[ReportAction], RS.[ScheduleID], RS.[ReportID], RS.[SubscriptionID], C.[Path] from [ReportSchedule] RS Inner join [Catalog] C on RS.[ReportID] = C.[ItemID] where RS.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetTimeBasedSubscriptionReportAction] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetTaskProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetTaskProperties] GO CREATE PROCEDURE [dbo].[GetTaskProperties] @ScheduleID uniqueidentifier AS -- Grab all of a tasks properties given a task id select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], SUSER_SNAME(Owner.[Sid]), Owner.[UserName] from [Schedule] S with (XLOCK) Inner join [Users] Owner on S.[CreatedById] = Owner.UserID where S.[ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[GetTaskProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteTask] GO CREATE PROCEDURE [dbo].[DeleteTask] @ScheduleID uniqueidentifier AS -- Delete the task with the given task id DELETE FROM Schedule WHERE [ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[DeleteTask] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSchedulesReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSchedulesReports] GO CREATE PROCEDURE [dbo].[GetSchedulesReports] @ID uniqueidentifier AS select C.Path from ReportSchedule RS inner join Catalog C on (C.ItemID = RS.ReportID) where ScheduleID = @ID GO GRANT EXECUTE ON [dbo].[GetSchedulesReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddReportSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddReportSchedule] GO CREATE PROCEDURE [dbo].[AddReportSchedule] @ScheduleID uniqueidentifier, @ReportID uniqueidentifier, @SubscriptionID uniqueidentifier = NULL, @Action int AS Insert into ReportSchedule ([ScheduleID], [ReportID], [SubscriptionID], [ReportAction]) values (@ScheduleID, @ReportID, @SubscriptionID, @Action) GO GRANT EXECUTE ON [dbo].[AddReportSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteReportSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteReportSchedule] GO CREATE PROCEDURE [dbo].[DeleteReportSchedule] @ScheduleID uniqueidentifier, @ReportID uniqueidentifier, @SubscriptionID uniqueidentifier = NULL, @ReportAction int AS IF @SubscriptionID is NULL BEGIN delete from ReportSchedule where ScheduleID = @ScheduleID and ReportID = @ReportID and ReportAction = @ReportAction END ELSE BEGIN delete from ReportSchedule where ScheduleID = @ScheduleID and ReportID = @ReportID and ReportAction = @ReportAction and SubscriptionID = @SubscriptionID END GO GRANT EXECUTE ON [dbo].[DeleteReportSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapShotSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapShotSchedule] GO CREATE PROCEDURE [dbo].[GetSnapShotSchedule] @ReportID uniqueidentifier AS select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], SUSER_SNAME(Owner.[Sid]), Owner.[UserName] from Schedule S with (XLOCK) inner join ReportSchedule RS on S.ScheduleID = RS.ScheduleID inner join [Users] Owner on S.[CreatedById] = Owner.[UserID] where RS.ReportAction = 2 and -- 2 == create snapshot RS.ReportID = @ReportID GO GRANT EXECUTE ON [dbo].[GetSnapShotSchedule] TO RSExecRole GO -------------------------------------------------- ------------- Time based subscriptions if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateTimeBasedSubscriptionSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateTimeBasedSubscriptionSchedule] GO CREATE PROCEDURE [dbo].[CreateTimeBasedSubscriptionSchedule] @SubscriptionID as uniqueidentifier, @ScheduleID uniqueidentifier, @Schedule_Name nvarchar (260), @Report_Name nvarchar (425), @StartDate datetime, @Flags int, @NextRunTime datetime = NULL, @LastRunTime datetime = NULL, @EndDate datetime = NULL, @RecurrenceType int = NULL, @MinutesInterval int = NULL, @DaysInterval int = NULL, @WeeksInterval int = NULL, @DaysOfWeek int = NULL, @DaysOfMonth int = NULL, @Month int = NULL, @MonthlyWeek int = NULL, @State int = NULL, @LastRunStatus nvarchar (260) = NULL, @ScheduledRunTimeout int = NULL, @UserSid varbinary (85) = NULL, @UserName nvarchar(260), @AuthType int, @EventType nvarchar (260), @EventData nvarchar (260) AS EXEC CreateTask @ScheduleID, @Schedule_Name, @StartDate, @Flags, @NextRunTime, @LastRunTime, @EndDate, @RecurrenceType, @MinutesInterval, @DaysInterval, @WeeksInterval, @DaysOfWeek, @DaysOfMonth, @Month, @MonthlyWeek, @State, @LastRunStatus, @ScheduledRunTimeout, @UserSid, @UserName, @AuthType, @EventType, @EventData, 1 -- scoped type -- add a row to the reportSchedule table declare @Report_OID uniqueidentifier select @Report_OID = (select [ItemID] from [Catalog] with (HOLDLOCK) where [Catalog].[Path] = @Report_Name and ([Catalog].[Type] = 2 or [Catalog].[Type] = 4)) EXEC AddReportSchedule @ScheduleID, @Report_OID, @SubscriptionID, 4 -- TimedSubscription action GO GRANT EXECUTE ON [dbo].[CreateTimeBasedSubscriptionSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetTimeBasedSubscriptionSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetTimeBasedSubscriptionSchedule] GO CREATE PROCEDURE [dbo].[GetTimeBasedSubscriptionSchedule] @SubscriptionID as uniqueidentifier AS select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], SUSER_SNAME(Owner.[Sid]), Owner.[UserName] from [ReportSchedule] R inner join Schedule S with (XLOCK) on R.[ScheduleID] = S.[ScheduleID] Inner join [Users] Owner on S.[CreatedById] = Owner.UserID where R.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetTimeBasedSubscriptionSchedule] TO RSExecRole GO -------------------------------------------------- ------------- Running Jobs if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddRunningJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddRunningJob] GO CREATE PROCEDURE [dbo].[AddRunningJob] @JobID as nvarchar(32), @StartDate as datetime, @ComputerName as nvarchar(32), @RequestName as nvarchar(425), @RequestPath as nvarchar(425), @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @Description as ntext = NULL, @Timeout as int, @JobAction as smallint, @JobType as smallint, @JobStatus as smallint AS DECLARE @UserID uniqueidentifier EXEC GetUserID @UserSid, @UserName, @AuthType, @UserID OUTPUT INSERT INTO RunningJobs (JobID, StartDate, ComputerName, RequestName, RequestPath, UserID, Description, Timeout, JobAction, JobType, JobStatus ) VALUES (@JobID, @StartDate, @ComputerName, @RequestName, @RequestPath, @UserID, @Description, @Timeout, @JobAction, @JobType, @JobStatus) GO GRANT EXECUTE ON [dbo].[AddRunningJob] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RemoveRunningJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RemoveRunningJob] GO CREATE PROCEDURE [dbo].[RemoveRunningJob] @JobID as nvarchar(32) AS DELETE FROM RunningJobs WHERE JobID = @JobID GO GRANT EXECUTE ON [dbo].[RemoveRunningJob] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateRunningJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateRunningJob] GO CREATE PROCEDURE [dbo].[UpdateRunningJob] @JobID as nvarchar(32), @JobStatus as smallint AS UPDATE RunningJobs SET JobStatus = @JobStatus WHERE JobID = @JobID GO GRANT EXECUTE ON [dbo].[UpdateRunningJob] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetMyRunningJobs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetMyRunningJobs] GO CREATE PROCEDURE [dbo].[GetMyRunningJobs] @ComputerName as nvarchar(32), @JobType as smallint AS SELECT JobID, StartDate, ComputerName, RequestName, RequestPath, SUSER_SNAME(Users.[Sid]), Users.[UserName], Description, Timeout, JobAction, JobType, JobStatus FROM RunningJobs INNER JOIN Users ON RunningJobs.UserID = Users.UserID WHERE ComputerName = @ComputerName AND JobType = @JobType GO GRANT EXECUTE ON [dbo].[GetMyRunningJobs] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListRunningJobs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListRunningJobs] GO CREATE PROCEDURE [dbo].[ListRunningJobs] AS SELECT JobID, StartDate, ComputerName, RequestName, RequestPath, SUSER_SNAME(Users.[Sid]), Users.[UserName], Description, Timeout, JobAction, JobType, JobStatus FROM RunningJobs INNER JOIN Users ON RunningJobs.UserID = Users.UserID GO GRANT EXECUTE ON [dbo].[ListRunningJobs] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredJobs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredJobs] GO CREATE PROCEDURE [dbo].[CleanExpiredJobs] AS DELETE FROM RunningJobs WHERE DATEADD(s, Timeout, StartDate) < GETDATE() GO GRANT EXECUTE ON [dbo].[CleanExpiredJobs] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateObject]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateObject] GO -- This SP should never be called with a policy ID unless it is guarenteed that -- the parent will not be deleted before the insert (such as while running this script) CREATE PROCEDURE [dbo].[CreateObject] @ItemID uniqueidentifier, @Name nvarchar (425), @Path nvarchar (425), @ParentID uniqueidentifier, @Type int, @Content image = NULL, @Intermediate uniqueidentifier = NULL, @LinkSourceID uniqueidentifier = NULL, @Property ntext = NULL, @Parameter ntext = NULL, @Description ntext = NULL, @Hidden bit = NULL, @CreatedBySid varbinary(85) = NULL, @CreatedByName nvarchar(260), @AuthType int, @CreationDate datetime, @MimeType nvarchar (260) = NULL, @SnapshotLimit int = NULL, @PolicyRoot int = 0, @PolicyID uniqueidentifier = NULL, @ExecutionFlag int = 1 -- allow live execution, don't keep history AS DECLARE @CreatedByID uniqueidentifier EXEC GetUserID @CreatedBySid, @CreatedByName, @AuthType, @CreatedByID OUTPUT UPDATE Catalog with (XLOCK) SET ModifiedByID = @CreatedByID, ModifiedDate = @CreationDate WHERE ItemID = @ParentID -- If no policyID, use the parent's IF @PolicyID is NULL BEGIN SET @PolicyID = (SELECT PolicyID FROM [dbo].[Catalog] WHERE Catalog.ItemID = @ParentID) END -- If there is no policy ID then we are guarenteed not to have a parent IF @PolicyID is NULL BEGIN RAISERROR ('Parent Not Found', 16, 1) return END INSERT INTO Catalog (ItemID, Path, Name, ParentID, Type, Content, Intermediate, LinkSourceID, Property, Description, Hidden, CreatedByID, CreationDate, ModifiedByID, ModifiedDate, MimeType, SnapshotLimit, [Parameter], PolicyID, PolicyRoot, ExecutionFlag ) VALUES (@ItemID, @Path, @Name, @ParentID, @Type, @Content, @Intermediate, @LinkSourceID, @Property, @Description, @Hidden, @CreatedByID, @CreationDate, @CreatedByID, @CreationDate, @MimeType, @SnapshotLimit, @Parameter, @PolicyID, @PolicyRoot , @ExecutionFlag) IF @Intermediate IS NOT NULL AND @@ERROR = 0 BEGIN UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount + 1, TransientRefcount = TransientRefcount - 1 WHERE SnapshotData.SnapshotDataID = @Intermediate END GO GRANT EXECUTE ON [dbo].[CreateObject] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteObject]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteObject] GO CREATE PROCEDURE [dbo].[DeleteObject] @Path nvarchar (425), @Prefix nvarchar (850) AS -- Remove reference for intermediate formats UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 FROM Catalog AS R WITH (XLOCK) INNER JOIN [SnapshotData] AS SD ON R.Intermediate = SD.SnapshotDataID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Remove reference for execution snapshots UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 FROM Catalog AS R WITH (XLOCK) INNER JOIN [SnapshotData] AS SD ON R.SnapshotDataID = SD.SnapshotDataID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Remove history for deleted reports and linked report DELETE History FROM [Catalog] AS R INNER JOIN [History] AS S ON R.ItemID = S.ReportID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Remove model drill reports DELETE ModelDrill FROM [Catalog] AS C INNER JOIN [ModelDrill] AS M ON C.ItemID = M.ReportID WHERE (C.Path = @Path OR C.Path LIKE @Prefix ESCAPE '*') -- Adjust data sources UPDATE [DataSource] SET [Flags] = [Flags] & 0x7FFFFFFD, -- broken link [Link] = NULL FROM [Catalog] AS C INNER JOIN [DataSource] AS DS ON C.[ItemID] = DS.[Link] WHERE (C.Path = @Path OR C.Path LIKE @Prefix ESCAPE '*') -- Clean all data sources DELETE [DataSource] FROM [Catalog] AS R INNER JOIN [DataSource] AS DS ON R.[ItemID] = DS.[ItemID] WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Update linked reports UPDATE LR SET LR.LinkSourceID = NULL FROM [Catalog] AS R INNER JOIN [Catalog] AS LR ON R.ItemID = LR.LinkSourceID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') AND (LR.Path NOT LIKE @Prefix ESCAPE '*') -- Remove references for cache entries UPDATE SN SET PermanentRefcount = PermanentRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC on SN.SnapshotDataID = EC.SnapshotDataID INNER JOIN Catalog AS C ON EC.ReportID = C.ItemID WHERE (Path = @Path OR Path LIKE @Prefix ESCAPE '*') -- Clean cache entries for items to be deleted DELETE EC FROM ReportServerTempDB.dbo.ExecutionCache AS EC INNER JOIN Catalog AS C ON EC.ReportID = C.ItemID WHERE (Path = @Path OR Path LIKE @Prefix ESCAPE '*') -- Finally delete items DELETE FROM [Catalog] WHERE (Path = @Path OR Path LIKE @Prefix ESCAPE '*') EXEC CleanOrphanedPolicies GO GRANT EXECUTE ON [dbo].[DeleteObject] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindObjectsNonRecursive]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindObjectsNonRecursive] GO CREATE PROCEDURE [dbo].[FindObjectsNonRecursive] @Path nvarchar (425), @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.[UserName], SUSER_SNAME(MU.Sid), MU.[UserName], C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Catalog AS P ON C.ParentID = P.ItemID INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE P.Path = @Path GO GRANT EXECUTE ON [dbo].[FindObjectsNonRecursive] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindObjectsRecursive]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindObjectsRecursive] GO CREATE PROCEDURE [dbo].[FindObjectsRecursive] @Prefix nvarchar (850), @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.UserName, SUSER_SNAME(MU.Sid), MU.UserName, C.MimeType, C.ExecutionTime, C.Hidden from Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE C.Path LIKE @Prefix ESCAPE '*' GO GRANT EXECUTE ON [dbo].[FindObjectsRecursive] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindObjectsByLink]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindObjectsByLink] GO CREATE PROCEDURE [dbo].[FindObjectsByLink] @Link uniqueidentifier, @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.UserName, SUSER_SNAME(MU.Sid), MU.UserName, C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE C.LinkSourceID = @Link GO GRANT EXECUTE ON [dbo].[FindObjectsByLink] TO RSExecRole GO -------------------------------------------------- ------------- Procedures used to update linked reports if exists (select * from sysobjects where id = object_id('[dbo].[GetIDPairsByLink]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetIDPairsByLink] GO CREATE PROCEDURE [dbo].[GetIDPairsByLink] @Link uniqueidentifier AS SELECT LinkSourceID, ItemID FROM Catalog WHERE LinkSourceID = @Link GO GRANT EXECUTE ON [dbo].[GetIDPairsByLink] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[GetChildrenBeforeDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetChildrenBeforeDelete] GO CREATE PROCEDURE [dbo].[GetChildrenBeforeDelete] @Prefix nvarchar (850), @AuthType int AS SELECT C.PolicyID, C.Type, SD.NtSecDescPrimary FROM Catalog AS C LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE C.Path LIKE @Prefix ESCAPE '*' -- return children only, not item itself GO GRANT EXECUTE ON [dbo].[GetChildrenBeforeDelete] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAllProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAllProperties] GO CREATE PROCEDURE [dbo].[GetAllProperties] @Path nvarchar (425), @AuthType int AS select Property, Description, Type, DATALENGTH( Content ), ItemID, SUSER_SNAME(C.Sid), C.UserName, CreationDate, SUSER_SNAME(M.Sid), M.UserName, ModifiedDate, MimeType, ExecutionTime, NtSecDescPrimary, [LinkSourceID], Hidden, ExecutionFlag, SnapshotLimit FROM Catalog INNER JOIN Users C ON Catalog.CreatedByID = C.UserID INNER JOIN Users M ON Catalog.ModifiedByID = M.UserID LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[GetAllProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetParameters] GO CREATE PROCEDURE [dbo].[GetParameters] @Path nvarchar (425), @AuthType int AS SELECT Type, [Parameter], ItemID, SecData.NtSecDescPrimary, [LinkSourceID], [ExecutionFlag] FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[GetParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetObjectContent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetObjectContent] GO CREATE PROCEDURE [dbo].[GetObjectContent] @Path nvarchar (425), @AuthType int AS SELECT Type, Content, LinkSourceID, MimeType, SecData.NtSecDescPrimary, ItemID FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[GetObjectContent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCompiledDefinition]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetCompiledDefinition] GO -- used to create snapshots CREATE PROCEDURE [dbo].[GetCompiledDefinition] @Path nvarchar (425), @AuthType int AS SELECT MainItem.Type, MainItem.Intermediate, MainItem.LinkSourceID, MainItem.Property, MainItem.Description, SecData.NtSecDescPrimary, MainItem.ItemID, MainItem.ExecutionFlag, LinkTarget.Intermediate, LinkTarget.Property, LinkTarget.Description, MainItem.[SnapshotDataID] FROM Catalog MainItem LEFT OUTER JOIN SecData ON MainItem.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog LinkTarget with (INDEX = PK_CATALOG) on MainItem.LinkSourceID = LinkTarget.ItemID WHERE MainItem.Path = @Path GO GRANT EXECUTE ON [dbo].[GetCompiledDefinition] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetReportForExecution]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetReportForExecution] GO -- gets either the intermediate format or snapshot from cache CREATE PROCEDURE [dbo].[GetReportForExecution] @Path nvarchar (425), @ParamsHash int, @AuthType int AS DECLARE @now AS datetime SET @now = GETDATE() IF ( NOT EXISTS ( SELECT * FROM Catalog AS C INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON C.ItemID = EC.ReportID INNER JOIN ReportServerTempDB.dbo.SnapshotData AS SN ON EC.SnapshotDataID = SN.SnapshotDataID WHERE C.Path = @Path AND EC.AbsoluteExpiration > @now AND SN.ParamsHash = @ParamsHash ) ) BEGIN -- no cache SELECT Cat.Type, Cat.LinkSourceID, Cat2.Path, Cat.Property, Cat.Description, SecData.NtSecDescPrimary, Cat.ItemID, CAST (0 AS BIT), -- not found, Cat.Intermediate, Cat.ExecutionFlag, SD.SnapshotDataID, SD.DependsOnUser, Cat.ExecutionTime, (SELECT Schedule.NextRunTime FROM Schedule WITH (XLOCK) INNER JOIN ReportSchedule ON Schedule.ScheduleID = ReportSchedule.ScheduleID WHERE ReportSchedule.ReportID = Cat.ItemID AND ReportSchedule.ReportAction = 1), -- update snapshot (SELECT Schedule.ScheduleID FROM Schedule INNER JOIN ReportSchedule ON Schedule.ScheduleID = ReportSchedule.ScheduleID WHERE ReportSchedule.ReportID = Cat.ItemID AND ReportSchedule.ReportAction = 1), -- update snapshot (SELECT CachePolicy.ExpirationFlags FROM CachePolicy WHERE CachePolicy.ReportID = Cat.ItemID), Cat2.Intermediate FROM Catalog AS Cat LEFT OUTER JOIN SecData ON Cat.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog AS Cat2 on Cat.LinkSourceID = Cat2.ItemID LEFT OUTER JOIN SnapshotData AS SD ON Cat.SnapshotDataID = SD.SnapshotDataID WHERE Cat.Path = @Path END ELSE BEGIN -- use cache SELECT TOP 1 Cat.Type, Cat.LinkSourceID, Cat2.Path, Cat.Property, Cat.Description, SecData.NtSecDescPrimary, Cat.ItemID, CAST (1 AS BIT), -- found, SN.SnapshotDataID, SN.DependsOnUser, SN.EffectiveParams, SN.CreatedDate, EC.AbsoluteExpiration, (SELECT CachePolicy.ExpirationFlags FROM CachePolicy WHERE CachePolicy.ReportID = Cat.ItemID), (SELECT Schedule.ScheduleID FROM Schedule WITH (XLOCK) INNER JOIN ReportSchedule ON Schedule.ScheduleID = ReportSchedule.ScheduleID WHERE ReportSchedule.ReportID = Cat.ItemID AND ReportSchedule.ReportAction = 1), -- update snapshot SN.QueryParams FROM Catalog AS Cat INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON Cat.ItemID = EC.ReportID INNER JOIN ReportServerTempDB.dbo.SnapshotData AS SN ON EC.SnapshotDataID = SN.SnapshotDataID LEFT OUTER JOIN SecData ON Cat.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog AS Cat2 on Cat.LinkSourceID = Cat2.ItemID WHERE Cat.Path = @Path AND AbsoluteExpiration > @now AND SN.ParamsHash = @ParamsHash ORDER BY SN.CreatedDate DESC END GO GRANT EXECUTE ON [dbo].[GetReportForExecution] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetReportParametersForExecution]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetReportParametersForExecution] GO -- gets either the intermediate format or snapshot from cache CREATE PROCEDURE [dbo].[GetReportParametersForExecution] @Path nvarchar (425), @HistoryID DateTime = NULL, @AuthType int AS SELECT C.[ItemID], C.[Type], C.[ExecutionFlag], [SecData].[NtSecDescPrimary], C.[Parameter], C.[Intermediate], C.[SnapshotDataID], [History].[SnapshotDataID], L.[Intermediate], C.[LinkSourceID], C.[ExecutionTime] FROM [Catalog] AS C LEFT OUTER JOIN [SecData] ON C.[PolicyID] = [SecData].[PolicyID] AND [SecData].AuthType = @AuthType LEFT OUTER JOIN [History] ON ( C.[ItemID] = [History].[ReportID] AND [History].[SnapshotDate] = @HistoryID ) LEFT OUTER JOIN [Catalog] AS L ON C.[LinkSourceID] = L.[ItemID] WHERE C.[Path] = @Path GO GRANT EXECUTE ON [dbo].[GetReportParametersForExecution] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[MoveObject]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[MoveObject] GO CREATE PROCEDURE [dbo].[MoveObject] @OldPath nvarchar (425), @OldPrefix nvarchar (850), @NewName nvarchar (425), @NewPath nvarchar (425), @NewParentID uniqueidentifier, @RenameOnly as bit, @MaxPathLength as int AS DECLARE @LongPath nvarchar(425) SET @LongPath = (SELECT TOP 1 Path FROM Catalog WHERE LEN(Path)-LEN(@OldPath)+LEN(@NewPath) > @MaxPathLength AND Path LIKE @OldPrefix ESCAPE '*') IF @LongPath IS NOT NULL BEGIN SELECT @LongPath RETURN END IF @RenameOnly = 0 -- if this a full-blown move, not just a rename BEGIN -- adjust policies on the top item that gets moved DECLARE @OldInheritedPolicyID as uniqueidentifier SELECT @OldInheritedPolicyID = (SELECT PolicyID FROM Catalog with (XLOCK) WHERE Path = @OldPath AND PolicyRoot = 0) IF (@OldInheritedPolicyID IS NOT NULL) BEGIN -- this was not a policy root, change it to inherit from target folder DECLARE @NewPolicyID as uniqueidentifier SELECT @NewPolicyID = (SELECT PolicyID FROM Catalog with (XLOCK) WHERE ItemID = @NewParentID) -- update item and children that shared the old policy UPDATE Catalog SET PolicyID = @NewPolicyID WHERE Path = @OldPath UPDATE Catalog SET PolicyID = @NewPolicyID WHERE Path LIKE @OldPrefix ESCAPE '*' AND Catalog.PolicyID = @OldInheritedPolicyID END END -- Update item that gets moved (Path, Name, and ParentId) update Catalog set Name = @NewName, Path = @NewPath, ParentID = @NewParentID where Path = @OldPath -- Update all its children (Path only, Names and ParentIds stay the same) update Catalog set Path = STUFF(Path, 1, LEN(@OldPath), @NewPath ) where Path like @OldPrefix escape '*' GO GRANT EXECUTE ON [dbo].[MoveObject] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ObjectExists]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ObjectExists] GO CREATE PROCEDURE [dbo].[ObjectExists] @Path nvarchar (425), @AuthType int AS SELECT Type, ItemID, SnapshotLimit, NtSecDescPrimary, ExecutionFlag, Intermediate, [LinkSourceID] FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[ObjectExists] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetAllProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetAllProperties] GO CREATE PROCEDURE [dbo].[SetAllProperties] @Path nvarchar (425), @Property ntext, @Description ntext = NULL, @Hidden bit = NULL, @ModifiedBySid varbinary (85) = NULL, @ModifiedByName nvarchar(260), @AuthType int, @ModifiedDate DateTime AS DECLARE @ModifiedByID uniqueidentifier EXEC GetUserID @ModifiedBySid, @ModifiedByName, @AuthType, @ModifiedByID OUTPUT UPDATE Catalog SET Property = @Property, Description = @Description, Hidden = @Hidden, ModifiedByID = @ModifiedByID, ModifiedDate = @ModifiedDate WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[SetAllProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FlushReportFromCache]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FlushReportFromCache] GO CREATE PROCEDURE [dbo].[FlushReportFromCache] @Path as nvarchar(425) AS UPDATE SN SET SN.PermanentRefcount = SN.PermanentRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON SN.SnapshotDataID = EC.SnapshotDataID INNER JOIN Catalog AS C ON EC.ReportID = C.ItemID WHERE C.Path = @Path DELETE EC FROM ReportServerTempDB.dbo.ExecutionCache AS EC INNER JOIN Catalog ON EC.ReportID = Catalog.ItemID WHERE Catalog.Path = @Path GO GRANT EXECUTE ON [dbo].[FlushReportFromCache] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetParameters] GO CREATE PROCEDURE [dbo].[SetParameters] @Path nvarchar (425), @Parameter ntext AS UPDATE Catalog SET [Parameter] = @Parameter WHERE Path = @Path EXEC FlushReportFromCache @Path GO GRANT EXECUTE ON [dbo].[SetParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetObjectContent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetObjectContent] GO CREATE PROCEDURE [dbo].[SetObjectContent] @Path nvarchar (425), @Type int, @Content image = NULL, @Intermediate uniqueidentifier = NULL, @Parameter ntext = NULL, @LinkSourceID uniqueidentifier = NULL, @MimeType nvarchar (260) = NULL AS DECLARE @OldIntermediate as uniqueidentifier SET @OldIntermediate = (SELECT Intermediate FROM Catalog WITH (XLOCK) WHERE Path = @Path) UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 WHERE SnapshotData.SnapshotDataID = @OldIntermediate UPDATE Catalog SET Type=@Type, Content = @Content, Intermediate = @Intermediate, [Parameter] = @Parameter, LinkSourceID = @LinkSourceID, MimeType = @MimeType WHERE Path = @Path UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount + 1, TransientRefcount = TransientRefcount - 1 WHERE SnapshotData.SnapshotDataID = @Intermediate EXEC FlushReportFromCache @Path GO GRANT EXECUTE ON [dbo].[SetObjectContent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetLastModified]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetLastModified] GO CREATE PROCEDURE [dbo].[SetLastModified] @Path nvarchar (425), @ModifiedBySid varbinary (85) = NULL, @ModifiedByName nvarchar(260), @AuthType int, @ModifiedDate DateTime AS DECLARE @ModifiedByID uniqueidentifier EXEC GetUserID @ModifiedBySid, @ModifiedByName, @AuthType, @ModifiedByID OUTPUT UPDATE Catalog SET ModifiedByID = @ModifiedByID, ModifiedDate = @ModifiedDate WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[SetLastModified] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetNameById]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetNameById] GO CREATE PROCEDURE [dbo].[GetNameById] @ItemID uniqueidentifier AS SELECT Path FROM Catalog WHERE ItemID = @ItemID GO GRANT EXECUTE ON [dbo].[GetNameById] TO RSExecRole GO -------------------------------------------------- ------------- Data source procedures to store user names and passwords if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddDataSource] GO CREATE PROCEDURE [dbo].[AddDataSource] @DSID [uniqueidentifier], @ItemID [uniqueidentifier] = NULL, -- null for future suport dynamic delivery @SubscriptionID [uniqueidentifier] = NULL, @Name [nvarchar] (260) = NULL, -- only for scoped data sources, MUST be NULL for standalone!!! @Extension [nvarchar] (260) = NULL, @LinkID [uniqueidentifier] = NULL, -- link id is trusted, if it is provided - we use it @LinkPath [nvarchar] (425) = NULL, -- if LinkId is not provided we try to look up LinkPath @CredentialRetrieval [int], @Prompt [ntext] = NULL, @ConnectionString [image] = NULL, @OriginalConnectionString [image] = NULL, @OriginalConnectStringExpressionBased [bit] = NULL, @UserName [image] = NULL, @Password [image] = NULL, @Flags [int], @AuthType [int], @Version [int] AS DECLARE @ActualLinkID uniqueidentifier SET @ActualLinkID = NULL IF (@LinkID is NULL) AND (@LinkPath is not NULL) BEGIN SELECT Type, ItemID, NtSecDescPrimary FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @LinkPath SET @ActualLinkID = (SELECT ItemID FROM Catalog WHERE Path = @LinkPath) END ELSE BEGIN SET @ActualLinkID = @LinkID END INSERT INTO DataSource ([DSID], [ItemID], [SubscriptionID], [Name], [Extension], [Link], [CredentialRetrieval], [Prompt], [ConnectionString], [OriginalConnectionString], [OriginalConnectStringExpressionBased], [UserName], [Password], [Flags], [Version]) VALUES (@DSID, @ItemID, @SubscriptionID, @Name, @Extension, @ActualLinkID, @CredentialRetrieval, @Prompt, @ConnectionString, @OriginalConnectionString, @OriginalConnectStringExpressionBased, @UserName, @Password, @Flags, @Version) GO GRANT EXECUTE ON [dbo].[AddDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDataSources]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDataSources] GO CREATE PROCEDURE [dbo].[GetDataSources] @ItemID [uniqueidentifier], @AuthType int AS SELECT -- select data sources and their links (if they exist) DS.[DSID], -- 0 DS.[ItemID], -- 1 DS.[Name], -- 2 DS.[Extension], -- 3 DS.[Link], -- 4 DS.[CredentialRetrieval], -- 5 DS.[Prompt], -- 6 DS.[ConnectionString], -- 7 DS.[OriginalConnectionString], -- 8 DS.[UserName], -- 9 DS.[Password], -- 10 DS.[Flags], -- 11 DSL.[DSID], -- 12 DSL.[ItemID], -- 13 DSL.[Name], -- 14 DSL.[Extension], -- 15 DSL.[Link], -- 16 DSL.[CredentialRetrieval], -- 17 DSL.[Prompt], -- 18 DSL.[ConnectionString], -- 19 DSL.[UserName], -- 20 DSL.[Password], -- 21 DSL.[Flags], -- 22 C.Path, -- 23 SD.NtSecDescPrimary, -- 24 DS.[OriginalConnectStringExpressionBased], -- 25 DS.[Version], -- 26 DSL.[Version], -- 27 (SELECT 1 WHERE EXISTS (SELECT * from [ModelItemPolicy] AS MIP WHERE C.[ItemID] = MIP.[CatalogItemID])) -- 28 FROM [DataSource] AS DS LEFT OUTER JOIN ([DataSource] AS DSL INNER JOIN [Catalog] AS C ON DSL.[ItemID] = C.[ItemID] LEFT OUTER JOIN [SecData] AS SD ON C.[PolicyID] = SD.[PolicyID] AND SD.AuthType = @AuthType) ON DS.[Link] = DSL.[ItemID] WHERE DS.[ItemID] = @ItemID or DS.[SubscriptionID] = @ItemID GO GRANT EXECUTE ON [dbo].[GetDataSources] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteDataSources]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteDataSources] GO CREATE PROCEDURE [dbo].[DeleteDataSources] @ItemID [uniqueidentifier] AS DELETE FROM [DataSource] WHERE [ItemID] = @ItemID or [SubscriptionID] = @ItemID GO GRANT EXECUTE ON [dbo].[DeleteDataSources] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ChangeStateOfDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ChangeStateOfDataSource] GO CREATE PROCEDURE [dbo].[ChangeStateOfDataSource] @ItemID [uniqueidentifier], @Enable bit AS IF @Enable != 0 BEGIN UPDATE [DataSource] SET [Flags] = [Flags] | 1 WHERE [ItemID] = @ItemID END ELSE BEGIN UPDATE [DataSource] SET [Flags] = [Flags] & 0x7FFFFFFE WHERE [ItemID] = @ItemID END GO GRANT EXECUTE ON [dbo].[ChangeStateOfDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindItemsByDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindItemsByDataSource] GO CREATE PROCEDURE [dbo].[FindItemsByDataSource] @ItemID uniqueidentifier, @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.UserName, SUSER_SNAME(MU.Sid), MU.UserName, C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType INNER JOIN DataSource AS DS ON C.ItemID = DS.ItemID WHERE DS.Link = @ItemID GO GRANT EXECUTE ON [dbo].[FindItemsByDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CopyExecutionSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CopyExecutionSnapshot] GO CREATE PROCEDURE [dbo].[CopyExecutionSnapshot] @SourceReportID uniqueidentifier, @TargetReportID uniqueidentifier, @ReservedUntilUTC datetime AS DECLARE @SourceSnapshotDataID uniqueidentifier SET @SourceSnapshotDataID = (SELECT SnapshotDataID FROM Catalog WHERE ItemID = @SourceReportID) DECLARE @TargetSnapshotDataID uniqueidentifier SET @TargetSnapshotDataID = newid() DECLARE @ChunkID uniqueidentifier IF @SourceSnapshotDataID IS NOT NULL BEGIN -- We need to copy entries in SnapshotData and ChunkData tables. INSERT INTO SnapshotData (SnapshotDataID, CreatedDate, ParamsHash, QueryParams, EffectiveParams, Description, PermanentRefcount, TransientRefcount, ExpirationDate) SELECT @TargetSnapshotDataID, SD.CreatedDate, SD.ParamsHash, SD.QueryParams, SD.EffectiveParams, SD.Description, 1, 0, @ReservedUntilUTC FROM SnapshotData as SD WHERE SD.SnapshotDataID = @SourceSnapshotDataID INSERT INTO ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, ChunkFlags, Content, Version) SELECT newid(), @TargetSnapshotDataID, CD.ChunkName, CD.ChunkType, CD.ChunkFlags, CD.Content, CD.Version FROM ChunkData as CD WHERE CD.SnapshotDataID = @SourceSnapshotDataID UPDATE Target SET Target.SnapshotDataID = @TargetSnapshotDataID, Target.ExecutionTime = Source.ExecutionTime FROM Catalog Target, Catalog Source WHERE Source.ItemID = @SourceReportID AND Target.ItemID = @TargetReportID END GO GRANT EXECUTE ON [dbo].[CopyExecutionSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateRole] GO CREATE PROCEDURE [dbo].[CreateRole] @RoleID as uniqueidentifier, @RoleName as nvarchar(260), @Description as nvarchar(512) = null, @TaskMask as nvarchar(32), @RoleFlags as tinyint AS INSERT INTO Roles (RoleID, RoleName, Description, TaskMask, RoleFlags) VALUES (@RoleID, @RoleName, @Description, @TaskMask, @RoleFlags) GO GRANT EXECUTE ON [dbo].[CreateRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetRoles]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetRoles] GO CREATE PROCEDURE [dbo].[GetRoles] @RoleFlags as tinyint = NULL AS SELECT RoleName, Description, TaskMask FROM Roles WHERE (@RoleFlags is NULL) OR (RoleFlags = @RoleFlags) GO GRANT EXECUTE ON [dbo].[GetRoles] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteRole] GO -- Delete all policies associated with this role CREATE PROCEDURE [dbo].[DeleteRole] @RoleName nvarchar(260) AS -- if you call this, you must delete/reconstruct all policies associated with this role DELETE FROM Roles WHERE RoleName = @RoleName GO GRANT EXECUTE ON [dbo].[DeleteRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadRoleProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadRoleProperties] GO CREATE PROCEDURE [dbo].[ReadRoleProperties] @RoleName as nvarchar(260) AS SELECT Description, TaskMask, RoleFlags FROM Roles WHERE RoleName = @RoleName GO GRANT EXECUTE ON [dbo].[ReadRoleProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetRoleProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetRoleProperties] GO CREATE PROCEDURE [dbo].[SetRoleProperties] @RoleName as nvarchar(260), @Description as nvarchar(512) = NULL, @TaskMask as nvarchar(32), @RoleFlags as tinyint AS DECLARE @ExistingRoleFlags as tinyint SET @ExistingRoleFlags = (SELECT RoleFlags FROM Roles WHERE RoleName = @RoleName) IF @ExistingRoleFlags IS NULL BEGIN RETURN END IF @ExistingRoleFlags <> @RoleFlags BEGIN RAISERROR ('Bad role flags', 16, 1) END UPDATE Roles SET Description = @Description, TaskMask = @TaskMask, RoleFlags = @RoleFlags WHERE RoleName = @RoleName GO GRANT EXECUTE ON [dbo].[SetRoleProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPoliciesForRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPoliciesForRole] GO CREATE PROCEDURE [dbo].[GetPoliciesForRole] @RoleName as nvarchar(260), @AuthType as int AS SELECT Policies.PolicyID, SecData.XmlDescription, Policies.PolicyFlag, Catalog.Type, Catalog.Path, ModelItemPolicy.CatalogItemID, ModelItemPolicy.ModelItemID, RelatedRoles.RoleID, RelatedRoles.RoleName, RelatedRoles.TaskMask, RelatedRoles.RoleFlags FROM Roles INNER JOIN PolicyUserRole ON Roles.RoleID = PolicyUserRole.RoleID INNER JOIN Policies ON PolicyUserRole.PolicyID = Policies.PolicyID INNER JOIN PolicyUserRole AS RelatedPolicyUserRole ON Policies.PolicyID = RelatedPolicyUserRole.PolicyID INNER JOIN Roles AS RelatedRoles ON RelatedPolicyUserRole.RoleID = RelatedRoles.RoleID LEFT OUTER JOIN SecData ON Policies.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog ON Policies.PolicyID = Catalog.PolicyID AND Catalog.PolicyRoot = 1 LEFT OUTER JOIN ModelItemPolicy ON Policies.PolicyID = ModelItemPolicy.PolicyID WHERE Roles.RoleName = @RoleName ORDER BY Policies.PolicyID GO GRANT EXECUTE ON [dbo].[GetPoliciesForRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdatePolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdatePolicy] GO CREATE PROCEDURE [dbo].[UpdatePolicy] @PolicyID as uniqueidentifier, @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @AuthType int AS UPDATE SecData SET NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND SecData.AuthType = @AuthType GO GRANT EXECUTE ON [dbo].[UpdatePolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetPolicy] GO -- this assumes the item exists in the catalog CREATE PROCEDURE [dbo].[SetPolicy] @ItemName as nvarchar(425), @ItemNameLike as nvarchar(850), @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @XmlPolicy as ntext, @AuthType int, @PolicyID uniqueidentifier OUTPUT AS SELECT @PolicyID = (SELECT PolicyID FROM Catalog WHERE Path = @ItemName AND PolicyRoot = 1) IF (@PolicyID IS NULL) BEGIN -- this is not a policy root SET @PolicyID = newid() INSERT INTO Policies (PolicyID, PolicyFlag) VALUES (@PolicyID, 0) INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) DECLARE @OldPolicyID as uniqueidentifier SELECT @OldPolicyID = (SELECT PolicyID FROM Catalog WHERE Path = @ItemName) -- update item and children that shared the old policy UPDATE Catalog SET PolicyID = @PolicyID, PolicyRoot = 1 WHERE Path = @ItemName UPDATE Catalog SET PolicyID = @PolicyID WHERE Path LIKE @ItemNameLike ESCAPE '*' AND Catalog.PolicyID = @OldPolicyID END ELSE BEGIN UPDATE Policies SET PolicyFlag = 0 WHERE Policies.PolicyID = @PolicyID DECLARE @SecDataID as uniqueidentifier SELECT @SecDataID = (SELECT SecDataID FROM SecData WHERE PolicyID = @PolicyID and AuthType = @AuthType) IF (@SecDataID IS NULL) BEGIN -- insert new sec desc's INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription ,NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN -- update existing sec desc's UPDATE SecData SET XmlDescription = @XmlPolicy, NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND AuthType = @AuthType END END DELETE FROM PolicyUserRole WHERE PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[SetPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSystemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSystemPolicy] GO -- update the system policy CREATE PROCEDURE [dbo].[SetSystemPolicy] @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @XmlPolicy as ntext, @AuthType as int, @PolicyID uniqueidentifier OUTPUT AS SELECT @PolicyID = (SELECT PolicyID FROM Policies WHERE PolicyFlag = 1) IF (@PolicyID IS NULL) BEGIN SET @PolicyID = newid() INSERT INTO Policies (PolicyID, PolicyFlag) VALUES (@PolicyID, 1) INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN DECLARE @SecDataID as uniqueidentifier SELECT @SecDataID = (SELECT SecDataID FROM SecData WHERE PolicyID = @PolicyID and AuthType = @AuthType) IF (@SecDataID IS NULL) BEGIN -- insert new sec desc's INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN -- update existing sec desc's UPDATE SecData SET XmlDescription = @XmlPolicy, NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND AuthType = @AuthType END END DELETE FROM PolicyUserRole WHERE PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[SetSystemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetModelItemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetModelItemPolicy] GO -- update the system policy CREATE PROCEDURE [dbo].[SetModelItemPolicy] @CatalogItemID as uniqueidentifier, @ModelItemID as nvarchar(425), @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @XmlPolicy as ntext, @AuthType as int, @PolicyID uniqueidentifier OUTPUT AS SELECT @PolicyID = (SELECT PolicyID FROM ModelItemPolicy WHERE CatalogItemID = @CatalogItemID AND ModelItemID = @ModelItemID ) IF (@PolicyID IS NULL) BEGIN SET @PolicyID = newid() INSERT INTO Policies (PolicyID, PolicyFlag) VALUES (@PolicyID, 2) INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) INSERT INTO ModelItemPolicy (ID, CatalogItemID, ModelItemID, PolicyID) VALUES (newid(), @CatalogItemID, @ModelItemID, @PolicyID) END ELSE BEGIN DECLARE @SecDataID as uniqueidentifier SELECT @SecDataID = (SELECT SecDataID FROM SecData WHERE PolicyID = @PolicyID and AuthType = @AuthType) IF (@SecDataID IS NULL) BEGIN -- insert new sec desc's INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN -- update existing sec desc's UPDATE SecData SET XmlDescription = @XmlPolicy, NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND AuthType = @AuthType END END DELETE FROM PolicyUserRole WHERE PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[SetModelItemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdatePolicyPrincipal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdatePolicyPrincipal] GO CREATE PROCEDURE [dbo].[UpdatePolicyPrincipal] @PolicyID uniqueidentifier, @PrincipalSid varbinary(85) = NULL, @PrincipalName nvarchar(260), @PrincipalAuthType int, @RoleName nvarchar(260), @PrincipalID uniqueidentifier OUTPUT, @RoleID uniqueidentifier OUTPUT AS EXEC GetPrincipalID @PrincipalSid , @PrincipalName, @PrincipalAuthType, @PrincipalID OUTPUT SELECT @RoleID = (SELECT RoleID FROM Roles WHERE RoleName = @RoleName) INSERT INTO PolicyUserRole (ID, RoleID, UserID, PolicyID) VALUES (newid(), @RoleID, @PrincipalID, @PolicyID) GO GRANT EXECUTE ON [dbo].[UpdatePolicyPrincipal] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdatePolicyRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdatePolicyRole] GO CREATE PROCEDURE [dbo].[UpdatePolicyRole] @PolicyID uniqueidentifier, @PrincipalID uniqueidentifier, @RoleName nvarchar(260), @RoleID uniqueidentifier OUTPUT AS SELECT @RoleID = (SELECT RoleID FROM Roles WHERE RoleName = @RoleName) INSERT INTO PolicyUserRole (ID, RoleID, UserID, PolicyID) VALUES (newid(), @RoleID, @PrincipalID, @PolicyID) GO GRANT EXECUTE ON [dbo].[UpdatePolicyRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPolicy] GO CREATE PROCEDURE [dbo].[GetPolicy] @ItemName as nvarchar(425), @AuthType int AS SELECT SecData.XmlDescription, Catalog.PolicyRoot , SecData.NtSecDescPrimary, Catalog.Type FROM Catalog INNER JOIN Policies ON Catalog.PolicyID = Policies.PolicyID LEFT OUTER JOIN SecData ON Policies.PolicyID = SecData.PolicyID AND AuthType = @AuthType WHERE Catalog.Path = @ItemName AND PolicyFlag = 0 GO GRANT EXECUTE ON [dbo].[GetPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSystemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSystemPolicy] GO CREATE PROCEDURE [dbo].[GetSystemPolicy] @AuthType int AS SELECT SecData.NtSecDescPrimary, SecData.XmlDescription FROM Policies LEFT OUTER JOIN SecData ON Policies.PolicyID = SecData.PolicyID AND AuthType = @AuthType WHERE PolicyFlag = 1 GO GRANT EXECUTE ON [dbo].[GetSystemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeletePolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeletePolicy] GO CREATE PROCEDURE [dbo].[DeletePolicy] @ItemName as nvarchar(425) AS DECLARE @OldPolicyID uniqueidentifier SELECT @OldPolicyID = (SELECT PolicyID FROM Catalog WHERE Catalog.Path = @ItemName) UPDATE Catalog SET PolicyID = (SELECT Parent.PolicyID FROM Catalog Parent, Catalog WHERE Parent.ItemID = Catalog.ParentID AND Catalog.Path = @ItemName), PolicyRoot = 0 WHERE Catalog.PolicyID = @OldPolicyID DELETE Policies FROM Policies WHERE Policies.PolicyID = @OldPolicyID GO GRANT EXECUTE ON [dbo].[DeletePolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateSession]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateSession] GO -- Writes or updates session record CREATE PROCEDURE [dbo].[CreateSession] @SessionID as varchar(32), @CompiledDefinition as uniqueidentifier = NULL, @SnapshotDataID as uniqueidentifier = NULL, @IsPermanentSnapshot as bit = NULL, @ReportPath as nvarchar(440) = NULL, @Timeout as int, @AutoRefreshSeconds as int = NULL, @DataSourceInfo as image = NULL, @OwnerName as nvarchar (260), @OwnerSid as varbinary (85) = NULL, @AuthType as int, @EffectiveParams as ntext = NULL, @HistoryDate as datetime = NULL, @PageHeight as float = NULL, @PageWidth as float = NULL, @TopMargin as float = NULL, @BottomMargin as float = NULL, @LeftMargin as float = NULL, @RightMargin as float = NULL, @AwaitingFirstExecution as bit = NULL AS UPDATE PS SET PS.RefCount = 1 FROM ReportServerTempDB.dbo.PersistedStream as PS WHERE PS.SessionID = @SessionID UPDATE SN SET TransientRefcount = TransientRefcount + 1 FROM SnapshotData AS SN WHERE SN.SnapshotDataID = @SnapshotDataID UPDATE SN SET TransientRefcount = TransientRefcount + 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN WHERE SN.SnapshotDataID = @SnapshotDataID DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT DECLARE @now datetime SET @now = GETDATE() INSERT INTO ReportServerTempDB.dbo.SessionData ( SessionID, CompiledDefinition, SnapshotDataID, IsPermanentSnapshot, ReportPath, Timeout, AutoRefreshSeconds, Expiration, DataSourceInfo, OwnerID, EffectiveParams, CreationTime, HistoryDate, PageHeight, PageWidth, TopMargin, BottomMargin, LeftMargin, RightMargin, AwaitingFirstExecution ) VALUES ( @SessionID, @CompiledDefinition, @SnapshotDataID, @IsPermanentSnapshot, @ReportPath, @Timeout, @AutoRefreshSeconds, DATEADD(s, @Timeout, @now), @DataSourceInfo, @OwnerID, @EffectiveParams, @now, @HistoryDate, @PageHeight, @PageWidth, @TopMargin, @BottomMargin, @LeftMargin, @RightMargin, @AwaitingFirstExecution ) GO GRANT EXECUTE ON [dbo].[CreateSession] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteModelItemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteModelItemPolicy] GO CREATE PROCEDURE [dbo].[DeleteModelItemPolicy] @CatalogItemID as uniqueidentifier, @ModelItemID as nvarchar(425) AS DECLARE @PolicyID uniqueidentifier SELECT @PolicyID = (SELECT PolicyID FROM ModelItemPolicy WHERE CatalogItemID = @CatalogItemID AND ModelItemID = @ModelItemID) DELETE Policies FROM Policies WHERE Policies.PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[DeleteModelItemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteAllModelItemPolicies]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteAllModelItemPolicies] GO CREATE PROCEDURE [dbo].[DeleteAllModelItemPolicies] @Path as nvarchar(450) AS DELETE Policies FROM Policies AS P INNER JOIN ModelItemPolicy AS MIP ON P.PolicyID = MIP.PolicyID INNER JOIN Catalog AS C ON MIP.CatalogItemID = C.ItemID WHERE C.[Path] = @Path GO GRANT EXECUTE ON [dbo].[DeleteAllModelItemPolicies] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelItemInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelItemInfo] GO CREATE PROCEDURE [dbo].[GetModelItemInfo] @Path nvarchar (425), @AuthType int AS SELECT C.[ItemID], C.[Type], C.[ModifiedDate], C.[Description], SD.[NtSecDescPrimary] FROM [Catalog] AS C LEFT OUTER JOIN [SecData] AS SD ON C.[PolicyID] = SD.[PolicyID] AND SD.[AuthType] = @AuthType WHERE C.[Path] = @Path SELECT MIP.[ModelItemID], SD.[NtSecDescPrimary], SD.[XmlDescription] FROM [Catalog] AS C INNER JOIN [ModelItemPolicy] AS MIP ON C.[ItemID] = MIP.[CatalogItemID] LEFT OUTER JOIN [SecData] AS SD ON MIP.[PolicyID] = SD.[PolicyID] WHERE C.[Path] = @Path GO GRANT EXECUTE ON [dbo].[GetModelItemInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelDefinition]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelDefinition] GO CREATE PROCEDURE [dbo].[GetModelDefinition] @CatalogItemID as uniqueidentifier AS SELECT C.[Content] FROM [Catalog] AS C WHERE C.[ItemID] = @CatalogItemID GO GRANT EXECUTE ON [dbo].[GetModelDefinition] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddModelPerspective]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddModelPerspective] GO CREATE PROCEDURE [dbo].[AddModelPerspective] @ModelID as uniqueidentifier, @PerspectiveID as ntext, @PerspectiveName as ntext = null, @PerspectiveDescription as ntext = null AS INSERT INTO [ModelPerspective] ([ID], [ModelID], [PerspectiveID], [PerspectiveName], [PerspectiveDescription]) VALUES (newid(), @ModelID, @PerspectiveID, @PerspectiveName, @PerspectiveDescription) GO GRANT EXECUTE ON [dbo].[AddModelPerspective] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteModelPerspectives]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteModelPerspectives] GO CREATE PROCEDURE [dbo].[DeleteModelPerspectives] @ModelID as uniqueidentifier AS DELETE FROM [ModelPerspective] WHERE [ModelID] = @ModelID GO GRANT EXECUTE ON [dbo].[DeleteModelPerspectives] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelsAndPerspectives]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelsAndPerspectives] GO CREATE PROCEDURE [dbo].[GetModelsAndPerspectives] @AuthType int AS SELECT C.[PolicyID], SD.[NtSecDescPrimary], C.[ItemID], C.[Path], C.[Description], P.[PerspectiveID], P.[PerspectiveName], P.[PerspectiveDescription] FROM [Catalog] as C LEFT OUTER JOIN [ModelPerspective] as P ON C.[ItemID] = P.[ModelID] LEFT OUTER JOIN [SecData] AS SD ON C.[PolicyID] = SD.[PolicyID] AND SD.[AuthType] = @AuthType WHERE C.[Type] = 6 -- Model ORDER BY C.[Path] GO GRANT EXECUTE ON [dbo].[GetModelsAndPerspectives] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelPerspectives]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelPerspectives] GO CREATE PROCEDURE [dbo].[GetModelPerspectives] @Path nvarchar (425), @AuthType int AS SELECT C.[Type], SD.[NtSecDescPrimary], C.[Description] FROM [Catalog] as C LEFT OUTER JOIN [SecData] AS SD ON C.[PolicyID] = SD.[PolicyID] AND SD.[AuthType] = @AuthType WHERE [Path] = @Path SELECT P.[PerspectiveID], P.[PerspectiveName], P.[PerspectiveDescription] FROM [Catalog] as C INNER JOIN [ModelPerspective] as P ON C.[ItemID] = P.[ModelID] WHERE [Path] = @Path GO GRANT EXECUTE ON [dbo].[GetModelPerspectives] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DereferenceSessionSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DereferenceSessionSnapshot] GO CREATE PROCEDURE [dbo].[DereferenceSessionSnapshot] @SessionID as varchar(32), @OwnerID as uniqueidentifier AS UPDATE SN SET TransientRefcount = TransientRefcount - 1 FROM SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.SessionData AS SE ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID UPDATE SN SET TransientRefcount = TransientRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.SessionData AS SE ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[DereferenceSessionSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSessionData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSessionData] GO -- Writes or updates session record CREATE PROCEDURE [dbo].[SetSessionData] @SessionID as varchar(32), @ReportPath as nvarchar(440), @HistoryDate as datetime = NULL, @Timeout as int, @AutoRefreshSeconds as int = NULL, @EffectiveParams ntext = NULL, @OwnerSid as varbinary (85) = NULL, @OwnerName as nvarchar (260), @AuthType as int, @ShowHideInfo as image = NULL, @DataSourceInfo as image = NULL, @SnapshotDataID as uniqueidentifier = NULL, @IsPermanentSnapshot as bit = NULL, @SnapshotTimeoutSeconds as int = NULL, @HasInteractivity as bit, @SnapshotExpirationDate as datetime = NULL, @AwaitingFirstExecution as bit = NULL AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT DECLARE @now datetime SET @now = GETDATE() -- is there a session for the same report ? DECLARE @OldSnapshotDataID uniqueidentifier DECLARE @OldIsPermanentSnapshot bit DECLARE @OldSessionID varchar(32) SELECT @OldSessionID = SessionID, @OldSnapshotDataID = SnapshotDataID, @OldIsPermanentSnapshot = IsPermanentSnapshot FROM ReportServerTempDB.dbo.SessionData WITH (XLOCK) WHERE SessionID = @SessionID IF @OldSessionID IS NOT NULL BEGIN -- Yes, update it IF @OldSnapshotDataID != @SnapshotDataID or @SnapshotDataID is NULL BEGIN EXEC DereferenceSessionSnapshot @SessionID, @OwnerID END UPDATE ReportServerTempDB.dbo.SessionData SET SnapshotDataID = @SnapshotDataID, IsPermanentSnapshot = @IsPermanentSnapshot, Timeout = @Timeout, AutoRefreshSeconds = @AutoRefreshSeconds, SnapshotExpirationDate = @SnapshotExpirationDate, -- we want database session to expire later than in-memory session Expiration = DATEADD(s, @Timeout+10, @now), ShowHideInfo = @ShowHideInfo, DataSourceInfo = @DataSourceInfo, AwaitingFirstExecution = @AwaitingFirstExecution -- EffectiveParams = @EffectiveParams, -- no need to update user params as they are always same -- ReportPath = @ReportPath -- OwnerID = @OwnerID WHERE SessionID = @SessionID -- update expiration date on a snapshot that we reference IF @IsPermanentSnapshot != 0 BEGIN UPDATE SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutSeconds, @now) WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutSeconds, @now) WHERE SnapshotDataID = @SnapshotDataID END END ELSE BEGIN -- no, insert it UPDATE PS SET PS.RefCount = 1 FROM ReportServerTempDB.dbo.PersistedStream as PS WHERE PS.SessionID = @SessionID INSERT INTO ReportServerTempDB.dbo.SessionData (SessionID, SnapshotDataID, IsPermanentSnapshot, ReportPath, EffectiveParams, Timeout, AutoRefreshSeconds, Expiration, ShowHideInfo, DataSourceInfo, OwnerID, CreationTime, HasInteractivity, SnapshotExpirationDate, HistoryDate, AwaitingFirstExecution) VALUES (@SessionID, @SnapshotDataID, @IsPermanentSnapshot, @ReportPath, @EffectiveParams, @Timeout, @AutoRefreshSeconds, DATEADD(s, @Timeout, @now), @ShowHideInfo, @DataSourceInfo, @OwnerID, @now, @HasInteractivity, @SnapshotExpirationDate, @HistoryDate, @AwaitingFirstExecution) END GO GRANT EXECUTE ON [dbo].[SetSessionData] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteLockSession]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteLockSession] GO CREATE PROCEDURE [dbo].[WriteLockSession] @SessionID as varchar(32) AS INSERT INTO ReportServerTempDB.dbo.SessionLock WITH (ROWLOCK) (SessionID) VALUES (@SessionID) GO GRANT EXECUTE ON [dbo].[WriteLockSession] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CheckSessionLock]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CheckSessionLock] GO CREATE PROCEDURE [dbo].[CheckSessionLock] @SessionID as varchar(32) AS DECLARE @Selected nvarchar(32) SELECT @Selected=SessionID FROM ReportServerTempDB.dbo.SessionLock WITH (ROWLOCK) WHERE SessionID = @SessionID GO GRANT EXECUTE ON [dbo].[CheckSessionLock] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadLockSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadLockSnapshot] GO CREATE PROCEDURE [dbo].[ReadLockSnapshot] @SnapshotDataID as uniqueidentifier AS SELECT SnapshotDataID FROM SnapshotData WITH (REPEATABLEREAD, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID GO GRANT EXECUTE ON [dbo].[ReadLockSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSessionData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSessionData] GO -- Get record from session data, update session and snapshot CREATE PROCEDURE [dbo].[GetSessionData] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @SnapshotTimeoutMinutes as int AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT DECLARE @now as datetime SET @now = GETDATE() DECLARE @DBSessionID varchar(32) DECLARE @SnapshotDataID uniqueidentifier DECLARE @IsPermanentSnapshot bit EXEC CheckSessionLock @SessionID = @SessionID SELECT @DBSessionID = SE.SessionID, @SnapshotDataID = SE.SnapshotDataID, @IsPermanentSnapshot = SE.IsPermanentSnapshot FROM ReportServerTempDB.dbo.SessionData AS SE WITH (XLOCK) WHERE SE.OwnerID = @OwnerID AND SE.SessionID = @SessionID AND SE.Expiration > @now -- We need this update to keep session around while we process it. -- TODO: This assumes that it will be processed within the session timeout. UPDATE SE SET Expiration = DATEADD(s, Timeout, @now) FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @DBSessionID -- Update snapshot expiration to prevent early deletion -- If session uses snapshot, it is already refcounted. However, if session lasts for too long, -- snapshot may expire. Therefore, every time we touch snapshot we should change expiration. IF (@DBSessionID IS NOT NULL) BEGIN -- We return something only if session is present IF @IsPermanentSnapshot != 0 BEGIN -- If session has snapshot and it is permanent SELECT SN.SnapshotDataID, SE.ShowHideInfo, SE.DataSourceInfo, SN.Description, SE.EffectiveParams, SN.CreatedDate, SE.IsPermanentSnapshot, SE.CreationTime, SE.HasInteractivity, SE.Timeout, SE.SnapshotExpirationDate, SE.ReportPath, SE.HistoryDate, SE.CompiledDefinition, SN.PageCount, SN.HasDocMap, SE.Expiration, SN.EffectiveParams, SE.PageHeight, SE.PageWidth, SE.TopMargin, SE.BottomMargin, SE.LeftMargin, SE.RightMargin, SE.AutoRefreshSeconds, SE.AwaitingFirstExecution, SN.[DependsOnUser] FROM ReportServerTempDB.dbo.SessionData AS SE INNER JOIN SnapshotData AS SN ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @DBSessionID UPDATE SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutMinutes, @now) WHERE SnapshotDataID = @SnapshotDataID END ELSE IF @IsPermanentSnapshot = 0 BEGIN -- If session has snapshot and it is temporary SELECT SN.SnapshotDataID, SE.ShowHideInfo, SE.DataSourceInfo, SN.Description, SE.EffectiveParams, SN.CreatedDate, SE.IsPermanentSnapshot, SE.CreationTime, SE.HasInteractivity, SE.Timeout, SE.SnapshotExpirationDate, SE.ReportPath, SE.HistoryDate, SE.CompiledDefinition, SN.PageCount, SN.HasDocMap, SE.Expiration, SN.EffectiveParams, SE.PageHeight, SE.PageWidth, SE.TopMargin, SE.BottomMargin, SE.LeftMargin, SE.RightMargin, SE.AutoRefreshSeconds, SE.AwaitingFirstExecution, SN.[DependsOnUser] FROM ReportServerTempDB.dbo.SessionData AS SE INNER JOIN ReportServerTempDB.dbo.SnapshotData AS SN ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @DBSessionID UPDATE ReportServerTempDB.dbo.SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutMinutes, @now) WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN -- If session doesn't have snapshot SELECT null, SE.ShowHideInfo, SE.DataSourceInfo, null, SE.EffectiveParams, null, SE.IsPermanentSnapshot, SE.CreationTime, SE.HasInteractivity, SE.Timeout, SE.SnapshotExpirationDate, SE.ReportPath, SE.HistoryDate, SE.CompiledDefinition, null, null, SE.Expiration, null, SE.PageHeight, SE.PageWidth, SE.TopMargin, SE.BottomMargin, SE.LeftMargin, SE.RightMargin, SE.AutoRefreshSeconds, SE.AwaitingFirstExecution, null FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @DBSessionID END END GO GRANT EXECUTE ON [dbo].[GetSessionData] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapshotFromHistory]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapshotFromHistory] GO CREATE PROCEDURE [dbo].[GetSnapshotFromHistory] @Path nvarchar (425), @SnapshotDate datetime, @AuthType int AS SELECT Catalog.ItemID, Catalog.Type, SnapshotData.SnapshotDataID, SnapshotData.DependsOnUser, SnapshotData.Description, SecData.NtSecDescPrimary, Catalog.[Property] FROM SnapshotData INNER JOIN History ON History.SnapshotDataID = SnapshotData.SnapshotDataID INNER JOIN Catalog ON History.ReportID = Catalog.ItemID LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Catalog.Path = @Path AND History.SnapshotDate = @SnapshotDate GO GRANT EXECUTE ON [dbo].[GetSnapshotFromHistory] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredSessions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredSessions] GO CREATE PROCEDURE [dbo].[CleanExpiredSessions] @SessionsCleaned int OUTPUT AS SET DEADLOCK_PRIORITY LOW DECLARE @now as datetime SET @now = GETDATE() CREATE TABLE #tempSession (SessionID varchar(32) COLLATE Latin1_General_CI_AS_KS_WS, SnapshotDataID uniqueidentifier, CompiledDefinition uniqueidentifier) INSERT INTO #tempSession SELECT TOP 20 SessionID, SnapshotDataID, CompiledDefinition FROM ReportServerTempDB.dbo.SessionData WITH (XLOCK) WHERE Expiration < @now SET @SessionsCleaned = @@ROWCOUNT IF @SessionsCleaned = 0 RETURN -- Mark persisted streams for this session to be deleted UPDATE PS SET RefCount = 0, ExpirationDate = GETDATE() FROM ReportServerTempDB.dbo.PersistedStream AS PS INNER JOIN #tempSession on PS.SessionID = #tempsession.SessionID DELETE SE FROM ReportServerTempDB.dbo.SessionData AS SE INNER JOIN #tempSession on SE.SessionID = #tempsession.SessionID UPDATE SN SET TransientRefcount = TransientRefcount-1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN #tempSession AS SE ON SN.SnapshotDataID = SE.CompiledDefinition UPDATE SN SET TransientRefcount = TransientRefcount- (SELECT COUNT(*) FROM #tempSession AS SE1 WHERE SE1.SnapshotDataID = SN.SnapshotDataID) FROM SnapshotData AS SN INNER JOIN #tempSession AS SE ON SN.SnapshotDataID = SE.SnapshotDataID UPDATE SN SET TransientRefcount = TransientRefcount- (SELECT COUNT(*) FROM #tempSession AS SE1 WHERE SE1.SnapshotDataID = SN.SnapshotDataID) FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN #tempSession AS SE ON SN.SnapshotDataID = SE.SnapshotDataID GO GRANT EXECUTE ON [dbo].[CleanExpiredSessions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredCache]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredCache] GO CREATE PROCEDURE [dbo].[CleanExpiredCache] AS DECLARE @now as datetime SET @now = DATEADD(minute, -1, GETDATE()) UPDATE SN SET PermanentRefcount = PermanentRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON SN.SnapshotDataID = EC.SnapshotDataID WHERE EC.AbsoluteExpiration < @now DELETE EC FROM ReportServerTempDB.dbo.ExecutionCache AS EC WHERE EC.AbsoluteExpiration < @now GO GRANT EXECUTE ON [dbo].[CleanExpiredCache] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSessionCredentials]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSessionCredentials] GO CREATE PROCEDURE [dbo].[SetSessionCredentials] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @DataSourceInfo as image = NULL, @Expiration as datetime, @EffectiveParams as ntext = NULL AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT EXEC DereferenceSessionSnapshot @SessionID, @OwnerID UPDATE SE SET SE.DataSourceInfo = @DataSourceInfo, SE.SnapshotDataID = null, SE.IsPermanentSnapshot = null, SE.SnapshotExpirationDate = null, SE.ShowHideInfo = null, SE.HasInteractivity = null, SE.AutoRefreshSeconds = null, SE.Expiration = @Expiration, SE.EffectiveParams = @EffectiveParams, SE.AwaitingFirstExecution = 1 FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[SetSessionCredentials] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSessionParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSessionParameters] GO CREATE PROCEDURE [dbo].[SetSessionParameters] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @EffectiveParams as ntext = NULL AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT UPDATE SE SET SE.EffectiveParams = @EffectiveParams, SE.AwaitingFirstExecution = 1 FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[SetSessionParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ClearSessionSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ClearSessionSnapshot] GO CREATE PROCEDURE [dbo].[ClearSessionSnapshot] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @Expiration as datetime AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT EXEC DereferenceSessionSnapshot @SessionID, @OwnerID UPDATE SE SET SE.SnapshotDataID = null, SE.IsPermanentSnapshot = null, SE.SnapshotExpirationDate = null, SE.ShowHideInfo = null, SE.HasInteractivity = null, SE.AutoRefreshSeconds = null, SE.Expiration = @Expiration FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[ClearSessionSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RemoveReportFromSession]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RemoveReportFromSession] GO CREATE PROCEDURE [dbo].[RemoveReportFromSession] @SessionID as varchar(32), @ReportPath as nvarchar(440), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT EXEC DereferenceSessionSnapshot @SessionID, @OwnerID DELETE SE FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.ReportPath = @ReportPath AND SE.OwnerID = @OwnerID -- Delete any persisted streams associated with this session UPDATE PS SET PS.RefCount = 0, PS.ExpirationDate = GETDATE() FROM ReportServerTempDB.dbo.PersistedStream AS PS WHERE PS.SessionID = @SessionID GO GRANT EXECUTE ON [dbo].[RemoveReportFromSession] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanBrokenSnapshots]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanBrokenSnapshots] GO CREATE PROCEDURE [dbo].[CleanBrokenSnapshots] @Machine nvarchar(512), @SnapshotsCleaned int OUTPUT, @ChunksCleaned int OUTPUT, @TempSnapshotID uniqueidentifier OUTPUT AS SET DEADLOCK_PRIORITY LOW DECLARE @now AS datetime SELECT @now = GETDATE() CREATE TABLE #tempSnapshot (SnapshotDataID uniqueidentifier) INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM SnapshotData WITH (NOLOCK) where SnapshotData.PermanentRefcount <= 0 AND ExpirationDate < @now SET @SnapshotsCleaned = @@ROWCOUNT DELETE ChunkData FROM ChunkData INNER JOIN #tempSnapshot ON ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @@ROWCOUNT DELETE SnapshotData FROM SnapshotData INNER JOIN #tempSnapshot ON SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID TRUNCATE TABLE #tempSnapshot INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM ReportServerTempDB.dbo.SnapshotData WITH (NOLOCK) where ReportServerTempDB.dbo.SnapshotData.PermanentRefcount <= 0 AND ReportServerTempDB.dbo.SnapshotData.ExpirationDate < @now AND ReportServerTempDB.dbo.SnapshotData.Machine = @Machine SET @SnapshotsCleaned = @SnapshotsCleaned + @@ROWCOUNT SELECT @TempSnapshotID = (SELECT SnapshotDataID FROM #tempSnapshot) DELETE ReportServerTempDB.dbo.ChunkData FROM ReportServerTempDB.dbo.ChunkData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @ChunksCleaned + @@ROWCOUNT DELETE ReportServerTempDB.dbo.SnapshotData FROM ReportServerTempDB.dbo.SnapshotData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID GO GRANT EXECUTE ON [dbo].[CleanBrokenSnapshots] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanOrphanedSnapshots]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanOrphanedSnapshots] GO CREATE PROCEDURE [dbo].[CleanOrphanedSnapshots] @Machine nvarchar(512), @SnapshotsCleaned int OUTPUT, @ChunksCleaned int OUTPUT, @TempSnapshotID uniqueidentifier OUTPUT AS SET DEADLOCK_PRIORITY LOW CREATE TABLE #tempSnapshot (SnapshotDataID uniqueidentifier) INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM SnapshotData WITH (NOLOCK) where SnapshotData.PermanentRefcount = 0 AND SnapshotData.TransientRefcount = 0 SET @SnapshotsCleaned = @@ROWCOUNT DELETE ChunkData FROM ChunkData INNER JOIN #tempSnapshot ON ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @@ROWCOUNT DELETE SnapshotData FROM SnapshotData INNER JOIN #tempSnapshot ON SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID TRUNCATE TABLE #tempSnapshot INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM ReportServerTempDB.dbo.SnapshotData WITH (NOLOCK) where ReportServerTempDB.dbo.SnapshotData.PermanentRefcount = 0 AND ReportServerTempDB.dbo.SnapshotData.TransientRefcount = 0 AND ReportServerTempDB.dbo.SnapshotData.Machine = @Machine SET @SnapshotsCleaned = @SnapshotsCleaned + @@ROWCOUNT SELECT @TempSnapshotID = (SELECT SnapshotDataID FROM #tempSnapshot) DELETE ReportServerTempDB.dbo.ChunkData FROM ReportServerTempDB.dbo.ChunkData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @ChunksCleaned + @@ROWCOUNT DELETE ReportServerTempDB.dbo.SnapshotData FROM ReportServerTempDB.dbo.SnapshotData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID GO GRANT EXECUTE ON [dbo].[CleanOrphanedSnapshots] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetCacheOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetCacheOptions] GO CREATE PROCEDURE [dbo].[SetCacheOptions] @Path as nvarchar(425), @CacheReport as bit, @ExpirationFlags as int, @CacheExpiration as int = NULL AS DECLARE @CachePolicyID as uniqueidentifier SELECT @CachePolicyID = (SELECT CachePolicyID FROM CachePolicy with (XLOCK) INNER JOIN Catalog ON Catalog.ItemID = CachePolicy.ReportID WHERE Catalog.Path = @Path) IF @CachePolicyID IS NULL -- no policy exists BEGIN IF @CacheReport = 1 -- create a new one BEGIN INSERT INTO CachePolicy (CachePolicyID, ReportID, ExpirationFlags, CacheExpiration) (SELECT NEWID(), ItemID, @ExpirationFlags, @CacheExpiration FROM Catalog WHERE Catalog.Path = @Path) END -- ELSE if it has no policy and we want to remove its policy do nothing END ELSE -- existing policy BEGIN IF @CacheReport = 1 BEGIN UPDATE CachePolicy SET ExpirationFlags = @ExpirationFlags, CacheExpiration = @CacheExpiration WHERE CachePolicyID = @CachePolicyID EXEC FlushReportFromCache @Path END ELSE BEGIN DELETE FROM CachePolicy WHERE CachePolicyID = @CachePolicyID EXEC FlushReportFromCache @Path END END GO GRANT EXECUTE ON [dbo].[SetCacheOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCacheOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetCacheOptions] GO CREATE PROCEDURE [dbo].[GetCacheOptions] @Path as nvarchar(425) AS SELECT ExpirationFlags, CacheExpiration, S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type] FROM CachePolicy INNER JOIN Catalog ON Catalog.ItemID = CachePolicy.ReportID LEFT outer join reportschedule rs on catalog.itemid = rs.reportid and rs.reportaction = 3 LEFT OUTER JOIN [Schedule] S ON S.ScheduleID = rs.ScheduleID LEFT OUTER JOIN [Users] Owner on Owner.UserID = S.[CreatedById] WHERE Catalog.Path = @Path GO GRANT EXECUTE ON [dbo].[GetCacheOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddReportToCache]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddReportToCache] GO CREATE PROCEDURE [dbo].[AddReportToCache] @ReportID as uniqueidentifier, @ExecutionDate datetime, @SnapshotDataID uniqueidentifier, @ExpirationDate datetime OUTPUT, @ScheduleID uniqueidentifier OUTPUT AS DECLARE @ExpirationFlags as int DECLARE @Timeout as int SET @ExpirationDate = NULL SET @ScheduleID = NULL SET @ExpirationFlags = (SELECT ExpirationFlags FROM CachePolicy WHERE ReportID = @ReportID) IF @ExpirationFlags = 1 -- timeout based BEGIN SET @Timeout = (SELECT CacheExpiration FROM CachePolicy WHERE ReportID = @ReportID) SET @ExpirationDate = DATEADD(n, @Timeout, @ExecutionDate) END ELSE IF @ExpirationFlags = 2 -- schedule based BEGIN SET @ScheduleID = (SELECT s.ScheduleID FROM Schedule s INNER JOIN ReportSchedule rs on rs.ScheduleID = s.ScheduleID and rs.ReportAction = 3 WHERE rs.ReportID = @ReportID) SET @ExpirationDate = (SELECT Schedule.NextRunTime FROM Schedule with (XLOCK) WHERE Schedule.ScheduleID = @ScheduleID) END ELSE BEGIN RAISERROR('Invalid cache flags', 16, 1) END -- and to the report cache INSERT INTO ReportServerTempDB.dbo.ExecutionCache (ExecutionCacheID, ReportID, ExpirationFlags, AbsoluteExpiration, RelativeExpiration, SnapshotDataID) VALUES (newid(), @ReportID, @ExpirationFlags, @ExpirationDate, @Timeout, @SnapshotDataID ) UPDATE ReportServerTempDB.dbo.SnapshotData SET PermanentRefcount = PermanentRefcount + 1 WHERE SnapshotDataID = @SnapshotDataID; GO GRANT EXECUTE ON [dbo].[AddReportToCache] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetExecutionOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetExecutionOptions] GO CREATE PROCEDURE [dbo].[GetExecutionOptions] @Path nvarchar(425) AS SELECT ExecutionFlag, S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type] FROM Catalog LEFT OUTER JOIN ReportSchedule ON Catalog.ItemID = ReportSchedule.ReportID AND ReportSchedule.ReportAction = 1 LEFT OUTER JOIN [Schedule] S ON S.ScheduleID = ReportSchedule.ScheduleID LEFT OUTER JOIN [Users] Owner on Owner.UserID = S.[CreatedById] WHERE Catalog.Path = @Path GO GRANT EXECUTE ON [dbo].[GetExecutionOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetExecutionOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetExecutionOptions] GO CREATE PROCEDURE [dbo].[SetExecutionOptions] @Path as nvarchar(425), @ExecutionFlag as int, @ExecutionChanged as bit = 0 AS IF @ExecutionChanged = 0 BEGIN UPDATE Catalog SET ExecutionFlag = @ExecutionFlag WHERE Catalog.Path = @Path END ELSE BEGIN IF (@ExecutionFlag & 3) = 2 BEGIN -- set it to snapshot, flush cache EXEC FlushReportFromCache @Path DELETE CachePolicy FROM CachePolicy INNER JOIN Catalog ON CachePolicy.ReportID = Catalog.ItemID WHERE Catalog.Path = @Path END -- now clean existing snapshot and execution time if any UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 FROM SnapshotData INNER JOIN Catalog ON SnapshotData.SnapshotDataID = Catalog.SnapshotDataID WHERE Catalog.Path = @Path UPDATE Catalog SET ExecutionFlag = @ExecutionFlag, SnapshotDataID = NULL, ExecutionTime = NULL WHERE Catalog.Path = @Path END GO GRANT EXECUTE ON [dbo].[SetExecutionOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSnapshot] GO CREATE PROCEDURE [dbo].[UpdateSnapshot] @Path as nvarchar(425), @SnapshotDataID as uniqueidentifier, @executionDate as datetime AS DECLARE @OldSnapshotDataID uniqueidentifier SET @OldSnapshotDataID = (SELECT SnapshotDataID FROM Catalog WITH (XLOCK) WHERE Catalog.Path = @Path) -- update reference count in snapshot table UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount-1 WHERE SnapshotData.SnapshotDataID = @OldSnapshotDataID -- update catalog to point to the new execution snapshot UPDATE Catalog SET SnapshotDataID = @SnapshotDataID, ExecutionTime = @executionDate WHERE Catalog.Path = @Path UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount+1, TransientRefcount = TransientRefcount-1 WHERE SnapshotData.SnapshotDataID = @SnapshotDataID GO GRANT EXECUTE ON [dbo].[UpdateSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateChunkAndGetPointer]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateChunkAndGetPointer] GO CREATE PROCEDURE [dbo].[CreateChunkAndGetPointer] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int, @MimeType nvarchar(260) = NULL, @Version smallint, @Content image, @ChunkFlags tinyint = NULL, @ChunkPointer binary(16) OUTPUT AS DECLARE @ChunkID uniqueidentifier SET @ChunkID = NEWID() IF @IsPermanentSnapshot != 0 BEGIN DELETE ChunkData WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType INSERT INTO ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) VALUES (@ChunkID, @SnapshotDataID, @ChunkName, @ChunkType, @MimeType, @Version, @ChunkFlags, @Content) SELECT @ChunkPointer = TEXTPTR(Content) FROM ChunkData WHERE ChunkData.ChunkID = @ChunkID END ELSE BEGIN DELETE ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType INSERT INTO ReportServerTempDB.dbo.ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) VALUES (@ChunkID, @SnapshotDataID, @ChunkName, @ChunkType, @MimeType, @Version, @ChunkFlags, @Content) SELECT @ChunkPointer = TEXTPTR(Content) FROM ReportServerTempDB.dbo.ChunkData AS CH WHERE CH.ChunkID = @ChunkID END GO GRANT EXECUTE ON [dbo].[CreateChunkAndGetPointer] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteChunkPortion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteChunkPortion] GO CREATE PROCEDURE [dbo].[WriteChunkPortion] @ChunkPointer binary(16), @IsPermanentSnapshot bit, @DataIndex int = NULL, @DeleteLength int = NULL, @Content image AS IF @IsPermanentSnapshot != 0 BEGIN UPDATETEXT ChunkData.Content @ChunkPointer @DataIndex @DeleteLength @Content END ELSE BEGIN UPDATETEXT ReportServerTempDB.dbo.ChunkData.Content @ChunkPointer @DataIndex @DeleteLength @Content END GO GRANT EXECUTE ON [dbo].[WriteChunkPortion] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetChunkPointerAndLength]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetChunkPointerAndLength] GO CREATE PROCEDURE [dbo].[GetChunkPointerAndLength] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int AS IF @IsPermanentSnapshot != 0 BEGIN SELECT TEXTPTR(Content), DATALENGTH(Content), MimeType, ChunkFlags, Version FROM ChunkData AS CH WITH (HOLDLOCK, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END ELSE BEGIN SELECT TEXTPTR(Content), DATALENGTH(Content), MimeType, ChunkFlags, Version FROM ReportServerTempDB.dbo.ChunkData AS CH WITH (HOLDLOCK, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END GO GRANT EXECUTE ON [dbo].[GetChunkPointerAndLength] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetChunkInformation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetChunkInformation] GO CREATE PROCEDURE [dbo].[GetChunkInformation] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int AS IF @IsPermanentSnapshot != 0 BEGIN SELECT MimeType FROM ChunkData AS CH WITH (HOLDLOCK, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END ELSE BEGIN SELECT MimeType FROM ReportServerTempDB.dbo.ChunkData AS CH WITH (HOLDLOCK, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END GO GRANT EXECUTE ON [dbo].[GetChunkInformation] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadChunkPortion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadChunkPortion] GO CREATE PROCEDURE [dbo].[ReadChunkPortion] @ChunkPointer binary(16), @IsPermanentSnapshot bit, @DataIndex int, @Length int AS IF @IsPermanentSnapshot != 0 BEGIN READTEXT ChunkData.Content @ChunkPointer @DataIndex @Length END ELSE BEGIN READTEXT ReportServerTempDB.dbo.ChunkData.Content @ChunkPointer @DataIndex @Length END GO GRANT EXECUTE ON [dbo].[ReadChunkPortion] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CopyChunksOfType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CopyChunksOfType] GO CREATE PROCEDURE [dbo].[CopyChunksOfType] @FromSnapshotID uniqueidentifier, @FromIsPermanent bit, @ToSnapshotID uniqueidentifier, @ToIsPermanent bit, @ChunkType int AS IF @FromIsPermanent != 0 AND @ToIsPermanent = 0 BEGIN INSERT INTO ReportServerTempDB.dbo.ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) SELECT newid(), @ToSnapshotID, S.ChunkName, S.ChunkType, S.MimeType, S.Version, S.ChunkFlags, S.Content FROM ChunkData AS S WHERE S.SnapshotDataID = @FromSnapshotID AND S.ChunkType = @ChunkType AND NOT EXISTS( SELECT T.ChunkName FROM ReportServerTempDB.dbo.ChunkData AS T -- exclude the ones in the target WHERE T.ChunkName = S.ChunkName AND T.ChunkType = S.ChunkType AND T.SnapshotDataID = @ToSnapshotID) END ELSE IF @FromIsPermanent = 0 AND @ToIsPermanent = 0 BEGIN INSERT INTO ReportServerTempDB.dbo.ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) SELECT newid(), @ToSnapshotID, S.ChunkName, S.ChunkType, S.MimeType, S.Version, S.ChunkFlags, S.Content FROM ReportServerTempDB.dbo.ChunkData AS S WHERE S.SnapshotDataID = @FromSnapshotID AND S.ChunkType = @ChunkType AND NOT EXISTS( SELECT T.ChunkName FROM ReportServerTempDB.dbo.ChunkData AS T -- exclude the ones in the target WHERE T.ChunkName = S.ChunkName AND T.ChunkType = S.ChunkType AND T.SnapshotDataID = @ToSnapshotID) END ELSE IF @FromIsPermanent != 0 AND @ToIsPermanent != 0 BEGIN INSERT INTO ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) SELECT newid(), @ToSnapshotID, S.ChunkName, S.ChunkType, S.MimeType, S.Version, S.ChunkFlags, S.Content FROM ChunkData AS S WHERE S.SnapshotDataID = @FromSnapshotID AND S.ChunkType = @ChunkType AND NOT EXISTS( SELECT T.ChunkName FROM ChunkData AS T -- exclude the ones in the target WHERE T.ChunkName = S.ChunkName AND T.ChunkType = S.ChunkType AND T.SnapshotDataID = @ToSnapshotID) END ELSE BEGIN RAISERROR('Unsupported chunk copy', 16, 1) END GO GRANT EXECUTE ON [dbo].[CopyChunksOfType] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteSnapshotAndChunks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteSnapshotAndChunks] GO CREATE PROCEDURE [dbo].[DeleteSnapshotAndChunks] @SnapshotID uniqueidentifier, @IsPermanentSnapshot bit AS IF @IsPermanentSnapshot != 0 BEGIN DELETE ChunkData WHERE ChunkData.SnapshotDataID = @SnapshotID DELETE SnapshotData WHERE SnapshotData.SnapshotDataID = @SnapshotID END ELSE BEGIN DELETE ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotID DELETE ReportServerTempDB.dbo.SnapshotData WHERE SnapshotDataID = @SnapshotID END GO GRANT EXECUTE ON [dbo].[DeleteSnapshotAndChunks] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteOneChunk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteOneChunk] GO CREATE PROCEDURE [dbo].[DeleteOneChunk] @SnapshotID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int AS IF @IsPermanentSnapshot != 0 BEGIN DELETE ChunkData WHERE SnapshotDataID = @SnapshotID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END ELSE BEGIN DELETE ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END GO GRANT EXECUTE ON [dbo].[DeleteOneChunk] TO RSExecRole GO -------------------------------------------------- ------------- Persisted stream SPs if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeletePersistedStreams]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeletePersistedStreams] GO CREATE PROCEDURE [dbo].[DeletePersistedStreams] @SessionID varchar(32) AS delete ReportServerTempDB.dbo.PersistedStream from (select top 1 * from ReportServerTempDB.dbo.PersistedStream PS2 where PS2.SessionID = @SessionID) as e1 where e1.SessionID = ReportServerTempDB.dbo.PersistedStream.[SessionID] and e1.[Index] = ReportServerTempDB.dbo.PersistedStream.[Index] GO GRANT EXECUTE ON [dbo].[DeletePersistedStreams] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteExpiredPersistedStreams]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteExpiredPersistedStreams] GO CREATE PROCEDURE [dbo].[DeleteExpiredPersistedStreams] AS SET DEADLOCK_PRIORITY LOW DELETE ReportServerTempDB.dbo.PersistedStream FROM (SELECT TOP 1 * FROM ReportServerTempDB.dbo.PersistedStream PS2 WHERE PS2.RefCount = 0 AND GETDATE() > PS2.ExpirationDate) AS e1 WHERE e1.SessionID = ReportServerTempDB.dbo.PersistedStream.[SessionID] AND e1.[Index] = ReportServerTempDB.dbo.PersistedStream.[Index] GO GRANT EXECUTE ON [dbo].[DeleteExpiredPersistedStreams] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeletePersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeletePersistedStream] GO CREATE PROCEDURE [dbo].[DeletePersistedStream] @SessionID varchar(32), @Index int AS delete from ReportServerTempDB.dbo.PersistedStream where SessionID = @SessionID and [Index] = @Index GO GRANT EXECUTE ON [dbo].[DeletePersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddPersistedStream] GO CREATE PROCEDURE [dbo].[AddPersistedStream] @SessionID varchar(32), @Index int AS DECLARE @RefCount int DECLARE @id varchar(32) DECLARE @ExpirationDate datetime set @RefCount = 0 set @ExpirationDate = DATEADD(day, 2, GETDATE()) set @id = (select SessionID from ReportServerTempDB.dbo.SessionData where SessionID = @SessionID) if @id is not null begin set @RefCount = 1 end INSERT INTO ReportServerTempDB.dbo.PersistedStream (SessionID, [Index], [RefCount], [ExpirationDate]) VALUES (@SessionID, @Index, @RefCount, @ExpirationDate) GO GRANT EXECUTE ON [dbo].[AddPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[LockPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[LockPersistedStream] GO CREATE PROCEDURE [dbo].[LockPersistedStream] @SessionID varchar(32), @Index int AS SELECT [Index] FROM ReportServerTempDB.dbo.PersistedStream WITH (XLOCK) WHERE SessionID = @SessionID AND [Index] = @Index GO GRANT EXECUTE ON [dbo].[LockPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteFirstPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteFirstPortionPersistedStream] GO CREATE PROCEDURE [dbo].[WriteFirstPortionPersistedStream] @SessionID varchar(32), @Index int, @Name nvarchar(260) = NULL, @MimeType nvarchar(260) = NULL, @Extension nvarchar(260) = NULL, @Encoding nvarchar(260) = NULL, @Content image AS UPDATE ReportServerTempDB.dbo.PersistedStream set Content = @Content, [Name] = @Name, MimeType = @MimeType, Extension = @Extension WHERE SessionID = @SessionID AND [Index] = @Index SELECT TEXTPTR(Content) FROM ReportServerTempDB.dbo.PersistedStream WHERE SessionID = @SessionID AND [Index] = @Index GO GRANT EXECUTE ON [dbo].[WriteFirstPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteNextPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteNextPortionPersistedStream] GO CREATE PROCEDURE [dbo].[WriteNextPortionPersistedStream] @DataPointer binary(16), @DataIndex int, @DeleteLength int, @Content image AS UPDATETEXT ReportServerTempDB.dbo.PersistedStream.Content @DataPointer @DataIndex @DeleteLength @Content GO GRANT EXECUTE ON [dbo].[WriteNextPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetFirstPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetFirstPortionPersistedStream] GO CREATE PROCEDURE [dbo].[GetFirstPortionPersistedStream] @SessionID varchar(32) AS SELECT TOP 1 TEXTPTR(P.Content), DATALENGTH(P.Content), P.[Index], P.[Name], P.MimeType, P.Extension, P.Encoding, P.Error FROM ReportServerTempDB.dbo.PersistedStream P WITH (XLOCK) WHERE P.SessionID = @SessionID GO GRANT EXECUTE ON [dbo].[GetFirstPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetPersistedStreamError]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetPersistedStreamError] GO CREATE PROCEDURE [dbo].[SetPersistedStreamError] @SessionID varchar(32), @Index int, @AllRows bit, @Error nvarchar(512) AS if @AllRows = 0 BEGIN UPDATE ReportServerTempDB.dbo.PersistedStream SET Error = @Error WHERE SessionID = @SessionID and [Index] = @Index END ELSE BEGIN UPDATE ReportServerTempDB.dbo.PersistedStream SET Error = @Error WHERE SessionID = @SessionID END GO GRANT EXECUTE ON [dbo].[SetPersistedStreamError] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetNextPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetNextPortionPersistedStream] GO CREATE PROCEDURE [dbo].[GetNextPortionPersistedStream] @DataPointer binary(16), @DataIndex int, @Length int AS READTEXT ReportServerTempDB.dbo.PersistedStream.Content @DataPointer @DataIndex @Length GO GRANT EXECUTE ON [dbo].[GetNextPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapshotChunks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapshotChunks] GO CREATE PROCEDURE [dbo].[GetSnapshotChunks] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit AS IF @IsPermanentSnapshot != 0 BEGIN SELECT ChunkName, ChunkType, ChunkFlags, MimeType, Version, datalength(Content) FROM ChunkData WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN SELECT ChunkName, ChunkType, ChunkFlags, MimeType, Version, datalength(Content) FROM ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[GetSnapshotChunks] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetDrillthroughReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetDrillthroughReports] GO CREATE PROCEDURE [dbo].[SetDrillthroughReports] @ReportID uniqueidentifier, @ModelID uniqueidentifier, @ModelItemID nvarchar(425), @Type tinyint AS INSERT INTO ModelDrill (ModelDrillID, ModelID, ReportID, ModelItemID, [Type]) VALUES (newid(), @ModelID, @ReportID, @ModelItemID, @Type) GO GRANT EXECUTE ON [dbo].[SetDrillthroughReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteDrillthroughReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteDrillthroughReports] GO CREATE PROCEDURE [dbo].[DeleteDrillthroughReports] @ModelID uniqueidentifier, @ModelItemID nvarchar(425) AS DELETE ModelDrill WHERE ModelID = @ModelID and ModelItemID = @ModelItemID GO GRANT EXECUTE ON [dbo].[DeleteDrillthroughReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDrillthroughReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDrillthroughReports] GO CREATE PROCEDURE [dbo].[GetDrillthroughReports] @ModelID uniqueidentifier, @ModelItemID nvarchar(425) AS SELECT ModelDrill.Type, Catalog.Path FROM ModelDrill INNER JOIN Catalog ON ModelDrill.ReportID = Catalog.ItemID WHERE ModelID = @ModelID AND ModelItemID = @ModelItemID GO GRANT EXECUTE ON [dbo].[GetDrillthroughReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDrillthroughReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDrillthroughReport] GO CREATE PROCEDURE [dbo].[GetDrillthroughReport] @ModelPath nvarchar(425), @ModelItemID nvarchar(425), @Type tinyint AS SELECT CatRep.Path FROM ModelDrill INNER JOIN Catalog CatMod ON ModelDrill.ModelID = CatMod.ItemID INNER JOIN Catalog CatRep ON ModelDrill.ReportID = CatRep.ItemID WHERE CatMod.Path = @ModelPath AND ModelItemID = @ModelItemID AND ModelDrill.[Type] = @Type GO GRANT EXECUTE ON [dbo].[GetDrillthroughReport] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUpgradeItems]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUpgradeItems] GO CREATE PROCEDURE [dbo].[GetUpgradeItems] AS SELECT [Item], [Status] FROM [UpgradeInfo] GO GRANT EXECUTE ON [dbo].[GetUpgradeItems] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetUpgradeItemStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetUpgradeItemStatus] GO CREATE PROCEDURE [dbo].[SetUpgradeItemStatus] @ItemName nvarchar(260), @Status nvarchar(512) AS UPDATE [UpgradeInfo] SET [Status] = @Status WHERE [Item] = @ItemName GO GRANT EXECUTE ON [dbo].[SetUpgradeItemStatus] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPolicyRoots]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPolicyRoots] GO CREATE PROCEDURE [dbo].[GetPolicyRoots] AS SELECT [Path], [Type] FROM [Catalog] WHERE [PolicyRoot] = 1 GO GRANT EXECUTE ON [dbo].[GetPolicyRoots] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDataSourceForUpgrade]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDataSourceForUpgrade] GO CREATE PROCEDURE [dbo].[GetDataSourceForUpgrade] @CurrentVersion int AS SELECT [DSID] FROM [DataSource] WHERE [Version] != @CurrentVersion GO GRANT EXECUTE ON [dbo].[GetDataSourceForUpgrade] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSubscriptionsForUpgrade]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSubscriptionsForUpgrade] GO CREATE PROCEDURE [dbo].[GetSubscriptionsForUpgrade] @CurrentVersion int AS SELECT [SubscriptionID] FROM [Subscriptions] WHERE [Version] != @CurrentVersion GO GRANT EXECUTE ON [dbo].[GetSubscriptionsForUpgrade] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[StoreServerParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[StoreServerParameters] GO CREATE PROCEDURE [dbo].[StoreServerParameters] @ServerParametersID nvarchar(32), @Path nvarchar(425), @CurrentDate datetime, @Timeout int, @Expiration datetime, @ParametersValues image, @ParentParametersID nvarchar(32) = NULL AS DECLARE @ExistingServerParametersID as nvarchar(32) SET @ExistingServerParametersID = (SELECT ServerParametersID from [dbo].[ServerParametersInstance] WHERE ServerParametersID = @ServerParametersID) IF @ExistingServerParametersID IS NULL -- new row BEGIN INSERT INTO [dbo].[ServerParametersInstance] (ServerParametersID, ParentID, Path, CreateDate, ModifiedDate, Timeout, Expiration, ParametersValues) VALUES (@ServerParametersID, @ParentParametersID, @Path, @CurrentDate, @CurrentDate, @Timeout, @Expiration, @ParametersValues) END ELSE BEGIN UPDATE [dbo].[ServerParametersInstance] SET Timeout = @Timeout, Expiration = @Expiration, ParametersValues = @ParametersValues, ModifiedDate = @CurrentDate, Path = @Path, ParentID = @ParentParametersID WHERE ServerParametersID = @ServerParametersID END GO GRANT EXECUTE ON [dbo].[StoreServerParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetServerParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetServerParameters] GO CREATE PROCEDURE [dbo].[GetServerParameters] @ServerParametersID nvarchar(32) AS DECLARE @now as DATETIME SET @now = GETDATE() SELECT Child.Path, Child.ParametersValues, Parent.ParametersValues FROM [dbo].[ServerParametersInstance] Child LEFT OUTER JOIN [dbo].[ServerParametersInstance] Parent ON Child.ParentID = Parent.ServerParametersID WHERE Child.ServerParametersID = @ServerParametersID AND Child.Expiration > @now GO GRANT EXECUTE ON [dbo].[GetServerParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredServerParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredServerParameters] GO CREATE PROCEDURE [dbo].[CleanExpiredServerParameters] @ParametersCleaned INT OUTPUT AS DECLARE @now as DATETIME SET @now = GETDATE() DELETE FROM [dbo].[ServerParametersInstance] WHERE ServerParametersID IN ( SELECT TOP 20 ServerParametersID FROM [dbo].[ServerParametersInstance] WHERE Expiration < @now ) SET @ParametersCleaned = @@ROWCOUNT GO GRANT EXECUTE ON [dbo].[CleanExpiredServerParameters] TO RSExecRole GO -- END STORED PROCEDURES PA-- START STORED PROCEDURES if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetKeysForInstallation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetKeysForInstallation] GO CREATE PROCEDURE [dbo].[SetKeysForInstallation] @InstallationID uniqueidentifier, @SymmetricKey image = NULL, @PublicKey image AS update [dbo].[Keys] set [SymmetricKey] = @SymmetricKey, [PublicKey] = @PublicKey where [InstallationID] = @InstallationID and [Client] = 1 GO GRANT EXECUTE ON [dbo].[SetKeysForInstallation] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAnnouncedKey]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAnnouncedKey] GO CREATE PROCEDURE [dbo].[GetAnnouncedKey] @InstallationID uniqueidentifier AS select PublicKey, MachineName, InstanceName from Keys where InstallationID = @InstallationID and Client = 1 GO GRANT EXECUTE ON [dbo].[GetAnnouncedKey] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AnnounceOrGetKey]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AnnounceOrGetKey] GO CREATE PROCEDURE [dbo].[AnnounceOrGetKey] @MachineName nvarchar(256), @InstanceName nvarchar(32), @InstallationID uniqueidentifier, @PublicKey image, @NumAnnouncedServices int OUTPUT AS -- Acquire lock IF NOT EXISTS (SELECT * FROM [dbo].[Keys] WITH(XLOCK) WHERE [Client] < 0) BEGIN RAISERROR('Keys lock row not found', 16, 1) RETURN END -- Get the number of services that have already announced their presence SELECT @NumAnnouncedServices = count(*) FROM [dbo].[Keys] WHERE [Client] = 1 DECLARE @StoredInstallationID uniqueidentifier DECLARE @StoredInstanceName nvarchar(32) SELECT @StoredInstallationID = [InstallationID], @StoredInstanceName = [InstanceName] FROM [dbo].[Keys] WHERE [InstallationID] = @InstallationID AND [Client] = 1 IF @StoredInstallationID IS NULL -- no record present BEGIN INSERT INTO [dbo].[Keys] ([MachineName], [InstanceName], [InstallationID], [Client], [PublicKey], [SymmetricKey]) VALUES (@MachineName, @InstanceName, @InstallationID, 1, @PublicKey, null) END ELSE BEGIN IF @StoredInstanceName IS NULL BEGIN UPDATE [dbo].[Keys] SET [InstanceName] = @InstanceName WHERE [InstallationID] = @InstallationID AND [Client] = 1 END END SELECT [MachineName], [SymmetricKey], [PublicKey] FROM [Keys] WHERE [InstallationID] = @InstallationID and [Client] = 1 GO GRANT EXECUTE ON [dbo].[AnnounceOrGetKey] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetMachineName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetMachineName] GO CREATE PROCEDURE [dbo].[SetMachineName] @MachineName nvarchar(256), @InstallationID uniqueidentifier AS UPDATE [dbo].[Keys] SET MachineName = @MachineName WHERE [InstallationID] = @InstallationID and [Client] = 1 GO GRANT EXECUTE ON [dbo].[SetMachineName] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListInstallations]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListInstallations] GO CREATE PROCEDURE [dbo].[ListInstallations] AS SELECT [MachineName], [InstanceName], [InstallationID], CASE WHEN [SymmetricKey] IS null THEN 0 ELSE 1 END FROM [dbo].[Keys] WHERE [Client] = 1 GO GRANT EXECUTE ON [dbo].[ListInstallations] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListInfoForReencryption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListInfoForReencryption] GO CREATE PROCEDURE [dbo].[ListInfoForReencryption] AS SELECT [DSID] FROM [dbo].[DataSource] WITH (XLOCK, TABLOCK) SELECT [SubscriptionID] FROM [dbo].[Subscriptions] WITH (XLOCK, TABLOCK) SELECT [InstallationID], [PublicKey] FROM [dbo].[Keys] WITH (XLOCK, TABLOCK) WHERE [Client] = 1 AND ([SymmetricKey] IS NOT NULL) GO GRANT EXECUTE ON [dbo].[ListInfoForReencryption] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDatasourceInfoForReencryption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDatasourceInfoForReencryption] GO CREATE PROCEDURE [dbo].[GetDatasourceInfoForReencryption] @DSID as uniqueidentifier AS SELECT [ConnectionString], [OriginalConnectionString], [UserName], [Password], [CredentialRetrieval], [Version] FROM [dbo].[DataSource] WHERE [DSID] = @DSID GO GRANT EXECUTE ON [dbo].[GetDatasourceInfoForReencryption] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetReencryptedDatasourceInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetReencryptedDatasourceInfo] GO CREATE PROCEDURE [dbo].[SetReencryptedDatasourceInfo] @DSID uniqueidentifier, @ConnectionString image = NULL, @OriginalConnectionString image = NULL, @UserName image = NULL, @Password image = NULL, @CredentialRetrieval int, @Version int AS UPDATE [dbo].[DataSource] SET [ConnectionString] = @ConnectionString, [OriginalConnectionString] = @OriginalConnectionString, [UserName] = @UserName, [Password] = @Password, [CredentialRetrieval] = @CredentialRetrieval, [Version] = @Version WHERE [DSID] = @DSID GO GRANT EXECUTE ON [dbo].[SetReencryptedDatasourceInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSubscriptionInfoForReencryption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSubscriptionInfoForReencryption] GO CREATE PROCEDURE [dbo].[GetSubscriptionInfoForReencryption] @SubscriptionID as uniqueidentifier AS SELECT [DeliveryExtension], [ExtensionSettings], [Version] FROM [dbo].[Subscriptions] WHERE [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetSubscriptionInfoForReencryption] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetReencryptedSubscriptionInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetReencryptedSubscriptionInfo] GO CREATE PROCEDURE [dbo].[SetReencryptedSubscriptionInfo] @SubscriptionID as uniqueidentifier, @ExtensionSettings as ntext = NULL, @Version as int AS UPDATE [dbo].[Subscriptions] SET [ExtensionSettings] = @ExtensionSettings, [Version] = @Version WHERE [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[SetReencryptedSubscriptionInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteEncryptedContent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteEncryptedContent] GO CREATE PROCEDURE [dbo].[DeleteEncryptedContent] AS -- Remove the encryption keys delete from keys where client >= 0 -- Remove the encrypted content update datasource set CredentialRetrieval = 1, -- CredentialRetrieval.Prompt ConnectionString = null, OriginalConnectionString = null, UserName = null, Password = null GO GRANT EXECUTE ON [dbo].[DeleteEncryptedContent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteKey]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteKey] GO CREATE PROCEDURE [dbo].[DeleteKey] @InstallationID uniqueidentifier AS if (@InstallationID = '00000000-0000-0000-0000-000000000000') RAISERROR('Cannot delete reserved key', 16, 1) -- Remove the encryption keys delete from keys where InstallationID = @InstallationID and Client = 1 GO GRANT EXECUTE ON [dbo].[DeleteKey] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAllConfigurationInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAllConfigurationInfo] GO CREATE PROCEDURE [dbo].[GetAllConfigurationInfo] AS SELECT [Name], [Value] FROM [ConfigurationInfo] GO GRANT EXECUTE ON [dbo].[GetAllConfigurationInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetOneConfigurationInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetOneConfigurationInfo] GO CREATE PROCEDURE [dbo].[GetOneConfigurationInfo] @Name nvarchar (260) AS SELECT [Value] FROM [ConfigurationInfo] WHERE [Name] = @Name GO GRANT EXECUTE ON [dbo].[GetOneConfigurationInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetConfigurationInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetConfigurationInfo] GO CREATE PROCEDURE [dbo].[SetConfigurationInfo] @Name nvarchar (260), @Value ntext AS DELETE FROM [ConfigurationInfo] WHERE [Name] = @Name IF @Value is not null BEGIN INSERT INTO ConfigurationInfo VALUES ( newid(), @Name, @Value ) END GO GRANT EXECUTE ON [dbo].[SetConfigurationInfo] TO RSExecRole if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddEvent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddEvent] GO CREATE PROCEDURE [dbo].[AddEvent] @EventType nvarchar (260), @EventData nvarchar (260) AS insert into [Event] ([EventID], [EventType], [EventData], [TimeEntered], [ProcessStart], [BatchID]) values (NewID(), @EventType, @EventData, GETUTCDATE(), NULL, NULL) GO GRANT EXECUTE ON [dbo].[AddEvent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteEvent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteEvent] GO CREATE PROCEDURE [dbo].[DeleteEvent] @ID uniqueidentifier AS delete from [Event] where [EventID] = @ID GO GRANT EXECUTE ON [dbo].[DeleteEvent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanEventRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanEventRecords] GO CREATE PROCEDURE [dbo].[CleanEventRecords] @MaxAgeMinutes int AS -- Reset all notifications which have been add over n minutes ago Update [Event] set [ProcessStart] = NULL, [ProcessHeartbeat] = NULL where [EventID] in ( SELECT [EventID] FROM [Event] WHERE [ProcessHeartbeat] < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) ) GO GRANT EXECUTE ON [dbo].[CleanEventRecords] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddExecutionLogEntry]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddExecutionLogEntry] GO CREATE PROCEDURE [dbo].[AddExecutionLogEntry] @InstanceName nvarchar(38), @Report nvarchar(260), @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @RequestType bit, @Format nvarchar(26), @Parameters ntext, @TimeStart DateTime, @TimeEnd DateTime, @TimeDataRetrieval int, @TimeProcessing int, @TimeRendering int, @Source tinyint, @Status nvarchar(32), @ByteCount bigint, @RowCount bigint AS -- Unless is is specifically 'False', it's true if exists (select * from ConfigurationInfo where [Name] = 'EnableExecutionLogging' and [Value] like 'False') begin return end Declare @ReportID uniqueidentifier select @ReportID = ItemID from Catalog with (nolock) where Path = @Report insert into ExecutionLog (InstanceName, ReportID, UserName, RequestType, [Format], Parameters, TimeStart, TimeEnd, TimeDataRetrieval, TimeProcessing, TimeRendering, Source, Status, ByteCount, [RowCount]) Values (@InstanceName, @ReportID, @UserName, @RequestType, @Format, @Parameters, @TimeStart, @TimeEnd, @TimeDataRetrieval, @TimeProcessing, @TimeRendering, @Source, @Status, @ByteCount, @RowCount) GO GRANT EXECUTE ON [dbo].[AddExecutionLogEntry] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ExpireExecutionLogEntries]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ExpireExecutionLogEntries] GO CREATE PROCEDURE [dbo].[ExpireExecutionLogEntries] AS -- -1 means no expiration if exists (select * from ConfigurationInfo where [Name] = 'ExecutionLogDaysKept' and CAST(CAST(Value as nvarchar) as integer) = -1) begin return end delete from ExecutionLog where DateDiff(day, TimeStart, getdate()) >= (select CAST(CAST(Value as nvarchar) as integer) from ConfigurationInfo where [Name] = 'ExecutionLogDaysKept') GO GRANT EXECUTE ON [dbo].[ExpireExecutionLogEntries] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUserIDBySid]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUserIDBySid] GO -- looks up any user name by its SID, if not it creates a regular user CREATE PROCEDURE [dbo].[GetUserIDBySid] @UserSid varbinary(85), @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS SELECT @UserID = (SELECT UserID FROM Users WHERE Sid = @UserSid AND AuthType = @AuthType) IF @UserID IS NULL BEGIN SET @UserID = newid() INSERT INTO Users (UserID, Sid, UserType, AuthType, UserName) VALUES (@UserID, @UserSid, 0, @AuthType, @UserName) END GO GRANT EXECUTE ON [dbo].[GetUserIDBySid] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUserIDByName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUserIDByName] GO -- looks up any user name by its User Name, if not it creates a regular user CREATE PROCEDURE [dbo].[GetUserIDByName] @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS SELECT @UserID = (SELECT UserID FROM Users WHERE UserName = @UserName AND AuthType = @AuthType) IF @UserID IS NULL BEGIN SET @UserID = newid() INSERT INTO Users (UserID, Sid, UserType, AuthType, UserName) VALUES (@UserID, NULL, 0, @AuthType, @UserName) END GO GRANT EXECUTE ON [dbo].[GetUserIDByName] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUserID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUserID] GO -- looks up any user name, if not it creates a regular user - uses Sid CREATE PROCEDURE [dbo].[GetUserID] @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS IF @AuthType = 1 -- Windows BEGIN EXEC GetUserIDBySid @UserSid, @UserName, @AuthType, @UserID OUTPUT END ELSE BEGIN EXEC GetUserIDByName @UserName, @AuthType, @UserID OUTPUT END GO GRANT EXECUTE ON [dbo].[GetUserID] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPrincipalID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPrincipalID] GO -- looks up a principal, if not there looks up regular users and turns them into principals -- if not, it creates a principal CREATE PROCEDURE [dbo].[GetPrincipalID] @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS -- windows auth IF @AuthType = 1 BEGIN -- is this a principal? SELECT @UserID = (SELECT UserID FROM Users WHERE Sid = @UserSid AND UserType = 1 AND AuthType = @AuthType) END ELSE BEGIN -- is this a principal? SELECT @UserID = (SELECT UserID FROM Users WHERE UserName = @UserName AND UserType = 1 AND AuthType = @AuthType) END IF @UserID IS NULL BEGIN IF @AuthType = 1 -- Windows BEGIN -- Is this a regular user SELECT @UserID = (SELECT UserID FROM Users WHERE Sid = @UserSid AND UserType = 0 AND AuthType = @AuthType) END ELSE BEGIN -- Is this a regular user SELECT @UserID = (SELECT UserID FROM Users WHERE UserName = @UserName AND UserType = 0 AND AuthType = @AuthType) END -- No, create a new principal IF @UserID IS NULL BEGIN SET @UserID = newid() INSERT INTO Users (UserID, Sid, UserType, AuthType, UserName) VALUES (@UserID, @UserSid, 1, @AuthType, @UserName) END ELSE BEGIN UPDATE Users SET UserType = 1 WHERE UserID = @UserID END END GO GRANT EXECUTE ON [dbo].[GetPrincipalID] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateSubscription] GO CREATE PROCEDURE [dbo].[CreateSubscription] @id uniqueidentifier, @Locale nvarchar (128), @Report_Name nvarchar (425), @OwnerSid varbinary (85) = NULL, @OwnerName nvarchar(260), @OwnerAuthType int, @DeliveryExtension nvarchar (260) = NULL, @InactiveFlags int, @ExtensionSettings ntext = NULL, @ModifiedBySid varbinary (85) = NULL, @ModifiedByName nvarchar(260), @ModifiedByAuthType int, @ModifiedDate datetime, @Description nvarchar(512) = NULL, @LastStatus nvarchar(260) = NULL, @EventType nvarchar(260), @MatchData ntext = NULL, @Parameters ntext = NULL, @DataSettings ntext = NULL, @Version int AS -- Create a subscription with the given data. The name must match a name in the -- Catalog table and it must be a report type (2) or linked report (4) DECLARE @Report_OID uniqueidentifier DECLARE @OwnerID uniqueidentifier DECLARE @ModifiedByID uniqueidentifier DECLARE @TempDeliveryID uniqueidentifier --Get the report id for this subscription select @Report_OID = (select [ItemID] from [Catalog] where [Catalog].[Path] = @Report_Name and ([Catalog].[Type] = 2 or [Catalog].[Type] = 4)) EXEC GetUserID @OwnerSid, @OwnerName, @OwnerAuthType, @OwnerID OUTPUT EXEC GetUserID @ModifiedBySid, @ModifiedByName, @ModifiedByAuthType, @ModifiedByID OUTPUT if (@Report_OID is NULL) begin RAISERROR('Report Not Found', 16, 1) return end Insert into Subscriptions ( [SubscriptionID], [OwnerID], [Report_OID], [Locale], [DeliveryExtension], [InactiveFlags], [ExtensionSettings], [ModifiedByID], [ModifiedDate], [Description], [LastStatus], [EventType], [MatchData], [LastRunTime], [Parameters], [DataSettings], [Version] ) values (@id, @OwnerID, @Report_OID, @Locale, @DeliveryExtension, @InactiveFlags, @ExtensionSettings, @ModifiedByID, @ModifiedDate, @Description, @LastStatus, @EventType, @MatchData, NULL, @Parameters, @DataSettings, @Version) GO GRANT EXECUTE ON [dbo].[CreateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeliveryRemovedInactivateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeliveryRemovedInactivateSubscription] GO CREATE PROCEDURE [dbo].[DeliveryRemovedInactivateSubscription] @DeliveryExtension nvarchar(260), @Status nvarchar(260) AS update Subscriptions set [DeliveryExtension] = '', [InactiveFlags] = [InactiveFlags] | 1, -- Delivery Provider Removed Flag == 1 [LastStatus] = @Status where [DeliveryExtension] = @DeliveryExtension GO GRANT EXECUTE ON [dbo].[DeliveryRemovedInactivateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteSubscription] GO CREATE PROCEDURE [dbo].[DeleteSubscription] @SubscriptionID uniqueidentifier AS -- Delete the given subscription delete from [Subscriptions] where [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[DeleteSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSubscription] GO CREATE PROCEDURE [dbo].[GetSubscription] @SubscriptionID uniqueidentifier AS -- Grab all of the-- subscription properties given a id select S.[SubscriptionID], S.[Report_OID], S.[Locale], S.[InactiveFlags], S.[DeliveryExtension], S.[ExtensionSettings], SUSER_SNAME(Modified.[Sid]), Modified.[UserName], S.[ModifiedDate], S.[Description], S.[LastStatus], S.[EventType], S.[MatchData], S.[Parameters], S.[DataSettings], A.[TotalNotifications], A.[TotalSuccesses], A.[TotalFailures], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], CAT.[Path], S.[LastRunTime], CAT.[Type], SD.NtSecDescPrimary, S.[Version], Owner.[AuthType] from [Subscriptions] S inner join [Catalog] CAT on S.[Report_OID] = CAT.[ItemID] inner join [Users] Owner on S.OwnerID = Owner.UserID inner join [Users] Modified on S.ModifiedByID = Modified.UserID left outer join [SecData] SD on CAT.PolicyID = SD.PolicyID AND SD.AuthType = Owner.AuthType left outer join [ActiveSubscriptions] A with (NOLOCK) on S.[SubscriptionID] = A.[SubscriptionID] where S.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListSubscriptionsUsingDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListSubscriptionsUsingDataSource] GO CREATE PROCEDURE [dbo].[ListSubscriptionsUsingDataSource] @DataSourceName nvarchar(450) AS select S.[SubscriptionID], S.[Report_OID], S.[Locale], S.[InactiveFlags], S.[DeliveryExtension], S.[ExtensionSettings], SUSER_SNAME(Modified.[Sid]), Modified.[UserName], S.[ModifiedDate], S.[Description], S.[LastStatus], S.[EventType], S.[MatchData], S.[Parameters], S.[DataSettings], A.[TotalNotifications], A.[TotalSuccesses], A.[TotalFailures], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], CAT.[Path], S.[LastRunTime], CAT.[Type], SD.NtSecDescPrimary, S.[Version], Owner.[AuthType] from [DataSource] DS inner join Catalog C on C.ItemID = DS.Link inner join Subscriptions S on S.[SubscriptionID] = DS.[SubscriptionID] inner join [Catalog] CAT on S.[Report_OID] = CAT.[ItemID] inner join [Users] Owner on S.OwnerID = Owner.UserID inner join [Users] Modified on S.ModifiedByID = Modified.UserID left join [SecData] SD on SD.[PolicyID] = CAT.[PolicyID] AND SD.AuthType = Owner.AuthType left outer join [ActiveSubscriptions] A with (NOLOCK) on S.[SubscriptionID] = A.[SubscriptionID] where C.Path = @DataSourceName GO GRANT EXECUTE ON [dbo].[ListSubscriptionsUsingDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSubscriptionStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSubscriptionStatus] GO CREATE PROCEDURE [dbo].[UpdateSubscriptionStatus] @SubscriptionID uniqueidentifier, @Status nvarchar(260) AS update Subscriptions set [LastStatus] = @Status where [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[UpdateSubscriptionStatus] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSubscription] GO CREATE PROCEDURE [dbo].[UpdateSubscription] @id uniqueidentifier, @Locale nvarchar(260), @OwnerSid varbinary(85) = NULL, @OwnerName nvarchar(260), @OwnerAuthType int, @DeliveryExtension nvarchar(260), @InactiveFlags int, @ExtensionSettings ntext = NULL, @ModifiedBySid varbinary(85) = NULL, @ModifiedByName nvarchar(260), @ModifiedByAuthType int, @ModifiedDate datetime, @Description nvarchar(512) = NULL, @LastStatus nvarchar(260) = NULL, @EventType nvarchar(260), @MatchData ntext = NULL, @Parameters ntext = NULL, @DataSettings ntext = NULL, @Version int AS -- Update a subscription's information. DECLARE @ModifiedByID uniqueidentifier DECLARE @OwnerID uniqueidentifier EXEC GetUserID @ModifiedBySid, @OwnerName,@OwnerAuthType, @ModifiedByID OUTPUT EXEC GetUserID @OwnerSid, @ModifiedByName, @ModifiedByAuthType, @OwnerID OUTPUT -- Make sure there is a valid provider update Subscriptions set [DeliveryExtension] = @DeliveryExtension, [Locale] = @Locale, [OwnerID] = @OwnerID, [InactiveFlags] = @InactiveFlags, [ExtensionSettings] = @ExtensionSettings, [ModifiedByID] = @ModifiedByID, [ModifiedDate] = @ModifiedDate, [Description] = @Description, [LastStatus] = @LastStatus, [EventType] = @EventType, [MatchData] = @MatchData, [Parameters] = @Parameters, [DataSettings] = @DataSettings, [Version] = @Version where [SubscriptionID] = @id GO GRANT EXECUTE ON [dbo].[UpdateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[InvalidateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[InvalidateSubscription] GO CREATE PROCEDURE [dbo].[InvalidateSubscription] @SubscriptionID uniqueidentifier, @Flags int, @LastStatus nvarchar(260) AS -- Mark all subscriptions for this report as inactive for the given flags update Subscriptions set [InactiveFlags] = S.[InactiveFlags] | @Flags, [LastStatus] = @LastStatus from Subscriptions S where SubscriptionID = @SubscriptionID GO GRANT EXECUTE ON [dbo].[InvalidateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanNotificationRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanNotificationRecords] GO CREATE PROCEDURE [dbo].[CleanNotificationRecords] @MaxAgeMinutes int AS -- Reset all notifications which have been add over n minutes ago Update [Notifications] set [ProcessStart] = NULL, [ProcessHeartbeat] = NULL, [Attempt] = 1 where [NotificationID] in ( SELECT [NotificationID] FROM [Notifications] WHERE [ProcessHeartbeat] < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) and [Attempt] is NULL ) Update [Notifications] set [ProcessStart] = NULL, [ProcessHeartbeat] = NULL, [Attempt] = [Attempt] + 1 where [NotificationID] in ( SELECT [NotificationID] FROM [Notifications] WHERE [ProcessHeartbeat] < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) and [Attempt] is not NULL ) GO GRANT EXECUTE ON [dbo].[CleanNotificationRecords] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateSnapShotNotifications]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateSnapShotNotifications] GO CREATE PROCEDURE [dbo].[CreateSnapShotNotifications] @HistoryID uniqueidentifier, @LastRunTime datetime AS update [Subscriptions] set [LastRunTime] = @LastRunTime from History SS inner join [Subscriptions] S on S.[Report_OID] = SS.[ReportID] where SS.[HistoryID] = @HistoryID and S.EventType = 'ReportHistorySnapshotCreated' and InactiveFlags = 0 -- Find all valid subscriptions for the given report and create a new notification row for -- each subscription insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) select NewID(), S.[SubscriptionID], NULL, S.[Report_OID], NULL, S.[ExtensionSettings], S.[Locale], S.[Parameters], GETUTCDATE(), S.[LastRunTime], S.[DeliveryExtension], S.[OwnerID], 0, S.[Version] from [Subscriptions] S with (READPAST) inner join History H on S.[Report_OID] = H.[ReportID] where H.[HistoryID] = @HistoryID and S.EventType = 'ReportHistorySnapshotCreated' and InactiveFlags = 0 and S.[DataSettings] is null -- Create any data driven subscription by creating a data driven event insert into [Event] ( [EventID], [EventType], [EventData], [TimeEntered] ) select NewID(), 'DataDrivenSubscription', S.SubscriptionID, GETUTCDATE() from [Subscriptions] S with (READPAST) inner join History H on S.[Report_OID] = H.[ReportID] where H.[HistoryID] = @HistoryID and S.EventType = 'ReportHistorySnapshotCreated' and InactiveFlags = 0 and S.[DataSettings] is not null GO GRANT EXECUTE ON [dbo].[CreateSnapShotNotifications] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateDataDrivenNotification]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateDataDrivenNotification] GO CREATE PROCEDURE [dbo].[CreateDataDrivenNotification] @SubscriptionID uniqueidentifier, @ActiveationID uniqueidentifier, @ReportID uniqueidentifier, @ExtensionSettings ntext, @Locale nvarchar(128), @Parameters ntext, @LastRunTime datetime, @DeliveryExtension nvarchar(260), @OwnerSid varbinary (85) = null, @OwnerName nvarchar(260), @OwnerAuthType int, @Version int AS declare @OwnerID as uniqueidentifier EXEC GetUserID @OwnerSid,@OwnerName, @OwnerAuthType, @OwnerID OUTPUT -- Insert into the notification table insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) values ( NewID(), @SubscriptionID, @ActiveationID, @ReportID, NULL, @ExtensionSettings, @Locale, @Parameters, GETUTCDATE(), @LastRunTime, @DeliveryExtension, @OwnerID, 1, @Version ) GO GRANT EXECUTE ON [dbo].[CreateDataDrivenNotification] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateNewActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateNewActiveSubscription] GO CREATE PROCEDURE [dbo].[CreateNewActiveSubscription] @ActiveID uniqueidentifier, @SubscriptionID uniqueidentifier AS -- Insert into the activesubscription table insert into [ActiveSubscriptions] ( [ActiveID], [SubscriptionID], [TotalNotifications], [TotalSuccesses], [TotalFailures] ) values ( @ActiveID, @SubscriptionID, NULL, 0, 0 ) GO GRANT EXECUTE ON [dbo].[CreateNewActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateActiveSubscription] GO CREATE PROCEDURE [dbo].[UpdateActiveSubscription] @ActiveID uniqueidentifier, @TotalNotifications int = NULL, @TotalSuccesses int = NULL, @TotalFailures int = NULL AS if @TotalNotifications is not NULL begin update ActiveSubscriptions set TotalNotifications = @TotalNotifications where ActiveID = @ActiveID end if @TotalSuccesses is not NULL begin update ActiveSubscriptions set TotalSuccesses = @TotalSuccesses where ActiveID = @ActiveID end if @TotalFailures is not NULL begin update ActiveSubscriptions set TotalFailures = @TotalFailures where ActiveID = @ActiveID end GO GRANT EXECUTE ON [dbo].[UpdateActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteActiveSubscription] GO CREATE PROCEDURE [dbo].[DeleteActiveSubscription] @ActiveID uniqueidentifier AS delete from ActiveSubscriptions where ActiveID = @ActiveID GO GRANT EXECUTE ON [dbo].[DeleteActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAndHoldLockActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAndHoldLockActiveSubscription] GO CREATE PROCEDURE [dbo].[GetAndHoldLockActiveSubscription] @ActiveID uniqueidentifier AS select TotalNotifications, TotalSuccesses, TotalFailures from ActiveSubscriptions with (XLOCK) where ActiveID = @ActiveID GO GRANT EXECUTE ON [dbo].[GetAndHoldLockActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateCacheUpdateNotifications]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateCacheUpdateNotifications] GO CREATE PROCEDURE [dbo].[CreateCacheUpdateNotifications] @ReportID uniqueidentifier, @LastRunTime datetime AS update [Subscriptions] set [LastRunTime] = @LastRunTime from [Subscriptions] S where S.[Report_OID] = @ReportID and S.EventType = 'SnapshotUpdated' and InactiveFlags = 0 -- Find all valid subscriptions for the given report and create a new notification row for -- each subscription insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) select NewID(), S.[SubscriptionID], NULL, S.[Report_OID], NULL, S.[ExtensionSettings], S.[Locale], S.[Parameters], GETUTCDATE(), S.[LastRunTime], S.[DeliveryExtension], S.[OwnerID], 0, S.[Version] from [Subscriptions] S inner join Catalog C on S.[Report_OID] = C.[ItemID] where C.[ItemID] = @ReportID and S.EventType = 'SnapshotUpdated' and InactiveFlags = 0 and S.[DataSettings] is null -- Create any data driven subscription by creating a data driven event insert into [Event] ( [EventID], [EventType], [EventData], [TimeEntered] ) select NewID(), 'DataDrivenSubscription', S.SubscriptionID, GETUTCDATE() from [Subscriptions] S inner join Catalog C on S.[Report_OID] = C.[ItemID] where C.[ItemID] = @ReportID and S.EventType = 'SnapshotUpdated' and InactiveFlags = 0 and S.[DataSettings] is not null GO GRANT EXECUTE ON [dbo].[CreateCacheUpdateNotifications] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCacheSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetCacheSchedule] GO CREATE PROCEDURE [dbo].[GetCacheSchedule] @ReportID uniqueidentifier AS SELECT S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], Owner.[AuthType], RS.ReportAction FROM Schedule S with (XLOCK) inner join ReportSchedule RS on S.ScheduleID = RS.ScheduleID inner join [Users] Owner on S.[CreatedById] = Owner.[UserID] WHERE (RS.ReportAction = 1 or RS.ReportAction = 3) and -- 1 == UpdateCache, 3 == Invalidate cache RS.[ReportID] = @ReportID GO GRANT EXECUTE ON [dbo].[GetCacheSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteNotification]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteNotification] GO CREATE PROCEDURE [dbo].[DeleteNotification] @ID uniqueidentifier AS delete from [Notifications] where [NotificationID] = @ID GO GRANT EXECUTE ON [dbo].[DeleteNotification] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetNotificationAttempt]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetNotificationAttempt] GO CREATE PROCEDURE [dbo].[SetNotificationAttempt] @Attempt int, @SecondsToAdd int, @NotificationID uniqueidentifier AS update [Notifications] set [ProcessStart] = NULL, [Attempt] = @Attempt, [ProcessAfter] = DateAdd(second, @SecondsToAdd, GetUtcDate()) where [NotificationID] = @NotificationID GO GRANT EXECUTE ON [dbo].[SetNotificationAttempt] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateTimeBasedSubscriptionNotification]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateTimeBasedSubscriptionNotification] GO CREATE PROCEDURE [dbo].[CreateTimeBasedSubscriptionNotification] @SubscriptionID uniqueidentifier, @LastRunTime datetime as insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) select NewID(), S.[SubscriptionID], NULL, S.[Report_OID], NULL, S.[ExtensionSettings], S.[Locale], S.[Parameters], GETUTCDATE(), @LastRunTime, S.[DeliveryExtension], S.[OwnerID], 0, S.[Version] from [Subscriptions] S where S.[SubscriptionID] = @SubscriptionID and InactiveFlags = 0 and S.[DataSettings] is null -- Create any data driven subscription by creating a data driven event insert into [Event] ( [EventID], [EventType], [EventData], [TimeEntered] ) select NewID(), 'DataDrivenSubscription', S.SubscriptionID, GETUTCDATE() from [Subscriptions] S where S.[SubscriptionID] = @SubscriptionID and InactiveFlags = 0 and S.[DataSettings] is not null update [Subscriptions] set [LastRunTime] = @LastRunTime where [SubscriptionID] = @SubscriptionID and InactiveFlags = 0 GO GRANT EXECUTE ON [dbo].[CreateTimeBasedSubscriptionNotification] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteTimeBasedSubscriptionSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteTimeBasedSubscriptionSchedule] GO CREATE PROCEDURE [dbo].[DeleteTimeBasedSubscriptionSchedule] @SubscriptionID as uniqueidentifier as delete ReportSchedule from ReportSchedule RS inner join Subscriptions S on S.[SubscriptionID] = RS.[SubscriptionID] where S.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[DeleteTimeBasedSubscriptionSchedule] TO RSExecRole GO -------------------------------------------------- ------------- Provider Info if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListUsedDeliveryProviders]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListUsedDeliveryProviders] GO CREATE PROCEDURE [dbo].[ListUsedDeliveryProviders] AS select distinct [DeliveryExtension] from Subscriptions where [DeliveryExtension] <> '' GO GRANT EXECUTE ON [dbo].[ListUsedDeliveryProviders] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id('[dbo].[AddBatchRecord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddBatchRecord] GO CREATE PROCEDURE [dbo].[AddBatchRecord] @BatchID uniqueidentifier, @UserName nvarchar(260), @Action varchar(32), @Item nvarchar(425) = NULL, @Parent nvarchar(425) = NULL, @Param nvarchar(425) = NULL, @BoolParam bit = NULL, @Content image = NULL, @Properties ntext = NULL AS IF @Action='BatchStart' BEGIN INSERT INTO [Batch] (BatchID, AddedOn, [Action], Item, Parent, Param, BoolParam, Content, Properties) VALUES (@BatchID, GETUTCDATE(), @Action, @UserName, @Parent, @Param, @BoolParam, @Content, @Properties) END ELSE BEGIN IF EXISTS (SELECT * FROM Batch WHERE BatchID = @BatchID AND [Action] = 'BatchStart' AND Item = @UserName) BEGIN INSERT INTO [Batch] (BatchID, AddedOn, [Action], Item, Parent, Param, BoolParam, Content, Properties) VALUES (@BatchID, GETUTCDATE(), @Action, @Item, @Parent, @Param, @BoolParam, @Content, @Properties) END ELSE BEGIN RAISERROR( 'Batch does not exist', 16, 1 ) END END GO GRANT EXECUTE ON [dbo].[AddBatchRecord] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[GetBatchRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetBatchRecords] GO CREATE PROCEDURE [dbo].[GetBatchRecords] @BatchID uniqueidentifier AS SELECT [Action], Item, Parent, Param, BoolParam, Content, Properties FROM [Batch] WHERE BatchID = @BatchID ORDER BY AddedOn GO GRANT EXECUTE ON [dbo].[GetBatchRecords] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteBatchRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteBatchRecords] GO CREATE PROCEDURE [dbo].[DeleteBatchRecords] @BatchID uniqueidentifier AS DELETE FROM [Batch] WHERE BatchID = @BatchID GO GRANT EXECUTE ON [dbo].[DeleteBatchRecords] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanBatchRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanBatchRecords] GO CREATE PROCEDURE [dbo].[CleanBatchRecords] @MaxAgeMinutes int AS DELETE FROM [Batch] where BatchID in ( SELECT BatchID FROM [Batch] WHERE AddedOn < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) ) GO GRANT EXECUTE ON [dbo].[CleanBatchRecords] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanOrphanedPolicies]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanOrphanedPolicies] GO -- Cleaning orphan policies CREATE PROCEDURE [dbo].[CleanOrphanedPolicies] AS DELETE [Policies] WHERE [Policies].[PolicyFlag] = 0 AND NOT EXISTS (SELECT ItemID FROM [Catalog] WHERE [Catalog].[PolicyID] = [Policies].[PolicyID]) DELETE [Policies] FROM [Policies] INNER JOIN [ModelItemPolicy] ON [ModelItemPolicy].[PolicyID] = [Policies].[PolicyID] WHERE NOT EXISTS (SELECT ItemID FROM [Catalog] WHERE [Catalog].[ItemID] = [ModelItemPolicy].[CatalogItemID]) GO GRANT EXECUTE ON [dbo].[CleanOrphanedPolicies] TO RSExecRole GO -------------------------------------------------- ------------- Snapshot manipulation if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[IncreaseTransientSnapshotRefcount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[IncreaseTransientSnapshotRefcount] GO CREATE PROCEDURE [dbo].[IncreaseTransientSnapshotRefcount] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @ExpirationMinutes as int AS DECLARE @soon AS datetime SET @soon = DATEADD(n, @ExpirationMinutes, GETDATE()) if @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET ExpirationDate = @soon, TransientRefcount = TransientRefcount + 1 WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET ExpirationDate = @soon, TransientRefcount = TransientRefcount + 1 WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[IncreaseTransientSnapshotRefcount] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DecreaseTransientSnapshotRefcount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DecreaseTransientSnapshotRefcount] GO CREATE PROCEDURE [dbo].[DecreaseTransientSnapshotRefcount] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS if @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET TransientRefcount = TransientRefcount - 1 WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET TransientRefcount = TransientRefcount - 1 WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[DecreaseTransientSnapshotRefcount] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[MarkSnapshotAsDependentOnUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[MarkSnapshotAsDependentOnUser] GO CREATE PROCEDURE [dbo].[MarkSnapshotAsDependentOnUser] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS if @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET DependsOnUser = 1 WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET DependsOnUser = 1 WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[MarkSnapshotAsDependentOnUser] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSnapshotChunksVersion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSnapshotChunksVersion] GO CREATE PROCEDURE [dbo].[SetSnapshotChunksVersion] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @Version as smallint AS if @IsPermanentSnapshot = 1 BEGIN if @Version > 0 BEGIN UPDATE ChunkData SET Version = @Version WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ChunkData SET Version = Version WHERE SnapshotDataID = @SnapshotDataID END END ELSE BEGIN if @Version > 0 BEGIN UPDATE ReportServerTempDB.dbo.ChunkData SET Version = @Version WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.ChunkData SET Version = Version WHERE SnapshotDataID = @SnapshotDataID END END GO GRANT EXECUTE ON [dbo].[SetSnapshotChunksVersion] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[LockSnapshotForUpgrade]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[LockSnapshotForUpgrade] GO CREATE PROCEDURE [dbo].[LockSnapshotForUpgrade] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS if @IsPermanentSnapshot = 1 BEGIN SELECT ChunkName from ChunkData with (XLOCK) WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN SELECT ChunkName from ReportServerTempDB.dbo.ChunkData with (XLOCK) WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[LockSnapshotForUpgrade] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[InsertUnreferencedSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[InsertUnreferencedSnapshot] GO CREATE PROCEDURE [dbo].[InsertUnreferencedSnapshot] @ReportID as uniqueidentifier = NULL, @EffectiveParams as ntext = NULL, @QueryParams as ntext = NULL, @ParamsHash as int = NULL, @CreatedDate as datetime, @Description as nvarchar(512) = NULL, @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @SnapshotTimeoutMinutes as int, @Machine as nvarchar(512) = NULL AS DECLARE @now datetime SET @now = GETDATE() IF @IsPermanentSnapshot = 1 BEGIN INSERT INTO SnapshotData (SnapshotDataID, CreatedDate, EffectiveParams, QueryParams, ParamsHash, Description, PermanentRefcount, TransientRefcount, ExpirationDate) VALUES (@SnapshotDataID, @CreatedDate, @EffectiveParams, @QueryParams, @ParamsHash, @Description, 0, 1, DATEADD(n, @SnapshotTimeoutMinutes, @now)) END ELSE BEGIN INSERT INTO ReportServerTempDB.dbo.SnapshotData (SnapshotDataID, CreatedDate, EffectiveParams, QueryParams, ParamsHash, Description, PermanentRefcount, TransientRefcount, ExpirationDate, Machine) VALUES (@SnapshotDataID, @CreatedDate, @EffectiveParams, @QueryParams, @ParamsHash, @Description, 0, 1, DATEADD(n, @SnapshotTimeoutMinutes, @now), @Machine) END GO GRANT EXECuTE ON [dbo].[InsertUnreferencedSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[PromoteSnapshotInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[PromoteSnapshotInfo] GO CREATE PROCEDURE [dbo].[PromoteSnapshotInfo] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @PageCount as int, @HasDocMap as bit AS IF @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET PageCount = @PageCount, HasDocMap = @HasDocMap WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET PageCount = @PageCount, HasDocMap = @HasDocMap WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[PromoteSnapshotInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapshotPromotedInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapshotPromotedInfo] GO CREATE PROCEDURE [dbo].[GetSnapshotPromotedInfo] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS IF @IsPermanentSnapshot = 1 BEGIN SELECT PageCount, HasDocMap FROM SnapshotData WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN SELECT PageCount, HasDocMap FROM ReportServerTempDB.dbo.SnapshotData WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[GetSnapshotPromotedInfo] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[AddHistoryRecord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddHistoryRecord] GO -- add new record to History table CREATE PROCEDURE [dbo].[AddHistoryRecord] @HistoryID uniqueidentifier, @ReportID uniqueidentifier, @SnapshotDate datetime, @SnapshotDataID uniqueidentifier, @SnapshotTransientRefcountChange int AS INSERT INTO History (HistoryID, ReportID, SnapshotDataID, SnapshotDate) VALUES (@HistoryID, @ReportID, @SnapshotDataID, @SnapshotDate) IF @@ERROR = 0 BEGIN UPDATE SnapshotData -- Snapshots, when created, have transient refcount set to 1. Here create permanent reference -- here so we need to increase permanent refcount and decrease transient refcount. However, -- if it was already referenced by the execution snapshot, transient refcount was already -- decreased. Hence, there's a parameter @SnapshotTransientRefcountChange that is 0 or -1. SET PermanentRefcount = PermanentRefcount + 1, TransientRefcount = TransientRefcount + @SnapshotTransientRefcountChange WHERE SnapshotData.SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[AddHistoryRecord] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[SetHistoryLimit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetHistoryLimit] GO CREATE PROCEDURE [dbo].[SetHistoryLimit] @Path nvarchar (425), @SnapshotLimit int = NULL AS UPDATE Catalog SET SnapshotLimit=@SnapshotLimit WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[SetHistoryLimit] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[ListHistory]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListHistory] GO -- list all historical snapshots for a specific report CREATE PROCEDURE [dbo].[ListHistory] @ReportID uniqueidentifier AS SELECT S.SnapshotDate, (SELECT SUM(DATALENGTH( CD.Content ) ) FROM ChunkData AS CD WHERE CD.SnapshotDataID = S.SnapshotDataID ) FROM History AS S -- skipping intermediate table SnapshotData WHERE S.ReportID = @ReportID GO GRANT EXECUTE ON [dbo].[ListHistory] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanHistoryForReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanHistoryForReport] GO -- delete snapshots exceeding # of snapshots. won't work if @SnapshotLimit = 0 CREATE PROCEDURE [dbo].[CleanHistoryForReport] @SnapshotLimit int, @ReportID uniqueidentifier AS DECLARE @cmd varchar(2000) SET @cmd = 'DELETE FROM History WHERE ReportID = ''' + cast(@ReportID as varchar(40) ) + ''' and SnapshotDate < (SELECT MIN(SnapshotDate) FROM (SELECT TOP ' + CAST(@SnapshotLimit as varchar(20)) + ' SnapshotDate FROM History WHERE ReportID = ''' + cast(@ReportID as varchar(40) ) + ''' ORDER BY SnapshotDate DESC ) AS TopSnapshots )' EXEC( @cmd ) GO GRANT EXECUTE ON [dbo].[CleanHistoryForReport] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanAllHistories]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanAllHistories] GO -- delete snapshots exceeding # of snapshots for the whole system CREATE PROCEDURE [dbo].[CleanAllHistories] @SnapshotLimit int AS DECLARE @cmd varchar(2000) SET @cmd = 'DELETE FROM History WHERE HistoryID in (SELECT HistoryID FROM History JOIN Catalog AS ReportJoinSnapshot ON ItemID = ReportID WHERE SnapshotLimit is NULL and SnapshotDate < (SELECT MIN(SnapshotDate) FROM (SELECT TOP ' + CAST(@SnapshotLimit as varchar(20)) + ' SnapshotDate FROM History AS InnerSnapshot WHERE InnerSnapshot.ReportID = ReportJoinSnapshot.ItemID ORDER BY SnapshotDate DESC ) AS TopSnapshots ) )' EXEC( @cmd ) GO GRANT EXECUTE ON [dbo].[CleanAllHistories] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteHistoryRecord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteHistoryRecord] GO -- delete one historical snapshot CREATE PROCEDURE [dbo].[DeleteHistoryRecord] @ReportID uniqueidentifier, @SnapshotDate DateTime AS DELETE FROM History WHERE ReportID = @ReportID AND SnapshotDate = @SnapshotDate GO GRANT EXECUTE ON [dbo].[DeleteHistoryRecord] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteAllHistoryForReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteAllHistoryForReport] GO -- delete all snapshots for a report CREATE PROCEDURE [dbo].[DeleteAllHistoryForReport] @ReportID uniqueidentifier AS DELETE FROM History WHERE HistoryID in (SELECT HistoryID FROM History JOIN Catalog on ItemID = ReportID WHERE ReportID = @ReportID ) GO GRANT EXECUTE ON [dbo].[DeleteAllHistoryForReport] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteHistoriesWithNoPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteHistoriesWithNoPolicy] GO -- delete all snapshots for all reports that inherit system History policy CREATE PROCEDURE [dbo].[DeleteHistoriesWithNoPolicy] AS DELETE FROM History WHERE HistoryID in (SELECT HistoryID FROM History JOIN Catalog on ItemID = ReportID WHERE SnapshotLimit is null ) GO GRANT EXECUTE ON [dbo].[DeleteHistoriesWithNoPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Get_sqlagent_job_status]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[Get_sqlagent_job_status] GO CREATE PROCEDURE [dbo].[Get_sqlagent_job_status] -- Individual job parameters @job_id UNIQUEIDENTIFIER = NULL, -- If provided will only return info about this job -- Note: Only @job_id or @job_name needs to be provided @job_name sysname = NULL, -- If provided will only return info about this job @owner_login_name sysname = NULL -- If provided will only return jobs for this owner AS BEGIN DECLARE @retval INT DECLARE @job_owner_sid VARBINARY(85) DECLARE @is_sysadmin INT SET NOCOUNT ON -- Remove any leading/trailing spaces from parameters (except @owner_login_name) SELECT @job_name = LTRIM(RTRIM(@job_name)) -- Turn [nullable] empty string parameters into NULLs IF (@job_name = N'') SELECT @job_name = NULL -- Verify the job if supplied. This also checks if the caller has rights to view the job IF ((@job_id IS NOT NULL) OR (@job_name IS NOT NULL)) BEGIN EXECUTE @retval = msdb..sp_verify_job_identifiers '@job_name', '@job_id', @job_name OUTPUT, @job_id OUTPUT IF (@retval <> 0) RETURN(1) -- Failure END -- If the login name isn't given, set it to the job owner or the current caller IF(@owner_login_name IS NULL) BEGIN SET @owner_login_name = (SELECT SUSER_SNAME(sj.owner_sid) FROM msdb.dbo.sysjobs sj where sj.job_id = @job_id) SET @is_sysadmin = ISNULL(IS_SRVROLEMEMBER(N'sysadmin', @owner_login_name), 0) END ELSE BEGIN -- Check owner IF (SUSER_SID(@owner_login_name) IS NULL) BEGIN RAISERROR(14262, -1, -1, '@owner_login_name', @owner_login_name) RETURN(1) -- Failure END --only allow sysadmin types to specify the owner IF ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1) AND (ISNULL(IS_MEMBER(N'SQLAgentAdminRole'), 0) = 1) AND (SUSER_SNAME() <> @owner_login_name)) BEGIN --TODO: RAISERROR(14525, -1, -1) RETURN(1) -- Failure END SET @is_sysadmin = 0 END IF (@job_id IS NOT NULL) BEGIN -- Individual job... EXECUTE @retval = master.dbo.xp_sqlagent_enum_jobs @is_sysadmin, @owner_login_name, @job_id IF (@retval <> 0) RETURN(1) -- Failure END ELSE BEGIN -- Set of jobs... EXECUTE @retval = master.dbo.xp_sqlagent_enum_jobs @is_sysadmin, @owner_login_name IF (@retval <> 0) RETURN(1) -- Failure END RETURN(0) -- Success END GO GRANT EXECUTE ON [dbo].[Get_sqlagent_job_status] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateTask] GO CREATE PROCEDURE [dbo].[CreateTask] @ScheduleID uniqueidentifier, @Name nvarchar (260), @StartDate datetime, @Flags int, @NextRunTime datetime = NULL, @LastRunTime datetime = NULL, @EndDate datetime = NULL, @RecurrenceType int = NULL, @MinutesInterval int = NULL, @DaysInterval int = NULL, @WeeksInterval int = NULL, @DaysOfWeek int = NULL, @DaysOfMonth int = NULL, @Month int = NULL, @MonthlyWeek int = NULL, @State int = NULL, @LastRunStatus nvarchar (260) = NULL, @ScheduledRunTimeout int = NULL, @UserSid varbinary (85) = null, @UserName nvarchar(260), @AuthType int, @EventType nvarchar (260), @EventData nvarchar (260), @Type int , @Path nvarchar (425) = NULL AS DECLARE @UserID uniqueidentifier EXEC GetUserID @UserSid, @UserName, @AuthType, @UserID OUTPUT -- Create a task with the given data. Insert into Schedule ( [ScheduleID], [Name], [StartDate], [Flags], [NextRunTime], [LastRunTime], [EndDate], [RecurrenceType], [MinutesInterval], [DaysInterval], [WeeksInterval], [DaysOfWeek], [DaysOfMonth], [Month], [MonthlyWeek], [State], [LastRunStatus], [ScheduledRunTimeout], [CreatedById], [EventType], [EventData], [Type], [Path] ) values (@ScheduleID, @Name, @StartDate, @Flags, @NextRunTime, @LastRunTime, @EndDate, @RecurrenceType, @MinutesInterval, @DaysInterval, @WeeksInterval, @DaysOfWeek, @DaysOfMonth, @Month, @MonthlyWeek, @State, @LastRunStatus, @ScheduledRunTimeout, @UserID, @EventType, @EventData, @Type, @Path) GO GRANT EXECUTE ON [dbo].[CreateTask] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateTask] GO CREATE PROCEDURE [dbo].[UpdateTask] @ScheduleID uniqueidentifier, @Name nvarchar (260), @StartDate datetime, @Flags int, @NextRunTime datetime = NULL, @LastRunTime datetime = NULL, @EndDate datetime = NULL, @RecurrenceType int = NULL, @MinutesInterval int = NULL, @DaysInterval int = NULL, @WeeksInterval int = NULL, @DaysOfWeek int = NULL, @DaysOfMonth int = NULL, @Month int = NULL, @MonthlyWeek int = NULL, @State int = NULL, @LastRunStatus nvarchar (260) = NULL, @ScheduledRunTimeout int = NULL AS -- Update a tasks values. ScheduleID and Report information can not be updated Update Schedule set [StartDate] = @StartDate, [Name] = @Name, [Flags] = @Flags, [NextRunTime] = @NextRunTime, [LastRunTime] = @LastRunTime, [EndDate] = @EndDate, [RecurrenceType] = @RecurrenceType, [MinutesInterval] = @MinutesInterval, [DaysInterval] = @DaysInterval, [WeeksInterval] = @WeeksInterval, [DaysOfWeek] = @DaysOfWeek, [DaysOfMonth] = @DaysOfMonth, [Month] = @Month, [MonthlyWeek] = @MonthlyWeek, [State] = @State, [LastRunStatus] = @LastRunStatus, [ScheduledRunTimeout] = @ScheduledRunTimeout where [ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[UpdateTask] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateScheduleNextRunTime]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateScheduleNextRunTime] GO CREATE PROCEDURE [dbo].[UpdateScheduleNextRunTime] @ScheduleID as uniqueidentifier, @NextRunTime as datetime as update Schedule set [NextRunTime] = @NextRunTime where [ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[UpdateScheduleNextRunTime] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListScheduledReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListScheduledReports] GO CREATE PROCEDURE [dbo].[ListScheduledReports] @ScheduleID uniqueidentifier AS -- List all reports for a schedule select RS.[ReportAction], RS.[ScheduleID], RS.[ReportID], RS.[SubscriptionID], C.[Path], C.[Name], C.[Description], C.[ModifiedDate], SUSER_SNAME(U.[Sid]), U.[UserName], DATALENGTH( C.Content ), C.ExecutionTime, S.[Type], SD.[NtSecDescPrimary] from [ReportSchedule] RS Inner join [Catalog] C on RS.[ReportID] = C.[ItemID] Inner join [Schedule] S on RS.[ScheduleID] = S.[ScheduleID] Inner join [Users] U on C.[ModifiedByID] = U.UserID left outer join [SecData] SD on SD.[PolicyID] = C.[PolicyID] AND SD.AuthType = U.AuthType where RS.[ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[ListScheduledReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListTasks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListTasks] GO CREATE PROCEDURE [dbo].[ListTasks] @Path nvarchar (425) = NULL, @Prefix nvarchar (425) = NULL AS select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], Owner.[AuthType], (select count(*) from ReportSchedule where ReportSchedule.ScheduleID = S.ScheduleID) from [Schedule] S inner join [Users] Owner on S.[CreatedById] = Owner.UserID where S.[Type] = 0 /*Type 0 is shared schedules*/ and ((@Path is null) OR (S.Path = @Path) or (S.Path like @Prefix escape '*')) GO GRANT EXECUTE ON [dbo].[ListTasks] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListTasksForMaintenance]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListTasksForMaintenance] GO CREATE PROCEDURE [dbo].[ListTasksForMaintenance] AS declare @date datetime set @date = GETUTCDATE() update [Schedule] set [ConsistancyCheck] = @date from ( SELECT TOP 20 [ScheduleID] FROM [Schedule] WITH(UPDLOCK) WHERE [ConsistancyCheck] is NULL ) AS t1 WHERE [Schedule].[ScheduleID] = t1.[ScheduleID] select top 20 S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path] from [Schedule] S where [ConsistancyCheck] = @date GO GRANT EXECUTE ON [dbo].[ListTasksForMaintenance] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ClearScheduleConsistancyFlags]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ClearScheduleConsistancyFlags] GO CREATE PROCEDURE [dbo].[ClearScheduleConsistancyFlags] AS update [Schedule] with (tablock, xlock) set [ConsistancyCheck] = NULL GO GRANT EXECUTE ON [dbo].[ClearScheduleConsistancyFlags] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAReportsReportAction]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAReportsReportAction] GO CREATE PROCEDURE [dbo].[GetAReportsReportAction] @ReportID uniqueidentifier, @ReportAction int AS select RS.[ReportAction], RS.[ScheduleID], RS.[ReportID], RS.[SubscriptionID], C.[Path] from [ReportSchedule] RS Inner join [Catalog] C on RS.[ReportID] = C.[ItemID] where C.ItemID = @ReportID and RS.[ReportAction] = @ReportAction GO GRANT EXECUTE ON [dbo].[GetAReportsReportAction] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetTimeBasedSubscriptionReportAction]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetTimeBasedSubscriptionReportAction] GO CREATE PROCEDURE [dbo].[GetTimeBasedSubscriptionReportAction] @SubscriptionID uniqueidentifier AS select RS.[ReportAction], RS.[ScheduleID], RS.[ReportID], RS.[SubscriptionID], C.[Path] from [ReportSchedule] RS Inner join [Catalog] C on RS.[ReportID] = C.[ItemID] where RS.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetTimeBasedSubscriptionReportAction] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetTaskProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetTaskProperties] GO CREATE PROCEDURE [dbo].[GetTaskProperties] @ScheduleID uniqueidentifier AS -- Grab all of a tasks properties given a task id select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], Owner.[AuthType] from [Schedule] S with (XLOCK) Inner join [Users] Owner on S.[CreatedById] = Owner.UserID where S.[ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[GetTaskProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteTask] GO CREATE PROCEDURE [dbo].[DeleteTask] @ScheduleID uniqueidentifier AS -- Delete the task with the given task id DELETE FROM Schedule WHERE [ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[DeleteTask] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSchedulesReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSchedulesReports] GO CREATE PROCEDURE [dbo].[GetSchedulesReports] @ID uniqueidentifier AS select C.Path from ReportSchedule RS inner join Catalog C on (C.ItemID = RS.ReportID) where ScheduleID = @ID GO GRANT EXECUTE ON [dbo].[GetSchedulesReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddReportSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddReportSchedule] GO CREATE PROCEDURE [dbo].[AddReportSchedule] @ScheduleID uniqueidentifier, @ReportID uniqueidentifier, @SubscriptionID uniqueidentifier = NULL, @Action int AS Insert into ReportSchedule ([ScheduleID], [ReportID], [SubscriptionID], [ReportAction]) values (@ScheduleID, @ReportID, @SubscriptionID, @Action) GO GRANT EXECUTE ON [dbo].[AddReportSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteReportSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteReportSchedule] GO CREATE PROCEDURE [dbo].[DeleteReportSchedule] @ScheduleID uniqueidentifier, @ReportID uniqueidentifier, @SubscriptionID uniqueidentifier = NULL, @ReportAction int AS IF @SubscriptionID is NULL BEGIN delete from ReportSchedule where ScheduleID = @ScheduleID and ReportID = @ReportID and ReportAction = @ReportAction END ELSE BEGIN delete from ReportSchedule where ScheduleID = @ScheduleID and ReportID = @ReportID and ReportAction = @ReportAction and SubscriptionID = @SubscriptionID END GO GRANT EXECUTE ON [dbo].[DeleteReportSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapShotSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapShotSchedule] GO CREATE PROCEDURE [dbo].[GetSnapShotSchedule] @ReportID uniqueidentifier AS select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], Owner.[AuthType] from Schedule S with (XLOCK) inner join ReportSchedule RS on S.ScheduleID = RS.ScheduleID inner join [Users] Owner on S.[CreatedById] = Owner.[UserID] where RS.ReportAction = 2 and -- 2 == create snapshot RS.ReportID = @ReportID GO GRANT EXECUTE ON [dbo].[GetSnapShotSchedule] TO RSExecRole GO -------------------------------------------------- ------------- Time based subscriptions if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateTimeBasedSubscriptionSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateTimeBasedSubscriptionSchedule] GO CREATE PROCEDURE [dbo].[CreateTimeBasedSubscriptionSchedule] @SubscriptionID as uniqueidentifier, @ScheduleID uniqueidentifier, @Schedule_Name nvarchar (260), @Report_Name nvarchar (425), @StartDate datetime, @Flags int, @NextRunTime datetime = NULL, @LastRunTime datetime = NULL, @EndDate datetime = NULL, @RecurrenceType int = NULL, @MinutesInterval int = NULL, @DaysInterval int = NULL, @WeeksInterval int = NULL, @DaysOfWeek int = NULL, @DaysOfMonth int = NULL, @Month int = NULL, @MonthlyWeek int = NULL, @State int = NULL, @LastRunStatus nvarchar (260) = NULL, @ScheduledRunTimeout int = NULL, @UserSid varbinary (85) = NULL, @UserName nvarchar(260), @AuthType int, @EventType nvarchar (260), @EventData nvarchar (260), @Path nvarchar (425) = NULL AS EXEC CreateTask @ScheduleID, @Schedule_Name, @StartDate, @Flags, @NextRunTime, @LastRunTime, @EndDate, @RecurrenceType, @MinutesInterval, @DaysInterval, @WeeksInterval, @DaysOfWeek, @DaysOfMonth, @Month, @MonthlyWeek, @State, @LastRunStatus, @ScheduledRunTimeout, @UserSid, @UserName, @AuthType, @EventType, @EventData, 1 /*scoped type*/, @Path if @@ERROR = 0 begin -- add a row to the reportSchedule table declare @Report_OID uniqueidentifier select @Report_OID = (select [ItemID] from [Catalog] with (HOLDLOCK) where [Catalog].[Path] = @Report_Name and ([Catalog].[Type] = 2 or [Catalog].[Type] = 4)) EXEC AddReportSchedule @ScheduleID, @Report_OID, @SubscriptionID, 4 -- TimedSubscription action end GO GRANT EXECUTE ON [dbo].[CreateTimeBasedSubscriptionSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetTimeBasedSubscriptionSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetTimeBasedSubscriptionSchedule] GO CREATE PROCEDURE [dbo].[GetTimeBasedSubscriptionSchedule] @SubscriptionID as uniqueidentifier AS select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], Owner.[AuthType] from [ReportSchedule] R inner join Schedule S with (XLOCK) on R.[ScheduleID] = S.[ScheduleID] Inner join [Users] Owner on S.[CreatedById] = Owner.UserID where R.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetTimeBasedSubscriptionSchedule] TO RSExecRole GO -------------------------------------------------- ------------- Running Jobs if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddRunningJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddRunningJob] GO CREATE PROCEDURE [dbo].[AddRunningJob] @JobID as nvarchar(32), @StartDate as datetime, @ComputerName as nvarchar(32), @RequestName as nvarchar(425), @RequestPath as nvarchar(425), @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @Description as ntext = NULL, @Timeout as int, @JobAction as smallint, @JobType as smallint, @JobStatus as smallint AS DECLARE @UserID uniqueidentifier EXEC GetUserID @UserSid, @UserName, @AuthType, @UserID OUTPUT INSERT INTO RunningJobs (JobID, StartDate, ComputerName, RequestName, RequestPath, UserID, Description, Timeout, JobAction, JobType, JobStatus ) VALUES (@JobID, @StartDate, @ComputerName, @RequestName, @RequestPath, @UserID, @Description, @Timeout, @JobAction, @JobType, @JobStatus) GO GRANT EXECUTE ON [dbo].[AddRunningJob] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RemoveRunningJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RemoveRunningJob] GO CREATE PROCEDURE [dbo].[RemoveRunningJob] @JobID as nvarchar(32) AS DELETE FROM RunningJobs WHERE JobID = @JobID GO GRANT EXECUTE ON [dbo].[RemoveRunningJob] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateRunningJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateRunningJob] GO CREATE PROCEDURE [dbo].[UpdateRunningJob] @JobID as nvarchar(32), @JobStatus as smallint AS UPDATE RunningJobs SET JobStatus = @JobStatus WHERE JobID = @JobID GO GRANT EXECUTE ON [dbo].[UpdateRunningJob] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetMyRunningJobs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetMyRunningJobs] GO CREATE PROCEDURE [dbo].[GetMyRunningJobs] @ComputerName as nvarchar(32), @JobType as smallint AS SELECT JobID, StartDate, ComputerName, RequestName, RequestPath, SUSER_SNAME(Users.[Sid]), Users.[UserName], Description, Timeout, JobAction, JobType, JobStatus, Users.[AuthType] FROM RunningJobs INNER JOIN Users ON RunningJobs.UserID = Users.UserID WHERE ComputerName = @ComputerName AND JobType = @JobType GO GRANT EXECUTE ON [dbo].[GetMyRunningJobs] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListRunningJobs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListRunningJobs] GO CREATE PROCEDURE [dbo].[ListRunningJobs] AS SELECT JobID, StartDate, ComputerName, RequestName, RequestPath, SUSER_SNAME(Users.[Sid]), Users.[UserName], Description, Timeout, JobAction, JobType, JobStatus, Users.[AuthType] FROM RunningJobs INNER JOIN Users ON RunningJobs.UserID = Users.UserID GO GRANT EXECUTE ON [dbo].[ListRunningJobs] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredJobs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredJobs] GO CREATE PROCEDURE [dbo].[CleanExpiredJobs] AS DELETE FROM RunningJobs WHERE DATEADD(s, Timeout, StartDate) < GETDATE() GO GRANT EXECUTE ON [dbo].[CleanExpiredJobs] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateObject]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateObject] GO -- This SP should never be called with a policy ID unless it is guarenteed that -- the parent will not be deleted before the insert (such as while running this script) CREATE PROCEDURE [dbo].[CreateObject] @ItemID uniqueidentifier, @Name nvarchar (425), @Path nvarchar (425), @ParentID uniqueidentifier, @Type int, @Content image = NULL, @Intermediate uniqueidentifier = NULL, @LinkSourceID uniqueidentifier = NULL, @Property ntext = NULL, @Parameter ntext = NULL, @Description ntext = NULL, @Hidden bit = NULL, @CreatedBySid varbinary(85) = NULL, @CreatedByName nvarchar(260), @AuthType int, @CreationDate datetime, @ModificationDate datetime, @MimeType nvarchar (260) = NULL, @SnapshotLimit int = NULL, @PolicyRoot int = 0, @PolicyID uniqueidentifier = NULL, @ExecutionFlag int = 1 -- allow live execution, don't keep history AS DECLARE @CreatedByID uniqueidentifier EXEC GetUserID @CreatedBySid, @CreatedByName, @AuthType, @CreatedByID OUTPUT UPDATE Catalog with (XLOCK) SET ModifiedByID = @CreatedByID, ModifiedDate = @ModificationDate WHERE ItemID = @ParentID -- If no policyID, use the parent's IF @PolicyID is NULL BEGIN SET @PolicyID = (SELECT PolicyID FROM [dbo].[Catalog] WHERE Catalog.ItemID = @ParentID) END -- If there is no policy ID then we are guarenteed not to have a parent IF @PolicyID is NULL BEGIN RAISERROR ('Parent Not Found', 16, 1) return END INSERT INTO Catalog (ItemID, Path, Name, ParentID, Type, Content, Intermediate, LinkSourceID, Property, Description, Hidden, CreatedByID, CreationDate, ModifiedByID, ModifiedDate, MimeType, SnapshotLimit, [Parameter], PolicyID, PolicyRoot, ExecutionFlag ) VALUES (@ItemID, @Path, @Name, @ParentID, @Type, @Content, @Intermediate, @LinkSourceID, @Property, @Description, @Hidden, @CreatedByID, @CreationDate, @CreatedByID, @ModificationDate, @MimeType, @SnapshotLimit, @Parameter, @PolicyID, @PolicyRoot , @ExecutionFlag) IF @Intermediate IS NOT NULL AND @@ERROR = 0 BEGIN UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount + 1, TransientRefcount = TransientRefcount - 1 WHERE SnapshotData.SnapshotDataID = @Intermediate END GO GRANT EXECUTE ON [dbo].[CreateObject] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteObject]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteObject] GO CREATE PROCEDURE [dbo].[DeleteObject] @Path nvarchar (425), @Prefix nvarchar (850) AS -- Remove reference for intermediate formats UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 FROM Catalog AS R WITH (XLOCK) INNER JOIN [SnapshotData] AS SD ON R.Intermediate = SD.SnapshotDataID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Remove reference for execution snapshots UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 FROM Catalog AS R WITH (XLOCK) INNER JOIN [SnapshotData] AS SD ON R.SnapshotDataID = SD.SnapshotDataID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Remove history for deleted reports and linked report DELETE History FROM [Catalog] AS R INNER JOIN [History] AS S ON R.ItemID = S.ReportID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Remove model drill reports DELETE ModelDrill FROM [Catalog] AS C INNER JOIN [ModelDrill] AS M ON C.ItemID = M.ReportID WHERE (C.Path = @Path OR C.Path LIKE @Prefix ESCAPE '*') -- Adjust data sources UPDATE [DataSource] SET [Flags] = [Flags] & 0x7FFFFFFD, -- broken link [Link] = NULL FROM [Catalog] AS C INNER JOIN [DataSource] AS DS ON C.[ItemID] = DS.[Link] WHERE (C.Path = @Path OR C.Path LIKE @Prefix ESCAPE '*') -- Clean all data sources DELETE [DataSource] FROM [Catalog] AS R INNER JOIN [DataSource] AS DS ON R.[ItemID] = DS.[ItemID] WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Update linked reports UPDATE LR SET LR.LinkSourceID = NULL FROM [Catalog] AS R INNER JOIN [Catalog] AS LR ON R.ItemID = LR.LinkSourceID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') AND (LR.Path NOT LIKE @Prefix ESCAPE '*') -- Remove references for cache entries UPDATE SN SET PermanentRefcount = PermanentRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC on SN.SnapshotDataID = EC.SnapshotDataID INNER JOIN Catalog AS C ON EC.ReportID = C.ItemID WHERE (Path = @Path OR Path LIKE @Prefix ESCAPE '*') -- Clean cache entries for items to be deleted DELETE EC FROM ReportServerTempDB.dbo.ExecutionCache AS EC INNER JOIN Catalog AS C ON EC.ReportID = C.ItemID WHERE (Path = @Path OR Path LIKE @Prefix ESCAPE '*') -- Finally delete items DELETE FROM [Catalog] WHERE (Path = @Path OR Path LIKE @Prefix ESCAPE '*') EXEC CleanOrphanedPolicies GO GRANT EXECUTE ON [dbo].[DeleteObject] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindObjectsNonRecursive]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindObjectsNonRecursive] GO CREATE PROCEDURE [dbo].[FindObjectsNonRecursive] @Path nvarchar (425), @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.[UserName], SUSER_SNAME(MU.Sid), MU.[UserName], C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Catalog AS P ON C.ParentID = P.ItemID INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE P.Path = @Path GO GRANT EXECUTE ON [dbo].[FindObjectsNonRecursive] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindObjectsRecursive]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindObjectsRecursive] GO CREATE PROCEDURE [dbo].[FindObjectsRecursive] @Prefix nvarchar (850), @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.UserName, SUSER_SNAME(MU.Sid), MU.UserName, C.MimeType, C.ExecutionTime, C.Hidden from Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE C.Path LIKE @Prefix ESCAPE '*' GO GRANT EXECUTE ON [dbo].[FindObjectsRecursive] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindParents]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindParents] GO CREATE PROCEDURE [dbo].[FindParents] @Path nvarchar (425), @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.[UserName], SUSER_SNAME(MU.Sid), MU.[UserName], C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE @Path LIKE C.Path + '/%' ORDER BY DATALENGTH(C.Path) desc GO GRANT EXECUTE ON [dbo].[FindParents] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindObjectsByLink]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindObjectsByLink] GO CREATE PROCEDURE [dbo].[FindObjectsByLink] @Link uniqueidentifier, @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.UserName, SUSER_SNAME(MU.Sid), MU.UserName, C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE C.LinkSourceID = @Link GO GRANT EXECUTE ON [dbo].[FindObjectsByLink] TO RSExecRole GO -------------------------------------------------- ------------- Procedures used to update linked reports if exists (select * from sysobjects where id = object_id('[dbo].[GetIDPairsByLink]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetIDPairsByLink] GO CREATE PROCEDURE [dbo].[GetIDPairsByLink] @Link uniqueidentifier AS SELECT LinkSourceID, ItemID FROM Catalog WHERE LinkSourceID = @Link GO GRANT EXECUTE ON [dbo].[GetIDPairsByLink] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[GetChildrenBeforeDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetChildrenBeforeDelete] GO CREATE PROCEDURE [dbo].[GetChildrenBeforeDelete] @Prefix nvarchar (850), @AuthType int AS SELECT C.PolicyID, C.Type, SD.NtSecDescPrimary FROM Catalog AS C LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE C.Path LIKE @Prefix ESCAPE '*' -- return children only, not item itself GO GRANT EXECUTE ON [dbo].[GetChildrenBeforeDelete] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAllProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAllProperties] GO CREATE PROCEDURE [dbo].[GetAllProperties] @Path nvarchar (425), @AuthType int AS select Property, Description, Type, DATALENGTH( Content ), ItemID, SUSER_SNAME(C.Sid), C.UserName, CreationDate, SUSER_SNAME(M.Sid), M.UserName, ModifiedDate, MimeType, ExecutionTime, NtSecDescPrimary, [LinkSourceID], Hidden, ExecutionFlag, SnapshotLimit, [Name] FROM Catalog INNER JOIN Users C ON Catalog.CreatedByID = C.UserID INNER JOIN Users M ON Catalog.ModifiedByID = M.UserID LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[GetAllProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetParameters] GO CREATE PROCEDURE [dbo].[GetParameters] @Path nvarchar (425), @AuthType int AS SELECT Type, [Parameter], ItemID, SecData.NtSecDescPrimary, [LinkSourceID], [ExecutionFlag] FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[GetParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetObjectContent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetObjectContent] GO CREATE PROCEDURE [dbo].[GetObjectContent] @Path nvarchar (425), @AuthType int AS SELECT Type, Content, LinkSourceID, MimeType, SecData.NtSecDescPrimary, ItemID FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[GetObjectContent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCompiledDefinition]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetCompiledDefinition] GO -- used to create snapshots CREATE PROCEDURE [dbo].[GetCompiledDefinition] @Path nvarchar (425), @AuthType int AS SELECT MainItem.Type, MainItem.Intermediate, MainItem.LinkSourceID, MainItem.Property, MainItem.Description, SecData.NtSecDescPrimary, MainItem.ItemID, MainItem.ExecutionFlag, LinkTarget.Intermediate, LinkTarget.Property, LinkTarget.Description, MainItem.[SnapshotDataID] FROM Catalog MainItem LEFT OUTER JOIN SecData ON MainItem.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog LinkTarget with (INDEX(PK_Catalog)) on MainItem.LinkSourceID = LinkTarget.ItemID WHERE MainItem.Path = @Path GO GRANT EXECUTE ON [dbo].[GetCompiledDefinition] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetReportForExecution]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetReportForExecution] GO -- gets either the intermediate format or snapshot from cache CREATE PROCEDURE [dbo].[GetReportForExecution] @Path nvarchar (425), @ParamsHash int, @AuthType int AS DECLARE @now AS datetime SET @now = GETDATE() IF ( NOT EXISTS ( SELECT * FROM Catalog AS C INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON C.ItemID = EC.ReportID INNER JOIN ReportServerTempDB.dbo.SnapshotData AS SN ON EC.SnapshotDataID = SN.SnapshotDataID WHERE C.Path = @Path AND EC.AbsoluteExpiration > @now AND SN.ParamsHash = @ParamsHash ) ) BEGIN -- no cache SELECT Cat.Type, Cat.LinkSourceID, Cat2.Path, Cat.Property, Cat.Description, SecData.NtSecDescPrimary, Cat.ItemID, CAST (0 AS BIT), -- not found, Cat.Intermediate, Cat.ExecutionFlag, SD.SnapshotDataID, SD.DependsOnUser, Cat.ExecutionTime, (SELECT Schedule.NextRunTime FROM Schedule WITH (XLOCK) INNER JOIN ReportSchedule ON Schedule.ScheduleID = ReportSchedule.ScheduleID WHERE ReportSchedule.ReportID = Cat.ItemID AND ReportSchedule.ReportAction = 1), -- update snapshot (SELECT Schedule.ScheduleID FROM Schedule INNER JOIN ReportSchedule ON Schedule.ScheduleID = ReportSchedule.ScheduleID WHERE ReportSchedule.ReportID = Cat.ItemID AND ReportSchedule.ReportAction = 1), -- update snapshot (SELECT CachePolicy.ExpirationFlags FROM CachePolicy WHERE CachePolicy.ReportID = Cat.ItemID), Cat2.Intermediate FROM Catalog AS Cat LEFT OUTER JOIN SecData ON Cat.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog AS Cat2 on Cat.LinkSourceID = Cat2.ItemID LEFT OUTER JOIN SnapshotData AS SD ON Cat.SnapshotDataID = SD.SnapshotDataID WHERE Cat.Path = @Path END ELSE BEGIN -- use cache SELECT TOP 1 Cat.Type, Cat.LinkSourceID, Cat2.Path, Cat.Property, Cat.Description, SecData.NtSecDescPrimary, Cat.ItemID, CAST (1 AS BIT), -- found, SN.SnapshotDataID, SN.DependsOnUser, SN.EffectiveParams, SN.CreatedDate, EC.AbsoluteExpiration, (SELECT CachePolicy.ExpirationFlags FROM CachePolicy WHERE CachePolicy.ReportID = Cat.ItemID), (SELECT Schedule.ScheduleID FROM Schedule WITH (XLOCK) INNER JOIN ReportSchedule ON Schedule.ScheduleID = ReportSchedule.ScheduleID WHERE ReportSchedule.ReportID = Cat.ItemID AND ReportSchedule.ReportAction = 1), -- update snapshot SN.QueryParams FROM Catalog AS Cat INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON Cat.ItemID = EC.ReportID INNER JOIN ReportServerTempDB.dbo.SnapshotData AS SN ON EC.SnapshotDataID = SN.SnapshotDataID LEFT OUTER JOIN SecData ON Cat.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog AS Cat2 on Cat.LinkSourceID = Cat2.ItemID WHERE Cat.Path = @Path AND AbsoluteExpiration > @now AND SN.ParamsHash = @ParamsHash ORDER BY SN.CreatedDate DESC END GO GRANT EXECUTE ON [dbo].[GetReportForExecution] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetReportParametersForExecution]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetReportParametersForExecution] GO -- gets either the intermediate format or snapshot from cache CREATE PROCEDURE [dbo].[GetReportParametersForExecution] @Path nvarchar (425), @HistoryID DateTime = NULL, @AuthType int AS SELECT C.[ItemID], C.[Type], C.[ExecutionFlag], [SecData].[NtSecDescPrimary], C.[Parameter], C.[Intermediate], C.[SnapshotDataID], [History].[SnapshotDataID], L.[Intermediate], C.[LinkSourceID], C.[ExecutionTime] FROM [Catalog] AS C LEFT OUTER JOIN [SecData] ON C.[PolicyID] = [SecData].[PolicyID] AND [SecData].AuthType = @AuthType LEFT OUTER JOIN [History] ON ( C.[ItemID] = [History].[ReportID] AND [History].[SnapshotDate] = @HistoryID ) LEFT OUTER JOIN [Catalog] AS L ON C.[LinkSourceID] = L.[ItemID] WHERE C.[Path] = @Path GO GRANT EXECUTE ON [dbo].[GetReportParametersForExecution] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[MoveObject]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[MoveObject] GO CREATE PROCEDURE [dbo].[MoveObject] @OldPath nvarchar (425), @OldPrefix nvarchar (850), @NewName nvarchar (425), @NewPath nvarchar (425), @NewParentID uniqueidentifier, @RenameOnly as bit, @MaxPathLength as int AS DECLARE @LongPath nvarchar(425) SET @LongPath = (SELECT TOP 1 Path FROM Catalog WHERE LEN(Path)-LEN(@OldPath)+LEN(@NewPath) > @MaxPathLength AND Path LIKE @OldPrefix ESCAPE '*') IF @LongPath IS NOT NULL BEGIN SELECT @LongPath RETURN END IF @RenameOnly = 0 -- if this a full-blown move, not just a rename BEGIN -- adjust policies on the top item that gets moved DECLARE @OldInheritedPolicyID as uniqueidentifier SELECT @OldInheritedPolicyID = (SELECT PolicyID FROM Catalog with (XLOCK) WHERE Path = @OldPath AND PolicyRoot = 0) IF (@OldInheritedPolicyID IS NOT NULL) BEGIN -- this was not a policy root, change it to inherit from target folder DECLARE @NewPolicyID as uniqueidentifier SELECT @NewPolicyID = (SELECT PolicyID FROM Catalog with (XLOCK) WHERE ItemID = @NewParentID) -- update item and children that shared the old policy UPDATE Catalog SET PolicyID = @NewPolicyID WHERE Path = @OldPath UPDATE Catalog SET PolicyID = @NewPolicyID WHERE Path LIKE @OldPrefix ESCAPE '*' AND Catalog.PolicyID = @OldInheritedPolicyID END END -- Update item that gets moved (Path, Name, and ParentId) update Catalog set Name = @NewName, Path = @NewPath, ParentID = @NewParentID where Path = @OldPath -- Update all its children (Path only, Names and ParentIds stay the same) update Catalog set Path = STUFF(Path, 1, LEN(@OldPath), @NewPath ) where Path like @OldPrefix escape '*' GO GRANT EXECUTE ON [dbo].[MoveObject] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ObjectExists]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ObjectExists] GO CREATE PROCEDURE [dbo].[ObjectExists] @Path nvarchar (425), @AuthType int AS SELECT Type, ItemID, SnapshotLimit, NtSecDescPrimary, ExecutionFlag, Intermediate, [LinkSourceID] FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[ObjectExists] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetAllProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetAllProperties] GO CREATE PROCEDURE [dbo].[SetAllProperties] @Path nvarchar (425), @Property ntext, @Description ntext = NULL, @Hidden bit = NULL, @ModifiedBySid varbinary (85) = NULL, @ModifiedByName nvarchar(260), @AuthType int, @ModifiedDate DateTime AS DECLARE @ModifiedByID uniqueidentifier EXEC GetUserID @ModifiedBySid, @ModifiedByName, @AuthType, @ModifiedByID OUTPUT UPDATE Catalog SET Property = @Property, Description = @Description, Hidden = @Hidden, ModifiedByID = @ModifiedByID, ModifiedDate = @ModifiedDate WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[SetAllProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FlushReportFromCache]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FlushReportFromCache] GO CREATE PROCEDURE [dbo].[FlushReportFromCache] @Path as nvarchar(425) AS UPDATE SN SET SN.PermanentRefcount = SN.PermanentRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON SN.SnapshotDataID = EC.SnapshotDataID INNER JOIN Catalog AS C ON EC.ReportID = C.ItemID WHERE C.Path = @Path DELETE EC FROM ReportServerTempDB.dbo.ExecutionCache AS EC INNER JOIN Catalog ON EC.ReportID = Catalog.ItemID WHERE Catalog.Path = @Path GO GRANT EXECUTE ON [dbo].[FlushReportFromCache] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetParameters] GO CREATE PROCEDURE [dbo].[SetParameters] @Path nvarchar (425), @Parameter ntext AS UPDATE Catalog SET [Parameter] = @Parameter WHERE Path = @Path EXEC FlushReportFromCache @Path GO GRANT EXECUTE ON [dbo].[SetParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetObjectContent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetObjectContent] GO CREATE PROCEDURE [dbo].[SetObjectContent] @Path nvarchar (425), @Type int, @Content image = NULL, @Intermediate uniqueidentifier = NULL, @Parameter ntext = NULL, @LinkSourceID uniqueidentifier = NULL, @MimeType nvarchar (260) = NULL AS DECLARE @OldIntermediate as uniqueidentifier SET @OldIntermediate = (SELECT Intermediate FROM Catalog WITH (XLOCK) WHERE Path = @Path) UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 WHERE SnapshotData.SnapshotDataID = @OldIntermediate UPDATE Catalog SET Type=@Type, Content = @Content, Intermediate = @Intermediate, [Parameter] = @Parameter, LinkSourceID = @LinkSourceID, MimeType = @MimeType WHERE Path = @Path UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount + 1, TransientRefcount = TransientRefcount - 1 WHERE SnapshotData.SnapshotDataID = @Intermediate EXEC FlushReportFromCache @Path GO GRANT EXECUTE ON [dbo].[SetObjectContent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetLastModified]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetLastModified] GO CREATE PROCEDURE [dbo].[SetLastModified] @Path nvarchar (425), @ModifiedBySid varbinary (85) = NULL, @ModifiedByName nvarchar(260), @AuthType int, @ModifiedDate DateTime AS DECLARE @ModifiedByID uniqueidentifier EXEC GetUserID @ModifiedBySid, @ModifiedByName, @AuthType, @ModifiedByID OUTPUT UPDATE Catalog SET ModifiedByID = @ModifiedByID, ModifiedDate = @ModifiedDate WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[SetLastModified] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetNameById]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetNameById] GO CREATE PROCEDURE [dbo].[GetNameById] @ItemID uniqueidentifier AS SELECT Path FROM Catalog WHERE ItemID = @ItemID GO GRANT EXECUTE ON [dbo].[GetNameById] TO RSExecRole GO -------------------------------------------------- ------------- Data source procedures to store user names and passwords if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddDataSource] GO CREATE PROCEDURE [dbo].[AddDataSource] @DSID [uniqueidentifier], @ItemID [uniqueidentifier] = NULL, -- null for future suport dynamic delivery @SubscriptionID [uniqueidentifier] = NULL, @Name [nvarchar] (260) = NULL, -- only for scoped data sources, MUST be NULL for standalone!!! @Extension [nvarchar] (260) = NULL, @LinkID [uniqueidentifier] = NULL, -- link id is trusted, if it is provided - we use it @LinkPath [nvarchar] (425) = NULL, -- if LinkId is not provided we try to look up LinkPath @CredentialRetrieval [int], @Prompt [ntext] = NULL, @ConnectionString [image] = NULL, @OriginalConnectionString [image] = NULL, @OriginalConnectStringExpressionBased [bit] = NULL, @UserName [image] = NULL, @Password [image] = NULL, @Flags [int], @AuthType [int], @Version [int] AS DECLARE @ActualLinkID uniqueidentifier SET @ActualLinkID = NULL IF (@LinkID is NULL) AND (@LinkPath is not NULL) BEGIN SELECT Type, ItemID, NtSecDescPrimary FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @LinkPath SET @ActualLinkID = (SELECT ItemID FROM Catalog WHERE Path = @LinkPath) END ELSE BEGIN SET @ActualLinkID = @LinkID END INSERT INTO DataSource ([DSID], [ItemID], [SubscriptionID], [Name], [Extension], [Link], [CredentialRetrieval], [Prompt], [ConnectionString], [OriginalConnectionString], [OriginalConnectStringExpressionBased], [UserName], [Password], [Flags], [Version]) VALUES (@DSID, @ItemID, @SubscriptionID, @Name, @Extension, @ActualLinkID, @CredentialRetrieval, @Prompt, @ConnectionString, @OriginalConnectionString, @OriginalConnectStringExpressionBased, @UserName, @Password, @Flags, @Version) GO GRANT EXECUTE ON [dbo].[AddDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDataSources]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDataSources] GO CREATE PROCEDURE [dbo].[GetDataSources] @ItemID [uniqueidentifier], @AuthType int AS SELECT -- select data sources and their links (if they exist) DS.[DSID], -- 0 DS.[ItemID], -- 1 DS.[Name], -- 2 DS.[Extension], -- 3 DS.[Link], -- 4 DS.[CredentialRetrieval], -- 5 DS.[Prompt], -- 6 DS.[ConnectionString], -- 7 DS.[OriginalConnectionString], -- 8 DS.[UserName], -- 9 DS.[Password], -- 10 DS.[Flags], -- 11 DSL.[DSID], -- 12 DSL.[ItemID], -- 13 DSL.[Name], -- 14 DSL.[Extension], -- 15 DSL.[Link], -- 16 DSL.[CredentialRetrieval], -- 17 DSL.[Prompt], -- 18 DSL.[ConnectionString], -- 19 DSL.[UserName], -- 20 DSL.[Password], -- 21 DSL.[Flags], -- 22 C.Path, -- 23 SD.NtSecDescPrimary, -- 24 DS.[OriginalConnectStringExpressionBased], -- 25 DS.[Version], -- 26 DSL.[Version], -- 27 (SELECT 1 WHERE EXISTS (SELECT * from [ModelItemPolicy] AS MIP WHERE C.[ItemID] = MIP.[CatalogItemID])) -- 28 FROM [DataSource] AS DS LEFT OUTER JOIN ([DataSource] AS DSL INNER JOIN [Catalog] AS C ON DSL.[ItemID] = C.[ItemID] LEFT OUTER JOIN [SecData] AS SD ON C.[PolicyID] = SD.[PolicyID] AND SD.AuthType = @AuthType) ON DS.[Link] = DSL.[ItemID] WHERE DS.[ItemID] = @ItemID or DS.[SubscriptionID] = @ItemID GO GRANT EXECUTE ON [dbo].[GetDataSources] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteDataSources]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteDataSources] GO CREATE PROCEDURE [dbo].[DeleteDataSources] @ItemID [uniqueidentifier] AS DELETE FROM [DataSource] WHERE [ItemID] = @ItemID or [SubscriptionID] = @ItemID GO GRANT EXECUTE ON [dbo].[DeleteDataSources] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ChangeStateOfDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ChangeStateOfDataSource] GO CREATE PROCEDURE [dbo].[ChangeStateOfDataSource] @ItemID [uniqueidentifier], @Enable bit AS IF @Enable != 0 BEGIN UPDATE [DataSource] SET [Flags] = [Flags] | 1 WHERE [ItemID] = @ItemID END ELSE BEGIN UPDATE [DataSource] SET [Flags] = [Flags] & 0x7FFFFFFE WHERE [ItemID] = @ItemID END GO GRANT EXECUTE ON [dbo].[ChangeStateOfDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindItemsByDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindItemsByDataSource] GO CREATE PROCEDURE [dbo].[FindItemsByDataSource] @ItemID uniqueidentifier, @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.UserName, SUSER_SNAME(MU.Sid), MU.UserName, C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType INNER JOIN DataSource AS DS ON C.ItemID = DS.ItemID WHERE DS.Link = @ItemID GO GRANT EXECUTE ON [dbo].[FindItemsByDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CopyExecutionSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CopyExecutionSnapshot] GO CREATE PROCEDURE [dbo].[CopyExecutionSnapshot] @SourceReportID uniqueidentifier, @TargetReportID uniqueidentifier, @ReservedUntilUTC datetime AS DECLARE @SourceSnapshotDataID uniqueidentifier SET @SourceSnapshotDataID = (SELECT SnapshotDataID FROM Catalog WHERE ItemID = @SourceReportID) DECLARE @TargetSnapshotDataID uniqueidentifier SET @TargetSnapshotDataID = newid() DECLARE @ChunkID uniqueidentifier IF @SourceSnapshotDataID IS NOT NULL BEGIN -- We need to copy entries in SnapshotData and ChunkData tables. INSERT INTO SnapshotData (SnapshotDataID, CreatedDate, ParamsHash, QueryParams, EffectiveParams, Description, PermanentRefcount, TransientRefcount, ExpirationDate) SELECT @TargetSnapshotDataID, SD.CreatedDate, SD.ParamsHash, SD.QueryParams, SD.EffectiveParams, SD.Description, 1, 0, @ReservedUntilUTC FROM SnapshotData as SD WHERE SD.SnapshotDataID = @SourceSnapshotDataID INSERT INTO ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, ChunkFlags, Content, Version) SELECT newid(), @TargetSnapshotDataID, CD.ChunkName, CD.ChunkType, CD.ChunkFlags, CD.Content, CD.Version FROM ChunkData as CD WHERE CD.SnapshotDataID = @SourceSnapshotDataID UPDATE Target SET Target.SnapshotDataID = @TargetSnapshotDataID, Target.ExecutionTime = Source.ExecutionTime FROM Catalog Target, Catalog Source WHERE Source.ItemID = @SourceReportID AND Target.ItemID = @TargetReportID END GO GRANT EXECUTE ON [dbo].[CopyExecutionSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateRole] GO CREATE PROCEDURE [dbo].[CreateRole] @RoleID as uniqueidentifier, @RoleName as nvarchar(260), @Description as nvarchar(512) = null, @TaskMask as nvarchar(32), @RoleFlags as tinyint AS INSERT INTO Roles (RoleID, RoleName, Description, TaskMask, RoleFlags) VALUES (@RoleID, @RoleName, @Description, @TaskMask, @RoleFlags) GO GRANT EXECUTE ON [dbo].[CreateRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetRoles]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetRoles] GO CREATE PROCEDURE [dbo].[GetRoles] @RoleFlags as tinyint = NULL AS SELECT RoleName, Description, TaskMask FROM Roles WHERE (@RoleFlags is NULL) OR (RoleFlags = @RoleFlags) GO GRANT EXECUTE ON [dbo].[GetRoles] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteRole] GO -- Delete all policies associated with this role CREATE PROCEDURE [dbo].[DeleteRole] @RoleName nvarchar(260) AS -- if you call this, you must delete/reconstruct all policies associated with this role DELETE FROM Roles WHERE RoleName = @RoleName GO GRANT EXECUTE ON [dbo].[DeleteRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadRoleProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadRoleProperties] GO CREATE PROCEDURE [dbo].[ReadRoleProperties] @RoleName as nvarchar(260) AS SELECT Description, TaskMask, RoleFlags FROM Roles WHERE RoleName = @RoleName GO GRANT EXECUTE ON [dbo].[ReadRoleProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetRoleProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetRoleProperties] GO CREATE PROCEDURE [dbo].[SetRoleProperties] @RoleName as nvarchar(260), @Description as nvarchar(512) = NULL, @TaskMask as nvarchar(32), @RoleFlags as tinyint AS DECLARE @ExistingRoleFlags as tinyint SET @ExistingRoleFlags = (SELECT RoleFlags FROM Roles WHERE RoleName = @RoleName) IF @ExistingRoleFlags IS NULL BEGIN RETURN END IF @ExistingRoleFlags <> @RoleFlags BEGIN RAISERROR ('Bad role flags', 16, 1) END UPDATE Roles SET Description = @Description, TaskMask = @TaskMask, RoleFlags = @RoleFlags WHERE RoleName = @RoleName GO GRANT EXECUTE ON [dbo].[SetRoleProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPoliciesForRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPoliciesForRole] GO CREATE PROCEDURE [dbo].[GetPoliciesForRole] @RoleName as nvarchar(260), @AuthType as int AS SELECT Policies.PolicyID, SecData.XmlDescription, Policies.PolicyFlag, Catalog.Type, Catalog.Path, ModelItemPolicy.CatalogItemID, ModelItemPolicy.ModelItemID, RelatedRoles.RoleID, RelatedRoles.RoleName, RelatedRoles.TaskMask, RelatedRoles.RoleFlags FROM Roles INNER JOIN PolicyUserRole ON Roles.RoleID = PolicyUserRole.RoleID INNER JOIN Policies ON PolicyUserRole.PolicyID = Policies.PolicyID INNER JOIN PolicyUserRole AS RelatedPolicyUserRole ON Policies.PolicyID = RelatedPolicyUserRole.PolicyID INNER JOIN Roles AS RelatedRoles ON RelatedPolicyUserRole.RoleID = RelatedRoles.RoleID LEFT OUTER JOIN SecData ON Policies.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog ON Policies.PolicyID = Catalog.PolicyID AND Catalog.PolicyRoot = 1 LEFT OUTER JOIN ModelItemPolicy ON Policies.PolicyID = ModelItemPolicy.PolicyID WHERE Roles.RoleName = @RoleName ORDER BY Policies.PolicyID GO GRANT EXECUTE ON [dbo].[GetPoliciesForRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdatePolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdatePolicy] GO CREATE PROCEDURE [dbo].[UpdatePolicy] @PolicyID as uniqueidentifier, @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @AuthType int AS UPDATE SecData SET NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND SecData.AuthType = @AuthType GO GRANT EXECUTE ON [dbo].[UpdatePolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetPolicy] GO -- this assumes the item exists in the catalog CREATE PROCEDURE [dbo].[SetPolicy] @ItemName as nvarchar(425), @ItemNameLike as nvarchar(850), @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @XmlPolicy as ntext, @AuthType int, @PolicyID uniqueidentifier OUTPUT AS SELECT @PolicyID = (SELECT PolicyID FROM Catalog WHERE Path = @ItemName AND PolicyRoot = 1) IF (@PolicyID IS NULL) BEGIN -- this is not a policy root SET @PolicyID = newid() INSERT INTO Policies (PolicyID, PolicyFlag) VALUES (@PolicyID, 0) INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) DECLARE @OldPolicyID as uniqueidentifier SELECT @OldPolicyID = (SELECT PolicyID FROM Catalog WHERE Path = @ItemName) -- update item and children that shared the old policy UPDATE Catalog SET PolicyID = @PolicyID, PolicyRoot = 1 WHERE Path = @ItemName UPDATE Catalog SET PolicyID = @PolicyID WHERE Path LIKE @ItemNameLike ESCAPE '*' AND Catalog.PolicyID = @OldPolicyID END ELSE BEGIN UPDATE Policies SET PolicyFlag = 0 WHERE Policies.PolicyID = @PolicyID DECLARE @SecDataID as uniqueidentifier SELECT @SecDataID = (SELECT SecDataID FROM SecData WHERE PolicyID = @PolicyID and AuthType = @AuthType) IF (@SecDataID IS NULL) BEGIN -- insert new sec desc's INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription ,NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN -- update existing sec desc's UPDATE SecData SET XmlDescription = @XmlPolicy, NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND AuthType = @AuthType END END DELETE FROM PolicyUserRole WHERE PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[SetPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSystemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSystemPolicy] GO -- update the system policy CREATE PROCEDURE [dbo].[SetSystemPolicy] @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @XmlPolicy as ntext, @AuthType as int, @PolicyID uniqueidentifier OUTPUT AS SELECT @PolicyID = (SELECT PolicyID FROM Policies WHERE PolicyFlag = 1) IF (@PolicyID IS NULL) BEGIN SET @PolicyID = newid() INSERT INTO Policies (PolicyID, PolicyFlag) VALUES (@PolicyID, 1) INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN DECLARE @SecDataID as uniqueidentifier SELECT @SecDataID = (SELECT SecDataID FROM SecData WHERE PolicyID = @PolicyID and AuthType = @AuthType) IF (@SecDataID IS NULL) BEGIN -- insert new sec desc's INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN -- update existing sec desc's UPDATE SecData SET XmlDescription = @XmlPolicy, NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND AuthType = @AuthType END END DELETE FROM PolicyUserRole WHERE PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[SetSystemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetModelItemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetModelItemPolicy] GO -- update the system policy CREATE PROCEDURE [dbo].[SetModelItemPolicy] @CatalogItemID as uniqueidentifier, @ModelItemID as nvarchar(425), @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @XmlPolicy as ntext, @AuthType as int, @PolicyID uniqueidentifier OUTPUT AS SELECT @PolicyID = (SELECT PolicyID FROM ModelItemPolicy WHERE CatalogItemID = @CatalogItemID AND ModelItemID = @ModelItemID ) IF (@PolicyID IS NULL) BEGIN SET @PolicyID = newid() INSERT INTO Policies (PolicyID, PolicyFlag) VALUES (@PolicyID, 2) INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) INSERT INTO ModelItemPolicy (ID, CatalogItemID, ModelItemID, PolicyID) VALUES (newid(), @CatalogItemID, @ModelItemID, @PolicyID) END ELSE BEGIN DECLARE @SecDataID as uniqueidentifier SELECT @SecDataID = (SELECT SecDataID FROM SecData WHERE PolicyID = @PolicyID and AuthType = @AuthType) IF (@SecDataID IS NULL) BEGIN -- insert new sec desc's INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN -- update existing sec desc's UPDATE SecData SET XmlDescription = @XmlPolicy, NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND AuthType = @AuthType END END DELETE FROM PolicyUserRole WHERE PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[SetModelItemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdatePolicyPrincipal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdatePolicyPrincipal] GO CREATE PROCEDURE [dbo].[UpdatePolicyPrincipal] @PolicyID uniqueidentifier, @PrincipalSid varbinary(85) = NULL, @PrincipalName nvarchar(260), @PrincipalAuthType int, @RoleName nvarchar(260), @PrincipalID uniqueidentifier OUTPUT, @RoleID uniqueidentifier OUTPUT AS EXEC GetPrincipalID @PrincipalSid , @PrincipalName, @PrincipalAuthType, @PrincipalID OUTPUT SELECT @RoleID = (SELECT RoleID FROM Roles WHERE RoleName = @RoleName) INSERT INTO PolicyUserRole (ID, RoleID, UserID, PolicyID) VALUES (newid(), @RoleID, @PrincipalID, @PolicyID) GO GRANT EXECUTE ON [dbo].[UpdatePolicyPrincipal] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdatePolicyRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdatePolicyRole] GO CREATE PROCEDURE [dbo].[UpdatePolicyRole] @PolicyID uniqueidentifier, @PrincipalID uniqueidentifier, @RoleName nvarchar(260), @RoleID uniqueidentifier OUTPUT AS SELECT @RoleID = (SELECT RoleID FROM Roles WHERE RoleName = @RoleName) INSERT INTO PolicyUserRole (ID, RoleID, UserID, PolicyID) VALUES (newid(), @RoleID, @PrincipalID, @PolicyID) GO GRANT EXECUTE ON [dbo].[UpdatePolicyRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPolicy] GO CREATE PROCEDURE [dbo].[GetPolicy] @ItemName as nvarchar(425), @AuthType int AS SELECT SecData.XmlDescription, Catalog.PolicyRoot , SecData.NtSecDescPrimary, Catalog.Type FROM Catalog INNER JOIN Policies ON Catalog.PolicyID = Policies.PolicyID LEFT OUTER JOIN SecData ON Policies.PolicyID = SecData.PolicyID AND AuthType = @AuthType WHERE Catalog.Path = @ItemName AND PolicyFlag = 0 GO GRANT EXECUTE ON [dbo].[GetPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSystemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSystemPolicy] GO CREATE PROCEDURE [dbo].[GetSystemPolicy] @AuthType int AS SELECT SecData.NtSecDescPrimary, SecData.XmlDescription FROM Policies LEFT OUTER JOIN SecData ON Policies.PolicyID = SecData.PolicyID AND AuthType = @AuthType WHERE PolicyFlag = 1 GO GRANT EXECUTE ON [dbo].[GetSystemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeletePolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeletePolicy] GO CREATE PROCEDURE [dbo].[DeletePolicy] @ItemName as nvarchar(425) AS DECLARE @OldPolicyID uniqueidentifier SELECT @OldPolicyID = (SELECT PolicyID FROM Catalog WHERE Catalog.Path = @ItemName) UPDATE Catalog SET PolicyID = (SELECT Parent.PolicyID FROM Catalog Parent, Catalog WHERE Parent.ItemID = Catalog.ParentID AND Catalog.Path = @ItemName), PolicyRoot = 0 WHERE Catalog.PolicyID = @OldPolicyID DELETE Policies FROM Policies WHERE Policies.PolicyID = @OldPolicyID GO GRANT EXECUTE ON [dbo].[DeletePolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateSession]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateSession] GO -- Writes or updates session record CREATE PROCEDURE [dbo].[CreateSession] @SessionID as varchar(32), @CompiledDefinition as uniqueidentifier = NULL, @SnapshotDataID as uniqueidentifier = NULL, @IsPermanentSnapshot as bit = NULL, @ReportPath as nvarchar(440) = NULL, @Timeout as int, @AutoRefreshSeconds as int = NULL, @DataSourceInfo as image = NULL, @OwnerName as nvarchar (260), @OwnerSid as varbinary (85) = NULL, @AuthType as int, @EffectiveParams as ntext = NULL, @HistoryDate as datetime = NULL, @PageHeight as float = NULL, @PageWidth as float = NULL, @TopMargin as float = NULL, @BottomMargin as float = NULL, @LeftMargin as float = NULL, @RightMargin as float = NULL, @AwaitingFirstExecution as bit = NULL AS UPDATE PS SET PS.RefCount = 1 FROM ReportServerTempDB.dbo.PersistedStream as PS WHERE PS.SessionID = @SessionID UPDATE SN SET TransientRefcount = TransientRefcount + 1 FROM SnapshotData AS SN WHERE SN.SnapshotDataID = @SnapshotDataID UPDATE SN SET TransientRefcount = TransientRefcount + 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN WHERE SN.SnapshotDataID = @SnapshotDataID DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT DECLARE @now datetime SET @now = GETDATE() INSERT INTO ReportServerTempDB.dbo.SessionData ( SessionID, CompiledDefinition, SnapshotDataID, IsPermanentSnapshot, ReportPath, Timeout, AutoRefreshSeconds, Expiration, DataSourceInfo, OwnerID, EffectiveParams, CreationTime, HistoryDate, PageHeight, PageWidth, TopMargin, BottomMargin, LeftMargin, RightMargin, AwaitingFirstExecution ) VALUES ( @SessionID, @CompiledDefinition, @SnapshotDataID, @IsPermanentSnapshot, @ReportPath, @Timeout, @AutoRefreshSeconds, DATEADD(s, @Timeout, @now), @DataSourceInfo, @OwnerID, @EffectiveParams, @now, @HistoryDate, @PageHeight, @PageWidth, @TopMargin, @BottomMargin, @LeftMargin, @RightMargin, @AwaitingFirstExecution ) GO GRANT EXECUTE ON [dbo].[CreateSession] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteModelItemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteModelItemPolicy] GO CREATE PROCEDURE [dbo].[DeleteModelItemPolicy] @CatalogItemID as uniqueidentifier, @ModelItemID as nvarchar(425) AS DECLARE @PolicyID uniqueidentifier SELECT @PolicyID = (SELECT PolicyID FROM ModelItemPolicy WHERE CatalogItemID = @CatalogItemID AND ModelItemID = @ModelItemID) DELETE Policies FROM Policies WHERE Policies.PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[DeleteModelItemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteAllModelItemPolicies]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteAllModelItemPolicies] GO CREATE PROCEDURE [dbo].[DeleteAllModelItemPolicies] @Path as nvarchar(450) AS DELETE Policies FROM Policies AS P INNER JOIN ModelItemPolicy AS MIP ON P.PolicyID = MIP.PolicyID INNER JOIN Catalog AS C ON MIP.CatalogItemID = C.ItemID WHERE C.[Path] = @Path GO GRANT EXECUTE ON [dbo].[DeleteAllModelItemPolicies] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelItemInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelItemInfo] GO CREATE PROCEDURE [dbo].[GetModelItemInfo] @Path nvarchar (425) AS SELECT MIP.[ModelItemID], SD.[NtSecDescPrimary], SD.[XmlDescription] FROM [Catalog] AS C INNER JOIN [ModelItemPolicy] AS MIP ON C.[ItemID] = MIP.[CatalogItemID] LEFT OUTER JOIN [SecData] AS SD ON MIP.[PolicyID] = SD.[PolicyID] WHERE C.[Path] = @Path GO GRANT EXECUTE ON [dbo].[GetModelItemInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelDefinition]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelDefinition] GO CREATE PROCEDURE [dbo].[GetModelDefinition] @CatalogItemID as uniqueidentifier AS SELECT C.[Content] FROM [Catalog] AS C WHERE C.[ItemID] = @CatalogItemID GO GRANT EXECUTE ON [dbo].[GetModelDefinition] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddModelPerspective]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddModelPerspective] GO CREATE PROCEDURE [dbo].[AddModelPerspective] @ModelID as uniqueidentifier, @PerspectiveID as ntext, @PerspectiveName as ntext = null, @PerspectiveDescription as ntext = null AS INSERT INTO [ModelPerspective] ([ID], [ModelID], [PerspectiveID], [PerspectiveName], [PerspectiveDescription]) VALUES (newid(), @ModelID, @PerspectiveID, @PerspectiveName, @PerspectiveDescription) GO GRANT EXECUTE ON [dbo].[AddModelPerspective] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteModelPerspectives]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteModelPerspectives] GO CREATE PROCEDURE [dbo].[DeleteModelPerspectives] @ModelID as uniqueidentifier AS DELETE FROM [ModelPerspective] WHERE [ModelID] = @ModelID GO GRANT EXECUTE ON [dbo].[DeleteModelPerspectives] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelsAndPerspectives]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelsAndPerspectives] GO CREATE PROCEDURE [dbo].[GetModelsAndPerspectives] @AuthType int, @SitePathPrefix nvarchar(520) = '%' AS SELECT C.[PolicyID], SD.[NtSecDescPrimary], C.[ItemID], C.[Path], C.[Description], P.[PerspectiveID], P.[PerspectiveName], P.[PerspectiveDescription] FROM [Catalog] as C LEFT OUTER JOIN [ModelPerspective] as P ON C.[ItemID] = P.[ModelID] LEFT OUTER JOIN [SecData] AS SD ON C.[PolicyID] = SD.[PolicyID] AND SD.[AuthType] = @AuthType WHERE C.Path like @SitePathPrefix AND C.[Type] = 6 -- Model ORDER BY C.[Path] GO GRANT EXECUTE ON [dbo].[GetModelsAndPerspectives] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelPerspectives]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelPerspectives] GO CREATE PROCEDURE [dbo].[GetModelPerspectives] @Path nvarchar (425), @AuthType int AS SELECT C.[Type], SD.[NtSecDescPrimary], C.[Description] FROM [Catalog] as C LEFT OUTER JOIN [SecData] AS SD ON C.[PolicyID] = SD.[PolicyID] AND SD.[AuthType] = @AuthType WHERE [Path] = @Path SELECT P.[PerspectiveID], P.[PerspectiveName], P.[PerspectiveDescription] FROM [Catalog] as C INNER JOIN [ModelPerspective] as P ON C.[ItemID] = P.[ModelID] WHERE [Path] = @Path GO GRANT EXECUTE ON [dbo].[GetModelPerspectives] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DereferenceSessionSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DereferenceSessionSnapshot] GO CREATE PROCEDURE [dbo].[DereferenceSessionSnapshot] @SessionID as varchar(32), @OwnerID as uniqueidentifier AS UPDATE SN SET TransientRefcount = TransientRefcount - 1 FROM SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.SessionData AS SE ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID UPDATE SN SET TransientRefcount = TransientRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.SessionData AS SE ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[DereferenceSessionSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSessionData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSessionData] GO -- Writes or updates session record CREATE PROCEDURE [dbo].[SetSessionData] @SessionID as varchar(32), @ReportPath as nvarchar(440), @HistoryDate as datetime = NULL, @Timeout as int, @AutoRefreshSeconds as int = NULL, @EffectiveParams ntext = NULL, @OwnerSid as varbinary (85) = NULL, @OwnerName as nvarchar (260), @AuthType as int, @ShowHideInfo as image = NULL, @DataSourceInfo as image = NULL, @SnapshotDataID as uniqueidentifier = NULL, @IsPermanentSnapshot as bit = NULL, @SnapshotTimeoutSeconds as int = NULL, @HasInteractivity as bit, @SnapshotExpirationDate as datetime = NULL, @AwaitingFirstExecution as bit = NULL AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT DECLARE @now datetime SET @now = GETDATE() -- is there a session for the same report ? DECLARE @OldSnapshotDataID uniqueidentifier DECLARE @OldIsPermanentSnapshot bit DECLARE @OldSessionID varchar(32) SELECT @OldSessionID = SessionID, @OldSnapshotDataID = SnapshotDataID, @OldIsPermanentSnapshot = IsPermanentSnapshot FROM ReportServerTempDB.dbo.SessionData WITH (XLOCK) WHERE SessionID = @SessionID IF @OldSessionID IS NOT NULL BEGIN -- Yes, update it IF @OldSnapshotDataID != @SnapshotDataID or @SnapshotDataID is NULL BEGIN EXEC DereferenceSessionSnapshot @SessionID, @OwnerID END UPDATE ReportServerTempDB.dbo.SessionData SET SnapshotDataID = @SnapshotDataID, IsPermanentSnapshot = @IsPermanentSnapshot, Timeout = @Timeout, AutoRefreshSeconds = @AutoRefreshSeconds, SnapshotExpirationDate = @SnapshotExpirationDate, -- we want database session to expire later than in-memory session Expiration = DATEADD(s, @Timeout+10, @now), ShowHideInfo = @ShowHideInfo, DataSourceInfo = @DataSourceInfo, AwaitingFirstExecution = @AwaitingFirstExecution -- EffectiveParams = @EffectiveParams, -- no need to update user params as they are always same -- ReportPath = @ReportPath -- OwnerID = @OwnerID WHERE SessionID = @SessionID -- update expiration date on a snapshot that we reference IF @IsPermanentSnapshot != 0 BEGIN UPDATE SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutSeconds, @now) WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutSeconds, @now) WHERE SnapshotDataID = @SnapshotDataID END END ELSE BEGIN -- no, insert it UPDATE PS SET PS.RefCount = 1 FROM ReportServerTempDB.dbo.PersistedStream as PS WHERE PS.SessionID = @SessionID INSERT INTO ReportServerTempDB.dbo.SessionData (SessionID, SnapshotDataID, IsPermanentSnapshot, ReportPath, EffectiveParams, Timeout, AutoRefreshSeconds, Expiration, ShowHideInfo, DataSourceInfo, OwnerID, CreationTime, HasInteractivity, SnapshotExpirationDate, HistoryDate, AwaitingFirstExecution) VALUES (@SessionID, @SnapshotDataID, @IsPermanentSnapshot, @ReportPath, @EffectiveParams, @Timeout, @AutoRefreshSeconds, DATEADD(s, @Timeout, @now), @ShowHideInfo, @DataSourceInfo, @OwnerID, @now, @HasInteractivity, @SnapshotExpirationDate, @HistoryDate, @AwaitingFirstExecution) END GO GRANT EXECUTE ON [dbo].[SetSessionData] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteLockSession]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteLockSession] GO CREATE PROCEDURE [dbo].[WriteLockSession] @SessionID as varchar(32) AS INSERT INTO ReportServerTempDB.dbo.SessionLock WITH (ROWLOCK) (SessionID) VALUES (@SessionID) GO GRANT EXECUTE ON [dbo].[WriteLockSession] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CheckSessionLock]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CheckSessionLock] GO CREATE PROCEDURE [dbo].[CheckSessionLock] @SessionID as varchar(32) AS DECLARE @Selected nvarchar(32) SELECT @Selected=SessionID FROM ReportServerTempDB.dbo.SessionLock WITH (ROWLOCK) WHERE SessionID = @SessionID GO GRANT EXECUTE ON [dbo].[CheckSessionLock] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadLockSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadLockSnapshot] GO CREATE PROCEDURE [dbo].[ReadLockSnapshot] @SnapshotDataID as uniqueidentifier AS SELECT SnapshotDataID FROM SnapshotData WITH (REPEATABLEREAD, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID GO GRANT EXECUTE ON [dbo].[ReadLockSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSessionData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSessionData] GO -- Get record from session data, update session and snapshot CREATE PROCEDURE [dbo].[GetSessionData] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @SnapshotTimeoutMinutes as int AS DECLARE @now as datetime SET @now = GETDATE() DECLARE @DBSessionID varchar(32) DECLARE @SnapshotDataID uniqueidentifier DECLARE @IsPermanentSnapshot bit EXEC CheckSessionLock @SessionID = @SessionID DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT SELECT @DBSessionID = SE.SessionID, @SnapshotDataID = SE.SnapshotDataID, @IsPermanentSnapshot = SE.IsPermanentSnapshot FROM ReportServerTempDB.dbo.SessionData AS SE WITH (XLOCK) WHERE SE.OwnerID = @OwnerID AND SE.SessionID = @SessionID AND SE.Expiration > @now -- We need this update to keep session around while we process it. -- TODO: This assumes that it will be processed within the session timeout. UPDATE SE SET Expiration = DATEADD(s, Timeout, @now) FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @DBSessionID -- Update snapshot expiration to prevent early deletion -- If session uses snapshot, it is already refcounted. However, if session lasts for too long, -- snapshot may expire. Therefore, every time we touch snapshot we should change expiration. IF (@DBSessionID IS NOT NULL) BEGIN -- We return something only if session is present IF @IsPermanentSnapshot != 0 BEGIN -- If session has snapshot and it is permanent SELECT SN.SnapshotDataID, SE.ShowHideInfo, SE.DataSourceInfo, SN.Description, SE.EffectiveParams, SN.CreatedDate, SE.IsPermanentSnapshot, SE.CreationTime, SE.HasInteractivity, SE.Timeout, SE.SnapshotExpirationDate, SE.ReportPath, SE.HistoryDate, SE.CompiledDefinition, SN.PageCount, SN.HasDocMap, SE.Expiration, SN.EffectiveParams, SE.PageHeight, SE.PageWidth, SE.TopMargin, SE.BottomMargin, SE.LeftMargin, SE.RightMargin, SE.AutoRefreshSeconds, SE.AwaitingFirstExecution, SN.[DependsOnUser] FROM ReportServerTempDB.dbo.SessionData AS SE INNER JOIN SnapshotData AS SN ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @DBSessionID UPDATE SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutMinutes, @now) WHERE SnapshotDataID = @SnapshotDataID END ELSE IF @IsPermanentSnapshot = 0 BEGIN -- If session has snapshot and it is temporary SELECT SN.SnapshotDataID, SE.ShowHideInfo, SE.DataSourceInfo, SN.Description, SE.EffectiveParams, SN.CreatedDate, SE.IsPermanentSnapshot, SE.CreationTime, SE.HasInteractivity, SE.Timeout, SE.SnapshotExpirationDate, SE.ReportPath, SE.HistoryDate, SE.CompiledDefinition, SN.PageCount, SN.HasDocMap, SE.Expiration, SN.EffectiveParams, SE.PageHeight, SE.PageWidth, SE.TopMargin, SE.BottomMargin, SE.LeftMargin, SE.RightMargin, SE.AutoRefreshSeconds, SE.AwaitingFirstExecution, SN.[DependsOnUser] FROM ReportServerTempDB.dbo.SessionData AS SE INNER JOIN ReportServerTempDB.dbo.SnapshotData AS SN ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @DBSessionID UPDATE ReportServerTempDB.dbo.SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutMinutes, @now) WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN -- If session doesn't have snapshot SELECT null, SE.ShowHideInfo, SE.DataSourceInfo, null, SE.EffectiveParams, null, SE.IsPermanentSnapshot, SE.CreationTime, SE.HasInteractivity, SE.Timeout, SE.SnapshotExpirationDate, SE.ReportPath, SE.HistoryDate, SE.CompiledDefinition, null, null, SE.Expiration, null, SE.PageHeight, SE.PageWidth, SE.TopMargin, SE.BottomMargin, SE.LeftMargin, SE.RightMargin, SE.AutoRefreshSeconds, SE.AwaitingFirstExecution, null FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @DBSessionID END END GO GRANT EXECUTE ON [dbo].[GetSessionData] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapshotFromHistory]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapshotFromHistory] GO CREATE PROCEDURE [dbo].[GetSnapshotFromHistory] @Path nvarchar (425), @SnapshotDate datetime, @AuthType int AS SELECT Catalog.ItemID, Catalog.Type, SnapshotData.SnapshotDataID, SnapshotData.DependsOnUser, SnapshotData.Description, SecData.NtSecDescPrimary, Catalog.[Property] FROM SnapshotData INNER JOIN History ON History.SnapshotDataID = SnapshotData.SnapshotDataID INNER JOIN Catalog ON History.ReportID = Catalog.ItemID LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Catalog.Path = @Path AND History.SnapshotDate = @SnapshotDate GO GRANT EXECUTE ON [dbo].[GetSnapshotFromHistory] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredSessions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredSessions] GO CREATE PROCEDURE [dbo].[CleanExpiredSessions] @SessionsCleaned int OUTPUT AS SET DEADLOCK_PRIORITY LOW DECLARE @now as datetime SET @now = GETDATE() CREATE TABLE #tempSession (SessionID varchar(32) COLLATE Latin1_General_CI_AS_KS_WS, SnapshotDataID uniqueidentifier, CompiledDefinition uniqueidentifier) INSERT INTO #tempSession SELECT TOP 20 SessionID, SnapshotDataID, CompiledDefinition FROM ReportServerTempDB.dbo.SessionData WITH (XLOCK) WHERE Expiration < @now SET @SessionsCleaned = @@ROWCOUNT IF @SessionsCleaned = 0 RETURN -- Mark persisted streams for this session to be deleted UPDATE PS SET RefCount = 0, ExpirationDate = GETDATE() FROM ReportServerTempDB.dbo.PersistedStream AS PS INNER JOIN #tempSession on PS.SessionID = #tempsession.SessionID DELETE SE FROM ReportServerTempDB.dbo.SessionData AS SE INNER JOIN #tempSession on SE.SessionID = #tempsession.SessionID UPDATE SN SET TransientRefcount = TransientRefcount-1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN #tempSession AS SE ON SN.SnapshotDataID = SE.CompiledDefinition UPDATE SN SET TransientRefcount = TransientRefcount- (SELECT COUNT(*) FROM #tempSession AS SE1 WHERE SE1.SnapshotDataID = SN.SnapshotDataID) FROM SnapshotData AS SN INNER JOIN #tempSession AS SE ON SN.SnapshotDataID = SE.SnapshotDataID UPDATE SN SET TransientRefcount = TransientRefcount- (SELECT COUNT(*) FROM #tempSession AS SE1 WHERE SE1.SnapshotDataID = SN.SnapshotDataID) FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN #tempSession AS SE ON SN.SnapshotDataID = SE.SnapshotDataID GO GRANT EXECUTE ON [dbo].[CleanExpiredSessions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredCache]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredCache] GO CREATE PROCEDURE [dbo].[CleanExpiredCache] AS DECLARE @now as datetime SET @now = DATEADD(minute, -1, GETDATE()) UPDATE SN SET PermanentRefcount = PermanentRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON SN.SnapshotDataID = EC.SnapshotDataID WHERE EC.AbsoluteExpiration < @now DELETE EC FROM ReportServerTempDB.dbo.ExecutionCache AS EC WHERE EC.AbsoluteExpiration < @now GO GRANT EXECUTE ON [dbo].[CleanExpiredCache] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSessionCredentials]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSessionCredentials] GO CREATE PROCEDURE [dbo].[SetSessionCredentials] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @DataSourceInfo as image = NULL, @Expiration as datetime, @EffectiveParams as ntext = NULL AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT EXEC DereferenceSessionSnapshot @SessionID, @OwnerID UPDATE SE SET SE.DataSourceInfo = @DataSourceInfo, SE.SnapshotDataID = null, SE.IsPermanentSnapshot = null, SE.SnapshotExpirationDate = null, SE.ShowHideInfo = null, SE.HasInteractivity = null, SE.AutoRefreshSeconds = null, SE.Expiration = @Expiration, SE.EffectiveParams = @EffectiveParams, SE.AwaitingFirstExecution = 1 FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[SetSessionCredentials] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSessionParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSessionParameters] GO CREATE PROCEDURE [dbo].[SetSessionParameters] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @EffectiveParams as ntext = NULL AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT UPDATE SE SET SE.EffectiveParams = @EffectiveParams, SE.AwaitingFirstExecution = 1 FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[SetSessionParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ClearSessionSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ClearSessionSnapshot] GO CREATE PROCEDURE [dbo].[ClearSessionSnapshot] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @Expiration as datetime AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT EXEC DereferenceSessionSnapshot @SessionID, @OwnerID UPDATE SE SET SE.SnapshotDataID = null, SE.IsPermanentSnapshot = null, SE.SnapshotExpirationDate = null, SE.ShowHideInfo = null, SE.HasInteractivity = null, SE.AutoRefreshSeconds = null, SE.Expiration = @Expiration FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[ClearSessionSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RemoveReportFromSession]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RemoveReportFromSession] GO CREATE PROCEDURE [dbo].[RemoveReportFromSession] @SessionID as varchar(32), @ReportPath as nvarchar(440), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT EXEC DereferenceSessionSnapshot @SessionID, @OwnerID DELETE SE FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.ReportPath = @ReportPath AND SE.OwnerID = @OwnerID -- Delete any persisted streams associated with this session UPDATE PS SET PS.RefCount = 0, PS.ExpirationDate = GETDATE() FROM ReportServerTempDB.dbo.PersistedStream AS PS WHERE PS.SessionID = @SessionID GO GRANT EXECUTE ON [dbo].[RemoveReportFromSession] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanBrokenSnapshots]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanBrokenSnapshots] GO CREATE PROCEDURE [dbo].[CleanBrokenSnapshots] @Machine nvarchar(512), @SnapshotsCleaned int OUTPUT, @ChunksCleaned int OUTPUT, @TempSnapshotID uniqueidentifier OUTPUT AS SET DEADLOCK_PRIORITY LOW DECLARE @now AS datetime SELECT @now = GETDATE() CREATE TABLE #tempSnapshot (SnapshotDataID uniqueidentifier) INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM SnapshotData WITH (NOLOCK) where SnapshotData.PermanentRefcount <= 0 AND ExpirationDate < @now SET @SnapshotsCleaned = @@ROWCOUNT DELETE ChunkData FROM ChunkData INNER JOIN #tempSnapshot ON ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @@ROWCOUNT DELETE SnapshotData FROM SnapshotData INNER JOIN #tempSnapshot ON SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID TRUNCATE TABLE #tempSnapshot INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM ReportServerTempDB.dbo.SnapshotData WITH (NOLOCK) where ReportServerTempDB.dbo.SnapshotData.PermanentRefcount <= 0 AND ReportServerTempDB.dbo.SnapshotData.ExpirationDate < @now AND ReportServerTempDB.dbo.SnapshotData.Machine = @Machine SET @SnapshotsCleaned = @SnapshotsCleaned + @@ROWCOUNT SELECT @TempSnapshotID = (SELECT SnapshotDataID FROM #tempSnapshot) DELETE ReportServerTempDB.dbo.ChunkData FROM ReportServerTempDB.dbo.ChunkData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @ChunksCleaned + @@ROWCOUNT DELETE ReportServerTempDB.dbo.SnapshotData FROM ReportServerTempDB.dbo.SnapshotData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID GO GRANT EXECUTE ON [dbo].[CleanBrokenSnapshots] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanOrphanedSnapshots]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanOrphanedSnapshots] GO CREATE PROCEDURE [dbo].[CleanOrphanedSnapshots] @Machine nvarchar(512), @SnapshotsCleaned int OUTPUT, @ChunksCleaned int OUTPUT, @TempSnapshotID uniqueidentifier OUTPUT AS SET DEADLOCK_PRIORITY LOW CREATE TABLE #tempSnapshot (SnapshotDataID uniqueidentifier) INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM SnapshotData WITH (NOLOCK) where SnapshotData.PermanentRefcount = 0 AND SnapshotData.TransientRefcount = 0 SET @SnapshotsCleaned = @@ROWCOUNT DELETE ChunkData FROM ChunkData INNER JOIN #tempSnapshot ON ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @@ROWCOUNT DELETE SnapshotData FROM SnapshotData INNER JOIN #tempSnapshot ON SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID TRUNCATE TABLE #tempSnapshot INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM ReportServerTempDB.dbo.SnapshotData WITH (NOLOCK) where ReportServerTempDB.dbo.SnapshotData.PermanentRefcount = 0 AND ReportServerTempDB.dbo.SnapshotData.TransientRefcount = 0 AND ReportServerTempDB.dbo.SnapshotData.Machine = @Machine SET @SnapshotsCleaned = @SnapshotsCleaned + @@ROWCOUNT SELECT @TempSnapshotID = (SELECT SnapshotDataID FROM #tempSnapshot) DELETE ReportServerTempDB.dbo.ChunkData FROM ReportServerTempDB.dbo.ChunkData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @ChunksCleaned + @@ROWCOUNT DELETE ReportServerTempDB.dbo.SnapshotData FROM ReportServerTempDB.dbo.SnapshotData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID GO GRANT EXECUTE ON [dbo].[CleanOrphanedSnapshots] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetCacheOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetCacheOptions] GO CREATE PROCEDURE [dbo].[SetCacheOptions] @Path as nvarchar(425), @CacheReport as bit, @ExpirationFlags as int, @CacheExpiration as int = NULL AS DECLARE @CachePolicyID as uniqueidentifier SELECT @CachePolicyID = (SELECT CachePolicyID FROM CachePolicy with (XLOCK) INNER JOIN Catalog ON Catalog.ItemID = CachePolicy.ReportID WHERE Catalog.Path = @Path) IF @CachePolicyID IS NULL -- no policy exists BEGIN IF @CacheReport = 1 -- create a new one BEGIN INSERT INTO CachePolicy (CachePolicyID, ReportID, ExpirationFlags, CacheExpiration) (SELECT NEWID(), ItemID, @ExpirationFlags, @CacheExpiration FROM Catalog WHERE Catalog.Path = @Path) END -- ELSE if it has no policy and we want to remove its policy do nothing END ELSE -- existing policy BEGIN IF @CacheReport = 1 BEGIN UPDATE CachePolicy SET ExpirationFlags = @ExpirationFlags, CacheExpiration = @CacheExpiration WHERE CachePolicyID = @CachePolicyID EXEC FlushReportFromCache @Path END ELSE BEGIN DELETE FROM CachePolicy WHERE CachePolicyID = @CachePolicyID EXEC FlushReportFromCache @Path END END GO GRANT EXECUTE ON [dbo].[SetCacheOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCacheOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetCacheOptions] GO CREATE PROCEDURE [dbo].[GetCacheOptions] @Path as nvarchar(425) AS SELECT ExpirationFlags, CacheExpiration, S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path] FROM CachePolicy INNER JOIN Catalog ON Catalog.ItemID = CachePolicy.ReportID LEFT outer join reportschedule rs on catalog.itemid = rs.reportid and rs.reportaction = 3 LEFT OUTER JOIN [Schedule] S ON S.ScheduleID = rs.ScheduleID LEFT OUTER JOIN [Users] Owner on Owner.UserID = S.[CreatedById] WHERE Catalog.Path = @Path GO GRANT EXECUTE ON [dbo].[GetCacheOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddReportToCache]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddReportToCache] GO CREATE PROCEDURE [dbo].[AddReportToCache] @ReportID as uniqueidentifier, @ExecutionDate datetime, @SnapshotDataID uniqueidentifier, @ExpirationDate datetime OUTPUT, @ScheduleID uniqueidentifier OUTPUT AS DECLARE @ExpirationFlags as int DECLARE @Timeout as int SET @ExpirationDate = NULL SET @ScheduleID = NULL SET @ExpirationFlags = (SELECT ExpirationFlags FROM CachePolicy WHERE ReportID = @ReportID) IF @ExpirationFlags = 1 -- timeout based BEGIN SET @Timeout = (SELECT CacheExpiration FROM CachePolicy WHERE ReportID = @ReportID) SET @ExpirationDate = DATEADD(n, @Timeout, @ExecutionDate) END ELSE IF @ExpirationFlags = 2 -- schedule based BEGIN SET @ScheduleID = (SELECT s.ScheduleID FROM Schedule s INNER JOIN ReportSchedule rs on rs.ScheduleID = s.ScheduleID and rs.ReportAction = 3 WHERE rs.ReportID = @ReportID) SET @ExpirationDate = (SELECT Schedule.NextRunTime FROM Schedule with (XLOCK) WHERE Schedule.ScheduleID = @ScheduleID) END ELSE BEGIN RAISERROR('Invalid cache flags', 16, 1) END -- and to the report cache INSERT INTO ReportServerTempDB.dbo.ExecutionCache (ExecutionCacheID, ReportID, ExpirationFlags, AbsoluteExpiration, RelativeExpiration, SnapshotDataID) VALUES (newid(), @ReportID, @ExpirationFlags, @ExpirationDate, @Timeout, @SnapshotDataID ) UPDATE ReportServerTempDB.dbo.SnapshotData SET PermanentRefcount = PermanentRefcount + 1 WHERE SnapshotDataID = @SnapshotDataID; GO GRANT EXECUTE ON [dbo].[AddReportToCache] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetExecutionOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetExecutionOptions] GO CREATE PROCEDURE [dbo].[GetExecutionOptions] @Path nvarchar(425) AS SELECT ExecutionFlag, S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path] FROM Catalog LEFT OUTER JOIN ReportSchedule ON Catalog.ItemID = ReportSchedule.ReportID AND ReportSchedule.ReportAction = 1 LEFT OUTER JOIN [Schedule] S ON S.ScheduleID = ReportSchedule.ScheduleID LEFT OUTER JOIN [Users] Owner on Owner.UserID = S.[CreatedById] WHERE Catalog.Path = @Path GO GRANT EXECUTE ON [dbo].[GetExecutionOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetExecutionOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetExecutionOptions] GO CREATE PROCEDURE [dbo].[SetExecutionOptions] @Path as nvarchar(425), @ExecutionFlag as int, @ExecutionChanged as bit = 0 AS IF @ExecutionChanged = 0 BEGIN UPDATE Catalog SET ExecutionFlag = @ExecutionFlag WHERE Catalog.Path = @Path END ELSE BEGIN IF (@ExecutionFlag & 3) = 2 BEGIN -- set it to snapshot, flush cache EXEC FlushReportFromCache @Path DELETE CachePolicy FROM CachePolicy INNER JOIN Catalog ON CachePolicy.ReportID = Catalog.ItemID WHERE Catalog.Path = @Path END -- now clean existing snapshot and execution time if any UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 FROM SnapshotData INNER JOIN Catalog ON SnapshotData.SnapshotDataID = Catalog.SnapshotDataID WHERE Catalog.Path = @Path UPDATE Catalog SET ExecutionFlag = @ExecutionFlag, SnapshotDataID = NULL, ExecutionTime = NULL WHERE Catalog.Path = @Path END GO GRANT EXECUTE ON [dbo].[SetExecutionOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSnapshot] GO CREATE PROCEDURE [dbo].[UpdateSnapshot] @Path as nvarchar(425), @SnapshotDataID as uniqueidentifier, @executionDate as datetime AS DECLARE @OldSnapshotDataID uniqueidentifier SET @OldSnapshotDataID = (SELECT SnapshotDataID FROM Catalog WITH (XLOCK) WHERE Catalog.Path = @Path) -- update reference count in snapshot table UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount-1 WHERE SnapshotData.SnapshotDataID = @OldSnapshotDataID -- update catalog to point to the new execution snapshot UPDATE Catalog SET SnapshotDataID = @SnapshotDataID, ExecutionTime = @executionDate WHERE Catalog.Path = @Path UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount+1, TransientRefcount = TransientRefcount-1 WHERE SnapshotData.SnapshotDataID = @SnapshotDataID GO GRANT EXECUTE ON [dbo].[UpdateSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateChunkAndGetPointer]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateChunkAndGetPointer] GO CREATE PROCEDURE [dbo].[CreateChunkAndGetPointer] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int, @MimeType nvarchar(260) = NULL, @Version smallint, @Content image, @ChunkFlags tinyint = NULL, @ChunkPointer binary(16) OUTPUT AS DECLARE @ChunkID uniqueidentifier SET @ChunkID = NEWID() IF @IsPermanentSnapshot != 0 BEGIN DELETE ChunkData WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType INSERT INTO ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) VALUES (@ChunkID, @SnapshotDataID, @ChunkName, @ChunkType, @MimeType, @Version, @ChunkFlags, @Content) SELECT @ChunkPointer = TEXTPTR(Content) FROM ChunkData WHERE ChunkData.ChunkID = @ChunkID END ELSE BEGIN DELETE ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType INSERT INTO ReportServerTempDB.dbo.ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) VALUES (@ChunkID, @SnapshotDataID, @ChunkName, @ChunkType, @MimeType, @Version, @ChunkFlags, @Content) SELECT @ChunkPointer = TEXTPTR(Content) FROM ReportServerTempDB.dbo.ChunkData AS CH WHERE CH.ChunkID = @ChunkID END GO GRANT EXECUTE ON [dbo].[CreateChunkAndGetPointer] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteChunkPortion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteChunkPortion] GO CREATE PROCEDURE [dbo].[WriteChunkPortion] @ChunkPointer binary(16), @IsPermanentSnapshot bit, @DataIndex int = NULL, @DeleteLength int = NULL, @Content image AS IF @IsPermanentSnapshot != 0 BEGIN UPDATETEXT ChunkData.Content @ChunkPointer @DataIndex @DeleteLength @Content END ELSE BEGIN UPDATETEXT ReportServerTempDB.dbo.ChunkData.Content @ChunkPointer @DataIndex @DeleteLength @Content END GO GRANT EXECUTE ON [dbo].[WriteChunkPortion] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetChunkPointerAndLength]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetChunkPointerAndLength] GO CREATE PROCEDURE [dbo].[GetChunkPointerAndLength] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int AS IF @IsPermanentSnapshot != 0 BEGIN SELECT TEXTPTR(Content), DATALENGTH(Content), MimeType, ChunkFlags, Version FROM ChunkData AS CH WITH (HOLDLOCK, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END ELSE BEGIN SELECT TEXTPTR(Content), DATALENGTH(Content), MimeType, ChunkFlags, Version FROM ReportServerTempDB.dbo.ChunkData AS CH WITH (HOLDLOCK, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END GO GRANT EXECUTE ON [dbo].[GetChunkPointerAndLength] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetChunkInformation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetChunkInformation] GO CREATE PROCEDURE [dbo].[GetChunkInformation] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int AS IF @IsPermanentSnapshot != 0 BEGIN SELECT MimeType FROM ChunkData AS CH WITH (HOLDLOCK, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END ELSE BEGIN SELECT MimeType FROM ReportServerTempDB.dbo.ChunkData AS CH WITH (HOLDLOCK, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END GO GRANT EXECUTE ON [dbo].[GetChunkInformation] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadChunkPortion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadChunkPortion] GO CREATE PROCEDURE [dbo].[ReadChunkPortion] @ChunkPointer binary(16), @IsPermanentSnapshot bit, @DataIndex int, @Length int AS IF @IsPermanentSnapshot != 0 BEGIN READTEXT ChunkData.Content @ChunkPointer @DataIndex @Length END ELSE BEGIN READTEXT ReportServerTempDB.dbo.ChunkData.Content @ChunkPointer @DataIndex @Length END GO GRANT EXECUTE ON [dbo].[ReadChunkPortion] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CopyChunksOfType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CopyChunksOfType] GO CREATE PROCEDURE [dbo].[CopyChunksOfType] @FromSnapshotID uniqueidentifier, @FromIsPermanent bit, @ToSnapshotID uniqueidentifier, @ToIsPermanent bit, @ChunkType int AS IF @FromIsPermanent != 0 AND @ToIsPermanent = 0 BEGIN INSERT INTO ReportServerTempDB.dbo.ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) SELECT newid(), @ToSnapshotID, S.ChunkName, S.ChunkType, S.MimeType, S.Version, S.ChunkFlags, S.Content FROM ChunkData AS S WHERE S.SnapshotDataID = @FromSnapshotID AND S.ChunkType = @ChunkType AND NOT EXISTS( SELECT T.ChunkName FROM ReportServerTempDB.dbo.ChunkData AS T -- exclude the ones in the target WHERE T.ChunkName = S.ChunkName AND T.ChunkType = S.ChunkType AND T.SnapshotDataID = @ToSnapshotID) END ELSE IF @FromIsPermanent = 0 AND @ToIsPermanent = 0 BEGIN INSERT INTO ReportServerTempDB.dbo.ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) SELECT newid(), @ToSnapshotID, S.ChunkName, S.ChunkType, S.MimeType, S.Version, S.ChunkFlags, S.Content FROM ReportServerTempDB.dbo.ChunkData AS S WHERE S.SnapshotDataID = @FromSnapshotID AND S.ChunkType = @ChunkType AND NOT EXISTS( SELECT T.ChunkName FROM ReportServerTempDB.dbo.ChunkData AS T -- exclude the ones in the target WHERE T.ChunkName = S.ChunkName AND T.ChunkType = S.ChunkType AND T.SnapshotDataID = @ToSnapshotID) END ELSE IF @FromIsPermanent != 0 AND @ToIsPermanent != 0 BEGIN INSERT INTO ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) SELECT newid(), @ToSnapshotID, S.ChunkName, S.ChunkType, S.MimeType, S.Version, S.ChunkFlags, S.Content FROM ChunkData AS S WHERE S.SnapshotDataID = @FromSnapshotID AND S.ChunkType = @ChunkType AND NOT EXISTS( SELECT T.ChunkName FROM ChunkData AS T -- exclude the ones in the target WHERE T.ChunkName = S.ChunkName AND T.ChunkType = S.ChunkType AND T.SnapshotDataID = @ToSnapshotID) END ELSE BEGIN RAISERROR('Unsupported chunk copy', 16, 1) END GO GRANT EXECUTE ON [dbo].[CopyChunksOfType] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteSnapshotAndChunks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteSnapshotAndChunks] GO CREATE PROCEDURE [dbo].[DeleteSnapshotAndChunks] @SnapshotID uniqueidentifier, @IsPermanentSnapshot bit AS IF @IsPermanentSnapshot != 0 BEGIN DELETE ChunkData WHERE ChunkData.SnapshotDataID = @SnapshotID DELETE SnapshotData WHERE SnapshotData.SnapshotDataID = @SnapshotID END ELSE BEGIN DELETE ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotID DELETE ReportServerTempDB.dbo.SnapshotData WHERE SnapshotDataID = @SnapshotID END GO GRANT EXECUTE ON [dbo].[DeleteSnapshotAndChunks] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteOneChunk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteOneChunk] GO CREATE PROCEDURE [dbo].[DeleteOneChunk] @SnapshotID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int AS IF @IsPermanentSnapshot != 0 BEGIN DELETE ChunkData WHERE SnapshotDataID = @SnapshotID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END ELSE BEGIN DELETE ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END GO GRANT EXECUTE ON [dbo].[DeleteOneChunk] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateRdlChunk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateRdlChunk] GO CREATE PROCEDURE [dbo].[CreateRdlChunk] @ItemId UNIQUEIDENTIFIER, @SnapshotId UNIQUEIDENTIFIER, @IsPermanentSnapshot BIT, @ChunkName NVARCHAR(260), @ChunkFlags TINYINT, @ChunkType INT, @Version SMALLINT, @MimeType NVARCHAR(260) = NULL AS BEGIN IF @IsPermanentSnapshot != 0 BEGIN INSERT INTO [ChunkData] ( ChunkId, SnapshotDataId, ChunkFlags, ChunkName, ChunkType, Version, MimeType, Content ) SELECT NEWID(), @SnapshotId, @ChunkFlags, @ChunkName, @ChunkType, @Version, @MimeType, ISNULL(Linked.Content, Original.Content) FROM [Catalog] Original LEFT OUTER JOIN [Catalog] Linked WITH (INDEX(PK_Catalog)) ON (Original.LinkSourceId = Linked.ItemId) WHERE Original.ItemId = @ItemId AND NOT EXISTS ( SELECT * FROM [ChunkData] WHERE SnapshotDataId = @SnapshotId AND ChunkName = @ChunkName AND ChunkType = @ChunkType ) END ELSE BEGIN INSERT INTO ReportServerTempDB.[dbo].[ChunkData] ( ChunkId, SnapshotDataId, ChunkFlags, ChunkName, ChunkType, Version, MimeType, Content ) SELECT NEWID(), @SnapshotId, @ChunkFlags, @ChunkName, @ChunkType, @Version, @MimeType, ISNULL(Linked.Content, Original.Content) FROM [Catalog] Original LEFT OUTER JOIN [Catalog] Linked WITH (INDEX(PK_Catalog)) ON (Original.LinkSourceId = Linked.ItemId) WHERE Original.ItemId = @ItemId AND NOT EXISTS ( SELECT * FROM ReportServerTempDB.[dbo].[ChunkData] WHERE SnapshotDataId = @SnapshotId AND ChunkName = @ChunkName AND ChunkType = @ChunkType ) END END GRANT EXECUTE ON [dbo].[CreateRdlChunk] TO RSExecRole GO -------------------------------------------------- ------------- Persisted stream SPs if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeletePersistedStreams]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeletePersistedStreams] GO CREATE PROCEDURE [dbo].[DeletePersistedStreams] @SessionID varchar(32) AS delete ReportServerTempDB.dbo.PersistedStream from (select top 1 * from ReportServerTempDB.dbo.PersistedStream PS2 where PS2.SessionID = @SessionID) as e1 where e1.SessionID = ReportServerTempDB.dbo.PersistedStream.[SessionID] and e1.[Index] = ReportServerTempDB.dbo.PersistedStream.[Index] GO GRANT EXECUTE ON [dbo].[DeletePersistedStreams] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteExpiredPersistedStreams]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteExpiredPersistedStreams] GO CREATE PROCEDURE [dbo].[DeleteExpiredPersistedStreams] AS SET DEADLOCK_PRIORITY LOW DELETE ReportServerTempDB.dbo.PersistedStream FROM (SELECT TOP 1 * FROM ReportServerTempDB.dbo.PersistedStream PS2 WHERE PS2.RefCount = 0 AND GETDATE() > PS2.ExpirationDate) AS e1 WHERE e1.SessionID = ReportServerTempDB.dbo.PersistedStream.[SessionID] AND e1.[Index] = ReportServerTempDB.dbo.PersistedStream.[Index] GO GRANT EXECUTE ON [dbo].[DeleteExpiredPersistedStreams] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeletePersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeletePersistedStream] GO CREATE PROCEDURE [dbo].[DeletePersistedStream] @SessionID varchar(32), @Index int AS delete from ReportServerTempDB.dbo.PersistedStream where SessionID = @SessionID and [Index] = @Index GO GRANT EXECUTE ON [dbo].[DeletePersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddPersistedStream] GO CREATE PROCEDURE [dbo].[AddPersistedStream] @SessionID varchar(32), @Index int AS DECLARE @RefCount int DECLARE @id varchar(32) DECLARE @ExpirationDate datetime set @RefCount = 0 set @ExpirationDate = DATEADD(day, 2, GETDATE()) set @id = (select SessionID from ReportServerTempDB.dbo.SessionData where SessionID = @SessionID) if @id is not null begin set @RefCount = 1 end INSERT INTO ReportServerTempDB.dbo.PersistedStream (SessionID, [Index], [RefCount], [ExpirationDate]) VALUES (@SessionID, @Index, @RefCount, @ExpirationDate) GO GRANT EXECUTE ON [dbo].[AddPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[LockPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[LockPersistedStream] GO CREATE PROCEDURE [dbo].[LockPersistedStream] @SessionID varchar(32), @Index int AS SELECT [Index] FROM ReportServerTempDB.dbo.PersistedStream WITH (XLOCK) WHERE SessionID = @SessionID AND [Index] = @Index GO GRANT EXECUTE ON [dbo].[LockPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteFirstPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteFirstPortionPersistedStream] GO CREATE PROCEDURE [dbo].[WriteFirstPortionPersistedStream] @SessionID varchar(32), @Index int, @Name nvarchar(260) = NULL, @MimeType nvarchar(260) = NULL, @Extension nvarchar(260) = NULL, @Encoding nvarchar(260) = NULL, @Content image AS UPDATE ReportServerTempDB.dbo.PersistedStream set Content = @Content, [Name] = @Name, MimeType = @MimeType, Extension = @Extension WHERE SessionID = @SessionID AND [Index] = @Index SELECT TEXTPTR(Content) FROM ReportServerTempDB.dbo.PersistedStream WHERE SessionID = @SessionID AND [Index] = @Index GO GRANT EXECUTE ON [dbo].[WriteFirstPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteNextPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteNextPortionPersistedStream] GO CREATE PROCEDURE [dbo].[WriteNextPortionPersistedStream] @DataPointer binary(16), @DataIndex int, @DeleteLength int, @Content image AS UPDATETEXT ReportServerTempDB.dbo.PersistedStream.Content @DataPointer @DataIndex @DeleteLength @Content GO GRANT EXECUTE ON [dbo].[WriteNextPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetFirstPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetFirstPortionPersistedStream] GO CREATE PROCEDURE [dbo].[GetFirstPortionPersistedStream] @SessionID varchar(32) AS SELECT TOP 1 TEXTPTR(P.Content), DATALENGTH(P.Content), P.[Index], P.[Name], P.MimeType, P.Extension, P.Encoding, P.Error FROM ReportServerTempDB.dbo.PersistedStream P WITH (XLOCK) WHERE P.SessionID = @SessionID GO GRANT EXECUTE ON [dbo].[GetFirstPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetPersistedStreamError]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetPersistedStreamError] GO CREATE PROCEDURE [dbo].[SetPersistedStreamError] @SessionID varchar(32), @Index int, @AllRows bit, @Error nvarchar(512) AS if @AllRows = 0 BEGIN UPDATE ReportServerTempDB.dbo.PersistedStream SET Error = @Error WHERE SessionID = @SessionID and [Index] = @Index END ELSE BEGIN UPDATE ReportServerTempDB.dbo.PersistedStream SET Error = @Error WHERE SessionID = @SessionID END GO GRANT EXECUTE ON [dbo].[SetPersistedStreamError] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetNextPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetNextPortionPersistedStream] GO CREATE PROCEDURE [dbo].[GetNextPortionPersistedStream] @DataPointer binary(16), @DataIndex int, @Length int AS READTEXT ReportServerTempDB.dbo.PersistedStream.Content @DataPointer @DataIndex @Length GO GRANT EXECUTE ON [dbo].[GetNextPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapshotChunks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapshotChunks] GO CREATE PROCEDURE [dbo].[GetSnapshotChunks] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit AS IF @IsPermanentSnapshot != 0 BEGIN SELECT ChunkName, ChunkType, ChunkFlags, MimeType, Version, datalength(Content) FROM ChunkData WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN SELECT ChunkName, ChunkType, ChunkFlags, MimeType, Version, datalength(Content) FROM ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[GetSnapshotChunks] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetDrillthroughReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetDrillthroughReports] GO CREATE PROCEDURE [dbo].[SetDrillthroughReports] @ReportID uniqueidentifier, @ModelID uniqueidentifier, @ModelItemID nvarchar(425), @Type tinyint AS INSERT INTO ModelDrill (ModelDrillID, ModelID, ReportID, ModelItemID, [Type]) VALUES (newid(), @ModelID, @ReportID, @ModelItemID, @Type) GO GRANT EXECUTE ON [dbo].[SetDrillthroughReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteDrillthroughReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteDrillthroughReports] GO CREATE PROCEDURE [dbo].[DeleteDrillthroughReports] @ModelID uniqueidentifier, @ModelItemID nvarchar(425) AS DELETE ModelDrill WHERE ModelID = @ModelID and ModelItemID = @ModelItemID GO GRANT EXECUTE ON [dbo].[DeleteDrillthroughReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDrillthroughReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDrillthroughReports] GO CREATE PROCEDURE [dbo].[GetDrillthroughReports] @ModelID uniqueidentifier, @ModelItemID nvarchar(425) AS SELECT ModelDrill.Type, Catalog.Path FROM ModelDrill INNER JOIN Catalog ON ModelDrill.ReportID = Catalog.ItemID WHERE ModelID = @ModelID AND ModelItemID = @ModelItemID GO GRANT EXECUTE ON [dbo].[GetDrillthroughReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDrillthroughReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDrillthroughReport] GO CREATE PROCEDURE [dbo].[GetDrillthroughReport] @ModelPath nvarchar(425), @ModelItemID nvarchar(425), @Type tinyint AS SELECT CatRep.Path FROM ModelDrill INNER JOIN Catalog CatMod ON ModelDrill.ModelID = CatMod.ItemID INNER JOIN Catalog CatRep ON ModelDrill.ReportID = CatRep.ItemID WHERE CatMod.Path = @ModelPath AND ModelItemID = @ModelItemID AND ModelDrill.[Type] = @Type GO GRANT EXECUTE ON [dbo].[GetDrillthroughReport] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUpgradeItems]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUpgradeItems] GO CREATE PROCEDURE [dbo].[GetUpgradeItems] AS SELECT [Item], [Status] FROM [UpgradeInfo] GO GRANT EXECUTE ON [dbo].[GetUpgradeItems] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetUpgradeItemStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetUpgradeItemStatus] GO CREATE PROCEDURE [dbo].[SetUpgradeItemStatus] @ItemName nvarchar(260), @Status nvarchar(512) AS UPDATE [UpgradeInfo] SET [Status] = @Status WHERE [Item] = @ItemName GO GRANT EXECUTE ON [dbo].[SetUpgradeItemStatus] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPolicyRoots]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPolicyRoots] GO CREATE PROCEDURE [dbo].[GetPolicyRoots] AS SELECT [Path], [Type] FROM [Catalog] WHERE [PolicyRoot] = 1 GO GRANT EXECUTE ON [dbo].[GetPolicyRoots] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDataSourceForUpgrade]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDataSourceForUpgrade] GO CREATE PROCEDURE [dbo].[GetDataSourceForUpgrade] @CurrentVersion int AS SELECT [DSID] FROM [DataSource] WHERE [Version] != @CurrentVersion GO GRANT EXECUTE ON [dbo].[GetDataSourceForUpgrade] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSubscriptionsForUpgrade]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSubscriptionsForUpgrade] GO CREATE PROCEDURE [dbo].[GetSubscriptionsForUpgrade] @CurrentVersion int AS SELECT [SubscriptionID] FROM [Subscriptions] WHERE [Version] != @CurrentVersion GO GRANT EXECUTE ON [dbo].[GetSubscriptionsForUpgrade] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[StoreServerParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[StoreServerParameters] GO CREATE PROCEDURE [dbo].[StoreServerParameters] @ServerParametersID nvarchar(32), @Path nvarchar(425), @CurrentDate datetime, @Timeout int, @Expiration datetime, @ParametersValues image, @ParentParametersID nvarchar(32) = NULL AS DECLARE @ExistingServerParametersID as nvarchar(32) SET @ExistingServerParametersID = (SELECT ServerParametersID from [dbo].[ServerParametersInstance] WHERE ServerParametersID = @ServerParametersID) IF @ExistingServerParametersID IS NULL -- new row BEGIN INSERT INTO [dbo].[ServerParametersInstance] (ServerParametersID, ParentID, Path, CreateDate, ModifiedDate, Timeout, Expiration, ParametersValues) VALUES (@ServerParametersID, @ParentParametersID, @Path, @CurrentDate, @CurrentDate, @Timeout, @Expiration, @ParametersValues) END ELSE BEGIN UPDATE [dbo].[ServerParametersInstance] SET Timeout = @Timeout, Expiration = @Expiration, ParametersValues = @ParametersValues, ModifiedDate = @CurrentDate, Path = @Path, ParentID = @ParentParametersID WHERE ServerParametersID = @ServerParametersID END GO GRANT EXECUTE ON [dbo].[StoreServerParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetServerParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetServerParameters] GO CREATE PROCEDURE [dbo].[GetServerParameters] @ServerParametersID nvarchar(32) AS DECLARE @now as DATETIME SET @now = GETDATE() SELECT Child.Path, Child.ParametersValues, Parent.ParametersValues FROM [dbo].[ServerParametersInstance] Child LEFT OUTER JOIN [dbo].[ServerParametersInstance] Parent ON Child.ParentID = Parent.ServerParametersID WHERE Child.ServerParametersID = @ServerParametersID AND Child.Expiration > @now GO GRANT EXECUTE ON [dbo].[GetServerParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredServerParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredServerParameters] GO CREATE PROCEDURE [dbo].[CleanExpiredServerParameters] @ParametersCleaned INT OUTPUT AS DECLARE @now as DATETIME SET @now = GETDATE() DELETE FROM [dbo].[ServerParametersInstance] WHERE ServerParametersID IN ( SELECT TOP 20 ServerParametersID FROM [dbo].[ServerParametersInstance] WHERE Expiration < @now ) SET @ParametersCleaned = @@ROWCOUNT GO GRANT EXECUTE ON [dbo].[CleanExpiredServerParameters] TO RSExecRole GO -- END STORED PROCEDURESPA-- START STORED PROCEDURES if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetKeysForInstallation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetKeysForInstallation] GO CREATE PROCEDURE [dbo].[SetKeysForInstallation] @InstallationID uniqueidentifier, @SymmetricKey image = NULL, @PublicKey image AS update [dbo].[Keys] set [SymmetricKey] = @SymmetricKey, [PublicKey] = @PublicKey where [InstallationID] = @InstallationID and [Client] = 1 GO GRANT EXECUTE ON [dbo].[SetKeysForInstallation] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAnnouncedKey]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAnnouncedKey] GO CREATE PROCEDURE [dbo].[GetAnnouncedKey] @InstallationID uniqueidentifier AS select PublicKey, MachineName, InstanceName from Keys where InstallationID = @InstallationID and Client = 1 GO GRANT EXECUTE ON [dbo].[GetAnnouncedKey] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AnnounceOrGetKey]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AnnounceOrGetKey] GO CREATE PROCEDURE [dbo].[AnnounceOrGetKey] @MachineName nvarchar(256), @InstanceName nvarchar(32), @InstallationID uniqueidentifier, @PublicKey image, @NumAnnouncedServices int OUTPUT AS -- Acquire lock IF NOT EXISTS (SELECT * FROM [dbo].[Keys] WITH(XLOCK) WHERE [Client] < 0) BEGIN RAISERROR('Keys lock row not found', 16, 1) RETURN END -- Get the number of services that have already announced their presence SELECT @NumAnnouncedServices = count(*) FROM [dbo].[Keys] WHERE [Client] = 1 DECLARE @StoredInstallationID uniqueidentifier DECLARE @StoredInstanceName nvarchar(32) SELECT @StoredInstallationID = [InstallationID], @StoredInstanceName = [InstanceName] FROM [dbo].[Keys] WHERE [InstallationID] = @InstallationID AND [Client] = 1 IF @StoredInstallationID IS NULL -- no record present BEGIN INSERT INTO [dbo].[Keys] ([MachineName], [InstanceName], [InstallationID], [Client], [PublicKey], [SymmetricKey]) VALUES (@MachineName, @InstanceName, @InstallationID, 1, @PublicKey, null) END ELSE BEGIN IF @StoredInstanceName IS NULL BEGIN UPDATE [dbo].[Keys] SET [InstanceName] = @InstanceName WHERE [InstallationID] = @InstallationID AND [Client] = 1 END END SELECT [MachineName], [SymmetricKey], [PublicKey] FROM [Keys] WHERE [InstallationID] = @InstallationID and [Client] = 1 GO GRANT EXECUTE ON [dbo].[AnnounceOrGetKey] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetMachineName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetMachineName] GO CREATE PROCEDURE [dbo].[SetMachineName] @MachineName nvarchar(256), @InstallationID uniqueidentifier AS UPDATE [dbo].[Keys] SET MachineName = @MachineName WHERE [InstallationID] = @InstallationID and [Client] = 1 GO GRANT EXECUTE ON [dbo].[SetMachineName] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListInstallations]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListInstallations] GO CREATE PROCEDURE [dbo].[ListInstallations] AS SELECT [MachineName], [InstanceName], [InstallationID], CASE WHEN [SymmetricKey] IS null THEN 0 ELSE 1 END FROM [dbo].[Keys] WHERE [Client] = 1 GO GRANT EXECUTE ON [dbo].[ListInstallations] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListInfoForReencryption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListInfoForReencryption] GO CREATE PROCEDURE [dbo].[ListInfoForReencryption] AS SELECT [DSID] FROM [dbo].[DataSource] WITH (XLOCK, TABLOCK) SELECT [SubscriptionID] FROM [dbo].[Subscriptions] WITH (XLOCK, TABLOCK) SELECT [InstallationID], [PublicKey] FROM [dbo].[Keys] WITH (XLOCK, TABLOCK) WHERE [Client] = 1 AND ([SymmetricKey] IS NOT NULL) GO GRANT EXECUTE ON [dbo].[ListInfoForReencryption] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDatasourceInfoForReencryption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDatasourceInfoForReencryption] GO CREATE PROCEDURE [dbo].[GetDatasourceInfoForReencryption] @DSID as uniqueidentifier AS SELECT [ConnectionString], [OriginalConnectionString], [UserName], [Password], [CredentialRetrieval], [Version] FROM [dbo].[DataSource] WHERE [DSID] = @DSID GO GRANT EXECUTE ON [dbo].[GetDatasourceInfoForReencryption] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetReencryptedDatasourceInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetReencryptedDatasourceInfo] GO CREATE PROCEDURE [dbo].[SetReencryptedDatasourceInfo] @DSID uniqueidentifier, @ConnectionString image = NULL, @OriginalConnectionString image = NULL, @UserName image = NULL, @Password image = NULL, @CredentialRetrieval int, @Version int AS UPDATE [dbo].[DataSource] SET [ConnectionString] = @ConnectionString, [OriginalConnectionString] = @OriginalConnectionString, [UserName] = @UserName, [Password] = @Password, [CredentialRetrieval] = @CredentialRetrieval, [Version] = @Version WHERE [DSID] = @DSID GO GRANT EXECUTE ON [dbo].[SetReencryptedDatasourceInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSubscriptionInfoForReencryption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSubscriptionInfoForReencryption] GO CREATE PROCEDURE [dbo].[GetSubscriptionInfoForReencryption] @SubscriptionID as uniqueidentifier AS SELECT [DeliveryExtension], [ExtensionSettings], [Version] FROM [dbo].[Subscriptions] WHERE [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetSubscriptionInfoForReencryption] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetReencryptedSubscriptionInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetReencryptedSubscriptionInfo] GO CREATE PROCEDURE [dbo].[SetReencryptedSubscriptionInfo] @SubscriptionID as uniqueidentifier, @ExtensionSettings as ntext = NULL, @Version as int AS UPDATE [dbo].[Subscriptions] SET [ExtensionSettings] = @ExtensionSettings, [Version] = @Version WHERE [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[SetReencryptedSubscriptionInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteEncryptedContent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteEncryptedContent] GO CREATE PROCEDURE [dbo].[DeleteEncryptedContent] AS -- Remove the encryption keys delete from keys where client >= 0 -- Remove the encrypted content update datasource set CredentialRetrieval = 1, -- CredentialRetrieval.Prompt ConnectionString = null, OriginalConnectionString = null, UserName = null, Password = null GO GRANT EXECUTE ON [dbo].[DeleteEncryptedContent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteKey]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteKey] GO CREATE PROCEDURE [dbo].[DeleteKey] @InstallationID uniqueidentifier AS if (@InstallationID = '00000000-0000-0000-0000-000000000000') RAISERROR('Cannot delete reserved key', 16, 1) -- Remove the encryption keys delete from keys where InstallationID = @InstallationID and Client = 1 GO GRANT EXECUTE ON [dbo].[DeleteKey] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAllConfigurationInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAllConfigurationInfo] GO CREATE PROCEDURE [dbo].[GetAllConfigurationInfo] AS SELECT [Name], [Value] FROM [ConfigurationInfo] GO GRANT EXECUTE ON [dbo].[GetAllConfigurationInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetOneConfigurationInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetOneConfigurationInfo] GO CREATE PROCEDURE [dbo].[GetOneConfigurationInfo] @Name nvarchar (260) AS SELECT [Value] FROM [ConfigurationInfo] WHERE [Name] = @Name GO GRANT EXECUTE ON [dbo].[GetOneConfigurationInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetConfigurationInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetConfigurationInfo] GO CREATE PROCEDURE [dbo].[SetConfigurationInfo] @Name nvarchar (260), @Value ntext AS DELETE FROM [ConfigurationInfo] WHERE [Name] = @Name IF @Value is not null BEGIN INSERT INTO ConfigurationInfo VALUES ( newid(), @Name, @Value ) END GO GRANT EXECUTE ON [dbo].[SetConfigurationInfo] TO RSExecRole if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddEvent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddEvent] GO CREATE PROCEDURE [dbo].[AddEvent] @EventType nvarchar (260), @EventData nvarchar (260) AS insert into [Event] ([EventID], [EventType], [EventData], [TimeEntered], [ProcessStart], [BatchID]) values (NewID(), @EventType, @EventData, GETUTCDATE(), NULL, NULL) GO GRANT EXECUTE ON [dbo].[AddEvent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteEvent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteEvent] GO CREATE PROCEDURE [dbo].[DeleteEvent] @ID uniqueidentifier AS delete from [Event] where [EventID] = @ID GO GRANT EXECUTE ON [dbo].[DeleteEvent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanEventRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanEventRecords] GO CREATE PROCEDURE [dbo].[CleanEventRecords] @MaxAgeMinutes int AS -- Reset all notifications which have been add over n minutes ago Update [Event] set [ProcessStart] = NULL, [ProcessHeartbeat] = NULL where [EventID] in ( SELECT [EventID] FROM [Event] WHERE [ProcessHeartbeat] < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) ) GO GRANT EXECUTE ON [dbo].[CleanEventRecords] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddExecutionLogEntry]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddExecutionLogEntry] GO CREATE PROCEDURE [dbo].[AddExecutionLogEntry] @InstanceName nvarchar(38), @Report nvarchar(260), @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @RequestType bit, @Format nvarchar(26), @Parameters ntext, @TimeStart DateTime, @TimeEnd DateTime, @TimeDataRetrieval int, @TimeProcessing int, @TimeRendering int, @Source tinyint, @Status nvarchar(32), @ByteCount bigint, @RowCount bigint, @ExecutionId nvarchar(64) = null, @ReportAction tinyint, @AdditionalInfo xml = null AS -- Unless is is specifically 'False', it's true if exists (select * from ConfigurationInfo where [Name] = 'EnableExecutionLogging' and [Value] like 'False') begin return end Declare @ReportID uniqueidentifier select @ReportID = ItemID from Catalog with (nolock) where Path = @Report insert into ExecutionLogStorage (InstanceName, ReportID, UserName, ExecutionId, RequestType, [Format], Parameters, ReportAction, TimeStart, TimeEnd, TimeDataRetrieval, TimeProcessing, TimeRendering, Source, Status, ByteCount, [RowCount], AdditionalInfo) Values (@InstanceName, @ReportID, @UserName, @ExecutionId, @RequestType, @Format, @Parameters, @ReportAction, @TimeStart, @TimeEnd, @TimeDataRetrieval, @TimeProcessing, @TimeRendering, @Source, @Status, @ByteCount, @RowCount, @AdditionalInfo) GO GRANT EXECUTE ON [dbo].[AddExecutionLogEntry] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ExpireExecutionLogEntries]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ExpireExecutionLogEntries] GO CREATE PROCEDURE [dbo].[ExpireExecutionLogEntries] AS -- -1 means no expiration if exists (select * from ConfigurationInfo where [Name] = 'ExecutionLogDaysKept' and CAST(CAST(Value as nvarchar) as integer) = -1) begin return end delete from ExecutionLogStorage where DateDiff(day, TimeStart, getdate()) >= (select CAST(CAST(Value as nvarchar) as integer) from ConfigurationInfo where [Name] = 'ExecutionLogDaysKept') GO GRANT EXECUTE ON [dbo].[ExpireExecutionLogEntries] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUserIDBySid]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUserIDBySid] GO -- looks up any user name by its SID, if not it creates a regular user CREATE PROCEDURE [dbo].[GetUserIDBySid] @UserSid varbinary(85), @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS SELECT @UserID = (SELECT UserID FROM Users WHERE Sid = @UserSid AND AuthType = @AuthType) IF @UserID IS NULL BEGIN SET @UserID = newid() INSERT INTO Users (UserID, Sid, UserType, AuthType, UserName) VALUES (@UserID, @UserSid, 0, @AuthType, @UserName) END GO GRANT EXECUTE ON [dbo].[GetUserIDBySid] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUserIDByName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUserIDByName] GO -- looks up any user name by its User Name, if not it creates a regular user CREATE PROCEDURE [dbo].[GetUserIDByName] @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS SELECT @UserID = (SELECT UserID FROM Users WHERE UserName = @UserName AND AuthType = @AuthType) IF @UserID IS NULL BEGIN SET @UserID = newid() INSERT INTO Users (UserID, Sid, UserType, AuthType, UserName) VALUES (@UserID, NULL, 0, @AuthType, @UserName) END GO GRANT EXECUTE ON [dbo].[GetUserIDByName] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUserID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUserID] GO -- looks up any user name, if not it creates a regular user - uses Sid CREATE PROCEDURE [dbo].[GetUserID] @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS IF @AuthType = 1 -- Windows BEGIN EXEC GetUserIDBySid @UserSid, @UserName, @AuthType, @UserID OUTPUT END ELSE BEGIN EXEC GetUserIDByName @UserName, @AuthType, @UserID OUTPUT END GO GRANT EXECUTE ON [dbo].[GetUserID] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPrincipalID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPrincipalID] GO -- looks up a principal, if not there looks up regular users and turns them into principals -- if not, it creates a principal CREATE PROCEDURE [dbo].[GetPrincipalID] @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS -- windows auth IF @AuthType = 1 BEGIN -- is this a principal? SELECT @UserID = (SELECT UserID FROM Users WHERE Sid = @UserSid AND UserType = 1 AND AuthType = @AuthType) END ELSE BEGIN -- is this a principal? SELECT @UserID = (SELECT UserID FROM Users WHERE UserName = @UserName AND UserType = 1 AND AuthType = @AuthType) END IF @UserID IS NULL BEGIN IF @AuthType = 1 -- Windows BEGIN -- Is this a regular user SELECT @UserID = (SELECT UserID FROM Users WHERE Sid = @UserSid AND UserType = 0 AND AuthType = @AuthType) END ELSE BEGIN -- Is this a regular user SELECT @UserID = (SELECT UserID FROM Users WHERE UserName = @UserName AND UserType = 0 AND AuthType = @AuthType) END -- No, create a new principal IF @UserID IS NULL BEGIN SET @UserID = newid() INSERT INTO Users (UserID, Sid, UserType, AuthType, UserName) VALUES (@UserID, @UserSid, 1, @AuthType, @UserName) END ELSE BEGIN UPDATE Users SET UserType = 1 WHERE UserID = @UserID END END GO GRANT EXECUTE ON [dbo].[GetPrincipalID] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateSubscription] GO CREATE PROCEDURE [dbo].[CreateSubscription] @id uniqueidentifier, @Locale nvarchar (128), @Report_Name nvarchar (425), @OwnerSid varbinary (85) = NULL, @OwnerName nvarchar(260), @OwnerAuthType int, @DeliveryExtension nvarchar (260) = NULL, @InactiveFlags int, @ExtensionSettings ntext = NULL, @ModifiedBySid varbinary (85) = NULL, @ModifiedByName nvarchar(260), @ModifiedByAuthType int, @ModifiedDate datetime, @Description nvarchar(512) = NULL, @LastStatus nvarchar(260) = NULL, @EventType nvarchar(260), @MatchData ntext = NULL, @Parameters ntext = NULL, @DataSettings ntext = NULL, @Version int AS -- Create a subscription with the given data. The name must match a name in the -- Catalog table and it must be a report type (2) or linked report (4) DECLARE @Report_OID uniqueidentifier DECLARE @OwnerID uniqueidentifier DECLARE @ModifiedByID uniqueidentifier DECLARE @TempDeliveryID uniqueidentifier --Get the report id for this subscription select @Report_OID = (select [ItemID] from [Catalog] where [Catalog].[Path] = @Report_Name and ([Catalog].[Type] = 2 or [Catalog].[Type] = 4)) EXEC GetUserID @OwnerSid, @OwnerName, @OwnerAuthType, @OwnerID OUTPUT EXEC GetUserID @ModifiedBySid, @ModifiedByName, @ModifiedByAuthType, @ModifiedByID OUTPUT if (@Report_OID is NULL) begin RAISERROR('Report Not Found', 16, 1) return end Insert into Subscriptions ( [SubscriptionID], [OwnerID], [Report_OID], [Locale], [DeliveryExtension], [InactiveFlags], [ExtensionSettings], [ModifiedByID], [ModifiedDate], [Description], [LastStatus], [EventType], [MatchData], [LastRunTime], [Parameters], [DataSettings], [Version] ) values (@id, @OwnerID, @Report_OID, @Locale, @DeliveryExtension, @InactiveFlags, @ExtensionSettings, @ModifiedByID, @ModifiedDate, @Description, @LastStatus, @EventType, @MatchData, NULL, @Parameters, @DataSettings, @Version) GO GRANT EXECUTE ON [dbo].[CreateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeliveryRemovedInactivateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeliveryRemovedInactivateSubscription] GO CREATE PROCEDURE [dbo].[DeliveryRemovedInactivateSubscription] @DeliveryExtension nvarchar(260), @Status nvarchar(260) AS update Subscriptions set [DeliveryExtension] = '', [InactiveFlags] = [InactiveFlags] | 1, -- Delivery Provider Removed Flag == 1 [LastStatus] = @Status where [DeliveryExtension] = @DeliveryExtension GO GRANT EXECUTE ON [dbo].[DeliveryRemovedInactivateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddSubscriptionToBeingDeleted]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddSubscriptionToBeingDeleted] GO CREATE PROCEDURE [dbo].[AddSubscriptionToBeingDeleted] @SubscriptionID uniqueidentifier AS -- Delete orphaned subscriptions, based on the age criteria: > 10 minutes delete from [SubscriptionsBeingDeleted] where DATEDIFF( minute, [CreationDate], GetUtcDate() ) > 10 -- Add subscription being deleted into the DeletedSubscription table insert into [SubscriptionsBeingDeleted] VALUES(@SubscriptionID, GetUtcDate()) GO GRANT EXECUTE ON [dbo].[AddSubscriptionToBeingDeleted] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RemoveSubscriptionFromBeingDeleted]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RemoveSubscriptionFromBeingDeleted] GO CREATE PROCEDURE [dbo].[RemoveSubscriptionFromBeingDeleted] @SubscriptionID uniqueidentifier AS delete from [SubscriptionsBeingDeleted] where SubscriptionID = @SubscriptionID GO GRANT EXECUTE ON [dbo].[RemoveSubscriptionFromBeingDeleted] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteSubscription] GO CREATE PROCEDURE [dbo].[DeleteSubscription] @SubscriptionID uniqueidentifier AS -- Delete the subscription delete from [Subscriptions] where [SubscriptionID] = @SubscriptionID -- Delete it from the SubscriptionsBeingDeleted EXEC RemoveSubscriptionFromBeingDeleted @SubscriptionID GO GRANT EXECUTE ON [dbo].[DeleteSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSubscription] GO CREATE PROCEDURE [dbo].[GetSubscription] @SubscriptionID uniqueidentifier AS -- Grab all of the-- subscription properties given a id select S.[SubscriptionID], S.[Report_OID], S.[Locale], S.[InactiveFlags], S.[DeliveryExtension], S.[ExtensionSettings], SUSER_SNAME(Modified.[Sid]), Modified.[UserName], S.[ModifiedDate], S.[Description], S.[LastStatus], S.[EventType], S.[MatchData], S.[Parameters], S.[DataSettings], A.[TotalNotifications], A.[TotalSuccesses], A.[TotalFailures], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], CAT.[Path], S.[LastRunTime], CAT.[Type], SD.NtSecDescPrimary, S.[Version], Owner.[AuthType] from [Subscriptions] S inner join [Catalog] CAT on S.[Report_OID] = CAT.[ItemID] inner join [Users] Owner on S.OwnerID = Owner.UserID inner join [Users] Modified on S.ModifiedByID = Modified.UserID left outer join [SecData] SD on CAT.PolicyID = SD.PolicyID AND SD.AuthType = Owner.AuthType left outer join [ActiveSubscriptions] A with (NOLOCK) on S.[SubscriptionID] = A.[SubscriptionID] where S.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListSubscriptionsUsingDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListSubscriptionsUsingDataSource] GO CREATE PROCEDURE [dbo].[ListSubscriptionsUsingDataSource] @DataSourceName nvarchar(450) AS select S.[SubscriptionID], S.[Report_OID], S.[Locale], S.[InactiveFlags], S.[DeliveryExtension], S.[ExtensionSettings], SUSER_SNAME(Modified.[Sid]), Modified.[UserName], S.[ModifiedDate], S.[Description], S.[LastStatus], S.[EventType], S.[MatchData], S.[Parameters], S.[DataSettings], A.[TotalNotifications], A.[TotalSuccesses], A.[TotalFailures], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], CAT.[Path], S.[LastRunTime], CAT.[Type], SD.NtSecDescPrimary, S.[Version], Owner.[AuthType] from [DataSource] DS inner join Catalog C on C.ItemID = DS.Link inner join Subscriptions S on S.[SubscriptionID] = DS.[SubscriptionID] inner join [Catalog] CAT on S.[Report_OID] = CAT.[ItemID] inner join [Users] Owner on S.OwnerID = Owner.UserID inner join [Users] Modified on S.ModifiedByID = Modified.UserID left join [SecData] SD on SD.[PolicyID] = CAT.[PolicyID] AND SD.AuthType = Owner.AuthType left outer join [ActiveSubscriptions] A with (NOLOCK) on S.[SubscriptionID] = A.[SubscriptionID] where C.Path = @DataSourceName GO GRANT EXECUTE ON [dbo].[ListSubscriptionsUsingDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSubscriptionStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSubscriptionStatus] GO CREATE PROCEDURE [dbo].[UpdateSubscriptionStatus] @SubscriptionID uniqueidentifier, @Status nvarchar(260) AS update Subscriptions set [LastStatus] = @Status where [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[UpdateSubscriptionStatus] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSubscription] GO CREATE PROCEDURE [dbo].[UpdateSubscription] @id uniqueidentifier, @Locale nvarchar(260), @OwnerSid varbinary(85) = NULL, @OwnerName nvarchar(260), @OwnerAuthType int, @DeliveryExtension nvarchar(260), @InactiveFlags int, @ExtensionSettings ntext = NULL, @ModifiedBySid varbinary(85) = NULL, @ModifiedByName nvarchar(260), @ModifiedByAuthType int, @ModifiedDate datetime, @Description nvarchar(512) = NULL, @LastStatus nvarchar(260) = NULL, @EventType nvarchar(260), @MatchData ntext = NULL, @Parameters ntext = NULL, @DataSettings ntext = NULL, @Version int AS -- Update a subscription's information. DECLARE @ModifiedByID uniqueidentifier DECLARE @OwnerID uniqueidentifier EXEC GetUserID @ModifiedBySid, @OwnerName,@OwnerAuthType, @ModifiedByID OUTPUT EXEC GetUserID @OwnerSid, @ModifiedByName, @ModifiedByAuthType, @OwnerID OUTPUT -- Make sure there is a valid provider update Subscriptions set [DeliveryExtension] = @DeliveryExtension, [Locale] = @Locale, [OwnerID] = @OwnerID, [InactiveFlags] = @InactiveFlags, [ExtensionSettings] = @ExtensionSettings, [ModifiedByID] = @ModifiedByID, [ModifiedDate] = @ModifiedDate, [Description] = @Description, [LastStatus] = @LastStatus, [EventType] = @EventType, [MatchData] = @MatchData, [Parameters] = @Parameters, [DataSettings] = @DataSettings, [Version] = @Version where [SubscriptionID] = @id GO GRANT EXECUTE ON [dbo].[UpdateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[InvalidateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[InvalidateSubscription] GO CREATE PROCEDURE [dbo].[InvalidateSubscription] @SubscriptionID uniqueidentifier, @Flags int, @LastStatus nvarchar(260) AS -- Mark all subscriptions for this report as inactive for the given flags update Subscriptions set [InactiveFlags] = S.[InactiveFlags] | @Flags, [LastStatus] = @LastStatus from Subscriptions S where SubscriptionID = @SubscriptionID GO GRANT EXECUTE ON [dbo].[InvalidateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanNotificationRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanNotificationRecords] GO CREATE PROCEDURE [dbo].[CleanNotificationRecords] @MaxAgeMinutes int AS -- Reset all notifications which have been add over n minutes ago Update [Notifications] set [ProcessStart] = NULL, [ProcessHeartbeat] = NULL, [Attempt] = 1 where [NotificationID] in ( SELECT [NotificationID] FROM [Notifications] WHERE [ProcessHeartbeat] < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) and [Attempt] is NULL ) Update [Notifications] set [ProcessStart] = NULL, [ProcessHeartbeat] = NULL, [Attempt] = [Attempt] + 1 where [NotificationID] in ( SELECT [NotificationID] FROM [Notifications] WHERE [ProcessHeartbeat] < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) and [Attempt] is not NULL ) GO GRANT EXECUTE ON [dbo].[CleanNotificationRecords] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateSnapShotNotifications]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateSnapShotNotifications] GO CREATE PROCEDURE [dbo].[CreateSnapShotNotifications] @HistoryID uniqueidentifier, @LastRunTime datetime AS update [Subscriptions] set [LastRunTime] = @LastRunTime from History SS inner join [Subscriptions] S on S.[Report_OID] = SS.[ReportID] where SS.[HistoryID] = @HistoryID and S.EventType = 'ReportHistorySnapshotCreated' and InactiveFlags = 0 -- Find all valid subscriptions for the given report and create a new notification row for -- each subscription insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) select NewID(), S.[SubscriptionID], NULL, S.[Report_OID], NULL, S.[ExtensionSettings], S.[Locale], S.[Parameters], GETUTCDATE(), S.[LastRunTime], S.[DeliveryExtension], S.[OwnerID], 0, S.[Version] from [Subscriptions] S with (READPAST) inner join History H on S.[Report_OID] = H.[ReportID] where H.[HistoryID] = @HistoryID and S.EventType = 'ReportHistorySnapshotCreated' and InactiveFlags = 0 and S.[DataSettings] is null -- Create any data driven subscription by creating a data driven event insert into [Event] ( [EventID], [EventType], [EventData], [TimeEntered] ) select NewID(), 'DataDrivenSubscription', S.SubscriptionID, GETUTCDATE() from [Subscriptions] S with (READPAST) inner join History H on S.[Report_OID] = H.[ReportID] where H.[HistoryID] = @HistoryID and S.EventType = 'ReportHistorySnapshotCreated' and InactiveFlags = 0 and S.[DataSettings] is not null GO GRANT EXECUTE ON [dbo].[CreateSnapShotNotifications] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateDataDrivenNotification]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateDataDrivenNotification] GO CREATE PROCEDURE [dbo].[CreateDataDrivenNotification] @SubscriptionID uniqueidentifier, @ActiveationID uniqueidentifier, @ReportID uniqueidentifier, @ExtensionSettings ntext, @Locale nvarchar(128), @Parameters ntext, @LastRunTime datetime, @DeliveryExtension nvarchar(260), @OwnerSid varbinary (85) = null, @OwnerName nvarchar(260), @OwnerAuthType int, @Version int AS declare @OwnerID as uniqueidentifier EXEC GetUserID @OwnerSid,@OwnerName, @OwnerAuthType, @OwnerID OUTPUT -- Verify if subscription is being deleted if exists (select 1 from [dbo].[SubscriptionsBeingDeleted] where [SubscriptionID]=@SubscriptionID) BEGIN RAISERROR( N'The subscription is being deleted', 16, 1) return; END -- Insert into the notification table insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) values ( NewID(), @SubscriptionID, @ActiveationID, @ReportID, NULL, @ExtensionSettings, @Locale, @Parameters, GETUTCDATE(), @LastRunTime, @DeliveryExtension, @OwnerID, 1, @Version ) GO GRANT EXECUTE ON [dbo].[CreateDataDrivenNotification] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateNewActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateNewActiveSubscription] GO CREATE PROCEDURE [dbo].[CreateNewActiveSubscription] @ActiveID uniqueidentifier, @SubscriptionID uniqueidentifier AS -- Insert into the activesubscription table insert into [ActiveSubscriptions] ( [ActiveID], [SubscriptionID], [TotalNotifications], [TotalSuccesses], [TotalFailures] ) values ( @ActiveID, @SubscriptionID, NULL, 0, 0 ) GO GRANT EXECUTE ON [dbo].[CreateNewActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateActiveSubscription] GO CREATE PROCEDURE [dbo].[UpdateActiveSubscription] @ActiveID uniqueidentifier, @TotalNotifications int = NULL, @TotalSuccesses int = NULL, @TotalFailures int = NULL AS if @TotalNotifications is not NULL begin update ActiveSubscriptions set TotalNotifications = @TotalNotifications where ActiveID = @ActiveID end if @TotalSuccesses is not NULL begin update ActiveSubscriptions set TotalSuccesses = @TotalSuccesses where ActiveID = @ActiveID end if @TotalFailures is not NULL begin update ActiveSubscriptions set TotalFailures = @TotalFailures where ActiveID = @ActiveID end GO GRANT EXECUTE ON [dbo].[UpdateActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteActiveSubscription] GO CREATE PROCEDURE [dbo].[DeleteActiveSubscription] @ActiveID uniqueidentifier AS delete from ActiveSubscriptions where ActiveID = @ActiveID GO GRANT EXECUTE ON [dbo].[DeleteActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAndHoldLockActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAndHoldLockActiveSubscription] GO CREATE PROCEDURE [dbo].[GetAndHoldLockActiveSubscription] @ActiveID uniqueidentifier AS select TotalNotifications, TotalSuccesses, TotalFailures from ActiveSubscriptions with (XLOCK) where ActiveID = @ActiveID GO GRANT EXECUTE ON [dbo].[GetAndHoldLockActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateCacheUpdateNotifications]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateCacheUpdateNotifications] GO CREATE PROCEDURE [dbo].[CreateCacheUpdateNotifications] @ReportID uniqueidentifier, @LastRunTime datetime AS update [Subscriptions] set [LastRunTime] = @LastRunTime from [Subscriptions] S where S.[Report_OID] = @ReportID and S.EventType = 'SnapshotUpdated' and InactiveFlags = 0 -- Find all valid subscriptions for the given report and create a new notification row for -- each subscription insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) select NewID(), S.[SubscriptionID], NULL, S.[Report_OID], NULL, S.[ExtensionSettings], S.[Locale], S.[Parameters], GETUTCDATE(), S.[LastRunTime], S.[DeliveryExtension], S.[OwnerID], 0, S.[Version] from [Subscriptions] S inner join Catalog C on S.[Report_OID] = C.[ItemID] where C.[ItemID] = @ReportID and S.EventType = 'SnapshotUpdated' and InactiveFlags = 0 and S.[DataSettings] is null -- Create any data driven subscription by creating a data driven event insert into [Event] ( [EventID], [EventType], [EventData], [TimeEntered] ) select NewID(), 'DataDrivenSubscription', S.SubscriptionID, GETUTCDATE() from [Subscriptions] S inner join Catalog C on S.[Report_OID] = C.[ItemID] where C.[ItemID] = @ReportID and S.EventType = 'SnapshotUpdated' and InactiveFlags = 0 and S.[DataSettings] is not null GO GRANT EXECUTE ON [dbo].[CreateCacheUpdateNotifications] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCacheSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetCacheSchedule] GO CREATE PROCEDURE [dbo].[GetCacheSchedule] @ReportID uniqueidentifier AS SELECT S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], Owner.[AuthType], RS.ReportAction FROM Schedule S with (XLOCK) inner join ReportSchedule RS on S.ScheduleID = RS.ScheduleID inner join [Users] Owner on S.[CreatedById] = Owner.[UserID] WHERE (RS.ReportAction = 1 or RS.ReportAction = 3) and -- 1 == UpdateCache, 3 == Invalidate cache RS.[ReportID] = @ReportID GO GRANT EXECUTE ON [dbo].[GetCacheSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteNotification]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteNotification] GO CREATE PROCEDURE [dbo].[DeleteNotification] @ID uniqueidentifier AS delete from [Notifications] where [NotificationID] = @ID GO GRANT EXECUTE ON [dbo].[DeleteNotification] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetNotificationAttempt]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetNotificationAttempt] GO CREATE PROCEDURE [dbo].[SetNotificationAttempt] @Attempt int, @SecondsToAdd int, @NotificationID uniqueidentifier AS update [Notifications] set [ProcessStart] = NULL, [Attempt] = @Attempt, [ProcessAfter] = DateAdd(second, @SecondsToAdd, GetUtcDate()) where [NotificationID] = @NotificationID GO GRANT EXECUTE ON [dbo].[SetNotificationAttempt] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateTimeBasedSubscriptionNotification]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateTimeBasedSubscriptionNotification] GO CREATE PROCEDURE [dbo].[CreateTimeBasedSubscriptionNotification] @SubscriptionID uniqueidentifier, @LastRunTime datetime as insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) select NewID(), S.[SubscriptionID], NULL, S.[Report_OID], NULL, S.[ExtensionSettings], S.[Locale], S.[Parameters], GETUTCDATE(), @LastRunTime, S.[DeliveryExtension], S.[OwnerID], 0, S.[Version] from [Subscriptions] S where S.[SubscriptionID] = @SubscriptionID and InactiveFlags = 0 and S.[DataSettings] is null -- Create any data driven subscription by creating a data driven event insert into [Event] ( [EventID], [EventType], [EventData], [TimeEntered] ) select NewID(), 'DataDrivenSubscription', S.SubscriptionID, GETUTCDATE() from [Subscriptions] S where S.[SubscriptionID] = @SubscriptionID and InactiveFlags = 0 and S.[DataSettings] is not null update [Subscriptions] set [LastRunTime] = @LastRunTime where [SubscriptionID] = @SubscriptionID and InactiveFlags = 0 GO GRANT EXECUTE ON [dbo].[CreateTimeBasedSubscriptionNotification] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteTimeBasedSubscriptionSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteTimeBasedSubscriptionSchedule] GO CREATE PROCEDURE [dbo].[DeleteTimeBasedSubscriptionSchedule] @SubscriptionID as uniqueidentifier as delete ReportSchedule from ReportSchedule RS inner join Subscriptions S on S.[SubscriptionID] = RS.[SubscriptionID] where S.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[DeleteTimeBasedSubscriptionSchedule] TO RSExecRole GO -------------------------------------------------- ------------- Provider Info if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListUsedDeliveryProviders]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListUsedDeliveryProviders] GO CREATE PROCEDURE [dbo].[ListUsedDeliveryProviders] AS select distinct [DeliveryExtension] from Subscriptions where [DeliveryExtension] <> '' GO GRANT EXECUTE ON [dbo].[ListUsedDeliveryProviders] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id('[dbo].[AddBatchRecord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddBatchRecord] GO CREATE PROCEDURE [dbo].[AddBatchRecord] @BatchID uniqueidentifier, @UserName nvarchar(260), @Action varchar(32), @Item nvarchar(425) = NULL, @Parent nvarchar(425) = NULL, @Param nvarchar(425) = NULL, @BoolParam bit = NULL, @Content image = NULL, @Properties ntext = NULL AS IF @Action='BatchStart' BEGIN INSERT INTO [Batch] (BatchID, AddedOn, [Action], Item, Parent, Param, BoolParam, Content, Properties) VALUES (@BatchID, GETUTCDATE(), @Action, @UserName, @Parent, @Param, @BoolParam, @Content, @Properties) END ELSE BEGIN IF EXISTS (SELECT * FROM Batch WHERE BatchID = @BatchID AND [Action] = 'BatchStart' AND Item = @UserName) BEGIN INSERT INTO [Batch] (BatchID, AddedOn, [Action], Item, Parent, Param, BoolParam, Content, Properties) VALUES (@BatchID, GETUTCDATE(), @Action, @Item, @Parent, @Param, @BoolParam, @Content, @Properties) END ELSE BEGIN RAISERROR( 'Batch does not exist', 16, 1 ) END END GO GRANT EXECUTE ON [dbo].[AddBatchRecord] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[GetBatchRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetBatchRecords] GO CREATE PROCEDURE [dbo].[GetBatchRecords] @BatchID uniqueidentifier AS SELECT [Action], Item, Parent, Param, BoolParam, Content, Properties FROM [Batch] WHERE BatchID = @BatchID ORDER BY AddedOn GO GRANT EXECUTE ON [dbo].[GetBatchRecords] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteBatchRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteBatchRecords] GO CREATE PROCEDURE [dbo].[DeleteBatchRecords] @BatchID uniqueidentifier AS DELETE FROM [Batch] WHERE BatchID = @BatchID GO GRANT EXECUTE ON [dbo].[DeleteBatchRecords] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanBatchRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanBatchRecords] GO CREATE PROCEDURE [dbo].[CleanBatchRecords] @MaxAgeMinutes int AS DELETE FROM [Batch] where BatchID in ( SELECT BatchID FROM [Batch] WHERE AddedOn < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) ) GO GRANT EXECUTE ON [dbo].[CleanBatchRecords] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanOrphanedPolicies]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanOrphanedPolicies] GO -- Cleaning orphan policies CREATE PROCEDURE [dbo].[CleanOrphanedPolicies] AS DELETE [Policies] WHERE [Policies].[PolicyFlag] = 0 AND NOT EXISTS (SELECT ItemID FROM [Catalog] WHERE [Catalog].[PolicyID] = [Policies].[PolicyID]) DELETE [Policies] FROM [Policies] INNER JOIN [ModelItemPolicy] ON [ModelItemPolicy].[PolicyID] = [Policies].[PolicyID] WHERE NOT EXISTS (SELECT ItemID FROM [Catalog] WHERE [Catalog].[ItemID] = [ModelItemPolicy].[CatalogItemID]) GO GRANT EXECUTE ON [dbo].[CleanOrphanedPolicies] TO RSExecRole GO -------------------------------------------------- ------------- Snapshot manipulation if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[IncreaseTransientSnapshotRefcount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[IncreaseTransientSnapshotRefcount] GO CREATE PROCEDURE [dbo].[IncreaseTransientSnapshotRefcount] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @ExpirationMinutes as int AS DECLARE @soon AS datetime SET @soon = DATEADD(n, @ExpirationMinutes, GETDATE()) if @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET ExpirationDate = @soon, TransientRefcount = TransientRefcount + 1 WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET ExpirationDate = @soon, TransientRefcount = TransientRefcount + 1 WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[IncreaseTransientSnapshotRefcount] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DecreaseTransientSnapshotRefcount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DecreaseTransientSnapshotRefcount] GO CREATE PROCEDURE [dbo].[DecreaseTransientSnapshotRefcount] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS if @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET TransientRefcount = TransientRefcount - 1 WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET TransientRefcount = TransientRefcount - 1 WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[DecreaseTransientSnapshotRefcount] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[MarkSnapshotAsDependentOnUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[MarkSnapshotAsDependentOnUser] GO CREATE PROCEDURE [dbo].[MarkSnapshotAsDependentOnUser] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS if @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET DependsOnUser = 1 WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET DependsOnUser = 1 WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[MarkSnapshotAsDependentOnUser] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSnapshotProcessingFlags]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSnapshotProcessingFlags] GO CREATE PROCEDURE [dbo].[SetSnapshotProcessingFlags] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @ProcessingFlags int AS if @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET ProcessingFlags = @ProcessingFlags WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET ProcessingFlags = @ProcessingFlags WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[SetSnapshotProcessingFlags] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSnapshotChunksVersion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSnapshotChunksVersion] GO CREATE PROCEDURE [dbo].[SetSnapshotChunksVersion] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @Version as smallint AS declare @affectedRows int set @affectedRows = 0 if @IsPermanentSnapshot = 1 BEGIN if @Version > 0 BEGIN UPDATE ChunkData SET Version = @Version WHERE SnapshotDataID = @SnapshotDataID SELECT @affectedRows = @affectedRows + @@rowcount UPDATE SegmentedChunk SET Version = @Version WHERE SnapshotDataId = @SnapshotDataID SELECT @affectedRows = @affectedRows + @@rowcount END ELSE BEGIN UPDATE ChunkData SET Version = Version WHERE SnapshotDataID = @SnapshotDataID SELECT @affectedRows = @affectedRows + @@rowcount UPDATE SegmentedChunk SET Version = Version WHERE SnapshotDataId = @SnapshotDataID SELECT @affectedRows = @affectedRows + @@rowcount END END ELSE BEGIN if @Version > 0 BEGIN UPDATE ReportServerTempDB.dbo.ChunkData SET Version = @Version WHERE SnapshotDataID = @SnapshotDataID SELECT @affectedRows = @affectedRows + @@rowcount UPDATE ReportServerTempDB.dbo.SegmentedChunk SET Version = @Version WHERE SnapshotDataId = @SnapshotDataID SELECT @affectedRows = @affectedRows + @@rowcount END ELSE BEGIN UPDATE ReportServerTempDB.dbo.ChunkData SET Version = Version WHERE SnapshotDataID = @SnapshotDataID SELECT @affectedRows = @affectedRows + @@rowcount UPDATE ReportServerTempDB.dbo.SegmentedChunk SET Version = Version WHERE SnapshotDataId = @SnapshotDataID SELECT @affectedRows = @affectedRows + @@rowcount END END SELECT @affectedRows GO GRANT EXECUTE ON [dbo].[SetSnapshotChunksVersion] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[LockSnapshotForUpgrade]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[LockSnapshotForUpgrade] GO CREATE PROCEDURE [dbo].[LockSnapshotForUpgrade] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS if @IsPermanentSnapshot = 1 BEGIN SELECT ChunkName from ChunkData with (XLOCK) WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN SELECT ChunkName from ReportServerTempDB.dbo.ChunkData with (XLOCK) WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[LockSnapshotForUpgrade] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[InsertUnreferencedSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[InsertUnreferencedSnapshot] GO CREATE PROCEDURE [dbo].[InsertUnreferencedSnapshot] @ReportID as uniqueidentifier = NULL, @EffectiveParams as ntext = NULL, @QueryParams as ntext = NULL, @ParamsHash as int = NULL, @CreatedDate as datetime, @Description as nvarchar(512) = NULL, @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @ProcessingFlags as int, @SnapshotTimeoutMinutes as int, @Machine as nvarchar(512) = NULL AS DECLARE @now datetime SET @now = GETDATE() IF @IsPermanentSnapshot = 1 BEGIN INSERT INTO SnapshotData (SnapshotDataID, CreatedDate, EffectiveParams, QueryParams, ParamsHash, Description, PermanentRefcount, TransientRefcount, ExpirationDate, ProcessingFlags) VALUES (@SnapshotDataID, @CreatedDate, @EffectiveParams, @QueryParams, @ParamsHash, @Description, 0, 1, DATEADD(n, @SnapshotTimeoutMinutes, @now), @ProcessingFlags) END ELSE BEGIN INSERT INTO ReportServerTempDB.dbo.SnapshotData (SnapshotDataID, CreatedDate, EffectiveParams, QueryParams, ParamsHash, Description, PermanentRefcount, TransientRefcount, ExpirationDate, Machine, ProcessingFlags) VALUES (@SnapshotDataID, @CreatedDate, @EffectiveParams, @QueryParams, @ParamsHash, @Description, 0, 1, DATEADD(n, @SnapshotTimeoutMinutes, @now), @Machine, @ProcessingFlags) END GO GRANT EXECuTE ON [dbo].[InsertUnreferencedSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[PromoteSnapshotInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[PromoteSnapshotInfo] GO CREATE PROCEDURE [dbo].[PromoteSnapshotInfo] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @PageCount as int, @HasDocMap as bit, @PaginationMode as smallint, @ProcessingFlags as int AS -- HasDocMap: Processing engine may not -- compute this flag in all cases, which -- can lead to it being false when passed into -- this proc, however the server needs this -- flag to be true if it was ever set to be -- true in order to communicate that there is a -- document map to the viewer control. IF @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET PageCount = @PageCount, HasDocMap = COALESCE(@HasDocMap | HasDocMap, @HasDocMap), PaginationMode = @PaginationMode, ProcessingFlags = @ProcessingFlags WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET PageCount = @PageCount, HasDocMap = COALESCE(@HasDocMap | HasDocMap, @HasDocMap), PaginationMode = @PaginationMode, ProcessingFlags = @ProcessingFlags WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[PromoteSnapshotInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSnapshotPaginationInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSnapshotPaginationInfo] GO CREATE PROCEDURE [dbo].[UpdateSnapshotPaginationInfo] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @PageCount as int, @PaginationMode as smallint AS IF @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET PageCount = @PageCount, PaginationMode = @PaginationMode WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET PageCount = @PageCount, PaginationMode = @PaginationMode WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[UpdateSnapshotPaginationInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapshotPromotedInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapshotPromotedInfo] GO CREATE PROCEDURE [dbo].[GetSnapshotPromotedInfo] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS IF @IsPermanentSnapshot = 1 BEGIN SELECT PageCount, HasDocMap, PaginationMode, ProcessingFlags FROM SnapshotData WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN SELECT PageCount, HasDocMap, PaginationMode, ProcessingFlags FROM ReportServerTempDB.dbo.SnapshotData WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[GetSnapshotPromotedInfo] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[AddHistoryRecord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddHistoryRecord] GO -- add new record to History table CREATE PROCEDURE [dbo].[AddHistoryRecord] @HistoryID uniqueidentifier, @ReportID uniqueidentifier, @SnapshotDate datetime, @SnapshotDataID uniqueidentifier, @SnapshotTransientRefcountChange int AS INSERT INTO History (HistoryID, ReportID, SnapshotDataID, SnapshotDate) VALUES (@HistoryID, @ReportID, @SnapshotDataID, @SnapshotDate) IF @@ERROR = 0 BEGIN UPDATE SnapshotData -- Snapshots, when created, have transient refcount set to 1. Here create permanent reference -- here so we need to increase permanent refcount and decrease transient refcount. However, -- if it was already referenced by the execution snapshot, transient refcount was already -- decreased. Hence, there's a parameter @SnapshotTransientRefcountChange that is 0 or -1. SET PermanentRefcount = PermanentRefcount + 1, TransientRefcount = TransientRefcount + @SnapshotTransientRefcountChange WHERE SnapshotData.SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[AddHistoryRecord] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[SetHistoryLimit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetHistoryLimit] GO CREATE PROCEDURE [dbo].[SetHistoryLimit] @Path nvarchar (425), @SnapshotLimit int = NULL AS UPDATE Catalog SET SnapshotLimit=@SnapshotLimit WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[SetHistoryLimit] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[ListHistory]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListHistory] GO -- list all historical snapshots for a specific report CREATE PROCEDURE [dbo].[ListHistory] @ReportID uniqueidentifier AS SELECT S.SnapshotDate, ISNULL((SELECT SUM(DATALENGTH( CD.Content ) ) FROM ChunkData AS CD WHERE CD.SnapshotDataID = S.SnapshotDataID ), 0) + ISNULL( ( SELECT SUM(DATALENGTH( SEG.Content) ) FROM Segment SEG WITH(NOLOCK) JOIN ChunkSegmentMapping CSM WITH(NOLOCK) ON (CSM.SegmentId = SEG.SegmentId) JOIN SegmentedChunk C WITH(NOLOCK) ON (C.ChunkId = CSM.ChunkId AND C.SnapshotDataId = S.SnapshotDataId) ), 0) FROM History AS S -- skipping intermediate table SnapshotData WHERE S.ReportID = @ReportID GO GRANT EXECUTE ON [dbo].[ListHistory] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanHistoryForReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanHistoryForReport] GO -- delete snapshots exceeding # of snapshots. won't work if @SnapshotLimit = 0 CREATE PROCEDURE [dbo].[CleanHistoryForReport] @SnapshotLimit int, @ReportID uniqueidentifier AS DECLARE @cmd varchar(2000) SET @cmd = 'DELETE FROM History WHERE ReportID = ''' + cast(@ReportID as varchar(40) ) + ''' and SnapshotDate < (SELECT MIN(SnapshotDate) FROM (SELECT TOP ' + CAST(@SnapshotLimit as varchar(20)) + ' SnapshotDate FROM History WHERE ReportID = ''' + cast(@ReportID as varchar(40) ) + ''' ORDER BY SnapshotDate DESC ) AS TopSnapshots )' EXEC( @cmd ) GO GRANT EXECUTE ON [dbo].[CleanHistoryForReport] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanAllHistories]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanAllHistories] GO -- delete snapshots exceeding # of snapshots for the whole system CREATE PROCEDURE [dbo].[CleanAllHistories] @SnapshotLimit int AS DECLARE @cmd varchar(2000) SET @cmd = 'DELETE FROM History WHERE HistoryID in (SELECT HistoryID FROM History JOIN Catalog AS ReportJoinSnapshot ON ItemID = ReportID WHERE SnapshotLimit is NULL and SnapshotDate < (SELECT MIN(SnapshotDate) FROM (SELECT TOP ' + CAST(@SnapshotLimit as varchar(20)) + ' SnapshotDate FROM History AS InnerSnapshot WHERE InnerSnapshot.ReportID = ReportJoinSnapshot.ItemID ORDER BY SnapshotDate DESC ) AS TopSnapshots ) )' EXEC( @cmd ) GO GRANT EXECUTE ON [dbo].[CleanAllHistories] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteHistoryRecord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteHistoryRecord] GO -- delete one historical snapshot CREATE PROCEDURE [dbo].[DeleteHistoryRecord] @ReportID uniqueidentifier, @SnapshotDate DateTime AS DELETE FROM History WHERE ReportID = @ReportID AND SnapshotDate = @SnapshotDate GO GRANT EXECUTE ON [dbo].[DeleteHistoryRecord] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteAllHistoryForReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteAllHistoryForReport] GO -- delete all snapshots for a report CREATE PROCEDURE [dbo].[DeleteAllHistoryForReport] @ReportID uniqueidentifier AS DELETE FROM History WHERE HistoryID in (SELECT HistoryID FROM History JOIN Catalog on ItemID = ReportID WHERE ReportID = @ReportID ) GO GRANT EXECUTE ON [dbo].[DeleteAllHistoryForReport] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteHistoriesWithNoPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteHistoriesWithNoPolicy] GO -- delete all snapshots for all reports that inherit system History policy CREATE PROCEDURE [dbo].[DeleteHistoriesWithNoPolicy] AS DELETE FROM History WHERE HistoryID in (SELECT HistoryID FROM History JOIN Catalog on ItemID = ReportID WHERE SnapshotLimit is null ) GO GRANT EXECUTE ON [dbo].[DeleteHistoriesWithNoPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Get_sqlagent_job_status]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[Get_sqlagent_job_status] GO CREATE PROCEDURE [dbo].[Get_sqlagent_job_status] -- Individual job parameters @job_id UNIQUEIDENTIFIER = NULL, -- If provided will only return info about this job -- Note: Only @job_id or @job_name needs to be provided @job_name sysname = NULL, -- If provided will only return info about this job @owner_login_name sysname = NULL -- If provided will only return jobs for this owner AS BEGIN DECLARE @retval INT DECLARE @job_owner_sid VARBINARY(85) DECLARE @is_sysadmin INT SET NOCOUNT ON -- Remove any leading/trailing spaces from parameters (except @owner_login_name) SELECT @job_name = LTRIM(RTRIM(@job_name)) -- Turn [nullable] empty string parameters into NULLs IF (@job_name = N'') SELECT @job_name = NULL -- Verify the job if supplied. This also checks if the caller has rights to view the job IF ((@job_id IS NOT NULL) OR (@job_name IS NOT NULL)) BEGIN EXECUTE @retval = msdb..sp_verify_job_identifiers '@job_name', '@job_id', @job_name OUTPUT, @job_id OUTPUT IF (@retval <> 0) RETURN(1) -- Failure END -- If the login name isn't given, set it to the job owner or the current caller IF(@owner_login_name IS NULL) BEGIN SET @owner_login_name = (SELECT SUSER_SNAME(sj.owner_sid) FROM msdb.dbo.sysjobs sj where sj.job_id = @job_id) SET @is_sysadmin = ISNULL(IS_SRVROLEMEMBER(N'sysadmin', @owner_login_name), 0) END ELSE BEGIN -- Check owner IF (SUSER_SID(@owner_login_name) IS NULL) BEGIN RAISERROR(14262, -1, -1, '@owner_login_name', @owner_login_name) RETURN(1) -- Failure END --only allow sysadmin types to specify the owner IF ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1) AND (ISNULL(IS_MEMBER(N'SQLAgentAdminRole'), 0) = 1) AND (SUSER_SNAME() <> @owner_login_name)) BEGIN --TODO: RAISERROR(14525, -1, -1) RETURN(1) -- Failure END SET @is_sysadmin = 0 END IF (@job_id IS NOT NULL) BEGIN -- Individual job... EXECUTE @retval = master.dbo.xp_sqlagent_enum_jobs @is_sysadmin, @owner_login_name, @job_id IF (@retval <> 0) RETURN(1) -- Failure END ELSE BEGIN -- Set of jobs... EXECUTE @retval = master.dbo.xp_sqlagent_enum_jobs @is_sysadmin, @owner_login_name IF (@retval <> 0) RETURN(1) -- Failure END RETURN(0) -- Success END GO GRANT EXECUTE ON [dbo].[Get_sqlagent_job_status] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateTask] GO CREATE PROCEDURE [dbo].[CreateTask] @ScheduleID uniqueidentifier, @Name nvarchar (260), @StartDate datetime, @Flags int, @NextRunTime datetime = NULL, @LastRunTime datetime = NULL, @EndDate datetime = NULL, @RecurrenceType int = NULL, @MinutesInterval int = NULL, @DaysInterval int = NULL, @WeeksInterval int = NULL, @DaysOfWeek int = NULL, @DaysOfMonth int = NULL, @Month int = NULL, @MonthlyWeek int = NULL, @State int = NULL, @LastRunStatus nvarchar (260) = NULL, @ScheduledRunTimeout int = NULL, @UserSid varbinary (85) = null, @UserName nvarchar(260), @AuthType int, @EventType nvarchar (260), @EventData nvarchar (260), @Type int , @Path nvarchar (425) = NULL AS DECLARE @UserID uniqueidentifier EXEC GetUserID @UserSid, @UserName, @AuthType, @UserID OUTPUT -- Create a task with the given data. Insert into Schedule ( [ScheduleID], [Name], [StartDate], [Flags], [NextRunTime], [LastRunTime], [EndDate], [RecurrenceType], [MinutesInterval], [DaysInterval], [WeeksInterval], [DaysOfWeek], [DaysOfMonth], [Month], [MonthlyWeek], [State], [LastRunStatus], [ScheduledRunTimeout], [CreatedById], [EventType], [EventData], [Type], [Path] ) values (@ScheduleID, @Name, @StartDate, @Flags, @NextRunTime, @LastRunTime, @EndDate, @RecurrenceType, @MinutesInterval, @DaysInterval, @WeeksInterval, @DaysOfWeek, @DaysOfMonth, @Month, @MonthlyWeek, @State, @LastRunStatus, @ScheduledRunTimeout, @UserID, @EventType, @EventData, @Type, @Path) GO GRANT EXECUTE ON [dbo].[CreateTask] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateTask] GO CREATE PROCEDURE [dbo].[UpdateTask] @ScheduleID uniqueidentifier, @Name nvarchar (260), @StartDate datetime, @Flags int, @NextRunTime datetime = NULL, @LastRunTime datetime = NULL, @EndDate datetime = NULL, @RecurrenceType int = NULL, @MinutesInterval int = NULL, @DaysInterval int = NULL, @WeeksInterval int = NULL, @DaysOfWeek int = NULL, @DaysOfMonth int = NULL, @Month int = NULL, @MonthlyWeek int = NULL, @State int = NULL, @LastRunStatus nvarchar (260) = NULL, @ScheduledRunTimeout int = NULL AS -- Update a tasks values. ScheduleID and Report information can not be updated Update Schedule set [StartDate] = @StartDate, [Name] = @Name, [Flags] = @Flags, [NextRunTime] = @NextRunTime, [LastRunTime] = @LastRunTime, [EndDate] = @EndDate, [RecurrenceType] = @RecurrenceType, [MinutesInterval] = @MinutesInterval, [DaysInterval] = @DaysInterval, [WeeksInterval] = @WeeksInterval, [DaysOfWeek] = @DaysOfWeek, [DaysOfMonth] = @DaysOfMonth, [Month] = @Month, [MonthlyWeek] = @MonthlyWeek, [State] = @State, [LastRunStatus] = @LastRunStatus, [ScheduledRunTimeout] = @ScheduledRunTimeout where [ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[UpdateTask] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateScheduleNextRunTime]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateScheduleNextRunTime] GO CREATE PROCEDURE [dbo].[UpdateScheduleNextRunTime] @ScheduleID as uniqueidentifier, @NextRunTime as datetime as update Schedule set [NextRunTime] = @NextRunTime where [ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[UpdateScheduleNextRunTime] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListScheduledReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListScheduledReports] GO CREATE PROCEDURE [dbo].[ListScheduledReports] @ScheduleID uniqueidentifier AS -- List all reports for a schedule select RS.[ReportAction], RS.[ScheduleID], RS.[ReportID], RS.[SubscriptionID], C.[Path], C.[Name], C.[Description], C.[ModifiedDate], SUSER_SNAME(U.[Sid]), U.[UserName], DATALENGTH( C.Content ), C.ExecutionTime, S.[Type], SD.[NtSecDescPrimary] from [ReportSchedule] RS Inner join [Catalog] C on RS.[ReportID] = C.[ItemID] Inner join [Schedule] S on RS.[ScheduleID] = S.[ScheduleID] Inner join [Users] U on C.[ModifiedByID] = U.UserID left outer join [SecData] SD on SD.[PolicyID] = C.[PolicyID] AND SD.AuthType = U.AuthType where RS.[ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[ListScheduledReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListTasks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListTasks] GO CREATE PROCEDURE [dbo].[ListTasks] @Path nvarchar (425) = NULL, @Prefix nvarchar (425) = NULL AS select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], Owner.[AuthType], (select count(*) from ReportSchedule where ReportSchedule.ScheduleID = S.ScheduleID) from [Schedule] S inner join [Users] Owner on S.[CreatedById] = Owner.UserID where S.[Type] = 0 /*Type 0 is shared schedules*/ and ((@Path is null) OR (S.Path = @Path) or (S.Path like @Prefix escape '*')) GO GRANT EXECUTE ON [dbo].[ListTasks] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListTasksForMaintenance]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListTasksForMaintenance] GO CREATE PROCEDURE [dbo].[ListTasksForMaintenance] AS declare @date datetime set @date = GETUTCDATE() update [Schedule] set [ConsistancyCheck] = @date from ( SELECT TOP 20 [ScheduleID] FROM [Schedule] WITH(UPDLOCK) WHERE [ConsistancyCheck] is NULL ) AS t1 WHERE [Schedule].[ScheduleID] = t1.[ScheduleID] select top 20 S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path] from [Schedule] S where [ConsistancyCheck] = @date GO GRANT EXECUTE ON [dbo].[ListTasksForMaintenance] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ClearScheduleConsistancyFlags]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ClearScheduleConsistancyFlags] GO CREATE PROCEDURE [dbo].[ClearScheduleConsistancyFlags] AS update [Schedule] with (tablock, xlock) set [ConsistancyCheck] = NULL GO GRANT EXECUTE ON [dbo].[ClearScheduleConsistancyFlags] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAReportsReportAction]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAReportsReportAction] GO CREATE PROCEDURE [dbo].[GetAReportsReportAction] @ReportID uniqueidentifier, @ReportAction int AS select RS.[ReportAction], RS.[ScheduleID], RS.[ReportID], RS.[SubscriptionID], C.[Path] from [ReportSchedule] RS Inner join [Catalog] C on RS.[ReportID] = C.[ItemID] where C.ItemID = @ReportID and RS.[ReportAction] = @ReportAction GO GRANT EXECUTE ON [dbo].[GetAReportsReportAction] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetTimeBasedSubscriptionReportAction]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetTimeBasedSubscriptionReportAction] GO CREATE PROCEDURE [dbo].[GetTimeBasedSubscriptionReportAction] @SubscriptionID uniqueidentifier AS select RS.[ReportAction], RS.[ScheduleID], RS.[ReportID], RS.[SubscriptionID], C.[Path] from [ReportSchedule] RS Inner join [Catalog] C on RS.[ReportID] = C.[ItemID] where RS.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetTimeBasedSubscriptionReportAction] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetTaskProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetTaskProperties] GO CREATE PROCEDURE [dbo].[GetTaskProperties] @ScheduleID uniqueidentifier AS -- Grab all of a tasks properties given a task id select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], Owner.[AuthType] from [Schedule] S with (XLOCK) Inner join [Users] Owner on S.[CreatedById] = Owner.UserID where S.[ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[GetTaskProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteTask] GO CREATE PROCEDURE [dbo].[DeleteTask] @ScheduleID uniqueidentifier AS -- Delete the task with the given task id DELETE FROM Schedule WHERE [ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[DeleteTask] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSchedulesReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSchedulesReports] GO CREATE PROCEDURE [dbo].[GetSchedulesReports] @ID uniqueidentifier AS select C.Path from ReportSchedule RS inner join Catalog C on (C.ItemID = RS.ReportID) where ScheduleID = @ID GO GRANT EXECUTE ON [dbo].[GetSchedulesReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddReportSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddReportSchedule] GO CREATE PROCEDURE [dbo].[AddReportSchedule] @ScheduleID uniqueidentifier, @ReportID uniqueidentifier, @SubscriptionID uniqueidentifier = NULL, @Action int AS Insert into ReportSchedule ([ScheduleID], [ReportID], [SubscriptionID], [ReportAction]) values (@ScheduleID, @ReportID, @SubscriptionID, @Action) GO GRANT EXECUTE ON [dbo].[AddReportSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteReportSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteReportSchedule] GO CREATE PROCEDURE [dbo].[DeleteReportSchedule] @ScheduleID uniqueidentifier, @ReportID uniqueidentifier, @SubscriptionID uniqueidentifier = NULL, @ReportAction int AS IF @SubscriptionID is NULL BEGIN delete from ReportSchedule where ScheduleID = @ScheduleID and ReportID = @ReportID and ReportAction = @ReportAction END ELSE BEGIN delete from ReportSchedule where ScheduleID = @ScheduleID and ReportID = @ReportID and ReportAction = @ReportAction and SubscriptionID = @SubscriptionID END GO GRANT EXECUTE ON [dbo].[DeleteReportSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapShotSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapShotSchedule] GO CREATE PROCEDURE [dbo].[GetSnapShotSchedule] @ReportID uniqueidentifier AS select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], Owner.[AuthType] from Schedule S with (XLOCK) inner join ReportSchedule RS on S.ScheduleID = RS.ScheduleID inner join [Users] Owner on S.[CreatedById] = Owner.[UserID] where RS.ReportAction = 2 and -- 2 == create snapshot RS.ReportID = @ReportID GO GRANT EXECUTE ON [dbo].[GetSnapShotSchedule] TO RSExecRole GO -------------------------------------------------- ------------- Time based subscriptions if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateTimeBasedSubscriptionSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateTimeBasedSubscriptionSchedule] GO CREATE PROCEDURE [dbo].[CreateTimeBasedSubscriptionSchedule] @SubscriptionID as uniqueidentifier, @ScheduleID uniqueidentifier, @Schedule_Name nvarchar (260), @Report_Name nvarchar (425), @StartDate datetime, @Flags int, @NextRunTime datetime = NULL, @LastRunTime datetime = NULL, @EndDate datetime = NULL, @RecurrenceType int = NULL, @MinutesInterval int = NULL, @DaysInterval int = NULL, @WeeksInterval int = NULL, @DaysOfWeek int = NULL, @DaysOfMonth int = NULL, @Month int = NULL, @MonthlyWeek int = NULL, @State int = NULL, @LastRunStatus nvarchar (260) = NULL, @ScheduledRunTimeout int = NULL, @UserSid varbinary (85) = NULL, @UserName nvarchar(260), @AuthType int, @EventType nvarchar (260), @EventData nvarchar (260), @Path nvarchar (425) = NULL AS EXEC CreateTask @ScheduleID, @Schedule_Name, @StartDate, @Flags, @NextRunTime, @LastRunTime, @EndDate, @RecurrenceType, @MinutesInterval, @DaysInterval, @WeeksInterval, @DaysOfWeek, @DaysOfMonth, @Month, @MonthlyWeek, @State, @LastRunStatus, @ScheduledRunTimeout, @UserSid, @UserName, @AuthType, @EventType, @EventData, 1 /*scoped type*/, @Path if @@ERROR = 0 begin -- add a row to the reportSchedule table declare @Report_OID uniqueidentifier select @Report_OID = (select [ItemID] from [Catalog] with (HOLDLOCK) where [Catalog].[Path] = @Report_Name and ([Catalog].[Type] = 2 or [Catalog].[Type] = 4)) EXEC AddReportSchedule @ScheduleID, @Report_OID, @SubscriptionID, 4 -- TimedSubscription action end GO GRANT EXECUTE ON [dbo].[CreateTimeBasedSubscriptionSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetTimeBasedSubscriptionSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetTimeBasedSubscriptionSchedule] GO CREATE PROCEDURE [dbo].[GetTimeBasedSubscriptionSchedule] @SubscriptionID as uniqueidentifier AS select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], Owner.[AuthType] from [ReportSchedule] R inner join Schedule S with (XLOCK) on R.[ScheduleID] = S.[ScheduleID] Inner join [Users] Owner on S.[CreatedById] = Owner.UserID where R.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetTimeBasedSubscriptionSchedule] TO RSExecRole GO -------------------------------------------------- ------------- Running Jobs if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddRunningJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddRunningJob] GO CREATE PROCEDURE [dbo].[AddRunningJob] @JobID as nvarchar(32), @StartDate as datetime, @ComputerName as nvarchar(32), @RequestName as nvarchar(425), @RequestPath as nvarchar(425), @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @Description as ntext = NULL, @Timeout as int, @JobAction as smallint, @JobType as smallint, @JobStatus as smallint AS DECLARE @UserID uniqueidentifier EXEC GetUserID @UserSid, @UserName, @AuthType, @UserID OUTPUT INSERT INTO RunningJobs (JobID, StartDate, ComputerName, RequestName, RequestPath, UserID, Description, Timeout, JobAction, JobType, JobStatus ) VALUES (@JobID, @StartDate, @ComputerName, @RequestName, @RequestPath, @UserID, @Description, @Timeout, @JobAction, @JobType, @JobStatus) GO GRANT EXECUTE ON [dbo].[AddRunningJob] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RemoveRunningJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RemoveRunningJob] GO CREATE PROCEDURE [dbo].[RemoveRunningJob] @JobID as nvarchar(32) AS DELETE FROM RunningJobs WHERE JobID = @JobID GO GRANT EXECUTE ON [dbo].[RemoveRunningJob] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateRunningJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateRunningJob] GO CREATE PROCEDURE [dbo].[UpdateRunningJob] @JobID as nvarchar(32), @JobStatus as smallint AS UPDATE RunningJobs SET JobStatus = @JobStatus WHERE JobID = @JobID GO GRANT EXECUTE ON [dbo].[UpdateRunningJob] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetMyRunningJobs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetMyRunningJobs] GO CREATE PROCEDURE [dbo].[GetMyRunningJobs] @ComputerName as nvarchar(32), @JobType as smallint AS SELECT JobID, StartDate, ComputerName, RequestName, RequestPath, SUSER_SNAME(Users.[Sid]), Users.[UserName], Description, Timeout, JobAction, JobType, JobStatus, Users.[AuthType] FROM RunningJobs INNER JOIN Users ON RunningJobs.UserID = Users.UserID WHERE ComputerName = @ComputerName AND JobType = @JobType GO GRANT EXECUTE ON [dbo].[GetMyRunningJobs] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListRunningJobs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListRunningJobs] GO CREATE PROCEDURE [dbo].[ListRunningJobs] AS SELECT JobID, StartDate, ComputerName, RequestName, RequestPath, SUSER_SNAME(Users.[Sid]), Users.[UserName], Description, Timeout, JobAction, JobType, JobStatus, Users.[AuthType] FROM RunningJobs INNER JOIN Users ON RunningJobs.UserID = Users.UserID GO GRANT EXECUTE ON [dbo].[ListRunningJobs] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredJobs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredJobs] GO CREATE PROCEDURE [dbo].[CleanExpiredJobs] AS DELETE FROM RunningJobs WHERE DATEADD(s, Timeout, StartDate) < GETDATE() GO GRANT EXECUTE ON [dbo].[CleanExpiredJobs] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateObject]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateObject] GO -- This SP should never be called with a policy ID unless it is guarenteed that -- the parent will not be deleted before the insert (such as while running this script) CREATE PROCEDURE [dbo].[CreateObject] @ItemID uniqueidentifier, @Name nvarchar (425), @Path nvarchar (425), @ParentID uniqueidentifier, @Type int, @Content image = NULL, @Intermediate uniqueidentifier = NULL, @LinkSourceID uniqueidentifier = NULL, @Property ntext = NULL, @Parameter ntext = NULL, @Description ntext = NULL, @Hidden bit = NULL, @CreatedBySid varbinary(85) = NULL, @CreatedByName nvarchar(260), @AuthType int, @CreationDate datetime, @ModificationDate datetime, @MimeType nvarchar (260) = NULL, @SnapshotLimit int = NULL, @PolicyRoot int = 0, @PolicyID uniqueidentifier = NULL, @ExecutionFlag int = 1 -- allow live execution, don't keep history AS DECLARE @CreatedByID uniqueidentifier EXEC GetUserID @CreatedBySid, @CreatedByName, @AuthType, @CreatedByID OUTPUT UPDATE Catalog with (XLOCK) SET ModifiedByID = @CreatedByID, ModifiedDate = @ModificationDate WHERE ItemID = @ParentID -- If no policyID, use the parent's IF @PolicyID is NULL BEGIN SET @PolicyID = (SELECT PolicyID FROM [dbo].[Catalog] WHERE Catalog.ItemID = @ParentID) END -- If there is no policy ID then we are guarenteed not to have a parent IF @PolicyID is NULL BEGIN RAISERROR ('Parent Not Found', 16, 1) return END INSERT INTO Catalog (ItemID, Path, Name, ParentID, Type, Content, Intermediate, LinkSourceID, Property, Description, Hidden, CreatedByID, CreationDate, ModifiedByID, ModifiedDate, MimeType, SnapshotLimit, [Parameter], PolicyID, PolicyRoot, ExecutionFlag ) VALUES (@ItemID, @Path, @Name, @ParentID, @Type, @Content, @Intermediate, @LinkSourceID, @Property, @Description, @Hidden, @CreatedByID, @CreationDate, @CreatedByID, @ModificationDate, @MimeType, @SnapshotLimit, @Parameter, @PolicyID, @PolicyRoot , @ExecutionFlag) IF @Intermediate IS NOT NULL AND @@ERROR = 0 BEGIN UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount + 1, TransientRefcount = TransientRefcount - 1 WHERE SnapshotData.SnapshotDataID = @Intermediate END GO GRANT EXECUTE ON [dbo].[CreateObject] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteObject]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteObject] GO CREATE PROCEDURE [dbo].[DeleteObject] @Path nvarchar (425), @Prefix nvarchar (850) AS -- Remove reference for intermediate formats UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 FROM Catalog AS R WITH (XLOCK) INNER JOIN [SnapshotData] AS SD ON R.Intermediate = SD.SnapshotDataID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Remove reference for execution snapshots UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 FROM Catalog AS R WITH (XLOCK) INNER JOIN [SnapshotData] AS SD ON R.SnapshotDataID = SD.SnapshotDataID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Remove history for deleted reports and linked report DELETE History FROM [Catalog] AS R INNER JOIN [History] AS S ON R.ItemID = S.ReportID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Remove model drill reports DELETE ModelDrill FROM [Catalog] AS C INNER JOIN [ModelDrill] AS M ON C.ItemID = M.ReportID WHERE (C.Path = @Path OR C.Path LIKE @Prefix ESCAPE '*') -- Adjust data sources UPDATE [DataSource] SET [Flags] = [Flags] & 0x7FFFFFFD, -- broken link [Link] = NULL FROM [Catalog] AS C INNER JOIN [DataSource] AS DS ON C.[ItemID] = DS.[Link] WHERE (C.Path = @Path OR C.Path LIKE @Prefix ESCAPE '*') -- Clean all data sources DELETE [DataSource] FROM [Catalog] AS R INNER JOIN [DataSource] AS DS ON R.[ItemID] = DS.[ItemID] WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Update linked reports UPDATE LR SET LR.LinkSourceID = NULL FROM [Catalog] AS R INNER JOIN [Catalog] AS LR ON R.ItemID = LR.LinkSourceID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') AND (LR.Path NOT LIKE @Prefix ESCAPE '*') -- Remove references for cache entries UPDATE SN SET PermanentRefcount = PermanentRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC on SN.SnapshotDataID = EC.SnapshotDataID INNER JOIN Catalog AS C ON EC.ReportID = C.ItemID WHERE (Path = @Path OR Path LIKE @Prefix ESCAPE '*') -- Clean cache entries for items to be deleted DELETE EC FROM ReportServerTempDB.dbo.ExecutionCache AS EC INNER JOIN Catalog AS C ON EC.ReportID = C.ItemID WHERE (Path = @Path OR Path LIKE @Prefix ESCAPE '*') -- Finally delete items DELETE FROM [Catalog] WHERE (Path = @Path OR Path LIKE @Prefix ESCAPE '*') EXEC CleanOrphanedPolicies GO GRANT EXECUTE ON [dbo].[DeleteObject] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindObjectsNonRecursive]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindObjectsNonRecursive] GO CREATE PROCEDURE [dbo].[FindObjectsNonRecursive] @Path nvarchar (425), @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.[UserName], SUSER_SNAME(MU.Sid), MU.[UserName], C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Catalog AS P ON C.ParentID = P.ItemID INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE P.Path = @Path GO GRANT EXECUTE ON [dbo].[FindObjectsNonRecursive] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindObjectsRecursive]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindObjectsRecursive] GO CREATE PROCEDURE [dbo].[FindObjectsRecursive] @Prefix nvarchar (850), @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.UserName, SUSER_SNAME(MU.Sid), MU.UserName, C.MimeType, C.ExecutionTime, C.Hidden from Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE C.Path LIKE @Prefix ESCAPE '*' GO GRANT EXECUTE ON [dbo].[FindObjectsRecursive] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindParents]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindParents] GO CREATE PROCEDURE [dbo].[FindParents] @Path nvarchar (425), @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.[UserName], SUSER_SNAME(MU.Sid), MU.[UserName], C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE @Path LIKE C.Path + '/%' ORDER BY DATALENGTH(C.Path) desc GO GRANT EXECUTE ON [dbo].[FindParents] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindObjectsByLink]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindObjectsByLink] GO CREATE PROCEDURE [dbo].[FindObjectsByLink] @Link uniqueidentifier, @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.UserName, SUSER_SNAME(MU.Sid), MU.UserName, C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE C.LinkSourceID = @Link GO GRANT EXECUTE ON [dbo].[FindObjectsByLink] TO RSExecRole GO -------------------------------------------------- ------------- Procedures used to update linked reports if exists (select * from sysobjects where id = object_id('[dbo].[GetIDPairsByLink]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetIDPairsByLink] GO CREATE PROCEDURE [dbo].[GetIDPairsByLink] @Link uniqueidentifier AS SELECT LinkSourceID, ItemID FROM Catalog WHERE LinkSourceID = @Link GO GRANT EXECUTE ON [dbo].[GetIDPairsByLink] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[GetChildrenBeforeDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetChildrenBeforeDelete] GO CREATE PROCEDURE [dbo].[GetChildrenBeforeDelete] @Prefix nvarchar (850), @AuthType int AS SELECT C.PolicyID, C.Type, SD.NtSecDescPrimary FROM Catalog AS C LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE C.Path LIKE @Prefix ESCAPE '*' -- return children only, not item itself GO GRANT EXECUTE ON [dbo].[GetChildrenBeforeDelete] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAllProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAllProperties] GO CREATE PROCEDURE [dbo].[GetAllProperties] @Path nvarchar (425), @AuthType int AS select Property, Description, Type, DATALENGTH( Content ), ItemID, SUSER_SNAME(C.Sid), C.UserName, CreationDate, SUSER_SNAME(M.Sid), M.UserName, ModifiedDate, MimeType, ExecutionTime, NtSecDescPrimary, [LinkSourceID], Hidden, ExecutionFlag, SnapshotLimit, [Name] FROM Catalog INNER JOIN Users C ON Catalog.CreatedByID = C.UserID INNER JOIN Users M ON Catalog.ModifiedByID = M.UserID LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[GetAllProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetParameters] GO CREATE PROCEDURE [dbo].[GetParameters] @Path nvarchar (425), @AuthType int AS SELECT Type, [Parameter], ItemID, SecData.NtSecDescPrimary, [LinkSourceID], [ExecutionFlag] FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[GetParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetObjectContent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetObjectContent] GO CREATE PROCEDURE [dbo].[GetObjectContent] @Path nvarchar (425), @AuthType int AS SELECT Type, Content, LinkSourceID, MimeType, SecData.NtSecDescPrimary, ItemID FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[GetObjectContent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[LoadForDefinitionCheck]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[LoadForDefinitionCheck] GO -- For loading compiled definitions to check for internal republishing, this is -- done before calling GetCompiledDefinition or GetReportForExecution CREATE PROCEDURE [dbo].[LoadForDefinitionCheck] @Path nvarchar(425), @AcquireUpdateLocks bit, @AuthType int AS IF(@AcquireUpdateLocks = 0) BEGIN SELECT CompiledDefinition.SnapshotDataID, CompiledDefinition.ProcessingFlags, SecData.NtSecDescPrimary FROM Catalog MainItem LEFT OUTER JOIN SecData ON (MainItem.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType) LEFT OUTER JOIN Catalog LinkTarget WITH (INDEX = PK_CATALOG) ON (MainItem.LinkSourceID = LinkTarget.ItemID) JOIN SnapshotData CompiledDefinition ON (CompiledDefinition.SnapshotDataID = COALESCE(LinkTarget.Intermediate, MainItem.Intermediate)) WHERE MainItem.Path = @Path AND (MainItem.Type = 2 /* Report */ OR MainItem.Type = 4 /* Linked Report */) END ELSE BEGIN -- acquire upgrade locks, this means that the check is being perform in a -- different transaction context which will be committed before trying to -- perform the actual load, to prevent deadlock in the case where we have to -- republish this new transaction will acquire and hold upgrade locks SELECT CompiledDefinition.SnapshotDataID, CompiledDefinition.ProcessingFlags, SecData.NtSecDescPrimary FROM Catalog MainItem WITH(UPDLOCK ROWLOCK) LEFT OUTER JOIN SecData ON (MainItem.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType) LEFT OUTER JOIN Catalog LinkTarget WITH (UPDLOCK ROWLOCK INDEX = PK_CATALOG) ON (MainItem.LinkSourceID = LinkTarget.ItemID) JOIN SnapshotData CompiledDefinition WITH(UPDLOCK ROWLOCK) ON (CompiledDefinition.SnapshotDataID = COALESCE(LinkTarget.Intermediate, MainItem.Intermediate)) WHERE MainItem.Path = @Path AND (MainItem.Type = 2 /* Report */ OR MainItem.Type = 4 /* Linked Report */) END GO GRANT EXECUTE ON [dbo].[LoadForDefinitionCheck] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[LoadForRepublishing]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[LoadForRepublishing] GO -- Loads a report's RDL for republishing CREATE PROCEDURE [dbo].[LoadForRepublishing] @Path nvarchar(425) AS SELECT COALESCE(LinkTarget.Content, MainItem.Content) AS [Content], CompiledDefinition.SnapshotDataID, CompiledDefinition.ProcessingFlags FROM Catalog MainItem LEFT OUTER JOIN Catalog LinkTarget WITH (INDEX = PK_CATALOG) ON (MainItem.LinkSourceID = LinkTarget.ItemID) JOIN SnapshotData CompiledDefinition ON (CompiledDefinition.SnapshotDataID = COALESCE(LinkTarget.Intermediate, MainItem.Intermediate)) WHERE MainItem.Path = @Path GO GRANT EXECUTE ON [dbo].[LoadForRepublishing] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateCompiledDefinition]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateCompiledDefinition] GO CREATE PROCEDURE [dbo].[UpdateCompiledDefinition] @Path NVARCHAR(425), @OldSnapshotId UNIQUEIDENTIFIER, @NewSnapshotId UNIQUEIDENTIFIER, @ItemId UNIQUEIDENTIFIER OUTPUT AS BEGIN -- we have a clustered unique index on [Path] which the QO -- should match for the filter UPDATE [dbo].[Catalog] SET [Intermediate] = @NewSnapshotId, @ItemId = [ItemID] WHERE [Path] = @Path AND ([Intermediate] = @OldSnapshotId OR (@OldSnapshotId IS NULL AND [Intermediate] IS NULL)); DECLARE @UpdatedReferences INT ; SELECT @UpdatedReferences = @@ROWCOUNT ; IF(@UpdatedReferences <> 0) BEGIN UPDATE [dbo].[SnapshotData] SET [PermanentRefcount] = [PermanentRefcount] + @UpdatedReferences, [TransientRefcount] = [TransientRefcount] - 1 WHERE [SnapshotDataID] = @NewSnapshotId ; UPDATE [dbo].[SnapshotData] SET [PermanentRefcount] = [PermanentRefcount] - @UpdatedReferences WHERE [SnapshotDataID] = @OldSnapshotId ; END END GRANT EXECUTE ON [dbo].[UpdateCompiledDefinition] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RebindDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RebindDataSource] GO -- Republishing generates new DSID and stores those in the object model, -- in order to resolve the data sources we need to rebind the old -- data source definition to the current DSID CREATE PROCEDURE [dbo].[RebindDataSource] @ItemId uniqueidentifier, @Name nvarchar(260), @NewDSID uniqueidentifier AS UPDATE DataSource SET DSID = @NewDSID WHERE ItemID = @ItemId AND [Name] = @Name GO GRANT EXECUTE ON [dbo].[RebindDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCompiledDefinition]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetCompiledDefinition] GO -- used to create snapshots CREATE PROCEDURE [dbo].[GetCompiledDefinition] @Path nvarchar (425), @AuthType int AS SELECT MainItem.Type, MainItem.Intermediate, MainItem.LinkSourceID, MainItem.Property, MainItem.Description, SecData.NtSecDescPrimary, MainItem.ItemID, MainItem.ExecutionFlag, LinkTarget.Intermediate, LinkTarget.Property, LinkTarget.Description, MainItem.[SnapshotDataID] FROM Catalog MainItem LEFT OUTER JOIN SecData ON MainItem.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog LinkTarget with (INDEX(PK_Catalog)) on MainItem.LinkSourceID = LinkTarget.ItemID WHERE MainItem.Path = @Path GO GRANT EXECUTE ON [dbo].[GetCompiledDefinition] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetReportForExecution]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetReportForExecution] GO -- gets either the intermediate format or snapshot from cache CREATE PROCEDURE [dbo].[GetReportForExecution] @Path nvarchar (425), @ParamsHash int, @AuthType int AS DECLARE @now AS datetime SET @now = GETDATE() IF ( NOT EXISTS ( SELECT * FROM Catalog AS C INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON C.ItemID = EC.ReportID INNER JOIN ReportServerTempDB.dbo.SnapshotData AS SN ON EC.SnapshotDataID = SN.SnapshotDataID WHERE C.Path = @Path AND EC.AbsoluteExpiration > @now AND SN.ParamsHash = @ParamsHash ) ) BEGIN -- no cache SELECT Cat.Type, Cat.LinkSourceID, Cat2.Path, Cat.Property, Cat.Description, SecData.NtSecDescPrimary, Cat.ItemID, CAST (0 AS BIT), -- not found, Cat.Intermediate, Cat.ExecutionFlag, SD.SnapshotDataID, SD.DependsOnUser, Cat.ExecutionTime, (SELECT Schedule.NextRunTime FROM Schedule WITH (XLOCK) INNER JOIN ReportSchedule ON Schedule.ScheduleID = ReportSchedule.ScheduleID WHERE ReportSchedule.ReportID = Cat.ItemID AND ReportSchedule.ReportAction = 1), -- update snapshot (SELECT Schedule.ScheduleID FROM Schedule INNER JOIN ReportSchedule ON Schedule.ScheduleID = ReportSchedule.ScheduleID WHERE ReportSchedule.ReportID = Cat.ItemID AND ReportSchedule.ReportAction = 1), -- update snapshot (SELECT CachePolicy.ExpirationFlags FROM CachePolicy WHERE CachePolicy.ReportID = Cat.ItemID), Cat2.Intermediate, SD.ProcessingFlags FROM Catalog AS Cat LEFT OUTER JOIN SecData ON Cat.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog AS Cat2 on Cat.LinkSourceID = Cat2.ItemID LEFT OUTER JOIN SnapshotData AS SD ON Cat.SnapshotDataID = SD.SnapshotDataID WHERE Cat.Path = @Path END ELSE BEGIN -- use cache SELECT TOP 1 Cat.Type, Cat.LinkSourceID, Cat2.Path, Cat.Property, Cat.Description, SecData.NtSecDescPrimary, Cat.ItemID, CAST (1 AS BIT), -- found, SN.SnapshotDataID, SN.DependsOnUser, SN.EffectiveParams, SN.CreatedDate, EC.AbsoluteExpiration, (SELECT CachePolicy.ExpirationFlags FROM CachePolicy WHERE CachePolicy.ReportID = Cat.ItemID), (SELECT Schedule.ScheduleID FROM Schedule WITH (XLOCK) INNER JOIN ReportSchedule ON Schedule.ScheduleID = ReportSchedule.ScheduleID WHERE ReportSchedule.ReportID = Cat.ItemID AND ReportSchedule.ReportAction = 1), -- update snapshot SN.QueryParams, SN.ProcessingFlags FROM Catalog AS Cat INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON Cat.ItemID = EC.ReportID INNER JOIN ReportServerTempDB.dbo.SnapshotData AS SN ON EC.SnapshotDataID = SN.SnapshotDataID LEFT OUTER JOIN SecData ON Cat.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog AS Cat2 on Cat.LinkSourceID = Cat2.ItemID WHERE Cat.Path = @Path AND AbsoluteExpiration > @now AND SN.ParamsHash = @ParamsHash ORDER BY SN.CreatedDate DESC END GO GRANT EXECUTE ON [dbo].[GetReportForExecution] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetReportParametersForExecution]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetReportParametersForExecution] GO -- gets either the intermediate format or snapshot from cache CREATE PROCEDURE [dbo].[GetReportParametersForExecution] @Path nvarchar (425), @HistoryID DateTime = NULL, @AuthType int AS SELECT C.[ItemID], C.[Type], C.[ExecutionFlag], [SecData].[NtSecDescPrimary], C.[Parameter], C.[Intermediate], C.[SnapshotDataID], [History].[SnapshotDataID], L.[Intermediate], C.[LinkSourceID], C.[ExecutionTime] FROM [Catalog] AS C LEFT OUTER JOIN [SecData] ON C.[PolicyID] = [SecData].[PolicyID] AND [SecData].AuthType = @AuthType LEFT OUTER JOIN [History] ON ( C.[ItemID] = [History].[ReportID] AND [History].[SnapshotDate] = @HistoryID ) LEFT OUTER JOIN [Catalog] AS L WITH (INDEX(PK_Catalog)) ON C.[LinkSourceID] = L.[ItemID] WHERE C.[Path] = @Path GO GRANT EXECUTE ON [dbo].[GetReportParametersForExecution] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[MoveObject]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[MoveObject] GO CREATE PROCEDURE [dbo].[MoveObject] @OldPath nvarchar (425), @OldPrefix nvarchar (850), @NewName nvarchar (425), @NewPath nvarchar (425), @NewParentID uniqueidentifier, @RenameOnly as bit, @MaxPathLength as int AS DECLARE @LongPath nvarchar(425) SET @LongPath = (SELECT TOP 1 Path FROM Catalog WHERE LEN(Path)-LEN(@OldPath)+LEN(@NewPath) > @MaxPathLength AND Path LIKE @OldPrefix ESCAPE '*') IF @LongPath IS NOT NULL BEGIN SELECT @LongPath RETURN END IF @RenameOnly = 0 -- if this a full-blown move, not just a rename BEGIN -- adjust policies on the top item that gets moved DECLARE @OldInheritedPolicyID as uniqueidentifier SELECT @OldInheritedPolicyID = (SELECT PolicyID FROM Catalog with (XLOCK) WHERE Path = @OldPath AND PolicyRoot = 0) IF (@OldInheritedPolicyID IS NOT NULL) BEGIN -- this was not a policy root, change it to inherit from target folder DECLARE @NewPolicyID as uniqueidentifier SELECT @NewPolicyID = (SELECT PolicyID FROM Catalog with (XLOCK) WHERE ItemID = @NewParentID) -- update item and children that shared the old policy UPDATE Catalog SET PolicyID = @NewPolicyID WHERE Path = @OldPath UPDATE Catalog SET PolicyID = @NewPolicyID WHERE Path LIKE @OldPrefix ESCAPE '*' AND Catalog.PolicyID = @OldInheritedPolicyID END END -- Update item that gets moved (Path, Name, and ParentId) update Catalog set Name = @NewName, Path = @NewPath, ParentID = @NewParentID where Path = @OldPath -- Update all its children (Path only, Names and ParentIds stay the same) update Catalog set Path = STUFF(Path, 1, LEN(@OldPath), @NewPath ) where Path like @OldPrefix escape '*' GO GRANT EXECUTE ON [dbo].[MoveObject] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ObjectExists]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ObjectExists] GO CREATE PROCEDURE [dbo].[ObjectExists] @Path nvarchar (425), @AuthType int AS SELECT Type, ItemID, SnapshotLimit, NtSecDescPrimary, ExecutionFlag, Intermediate, [LinkSourceID] FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[ObjectExists] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetAllProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetAllProperties] GO CREATE PROCEDURE [dbo].[SetAllProperties] @Path nvarchar (425), @Property ntext, @Description ntext = NULL, @Hidden bit = NULL, @ModifiedBySid varbinary (85) = NULL, @ModifiedByName nvarchar(260), @AuthType int, @ModifiedDate DateTime AS DECLARE @ModifiedByID uniqueidentifier EXEC GetUserID @ModifiedBySid, @ModifiedByName, @AuthType, @ModifiedByID OUTPUT UPDATE Catalog SET Property = @Property, Description = @Description, Hidden = @Hidden, ModifiedByID = @ModifiedByID, ModifiedDate = @ModifiedDate WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[SetAllProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FlushReportFromCache]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FlushReportFromCache] GO CREATE PROCEDURE [dbo].[FlushReportFromCache] @Path as nvarchar(425) AS UPDATE SN SET SN.PermanentRefcount = SN.PermanentRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON SN.SnapshotDataID = EC.SnapshotDataID INNER JOIN Catalog AS C ON EC.ReportID = C.ItemID WHERE C.Path = @Path DELETE EC FROM ReportServerTempDB.dbo.ExecutionCache AS EC INNER JOIN Catalog ON EC.ReportID = Catalog.ItemID WHERE Catalog.Path = @Path GO GRANT EXECUTE ON [dbo].[FlushReportFromCache] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetParameters] GO CREATE PROCEDURE [dbo].[SetParameters] @Path nvarchar (425), @Parameter ntext AS UPDATE Catalog SET [Parameter] = @Parameter WHERE Path = @Path EXEC FlushReportFromCache @Path GO GRANT EXECUTE ON [dbo].[SetParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetObjectContent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetObjectContent] GO CREATE PROCEDURE [dbo].[SetObjectContent] @Path nvarchar (425), @Type int, @Content image = NULL, @Intermediate uniqueidentifier = NULL, @Parameter ntext = NULL, @LinkSourceID uniqueidentifier = NULL, @MimeType nvarchar (260) = NULL AS DECLARE @OldIntermediate as uniqueidentifier SET @OldIntermediate = (SELECT Intermediate FROM Catalog WITH (XLOCK) WHERE Path = @Path) UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 WHERE SnapshotData.SnapshotDataID = @OldIntermediate UPDATE Catalog SET Type=@Type, Content = @Content, Intermediate = @Intermediate, [Parameter] = @Parameter, LinkSourceID = @LinkSourceID, MimeType = @MimeType WHERE Path = @Path UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount + 1, TransientRefcount = TransientRefcount - 1 WHERE SnapshotData.SnapshotDataID = @Intermediate EXEC FlushReportFromCache @Path GO GRANT EXECUTE ON [dbo].[SetObjectContent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetLastModified]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetLastModified] GO CREATE PROCEDURE [dbo].[SetLastModified] @Path nvarchar (425), @ModifiedBySid varbinary (85) = NULL, @ModifiedByName nvarchar(260), @AuthType int, @ModifiedDate DateTime AS DECLARE @ModifiedByID uniqueidentifier EXEC GetUserID @ModifiedBySid, @ModifiedByName, @AuthType, @ModifiedByID OUTPUT UPDATE Catalog SET ModifiedByID = @ModifiedByID, ModifiedDate = @ModifiedDate WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[SetLastModified] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetNameById]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetNameById] GO CREATE PROCEDURE [dbo].[GetNameById] @ItemID uniqueidentifier AS SELECT Path FROM Catalog WHERE ItemID = @ItemID GO GRANT EXECUTE ON [dbo].[GetNameById] TO RSExecRole GO -------------------------------------------------- ------------- Data source procedures to store user names and passwords if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddDataSource] GO CREATE PROCEDURE [dbo].[AddDataSource] @DSID [uniqueidentifier], @ItemID [uniqueidentifier] = NULL, -- null for future suport dynamic delivery @SubscriptionID [uniqueidentifier] = NULL, @Name [nvarchar] (260) = NULL, -- only for scoped data sources, MUST be NULL for standalone!!! @Extension [nvarchar] (260) = NULL, @LinkID [uniqueidentifier] = NULL, -- link id is trusted, if it is provided - we use it @LinkPath [nvarchar] (425) = NULL, -- if LinkId is not provided we try to look up LinkPath @CredentialRetrieval [int], @Prompt [ntext] = NULL, @ConnectionString [image] = NULL, @OriginalConnectionString [image] = NULL, @OriginalConnectStringExpressionBased [bit] = NULL, @UserName [image] = NULL, @Password [image] = NULL, @Flags [int], @AuthType [int], @Version [int] AS DECLARE @ActualLinkID uniqueidentifier SET @ActualLinkID = NULL IF (@LinkID is NULL) AND (@LinkPath is not NULL) BEGIN SELECT Type, ItemID, NtSecDescPrimary FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @LinkPath SET @ActualLinkID = (SELECT ItemID FROM Catalog WHERE Path = @LinkPath) END ELSE BEGIN SET @ActualLinkID = @LinkID END INSERT INTO DataSource ([DSID], [ItemID], [SubscriptionID], [Name], [Extension], [Link], [CredentialRetrieval], [Prompt], [ConnectionString], [OriginalConnectionString], [OriginalConnectStringExpressionBased], [UserName], [Password], [Flags], [Version]) VALUES (@DSID, @ItemID, @SubscriptionID, @Name, @Extension, @ActualLinkID, @CredentialRetrieval, @Prompt, @ConnectionString, @OriginalConnectionString, @OriginalConnectStringExpressionBased, @UserName, @Password, @Flags, @Version) GO GRANT EXECUTE ON [dbo].[AddDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDataSources]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDataSources] GO CREATE PROCEDURE [dbo].[GetDataSources] @ItemID [uniqueidentifier], @AuthType int AS SELECT -- select data sources and their links (if they exist) DS.[DSID], -- 0 DS.[ItemID], -- 1 DS.[Name], -- 2 DS.[Extension], -- 3 DS.[Link], -- 4 DS.[CredentialRetrieval], -- 5 DS.[Prompt], -- 6 DS.[ConnectionString], -- 7 DS.[OriginalConnectionString], -- 8 DS.[UserName], -- 9 DS.[Password], -- 10 DS.[Flags], -- 11 DSL.[DSID], -- 12 DSL.[ItemID], -- 13 DSL.[Name], -- 14 DSL.[Extension], -- 15 DSL.[Link], -- 16 DSL.[CredentialRetrieval], -- 17 DSL.[Prompt], -- 18 DSL.[ConnectionString], -- 19 DSL.[UserName], -- 20 DSL.[Password], -- 21 DSL.[Flags], -- 22 C.Path, -- 23 SD.NtSecDescPrimary, -- 24 DS.[OriginalConnectStringExpressionBased], -- 25 DS.[Version], -- 26 DSL.[Version], -- 27 (SELECT 1 WHERE EXISTS (SELECT * from [ModelItemPolicy] AS MIP WHERE C.[ItemID] = MIP.[CatalogItemID])) -- 28 FROM [DataSource] AS DS LEFT OUTER JOIN ([DataSource] AS DSL INNER JOIN [Catalog] AS C ON DSL.[ItemID] = C.[ItemID] LEFT OUTER JOIN [SecData] AS SD ON C.[PolicyID] = SD.[PolicyID] AND SD.AuthType = @AuthType) ON DS.[Link] = DSL.[ItemID] WHERE DS.[ItemID] = @ItemID or DS.[SubscriptionID] = @ItemID GO GRANT EXECUTE ON [dbo].[GetDataSources] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteDataSources]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteDataSources] GO CREATE PROCEDURE [dbo].[DeleteDataSources] @ItemID [uniqueidentifier] AS DELETE FROM [DataSource] WHERE [ItemID] = @ItemID or [SubscriptionID] = @ItemID GO GRANT EXECUTE ON [dbo].[DeleteDataSources] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ChangeStateOfDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ChangeStateOfDataSource] GO CREATE PROCEDURE [dbo].[ChangeStateOfDataSource] @ItemID [uniqueidentifier], @Enable bit AS IF @Enable != 0 BEGIN UPDATE [DataSource] SET [Flags] = [Flags] | 1 WHERE [ItemID] = @ItemID END ELSE BEGIN UPDATE [DataSource] SET [Flags] = [Flags] & 0x7FFFFFFE WHERE [ItemID] = @ItemID END GO GRANT EXECUTE ON [dbo].[ChangeStateOfDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindItemsByDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindItemsByDataSource] GO CREATE PROCEDURE [dbo].[FindItemsByDataSource] @ItemID uniqueidentifier, @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.UserName, SUSER_SNAME(MU.Sid), MU.UserName, C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType INNER JOIN DataSource AS DS ON C.ItemID = DS.ItemID WHERE DS.Link = @ItemID GO GRANT EXECUTE ON [dbo].[FindItemsByDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateRole] GO CREATE PROCEDURE [dbo].[CreateRole] @RoleID as uniqueidentifier, @RoleName as nvarchar(260), @Description as nvarchar(512) = null, @TaskMask as nvarchar(32), @RoleFlags as tinyint AS INSERT INTO Roles (RoleID, RoleName, Description, TaskMask, RoleFlags) VALUES (@RoleID, @RoleName, @Description, @TaskMask, @RoleFlags) GO GRANT EXECUTE ON [dbo].[CreateRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetRoles]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetRoles] GO CREATE PROCEDURE [dbo].[GetRoles] @RoleFlags as tinyint = NULL AS SELECT RoleName, Description, TaskMask FROM Roles WHERE (@RoleFlags is NULL) OR (RoleFlags = @RoleFlags) GO GRANT EXECUTE ON [dbo].[GetRoles] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteRole] GO -- Delete all policies associated with this role CREATE PROCEDURE [dbo].[DeleteRole] @RoleName nvarchar(260) AS -- if you call this, you must delete/reconstruct all policies associated with this role DELETE FROM Roles WHERE RoleName = @RoleName GO GRANT EXECUTE ON [dbo].[DeleteRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadRoleProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadRoleProperties] GO CREATE PROCEDURE [dbo].[ReadRoleProperties] @RoleName as nvarchar(260) AS SELECT Description, TaskMask, RoleFlags FROM Roles WHERE RoleName = @RoleName GO GRANT EXECUTE ON [dbo].[ReadRoleProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetRoleProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetRoleProperties] GO CREATE PROCEDURE [dbo].[SetRoleProperties] @RoleName as nvarchar(260), @Description as nvarchar(512) = NULL, @TaskMask as nvarchar(32), @RoleFlags as tinyint AS DECLARE @ExistingRoleFlags as tinyint SET @ExistingRoleFlags = (SELECT RoleFlags FROM Roles WHERE RoleName = @RoleName) IF @ExistingRoleFlags IS NULL BEGIN RETURN END IF @ExistingRoleFlags <> @RoleFlags BEGIN RAISERROR ('Bad role flags', 16, 1) END UPDATE Roles SET Description = @Description, TaskMask = @TaskMask, RoleFlags = @RoleFlags WHERE RoleName = @RoleName GO GRANT EXECUTE ON [dbo].[SetRoleProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPoliciesForRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPoliciesForRole] GO CREATE PROCEDURE [dbo].[GetPoliciesForRole] @RoleName as nvarchar(260), @AuthType as int AS SELECT Policies.PolicyID, SecData.XmlDescription, Policies.PolicyFlag, Catalog.Type, Catalog.Path, ModelItemPolicy.CatalogItemID, ModelItemPolicy.ModelItemID, RelatedRoles.RoleID, RelatedRoles.RoleName, RelatedRoles.TaskMask, RelatedRoles.RoleFlags FROM Roles INNER JOIN PolicyUserRole ON Roles.RoleID = PolicyUserRole.RoleID INNER JOIN Policies ON PolicyUserRole.PolicyID = Policies.PolicyID INNER JOIN PolicyUserRole AS RelatedPolicyUserRole ON Policies.PolicyID = RelatedPolicyUserRole.PolicyID INNER JOIN Roles AS RelatedRoles ON RelatedPolicyUserRole.RoleID = RelatedRoles.RoleID LEFT OUTER JOIN SecData ON Policies.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog ON Policies.PolicyID = Catalog.PolicyID AND Catalog.PolicyRoot = 1 LEFT OUTER JOIN ModelItemPolicy ON Policies.PolicyID = ModelItemPolicy.PolicyID WHERE Roles.RoleName = @RoleName ORDER BY Policies.PolicyID GO GRANT EXECUTE ON [dbo].[GetPoliciesForRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdatePolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdatePolicy] GO CREATE PROCEDURE [dbo].[UpdatePolicy] @PolicyID as uniqueidentifier, @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @AuthType int AS UPDATE SecData SET NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND SecData.AuthType = @AuthType GO GRANT EXECUTE ON [dbo].[UpdatePolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetPolicy] GO -- this assumes the item exists in the catalog CREATE PROCEDURE [dbo].[SetPolicy] @ItemName as nvarchar(425), @ItemNameLike as nvarchar(850), @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @XmlPolicy as ntext, @AuthType int, @PolicyID uniqueidentifier OUTPUT AS SELECT @PolicyID = (SELECT PolicyID FROM Catalog WHERE Path = @ItemName AND PolicyRoot = 1) IF (@PolicyID IS NULL) BEGIN -- this is not a policy root SET @PolicyID = newid() INSERT INTO Policies (PolicyID, PolicyFlag) VALUES (@PolicyID, 0) INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) DECLARE @OldPolicyID as uniqueidentifier SELECT @OldPolicyID = (SELECT PolicyID FROM Catalog WHERE Path = @ItemName) -- update item and children that shared the old policy UPDATE Catalog SET PolicyID = @PolicyID, PolicyRoot = 1 WHERE Path = @ItemName UPDATE Catalog SET PolicyID = @PolicyID WHERE Path LIKE @ItemNameLike ESCAPE '*' AND Catalog.PolicyID = @OldPolicyID END ELSE BEGIN UPDATE Policies SET PolicyFlag = 0 WHERE Policies.PolicyID = @PolicyID DECLARE @SecDataID as uniqueidentifier SELECT @SecDataID = (SELECT SecDataID FROM SecData WHERE PolicyID = @PolicyID and AuthType = @AuthType) IF (@SecDataID IS NULL) BEGIN -- insert new sec desc's INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription ,NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN -- update existing sec desc's UPDATE SecData SET XmlDescription = @XmlPolicy, NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND AuthType = @AuthType END END DELETE FROM PolicyUserRole WHERE PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[SetPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSystemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSystemPolicy] GO -- update the system policy CREATE PROCEDURE [dbo].[SetSystemPolicy] @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @XmlPolicy as ntext, @AuthType as int, @PolicyID uniqueidentifier OUTPUT AS SELECT @PolicyID = (SELECT PolicyID FROM Policies WHERE PolicyFlag = 1) IF (@PolicyID IS NULL) BEGIN SET @PolicyID = newid() INSERT INTO Policies (PolicyID, PolicyFlag) VALUES (@PolicyID, 1) INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN DECLARE @SecDataID as uniqueidentifier SELECT @SecDataID = (SELECT SecDataID FROM SecData WHERE PolicyID = @PolicyID and AuthType = @AuthType) IF (@SecDataID IS NULL) BEGIN -- insert new sec desc's INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN -- update existing sec desc's UPDATE SecData SET XmlDescription = @XmlPolicy, NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND AuthType = @AuthType END END DELETE FROM PolicyUserRole WHERE PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[SetSystemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetModelItemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetModelItemPolicy] GO -- update the system policy CREATE PROCEDURE [dbo].[SetModelItemPolicy] @CatalogItemID as uniqueidentifier, @ModelItemID as nvarchar(425), @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @XmlPolicy as ntext, @AuthType as int, @PolicyID uniqueidentifier OUTPUT AS SELECT @PolicyID = (SELECT PolicyID FROM ModelItemPolicy WHERE CatalogItemID = @CatalogItemID AND ModelItemID = @ModelItemID ) IF (@PolicyID IS NULL) BEGIN SET @PolicyID = newid() INSERT INTO Policies (PolicyID, PolicyFlag) VALUES (@PolicyID, 2) INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) INSERT INTO ModelItemPolicy (ID, CatalogItemID, ModelItemID, PolicyID) VALUES (newid(), @CatalogItemID, @ModelItemID, @PolicyID) END ELSE BEGIN DECLARE @SecDataID as uniqueidentifier SELECT @SecDataID = (SELECT SecDataID FROM SecData WHERE PolicyID = @PolicyID and AuthType = @AuthType) IF (@SecDataID IS NULL) BEGIN -- insert new sec desc's INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN -- update existing sec desc's UPDATE SecData SET XmlDescription = @XmlPolicy, NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND AuthType = @AuthType END END DELETE FROM PolicyUserRole WHERE PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[SetModelItemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdatePolicyPrincipal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdatePolicyPrincipal] GO CREATE PROCEDURE [dbo].[UpdatePolicyPrincipal] @PolicyID uniqueidentifier, @PrincipalSid varbinary(85) = NULL, @PrincipalName nvarchar(260), @PrincipalAuthType int, @RoleName nvarchar(260), @PrincipalID uniqueidentifier OUTPUT, @RoleID uniqueidentifier OUTPUT AS EXEC GetPrincipalID @PrincipalSid , @PrincipalName, @PrincipalAuthType, @PrincipalID OUTPUT SELECT @RoleID = (SELECT RoleID FROM Roles WHERE RoleName = @RoleName) INSERT INTO PolicyUserRole (ID, RoleID, UserID, PolicyID) VALUES (newid(), @RoleID, @PrincipalID, @PolicyID) GO GRANT EXECUTE ON [dbo].[UpdatePolicyPrincipal] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdatePolicyRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdatePolicyRole] GO CREATE PROCEDURE [dbo].[UpdatePolicyRole] @PolicyID uniqueidentifier, @PrincipalID uniqueidentifier, @RoleName nvarchar(260), @RoleID uniqueidentifier OUTPUT AS SELECT @RoleID = (SELECT RoleID FROM Roles WHERE RoleName = @RoleName) INSERT INTO PolicyUserRole (ID, RoleID, UserID, PolicyID) VALUES (newid(), @RoleID, @PrincipalID, @PolicyID) GO GRANT EXECUTE ON [dbo].[UpdatePolicyRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPolicy] GO CREATE PROCEDURE [dbo].[GetPolicy] @ItemName as nvarchar(425), @AuthType int AS SELECT SecData.XmlDescription, Catalog.PolicyRoot , SecData.NtSecDescPrimary, Catalog.Type FROM Catalog INNER JOIN Policies ON Catalog.PolicyID = Policies.PolicyID LEFT OUTER JOIN SecData ON Policies.PolicyID = SecData.PolicyID AND AuthType = @AuthType WHERE Catalog.Path = @ItemName AND PolicyFlag = 0 GO GRANT EXECUTE ON [dbo].[GetPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSystemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSystemPolicy] GO CREATE PROCEDURE [dbo].[GetSystemPolicy] @AuthType int AS SELECT SecData.NtSecDescPrimary, SecData.XmlDescription FROM Policies LEFT OUTER JOIN SecData ON Policies.PolicyID = SecData.PolicyID AND AuthType = @AuthType WHERE PolicyFlag = 1 GO GRANT EXECUTE ON [dbo].[GetSystemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeletePolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeletePolicy] GO CREATE PROCEDURE [dbo].[DeletePolicy] @ItemName as nvarchar(425) AS DECLARE @OldPolicyID uniqueidentifier SELECT @OldPolicyID = (SELECT PolicyID FROM Catalog WHERE Catalog.Path = @ItemName) UPDATE Catalog SET PolicyID = (SELECT Parent.PolicyID FROM Catalog Parent, Catalog WHERE Parent.ItemID = Catalog.ParentID AND Catalog.Path = @ItemName), PolicyRoot = 0 WHERE Catalog.PolicyID = @OldPolicyID DELETE Policies FROM Policies WHERE Policies.PolicyID = @OldPolicyID GO GRANT EXECUTE ON [dbo].[DeletePolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateSession]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateSession] GO -- Writes or updates session record CREATE PROCEDURE [dbo].[CreateSession] @SessionID as varchar(32), @CompiledDefinition as uniqueidentifier = NULL, @SnapshotDataID as uniqueidentifier = NULL, @IsPermanentSnapshot as bit = NULL, @ReportPath as nvarchar(440) = NULL, @Timeout as int, @AutoRefreshSeconds as int = NULL, @DataSourceInfo as image = NULL, @OwnerName as nvarchar (260), @OwnerSid as varbinary (85) = NULL, @AuthType as int, @EffectiveParams as ntext = NULL, @HistoryDate as datetime = NULL, @PageHeight as float = NULL, @PageWidth as float = NULL, @TopMargin as float = NULL, @BottomMargin as float = NULL, @LeftMargin as float = NULL, @RightMargin as float = NULL, @AwaitingFirstExecution as bit = NULL AS UPDATE PS SET PS.RefCount = 1 FROM ReportServerTempDB.dbo.PersistedStream as PS WHERE PS.SessionID = @SessionID UPDATE SN SET TransientRefcount = TransientRefcount + 1 FROM SnapshotData AS SN WHERE SN.SnapshotDataID = @SnapshotDataID UPDATE SN SET TransientRefcount = TransientRefcount + 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN WHERE SN.SnapshotDataID = @SnapshotDataID DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT DECLARE @now datetime SET @now = GETDATE() INSERT INTO ReportServerTempDB.dbo.SessionData ( SessionID, CompiledDefinition, SnapshotDataID, IsPermanentSnapshot, ReportPath, Timeout, AutoRefreshSeconds, Expiration, DataSourceInfo, OwnerID, EffectiveParams, CreationTime, HistoryDate, PageHeight, PageWidth, TopMargin, BottomMargin, LeftMargin, RightMargin, AwaitingFirstExecution ) VALUES ( @SessionID, @CompiledDefinition, @SnapshotDataID, @IsPermanentSnapshot, @ReportPath, @Timeout, @AutoRefreshSeconds, DATEADD(s, @Timeout, @now), @DataSourceInfo, @OwnerID, @EffectiveParams, @now, @HistoryDate, @PageHeight, @PageWidth, @TopMargin, @BottomMargin, @LeftMargin, @RightMargin, @AwaitingFirstExecution ) GO GRANT EXECUTE ON [dbo].[CreateSession] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteModelItemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteModelItemPolicy] GO CREATE PROCEDURE [dbo].[DeleteModelItemPolicy] @CatalogItemID as uniqueidentifier, @ModelItemID as nvarchar(425) AS DECLARE @PolicyID uniqueidentifier SELECT @PolicyID = (SELECT PolicyID FROM ModelItemPolicy WHERE CatalogItemID = @CatalogItemID AND ModelItemID = @ModelItemID) DELETE Policies FROM Policies WHERE Policies.PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[DeleteModelItemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteAllModelItemPolicies]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteAllModelItemPolicies] GO CREATE PROCEDURE [dbo].[DeleteAllModelItemPolicies] @Path as nvarchar(450) AS DELETE Policies FROM Policies AS P INNER JOIN ModelItemPolicy AS MIP ON P.PolicyID = MIP.PolicyID INNER JOIN Catalog AS C ON MIP.CatalogItemID = C.ItemID WHERE C.[Path] = @Path GO GRANT EXECUTE ON [dbo].[DeleteAllModelItemPolicies] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelItemInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelItemInfo] GO CREATE PROCEDURE [dbo].[GetModelItemInfo] @Path nvarchar (425), @UseUpdateLock bit AS IF(@UseUpdateLock = 0) BEGIN SELECT C.[Intermediate] FROM [Catalog] AS C WHERE C.[Path] = @Path END ELSE BEGIN -- acquire update lock, this means that the operation is being performed in a -- different transaction context which will be committed before trying to -- perform the actual load, to prevent deadlock in the case where we have to -- republish, this new transaction will acquire and hold upgrade locks SELECT C.[Intermediate] FROM [Catalog] AS C WITH(UPDLOCK ROWLOCK) WHERE C.[Path] = @Path END SELECT MIP.[ModelItemID], SD.[NtSecDescPrimary], SD.[XmlDescription] FROM [Catalog] AS C INNER JOIN [ModelItemPolicy] AS MIP ON C.[ItemID] = MIP.[CatalogItemID] LEFT OUTER JOIN [SecData] AS SD ON MIP.[PolicyID] = SD.[PolicyID] WHERE C.[Path] = @Path GO GRANT EXECUTE ON [dbo].[GetModelItemInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelDefinition]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelDefinition] GO CREATE PROCEDURE [dbo].[GetModelDefinition] @CatalogItemID as uniqueidentifier AS SELECT C.[Content] FROM [Catalog] AS C WHERE C.[ItemID] = @CatalogItemID GO GRANT EXECUTE ON [dbo].[GetModelDefinition] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddModelPerspective]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddModelPerspective] GO CREATE PROCEDURE [dbo].[AddModelPerspective] @ModelID as uniqueidentifier, @PerspectiveID as ntext, @PerspectiveName as ntext = null, @PerspectiveDescription as ntext = null AS INSERT INTO [ModelPerspective] ([ID], [ModelID], [PerspectiveID], [PerspectiveName], [PerspectiveDescription]) VALUES (newid(), @ModelID, @PerspectiveID, @PerspectiveName, @PerspectiveDescription) GO GRANT EXECUTE ON [dbo].[AddModelPerspective] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteModelPerspectives]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteModelPerspectives] GO CREATE PROCEDURE [dbo].[DeleteModelPerspectives] @ModelID as uniqueidentifier AS DELETE FROM [ModelPerspective] WHERE [ModelID] = @ModelID GO GRANT EXECUTE ON [dbo].[DeleteModelPerspectives] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelsAndPerspectives]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelsAndPerspectives] GO CREATE PROCEDURE [dbo].[GetModelsAndPerspectives] @AuthType int, @SitePathPrefix nvarchar(520) = '%' AS SELECT C.[PolicyID], SD.[NtSecDescPrimary], C.[ItemID], C.[Path], C.[Description], P.[PerspectiveID], P.[PerspectiveName], P.[PerspectiveDescription] FROM [Catalog] as C LEFT OUTER JOIN [ModelPerspective] as P ON C.[ItemID] = P.[ModelID] LEFT OUTER JOIN [SecData] AS SD ON C.[PolicyID] = SD.[PolicyID] AND SD.[AuthType] = @AuthType WHERE C.Path like @SitePathPrefix AND C.[Type] = 6 -- Model ORDER BY C.[Path] GO GRANT EXECUTE ON [dbo].[GetModelsAndPerspectives] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelPerspectives]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelPerspectives] GO CREATE PROCEDURE [dbo].[GetModelPerspectives] @Path nvarchar (425), @AuthType int AS SELECT C.[Type], SD.[NtSecDescPrimary], C.[Description] FROM [Catalog] as C LEFT OUTER JOIN [SecData] AS SD ON C.[PolicyID] = SD.[PolicyID] AND SD.[AuthType] = @AuthType WHERE [Path] = @Path SELECT P.[PerspectiveID], P.[PerspectiveName], P.[PerspectiveDescription] FROM [Catalog] as C INNER JOIN [ModelPerspective] as P ON C.[ItemID] = P.[ModelID] WHERE [Path] = @Path GO GRANT EXECUTE ON [dbo].[GetModelPerspectives] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DereferenceSessionSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DereferenceSessionSnapshot] GO CREATE PROCEDURE [dbo].[DereferenceSessionSnapshot] @SessionID as varchar(32), @OwnerID as uniqueidentifier AS UPDATE SN SET TransientRefcount = TransientRefcount - 1 FROM SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.SessionData AS SE ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID UPDATE SN SET TransientRefcount = TransientRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.SessionData AS SE ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[DereferenceSessionSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSessionData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSessionData] GO -- Writes or updates session record CREATE PROCEDURE [dbo].[SetSessionData] @SessionID as varchar(32), @ReportPath as nvarchar(440), @HistoryDate as datetime = NULL, @Timeout as int, @AutoRefreshSeconds as int = NULL, @EffectiveParams ntext = NULL, @OwnerSid as varbinary (85) = NULL, @OwnerName as nvarchar (260), @AuthType as int, @ShowHideInfo as image = NULL, @DataSourceInfo as image = NULL, @SnapshotDataID as uniqueidentifier = NULL, @IsPermanentSnapshot as bit = NULL, @SnapshotTimeoutSeconds as int = NULL, @HasInteractivity as bit, @SnapshotExpirationDate as datetime = NULL, @AwaitingFirstExecution as bit = NULL AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT DECLARE @now datetime SET @now = GETDATE() -- is there a session for the same report ? DECLARE @OldSnapshotDataID uniqueidentifier DECLARE @OldIsPermanentSnapshot bit DECLARE @OldSessionID varchar(32) SELECT @OldSessionID = SessionID, @OldSnapshotDataID = SnapshotDataID, @OldIsPermanentSnapshot = IsPermanentSnapshot FROM ReportServerTempDB.dbo.SessionData WITH (XLOCK) WHERE SessionID = @SessionID IF @OldSessionID IS NOT NULL BEGIN -- Yes, update it IF @OldSnapshotDataID != @SnapshotDataID or @SnapshotDataID is NULL BEGIN EXEC DereferenceSessionSnapshot @SessionID, @OwnerID END UPDATE ReportServerTempDB.dbo.SessionData SET SnapshotDataID = @SnapshotDataID, IsPermanentSnapshot = @IsPermanentSnapshot, Timeout = @Timeout, AutoRefreshSeconds = @AutoRefreshSeconds, SnapshotExpirationDate = @SnapshotExpirationDate, -- we want database session to expire later than in-memory session Expiration = DATEADD(s, @Timeout+10, @now), ShowHideInfo = @ShowHideInfo, DataSourceInfo = @DataSourceInfo, AwaitingFirstExecution = @AwaitingFirstExecution -- EffectiveParams = @EffectiveParams, -- no need to update user params as they are always same -- ReportPath = @ReportPath -- OwnerID = @OwnerID WHERE SessionID = @SessionID -- update expiration date on a snapshot that we reference IF @IsPermanentSnapshot != 0 BEGIN UPDATE SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutSeconds, @now) WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutSeconds, @now) WHERE SnapshotDataID = @SnapshotDataID END END ELSE BEGIN -- no, insert it UPDATE PS SET PS.RefCount = 1 FROM ReportServerTempDB.dbo.PersistedStream as PS WHERE PS.SessionID = @SessionID INSERT INTO ReportServerTempDB.dbo.SessionData (SessionID, SnapshotDataID, IsPermanentSnapshot, ReportPath, EffectiveParams, Timeout, AutoRefreshSeconds, Expiration, ShowHideInfo, DataSourceInfo, OwnerID, CreationTime, HasInteractivity, SnapshotExpirationDate, HistoryDate, AwaitingFirstExecution) VALUES (@SessionID, @SnapshotDataID, @IsPermanentSnapshot, @ReportPath, @EffectiveParams, @Timeout, @AutoRefreshSeconds, DATEADD(s, @Timeout, @now), @ShowHideInfo, @DataSourceInfo, @OwnerID, @now, @HasInteractivity, @SnapshotExpirationDate, @HistoryDate, @AwaitingFirstExecution) END GO GRANT EXECUTE ON [dbo].[SetSessionData] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteLockSession]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteLockSession] GO CREATE PROCEDURE [dbo].[WriteLockSession] @SessionID as varchar(32) AS INSERT INTO ReportServerTempDB.dbo.SessionLock WITH (ROWLOCK) (SessionID) VALUES (@SessionID) GO GRANT EXECUTE ON [dbo].[WriteLockSession] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CheckSessionLock]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CheckSessionLock] GO CREATE PROCEDURE [dbo].[CheckSessionLock] @SessionID as varchar(32) AS DECLARE @Selected nvarchar(32) SELECT @Selected=SessionID FROM ReportServerTempDB.dbo.SessionLock WITH (ROWLOCK) WHERE SessionID = @SessionID GO GRANT EXECUTE ON [dbo].[CheckSessionLock] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadLockSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadLockSnapshot] GO CREATE PROCEDURE [dbo].[ReadLockSnapshot] @SnapshotDataID as uniqueidentifier AS SELECT SnapshotDataID FROM SnapshotData WITH (REPEATABLEREAD, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID GO GRANT EXECUTE ON [dbo].[ReadLockSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSessionData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSessionData] GO -- Get record from session data, update session and snapshot CREATE PROCEDURE [dbo].[GetSessionData] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @SnapshotTimeoutMinutes as int AS DECLARE @now as datetime SET @now = GETDATE() DECLARE @DBSessionID varchar(32) DECLARE @SnapshotDataID uniqueidentifier DECLARE @IsPermanentSnapshot bit EXEC CheckSessionLock @SessionID = @SessionID DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT SELECT @DBSessionID = SE.SessionID, @SnapshotDataID = SE.SnapshotDataID, @IsPermanentSnapshot = SE.IsPermanentSnapshot FROM ReportServerTempDB.dbo.SessionData AS SE WITH (XLOCK) WHERE SE.OwnerID = @OwnerID AND SE.SessionID = @SessionID AND SE.Expiration > @now -- We need this update to keep session around while we process it. -- TODO: This assumes that it will be processed within the session timeout. UPDATE SE SET Expiration = DATEADD(s, Timeout, @now) FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @DBSessionID -- Update snapshot expiration to prevent early deletion -- If session uses snapshot, it is already refcounted. However, if session lasts for too long, -- snapshot may expire. Therefore, every time we touch snapshot we should change expiration. IF (@DBSessionID IS NOT NULL) BEGIN -- We return something only if session is present IF @IsPermanentSnapshot != 0 BEGIN -- If session has snapshot and it is permanent SELECT SN.SnapshotDataID, SE.ShowHideInfo, SE.DataSourceInfo, SN.Description, SE.EffectiveParams, SN.CreatedDate, SE.IsPermanentSnapshot, SE.CreationTime, SE.HasInteractivity, SE.Timeout, SE.SnapshotExpirationDate, SE.ReportPath, SE.HistoryDate, SE.CompiledDefinition, SN.PageCount, SN.HasDocMap, SE.Expiration, SN.EffectiveParams, SE.PageHeight, SE.PageWidth, SE.TopMargin, SE.BottomMargin, SE.LeftMargin, SE.RightMargin, SE.AutoRefreshSeconds, SE.AwaitingFirstExecution, SN.[DependsOnUser], SN.PaginationMode, SN.ProcessingFlags, NULL, -- No compiled definition in tempdb to get flags from CONVERT(BIT, 0) AS [FoundInCache] -- permanent snapshot is never from Cache FROM ReportServerTempDB.dbo.SessionData AS SE INNER JOIN SnapshotData AS SN ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @DBSessionID UPDATE SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutMinutes, @now) WHERE SnapshotDataID = @SnapshotDataID END ELSE IF @IsPermanentSnapshot = 0 BEGIN -- If session has snapshot and it is temporary SELECT SN.SnapshotDataID, SE.ShowHideInfo, SE.DataSourceInfo, SN.Description, SE.EffectiveParams, SN.CreatedDate, SE.IsPermanentSnapshot, SE.CreationTime, SE.HasInteractivity, SE.Timeout, SE.SnapshotExpirationDate, SE.ReportPath, SE.HistoryDate, SE.CompiledDefinition, SN.PageCount, SN.HasDocMap, SE.Expiration, SN.EffectiveParams, SE.PageHeight, SE.PageWidth, SE.TopMargin, SE.BottomMargin, SE.LeftMargin, SE.RightMargin, SE.AutoRefreshSeconds, SE.AwaitingFirstExecution, SN.[DependsOnUser], SN.PaginationMode, SN.ProcessingFlags, COMP.ProcessingFlags, -- If we are AwaitingFirstExecution, then we haven't executed a -- report and therefore have not been bound to a cached snapshot -- because that binding only happens at report execution time. CASE SE.AwaitingFirstExecution WHEN 1 THEN CONVERT(BIT, 0) ELSE SN.IsCached END FROM ReportServerTempDB.dbo.SessionData AS SE INNER JOIN ReportServerTempDB.dbo.SnapshotData AS SN ON SN.SnapshotDataID = SE.SnapshotDataID LEFT OUTER JOIN ReportServerTempDB.dbo.SnapshotData AS COMP ON SE.CompiledDefinition = COMP.SnapshotDataID WHERE SE.SessionID = @DBSessionID UPDATE ReportServerTempDB.dbo.SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutMinutes, @now) WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN -- If session doesn't have snapshot SELECT null, SE.ShowHideInfo, SE.DataSourceInfo, null, SE.EffectiveParams, null, SE.IsPermanentSnapshot, SE.CreationTime, SE.HasInteractivity, SE.Timeout, SE.SnapshotExpirationDate, SE.ReportPath, SE.HistoryDate, SE.CompiledDefinition, null, null, SE.Expiration, null, SE.PageHeight, SE.PageWidth, SE.TopMargin, SE.BottomMargin, SE.LeftMargin, SE.RightMargin, SE.AutoRefreshSeconds, SE.AwaitingFirstExecution, null, null, null, COMP.ProcessingFlags, CONVERT(BIT, 0) AS [FoundInCache] -- no snapshot, so it can't be from the cache FROM ReportServerTempDB.dbo.SessionData AS SE LEFT OUTER JOIN ReportServerTempDB.dbo.SnapshotData AS COMP ON (SE.CompiledDefinition = COMP.SnapshotDataID) WHERE SE.SessionID = @DBSessionID END END GO GRANT EXECUTE ON [dbo].[GetSessionData] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapshotFromHistory]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapshotFromHistory] GO CREATE PROCEDURE [dbo].[GetSnapshotFromHistory] @Path nvarchar (425), @SnapshotDate datetime, @AuthType int AS SELECT Catalog.ItemID, Catalog.Type, SnapshotData.SnapshotDataID, SnapshotData.DependsOnUser, SnapshotData.Description, SecData.NtSecDescPrimary, Catalog.[Property], SnapshotData.ProcessingFlags FROM SnapshotData INNER JOIN History ON History.SnapshotDataID = SnapshotData.SnapshotDataID INNER JOIN Catalog ON History.ReportID = Catalog.ItemID LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Catalog.Path = @Path AND History.SnapshotDate = @SnapshotDate GO GRANT EXECUTE ON [dbo].[GetSnapshotFromHistory] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredSessions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredSessions] GO CREATE PROCEDURE [dbo].[CleanExpiredSessions] @SessionsCleaned int OUTPUT AS SET DEADLOCK_PRIORITY LOW DECLARE @now as datetime SET @now = GETDATE() CREATE TABLE #tempSession (SessionID varchar(32) COLLATE Latin1_General_CI_AS_KS_WS, SnapshotDataID uniqueidentifier, CompiledDefinition uniqueidentifier) INSERT INTO #tempSession SELECT TOP 20 SessionID, SnapshotDataID, CompiledDefinition FROM ReportServerTempDB.dbo.SessionData WITH (XLOCK) WHERE Expiration < @now SET @SessionsCleaned = @@ROWCOUNT IF @SessionsCleaned = 0 RETURN -- Mark persisted streams for this session to be deleted UPDATE PS SET RefCount = 0, ExpirationDate = GETDATE() FROM ReportServerTempDB.dbo.PersistedStream AS PS INNER JOIN #tempSession on PS.SessionID = #tempsession.SessionID DELETE SE FROM ReportServerTempDB.dbo.SessionData AS SE INNER JOIN #tempSession on SE.SessionID = #tempsession.SessionID UPDATE SN SET TransientRefcount = TransientRefcount-1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN #tempSession AS SE ON SN.SnapshotDataID = SE.CompiledDefinition UPDATE SN SET TransientRefcount = TransientRefcount- (SELECT COUNT(*) FROM #tempSession AS SE1 WHERE SE1.SnapshotDataID = SN.SnapshotDataID) FROM SnapshotData AS SN INNER JOIN #tempSession AS SE ON SN.SnapshotDataID = SE.SnapshotDataID UPDATE SN SET TransientRefcount = TransientRefcount- (SELECT COUNT(*) FROM #tempSession AS SE1 WHERE SE1.SnapshotDataID = SN.SnapshotDataID) FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN #tempSession AS SE ON SN.SnapshotDataID = SE.SnapshotDataID GO GRANT EXECUTE ON [dbo].[CleanExpiredSessions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredCache]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredCache] GO CREATE PROCEDURE [dbo].[CleanExpiredCache] AS DECLARE @now as datetime SET @now = DATEADD(minute, -1, GETDATE()) UPDATE SN SET PermanentRefcount = PermanentRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON SN.SnapshotDataID = EC.SnapshotDataID WHERE EC.AbsoluteExpiration < @now DELETE EC FROM ReportServerTempDB.dbo.ExecutionCache AS EC WHERE EC.AbsoluteExpiration < @now GO GRANT EXECUTE ON [dbo].[CleanExpiredCache] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSessionCredentials]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSessionCredentials] GO CREATE PROCEDURE [dbo].[SetSessionCredentials] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @DataSourceInfo as image = NULL, @Expiration as datetime, @EffectiveParams as ntext = NULL AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT EXEC DereferenceSessionSnapshot @SessionID, @OwnerID UPDATE SE SET SE.DataSourceInfo = @DataSourceInfo, SE.SnapshotDataID = null, SE.IsPermanentSnapshot = null, SE.SnapshotExpirationDate = null, SE.ShowHideInfo = null, SE.HasInteractivity = null, SE.AutoRefreshSeconds = null, SE.Expiration = @Expiration, SE.EffectiveParams = @EffectiveParams, SE.AwaitingFirstExecution = 1 FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[SetSessionCredentials] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSessionParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSessionParameters] GO CREATE PROCEDURE [dbo].[SetSessionParameters] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @EffectiveParams as ntext = NULL AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT UPDATE SE SET SE.EffectiveParams = @EffectiveParams, SE.AwaitingFirstExecution = 1 FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[SetSessionParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ClearSessionSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ClearSessionSnapshot] GO CREATE PROCEDURE [dbo].[ClearSessionSnapshot] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @Expiration as datetime AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT EXEC DereferenceSessionSnapshot @SessionID, @OwnerID UPDATE SE SET SE.SnapshotDataID = null, SE.IsPermanentSnapshot = null, SE.SnapshotExpirationDate = null, SE.ShowHideInfo = null, SE.HasInteractivity = null, SE.AutoRefreshSeconds = null, SE.Expiration = @Expiration FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[ClearSessionSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RemoveReportFromSession]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RemoveReportFromSession] GO CREATE PROCEDURE [dbo].[RemoveReportFromSession] @SessionID as varchar(32), @ReportPath as nvarchar(440), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT EXEC DereferenceSessionSnapshot @SessionID, @OwnerID DELETE SE FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.ReportPath = @ReportPath AND SE.OwnerID = @OwnerID -- Delete any persisted streams associated with this session UPDATE PS SET PS.RefCount = 0, PS.ExpirationDate = GETDATE() FROM ReportServerTempDB.dbo.PersistedStream AS PS WHERE PS.SessionID = @SessionID GO GRANT EXECUTE ON [dbo].[RemoveReportFromSession] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanBrokenSnapshots]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanBrokenSnapshots] GO CREATE PROCEDURE [dbo].[CleanBrokenSnapshots] @Machine nvarchar(512), @SnapshotsCleaned int OUTPUT, @ChunksCleaned int OUTPUT, @TempSnapshotID uniqueidentifier OUTPUT AS SET DEADLOCK_PRIORITY LOW DECLARE @now AS datetime SELECT @now = GETDATE() CREATE TABLE #tempSnapshot (SnapshotDataID uniqueidentifier) INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM SnapshotData WITH (NOLOCK) where SnapshotData.PermanentRefcount <= 0 AND ExpirationDate < @now SET @SnapshotsCleaned = @@ROWCOUNT DELETE ChunkData FROM ChunkData INNER JOIN #tempSnapshot ON ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @@ROWCOUNT DELETE SnapshotData FROM SnapshotData INNER JOIN #tempSnapshot ON SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID TRUNCATE TABLE #tempSnapshot INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM ReportServerTempDB.dbo.SnapshotData WITH (NOLOCK) where ReportServerTempDB.dbo.SnapshotData.PermanentRefcount <= 0 AND ReportServerTempDB.dbo.SnapshotData.ExpirationDate < @now AND ReportServerTempDB.dbo.SnapshotData.Machine = @Machine SET @SnapshotsCleaned = @SnapshotsCleaned + @@ROWCOUNT SELECT @TempSnapshotID = (SELECT SnapshotDataID FROM #tempSnapshot) DELETE ReportServerTempDB.dbo.ChunkData FROM ReportServerTempDB.dbo.ChunkData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @ChunksCleaned + @@ROWCOUNT DELETE ReportServerTempDB.dbo.SnapshotData FROM ReportServerTempDB.dbo.SnapshotData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID GO GRANT EXECUTE ON [dbo].[CleanBrokenSnapshots] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanOrphanedSnapshots]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanOrphanedSnapshots] GO CREATE PROCEDURE [dbo].[CleanOrphanedSnapshots] @Machine nvarchar(512), @SnapshotsCleaned int OUTPUT, @ChunksCleaned int OUTPUT, @TempSnapshotID uniqueidentifier OUTPUT AS SET DEADLOCK_PRIORITY LOW CREATE TABLE #tempSnapshot (SnapshotDataID uniqueidentifier) INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM SnapshotData WITH (NOLOCK) where SnapshotData.PermanentRefcount = 0 AND SnapshotData.TransientRefcount = 0 SET @SnapshotsCleaned = @@ROWCOUNT DELETE ChunkData FROM ChunkData INNER JOIN #tempSnapshot ON ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @@ROWCOUNT DELETE SnapshotData FROM SnapshotData INNER JOIN #tempSnapshot ON SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID TRUNCATE TABLE #tempSnapshot INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM ReportServerTempDB.dbo.SnapshotData WITH (NOLOCK) where ReportServerTempDB.dbo.SnapshotData.PermanentRefcount = 0 AND ReportServerTempDB.dbo.SnapshotData.TransientRefcount = 0 AND ReportServerTempDB.dbo.SnapshotData.Machine = @Machine SET @SnapshotsCleaned = @SnapshotsCleaned + @@ROWCOUNT SELECT @TempSnapshotID = (SELECT SnapshotDataID FROM #tempSnapshot) DELETE ReportServerTempDB.dbo.ChunkData FROM ReportServerTempDB.dbo.ChunkData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @ChunksCleaned + @@ROWCOUNT DELETE ReportServerTempDB.dbo.SnapshotData FROM ReportServerTempDB.dbo.SnapshotData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID GO GRANT EXECUTE ON [dbo].[CleanOrphanedSnapshots] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetCacheOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetCacheOptions] GO CREATE PROCEDURE [dbo].[SetCacheOptions] @Path as nvarchar(425), @CacheReport as bit, @ExpirationFlags as int, @CacheExpiration as int = NULL AS DECLARE @CachePolicyID as uniqueidentifier SELECT @CachePolicyID = (SELECT CachePolicyID FROM CachePolicy with (XLOCK) INNER JOIN Catalog ON Catalog.ItemID = CachePolicy.ReportID WHERE Catalog.Path = @Path) IF @CachePolicyID IS NULL -- no policy exists BEGIN IF @CacheReport = 1 -- create a new one BEGIN INSERT INTO CachePolicy (CachePolicyID, ReportID, ExpirationFlags, CacheExpiration) (SELECT NEWID(), ItemID, @ExpirationFlags, @CacheExpiration FROM Catalog WHERE Catalog.Path = @Path) END -- ELSE if it has no policy and we want to remove its policy do nothing END ELSE -- existing policy BEGIN IF @CacheReport = 1 BEGIN UPDATE CachePolicy SET ExpirationFlags = @ExpirationFlags, CacheExpiration = @CacheExpiration WHERE CachePolicyID = @CachePolicyID EXEC FlushReportFromCache @Path END ELSE BEGIN DELETE FROM CachePolicy WHERE CachePolicyID = @CachePolicyID EXEC FlushReportFromCache @Path END END GO GRANT EXECUTE ON [dbo].[SetCacheOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCacheOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetCacheOptions] GO CREATE PROCEDURE [dbo].[GetCacheOptions] @Path as nvarchar(425) AS SELECT ExpirationFlags, CacheExpiration, S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path] FROM CachePolicy INNER JOIN Catalog ON Catalog.ItemID = CachePolicy.ReportID LEFT outer join reportschedule rs on catalog.itemid = rs.reportid and rs.reportaction = 3 LEFT OUTER JOIN [Schedule] S ON S.ScheduleID = rs.ScheduleID LEFT OUTER JOIN [Users] Owner on Owner.UserID = S.[CreatedById] WHERE Catalog.Path = @Path GO GRANT EXECUTE ON [dbo].[GetCacheOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddReportToCache]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddReportToCache] GO CREATE PROCEDURE [dbo].[AddReportToCache] @ReportID as uniqueidentifier, @ExecutionDate datetime, @SnapshotDataID uniqueidentifier, @ExpirationDate datetime OUTPUT, @ScheduleID uniqueidentifier OUTPUT AS DECLARE @ExpirationFlags as int DECLARE @Timeout as int SET @ExpirationDate = NULL SET @ScheduleID = NULL SET @ExpirationFlags = (SELECT ExpirationFlags FROM CachePolicy WHERE ReportID = @ReportID) IF @ExpirationFlags = 1 -- timeout based BEGIN SET @Timeout = (SELECT CacheExpiration FROM CachePolicy WHERE ReportID = @ReportID) SET @ExpirationDate = DATEADD(n, @Timeout, @ExecutionDate) END ELSE IF @ExpirationFlags = 2 -- schedule based BEGIN SET @ScheduleID = (SELECT s.ScheduleID FROM Schedule s INNER JOIN ReportSchedule rs on rs.ScheduleID = s.ScheduleID and rs.ReportAction = 3 WHERE rs.ReportID = @ReportID) SET @ExpirationDate = (SELECT Schedule.NextRunTime FROM Schedule with (XLOCK) WHERE Schedule.ScheduleID = @ScheduleID) END ELSE BEGIN RAISERROR('Invalid cache flags', 16, 1) END -- and to the report cache INSERT INTO ReportServerTempDB.dbo.ExecutionCache (ExecutionCacheID, ReportID, ExpirationFlags, AbsoluteExpiration, RelativeExpiration, SnapshotDataID) VALUES (newid(), @ReportID, @ExpirationFlags, @ExpirationDate, @Timeout, @SnapshotDataID ) UPDATE ReportServerTempDB.dbo.SnapshotData SET PermanentRefcount = PermanentRefcount + 1, IsCached = CONVERT(BIT, 1) WHERE SnapshotDataID = @SnapshotDataID; GO GRANT EXECUTE ON [dbo].[AddReportToCache] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetExecutionOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetExecutionOptions] GO CREATE PROCEDURE [dbo].[GetExecutionOptions] @Path nvarchar(425) AS SELECT ExecutionFlag, S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path] FROM Catalog LEFT OUTER JOIN ReportSchedule ON Catalog.ItemID = ReportSchedule.ReportID AND ReportSchedule.ReportAction = 1 LEFT OUTER JOIN [Schedule] S ON S.ScheduleID = ReportSchedule.ScheduleID LEFT OUTER JOIN [Users] Owner on Owner.UserID = S.[CreatedById] WHERE Catalog.Path = @Path GO GRANT EXECUTE ON [dbo].[GetExecutionOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetExecutionOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetExecutionOptions] GO CREATE PROCEDURE [dbo].[SetExecutionOptions] @Path as nvarchar(425), @ExecutionFlag as int, @ExecutionChanged as bit = 0 AS IF @ExecutionChanged = 0 BEGIN UPDATE Catalog SET ExecutionFlag = @ExecutionFlag WHERE Catalog.Path = @Path END ELSE BEGIN IF (@ExecutionFlag & 3) = 2 BEGIN -- set it to snapshot, flush cache EXEC FlushReportFromCache @Path DELETE CachePolicy FROM CachePolicy INNER JOIN Catalog ON CachePolicy.ReportID = Catalog.ItemID WHERE Catalog.Path = @Path END -- now clean existing snapshot and execution time if any UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 FROM SnapshotData INNER JOIN Catalog ON SnapshotData.SnapshotDataID = Catalog.SnapshotDataID WHERE Catalog.Path = @Path UPDATE Catalog SET ExecutionFlag = @ExecutionFlag, SnapshotDataID = NULL, ExecutionTime = NULL WHERE Catalog.Path = @Path END GO GRANT EXECUTE ON [dbo].[SetExecutionOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSnapshot] GO CREATE PROCEDURE [dbo].[UpdateSnapshot] @Path as nvarchar(425), @SnapshotDataID as uniqueidentifier, @executionDate as datetime AS DECLARE @OldSnapshotDataID uniqueidentifier SET @OldSnapshotDataID = (SELECT SnapshotDataID FROM Catalog WITH (XLOCK) WHERE Catalog.Path = @Path) -- update reference count in snapshot table UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount-1 WHERE SnapshotData.SnapshotDataID = @OldSnapshotDataID -- update catalog to point to the new execution snapshot UPDATE Catalog SET SnapshotDataID = @SnapshotDataID, ExecutionTime = @executionDate WHERE Catalog.Path = @Path UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount+1, TransientRefcount = TransientRefcount-1 WHERE SnapshotData.SnapshotDataID = @SnapshotDataID GO GRANT EXECUTE ON [dbo].[UpdateSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateChunkAndGetPointer]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateChunkAndGetPointer] GO CREATE PROCEDURE [dbo].[CreateChunkAndGetPointer] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int, @MimeType nvarchar(260) = NULL, @Version smallint, @Content image, @ChunkFlags tinyint = NULL, @ChunkPointer binary(16) OUTPUT AS DECLARE @ChunkID uniqueidentifier SET @ChunkID = NEWID() IF @IsPermanentSnapshot != 0 BEGIN DELETE ChunkData WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType INSERT INTO ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) VALUES (@ChunkID, @SnapshotDataID, @ChunkName, @ChunkType, @MimeType, @Version, @ChunkFlags, @Content) SELECT @ChunkPointer = TEXTPTR(Content) FROM ChunkData WHERE ChunkData.ChunkID = @ChunkID END ELSE BEGIN DELETE ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType INSERT INTO ReportServerTempDB.dbo.ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) VALUES (@ChunkID, @SnapshotDataID, @ChunkName, @ChunkType, @MimeType, @Version, @ChunkFlags, @Content) SELECT @ChunkPointer = TEXTPTR(Content) FROM ReportServerTempDB.dbo.ChunkData AS CH WHERE CH.ChunkID = @ChunkID END GO GRANT EXECUTE ON [dbo].[CreateChunkAndGetPointer] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteChunkPortion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteChunkPortion] GO CREATE PROCEDURE [dbo].[WriteChunkPortion] @ChunkPointer binary(16), @IsPermanentSnapshot bit, @DataIndex int = NULL, @DeleteLength int = NULL, @Content image AS IF @IsPermanentSnapshot != 0 BEGIN UPDATETEXT ChunkData.Content @ChunkPointer @DataIndex @DeleteLength @Content END ELSE BEGIN UPDATETEXT ReportServerTempDB.dbo.ChunkData.Content @ChunkPointer @DataIndex @DeleteLength @Content END GO GRANT EXECUTE ON [dbo].[WriteChunkPortion] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetChunkPointerAndLength]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetChunkPointerAndLength] GO CREATE PROCEDURE [dbo].[GetChunkPointerAndLength] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int AS IF @IsPermanentSnapshot != 0 BEGIN SELECT TEXTPTR(Content), DATALENGTH(Content), MimeType, ChunkFlags, Version FROM ChunkData AS CH WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END ELSE BEGIN SELECT TEXTPTR(Content), DATALENGTH(Content), MimeType, ChunkFlags, Version FROM ReportServerTempDB.dbo.ChunkData AS CH WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END GO GRANT EXECUTE ON [dbo].[GetChunkPointerAndLength] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetChunkInformation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetChunkInformation] GO CREATE PROCEDURE [dbo].[GetChunkInformation] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int AS IF @IsPermanentSnapshot != 0 BEGIN SELECT MimeType FROM ChunkData AS CH WITH (HOLDLOCK, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END ELSE BEGIN SELECT MimeType FROM ReportServerTempDB.dbo.ChunkData AS CH WITH (HOLDLOCK, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END GO GRANT EXECUTE ON [dbo].[GetChunkInformation] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadChunkPortion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadChunkPortion] GO CREATE PROCEDURE [dbo].[ReadChunkPortion] @ChunkPointer binary(16), @IsPermanentSnapshot bit, @DataIndex int, @Length int AS IF @IsPermanentSnapshot != 0 BEGIN READTEXT ChunkData.Content @ChunkPointer @DataIndex @Length END ELSE BEGIN READTEXT ReportServerTempDB.dbo.ChunkData.Content @ChunkPointer @DataIndex @Length END GO GRANT EXECUTE ON [dbo].[ReadChunkPortion] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CopyChunksOfType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CopyChunksOfType] GO CREATE PROCEDURE [dbo].[CopyChunksOfType] @FromSnapshotID uniqueidentifier, @FromIsPermanent bit, @ToSnapshotID uniqueidentifier, @ToIsPermanent bit, @ChunkType int, @ChunkName nvarchar(260) = NULL, @TargetChunkName nvarchar(260) = NULL AS DECLARE @Machine nvarchar(512) IF @FromIsPermanent != 0 AND @ToIsPermanent = 0 BEGIN -- copy the contiguous chunks INSERT INTO ReportServerTempDB.dbo.ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) SELECT newid(), @ToSnapshotID, COALESCE(@TargetChunkName, S.ChunkName), S.ChunkType, S.MimeType, S.Version, S.ChunkFlags, S.Content FROM ChunkData AS S WHERE S.SnapshotDataID = @FromSnapshotID AND (S.ChunkType = @ChunkType OR @ChunkType IS NULL) AND (S.ChunkName = @ChunkName OR @ChunkName IS NUll) AND NOT EXISTS( SELECT T.ChunkName FROM ReportServerTempDB.dbo.ChunkData AS T -- exclude the ones in the target WHERE T.ChunkName = COALESCE(@TargetChunkName, S.ChunkName) AND T.ChunkType = S.ChunkType AND T.SnapshotDataID = @ToSnapshotID) -- copying a segmented chunk from permanent to temp database -- requires doing a deep copy and updating all of the -- mapping tables DECLARE @CopiedChunkMetadata TABLE ( NewChunkId uniqueidentifier not null, OldChunkId uniqueidentifier not null ) -- generate ids for the chunks which we will copy -- @CopiedChunkMetadata will be already be filtered for chunks -- which already exist in the target snapshot INSERT INTO @CopiedChunkMetadata (NewChunkId, OldChunkId) SELECT newid(), SC.ChunkId FROM SegmentedChunk SC -- JOIN SnapshotChunkMapping SCM ON (SCM.ChunkId = SC.ChunkId) WHERE SC.SnapshotDataId = @FromSnapshotID AND (SC.ChunkType = @ChunkType OR @ChunkType IS NULL) AND (SC.ChunkName = @ChunkName OR @ChunkName IS NULL) AND NOT EXISTS( -- exclude chunks already in the target SELECT TSC.ChunkName FROM ReportServerTempDB.dbo.SegmentedChunk TSC -- JOIN ReportServerTempDB.dbo.SnapshotChunkMapping TSCM ON (TSC.ChunkId = TSCM.ChunkId) WHERE TSC.ChunkName = COALESCE(@TargetChunkName, SC.ChunkName) AND TSC.ChunkType = SC.ChunkType AND TSC.SnapshotDataId = @ToSnapshotID ) -- insert those chunks -- the chunks will be cleaned up by the machine in which they are being allocated to select @Machine = Machine from ReportServerTempDB.dbo.SnapshotData SD where SD.SnapshotDataID = @ToSnapshotID INSERT INTO ReportServerTempDB.dbo.SegmentedChunk (SnapshotDataId, ChunkID, ChunkFlags, ChunkName, ChunkType, Version, MimeType, Machine) SELECT @ToSnapshotID, CCM.NewChunkId, SC.ChunkFlags, COALESCE(@TargetChunkName, SC.ChunkName), SC.ChunkType, SC.Version, SC.MimeType, @Machine FROM SegmentedChunk SC JOIN @CopiedChunkMetadata CCM ON (CCM.OldChunkId = SC.ChunkId AND SC.SnapshotDataId = @FromSnapshotID) DECLARE @CopiedSegmentMetadata TABLE ( NewChunkId uniqueidentifier not null, OldChunkId uniqueidentifier not null, NewSegmentId uniqueidentifier not null, OldSegmentId uniqueidentifier not null, StartByte bigint not null ) INSERT INTO @CopiedSegmentMetadata (NewChunkId, OldChunkId, NewSegmentId, OldSegmentId, CSM.StartByte) SELECT CCM.NewChunkId, CCM.OldChunkId, newid(), S.SegmentId, CSM.StartByte FROM Segment S JOIN ChunkSegmentMapping CSM ON (S.SegmentId = CSM.SegmentId) JOIN @CopiedChunkMetadata CCM ON (CSM.ChunkId = CCM.OldChunkId) -- now copy the actual segment data into the tempdb INSERT INTO ReportServerTempDB.dbo.Segment (SegmentId, LogicalByteCount, Content) SELECT CSMETA.NewSegmentId, S.LogicalByteCount, S.Content FROM Segment S JOIN @CopiedSegmentMetadata CSMETA ON (S.SegmentId = CSMETA.OldSegmentId) -- now build the chunk->segment mapping INSERT INTO ReportServerTempDB.dbo.ChunkSegmentMapping (ChunkId, SegmentId, StartByte) SELECT CSMETA.NewChunkId, CSMETA.NewSegmentId, CSMETA.StartByte FROM @CopiedSegmentMetadata CSMETA END ELSE IF @FromIsPermanent = 0 AND @ToIsPermanent = 0 BEGIN -- the chunks exist on the node in which they were originally allocated on, they should -- be cleaned up by that node select @Machine = Machine from ReportServerTempDB.dbo.SnapshotData SD where SD.SnapshotDataID = @FromSnapshotID INSERT INTO ReportServerTempDB.dbo.ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) SELECT newid(), @ToSnapshotID, COALESCE(@TargetChunkName, S.ChunkName), S.ChunkType, S.MimeType, S.Version, S.ChunkFlags, S.Content FROM ReportServerTempDB.dbo.ChunkData AS S WHERE S.SnapshotDataID = @FromSnapshotID AND (S.ChunkType = @ChunkType OR @ChunkType IS NULL) AND (S.ChunkName = @ChunkName OR @ChunkName IS NULL) AND NOT EXISTS( SELECT T.ChunkName FROM ReportServerTempDB.dbo.ChunkData AS T -- exclude the ones in the target WHERE T.ChunkName = COALESCE(@TargetChunkName, S.ChunkName) AND T.ChunkType = S.ChunkType AND T.SnapshotDataID = @ToSnapshotID) -- copy the segmented chunks, copying the segmented -- chunks really just needs to update the mappings INSERT INTO ReportServerTempDB.dbo.SegmentedChunk (SnapshotDataId, ChunkId, ChunkName, ChunkType, Version, ChunkFlags, MimeType, Machine) SELECT @ToSnapshotID, ChunkId, COALESCE(@TargetChunkName, C.ChunkName), C.ChunkType, C.Version, C.ChunkFlags, C.MimeType, @Machine -- FROM ReportServerTempDB.dbo.SnapshotChunkMapping SCM FROM ReportServerTempDB.dbo.SegmentedChunk C WHERE C.SnapshotDataId = @FromSnapshotID AND (C.ChunkType = @ChunkType OR @ChunkType IS NULL) AND (C.ChunkName = @ChunkName OR @ChunkName IS NULL) AND NOT EXISTS( -- exclude chunks that are already mapped into this snapshot SELECT T.ChunkId FROM ReportServerTempDB.dbo.SegmentedChunk T WHERE T.SnapshotDataId = @ToSnapshotID and T.ChunkName = COALESCE(@TargetChunkName, C.ChunkName) and T.ChunkType = C.ChunkType ) END ELSE IF @FromIsPermanent != 0 AND @ToIsPermanent != 0 BEGIN INSERT INTO ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) SELECT newid(), @ToSnapshotID, COALESCE(@TargetChunkName, S.ChunkName), S.ChunkType, S.MimeType, S.Version, S.ChunkFlags, S.Content FROM ChunkData AS S WHERE S.SnapshotDataID = @FromSnapshotID AND (S.ChunkType = @ChunkType OR @ChunkType IS NULL) AND (S.ChunkName = @ChunkName OR @ChunkName IS NULL) AND NOT EXISTS( SELECT T.ChunkName FROM ChunkData AS T -- exclude the ones in the target WHERE T.ChunkName = COALESCE(@TargetChunkName, S.ChunkName) AND T.ChunkType = S.ChunkType AND T.SnapshotDataID = @ToSnapshotID) -- copy the segmented chunks, copying the segmented -- chunks really just needs to update the mappings INSERT INTO SegmentedChunk (SnapshotDataId, ChunkId, ChunkName, ChunkType, Version, ChunkFlags, C.MimeType) SELECT @ToSnapshotID, ChunkId, COALESCE(@TargetChunkName, C.ChunkName), C.ChunkType, C.Version, C.ChunkFlags, C.MimeType -- FROM ReportServerTempDB.dbo.SnapshotChunkMapping SCM FROM SegmentedChunk C WHERE C.SnapshotDataId = @FromSnapshotID AND (C.ChunkType = @ChunkType OR @ChunkType IS NULL) AND (C.ChunkName = @ChunkName OR @ChunkName IS NULL) AND NOT EXISTS( -- exclude chunks that are already mapped into this snapshot SELECT T.ChunkId FROM SegmentedChunk T WHERE T.SnapshotDataId = @ToSnapshotID and T.ChunkName = COALESCE(@TargetChunkName, C.ChunkName) and T.ChunkType = C.ChunkType ) END ELSE BEGIN RAISERROR('Unsupported chunk copy', 16, 1) END GO GRANT EXECUTE ON [dbo].[CopyChunksOfType] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteSnapshotAndChunks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteSnapshotAndChunks] GO CREATE PROCEDURE [dbo].[DeleteSnapshotAndChunks] @SnapshotID uniqueidentifier, @IsPermanentSnapshot bit AS -- Deleting from SnapshotData will cascade -- the deletion to the SegmentedChunk -- we will then lazily clean up the SegmentedChunk metadata -- along with the actual segment data IF @IsPermanentSnapshot != 0 BEGIN DELETE ChunkData WHERE ChunkData.SnapshotDataID = @SnapshotID DELETE SnapshotData WHERE SnapshotData.SnapshotDataID = @SnapshotID END ELSE BEGIN DELETE ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotID DELETE ReportServerTempDB.dbo.SnapshotData WHERE SnapshotDataID = @SnapshotID END GO GRANT EXECUTE ON [dbo].[DeleteSnapshotAndChunks] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteOneChunk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteOneChunk] GO CREATE PROCEDURE [dbo].[DeleteOneChunk] @SnapshotID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int AS -- for segmented chunks we just need to -- remove the mapping, the cleanup thread -- will pick up the rest of the pieces IF @IsPermanentSnapshot != 0 BEGIN DELETE ChunkData WHERE SnapshotDataID = @SnapshotID AND ChunkName = @ChunkName AND ChunkType = @ChunkType DELETE SegmentedChunk WHERE SnapshotDataId = @SnapshotID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END ELSE BEGIN DELETE ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotID AND ChunkName = @ChunkName AND ChunkType = @ChunkType DELETE ReportServerTempDB.dbo.SegmentedChunk WHERE SnapshotDataId = @SnapshotID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END GO GRANT EXECUTE ON [dbo].[DeleteOneChunk] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateRdlChunk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateRdlChunk] GO CREATE PROCEDURE [dbo].[CreateRdlChunk] @ItemId UNIQUEIDENTIFIER, @SnapshotId UNIQUEIDENTIFIER, @IsPermanentSnapshot BIT, @ChunkName NVARCHAR(260), @ChunkFlags TINYINT, @ChunkType INT, @Version SMALLINT, @MimeType NVARCHAR(260) = NULL AS BEGIN IF @IsPermanentSnapshot != 0 BEGIN INSERT INTO [ChunkData] ( ChunkId, SnapshotDataId, ChunkFlags, ChunkName, ChunkType, Version, MimeType, Content ) SELECT NEWID(), @SnapshotId, @ChunkFlags, @ChunkName, @ChunkType, @Version, @MimeType, ISNULL(Linked.Content, Original.Content) FROM [Catalog] Original LEFT OUTER JOIN [Catalog] Linked WITH (INDEX(PK_Catalog)) ON (Original.LinkSourceId = Linked.ItemId) WHERE Original.ItemId = @ItemId AND NOT EXISTS ( SELECT * FROM [ChunkData] WHERE SnapshotDataId = @SnapshotId AND ChunkName = @ChunkName AND ChunkType = @ChunkType ) END ELSE BEGIN INSERT INTO ReportServerTempDB.[dbo].[ChunkData] ( ChunkId, SnapshotDataId, ChunkFlags, ChunkName, ChunkType, Version, MimeType, Content ) SELECT NEWID(), @SnapshotId, @ChunkFlags, @ChunkName, @ChunkType, @Version, @MimeType, ISNULL(Linked.Content, Original.Content) FROM [Catalog] Original LEFT OUTER JOIN [Catalog] Linked WITH (INDEX(PK_Catalog)) ON (Original.LinkSourceId = Linked.ItemId) WHERE Original.ItemId = @ItemId AND NOT EXISTS ( SELECT * FROM ReportServerTempDB.[dbo].[ChunkData] WHERE SnapshotDataId = @SnapshotId AND ChunkName = @ChunkName AND ChunkType = @ChunkType ) END END GRANT EXECUTE ON [dbo].[CreateRdlChunk] TO RSExecRole GO -------------------------------------------------- ------------- Persisted stream SPs if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeletePersistedStreams]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeletePersistedStreams] GO CREATE PROCEDURE [dbo].[DeletePersistedStreams] @SessionID varchar(32) AS delete ReportServerTempDB.dbo.PersistedStream from (select top 1 * from ReportServerTempDB.dbo.PersistedStream PS2 where PS2.SessionID = @SessionID) as e1 where e1.SessionID = ReportServerTempDB.dbo.PersistedStream.[SessionID] and e1.[Index] = ReportServerTempDB.dbo.PersistedStream.[Index] GO GRANT EXECUTE ON [dbo].[DeletePersistedStreams] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteExpiredPersistedStreams]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteExpiredPersistedStreams] GO CREATE PROCEDURE [dbo].[DeleteExpiredPersistedStreams] AS SET DEADLOCK_PRIORITY LOW DELETE ReportServerTempDB.dbo.PersistedStream FROM (SELECT TOP 1 * FROM ReportServerTempDB.dbo.PersistedStream PS2 WHERE PS2.RefCount = 0 AND GETDATE() > PS2.ExpirationDate) AS e1 WHERE e1.SessionID = ReportServerTempDB.dbo.PersistedStream.[SessionID] AND e1.[Index] = ReportServerTempDB.dbo.PersistedStream.[Index] GO GRANT EXECUTE ON [dbo].[DeleteExpiredPersistedStreams] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeletePersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeletePersistedStream] GO CREATE PROCEDURE [dbo].[DeletePersistedStream] @SessionID varchar(32), @Index int AS delete from ReportServerTempDB.dbo.PersistedStream where SessionID = @SessionID and [Index] = @Index GO GRANT EXECUTE ON [dbo].[DeletePersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddPersistedStream] GO CREATE PROCEDURE [dbo].[AddPersistedStream] @SessionID varchar(32), @Index int AS DECLARE @RefCount int DECLARE @id varchar(32) DECLARE @ExpirationDate datetime set @RefCount = 0 set @ExpirationDate = DATEADD(day, 2, GETDATE()) set @id = (select SessionID from ReportServerTempDB.dbo.SessionData where SessionID = @SessionID) if @id is not null begin set @RefCount = 1 end INSERT INTO ReportServerTempDB.dbo.PersistedStream (SessionID, [Index], [RefCount], [ExpirationDate]) VALUES (@SessionID, @Index, @RefCount, @ExpirationDate) GO GRANT EXECUTE ON [dbo].[AddPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[LockPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[LockPersistedStream] GO CREATE PROCEDURE [dbo].[LockPersistedStream] @SessionID varchar(32), @Index int AS SELECT [Index] FROM ReportServerTempDB.dbo.PersistedStream WITH (XLOCK) WHERE SessionID = @SessionID AND [Index] = @Index GO GRANT EXECUTE ON [dbo].[LockPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteFirstPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteFirstPortionPersistedStream] GO CREATE PROCEDURE [dbo].[WriteFirstPortionPersistedStream] @SessionID varchar(32), @Index int, @Name nvarchar(260) = NULL, @MimeType nvarchar(260) = NULL, @Extension nvarchar(260) = NULL, @Encoding nvarchar(260) = NULL, @Content image AS UPDATE ReportServerTempDB.dbo.PersistedStream set Content = @Content, [Name] = @Name, MimeType = @MimeType, Extension = @Extension WHERE SessionID = @SessionID AND [Index] = @Index SELECT TEXTPTR(Content) FROM ReportServerTempDB.dbo.PersistedStream WHERE SessionID = @SessionID AND [Index] = @Index GO GRANT EXECUTE ON [dbo].[WriteFirstPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteNextPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteNextPortionPersistedStream] GO CREATE PROCEDURE [dbo].[WriteNextPortionPersistedStream] @DataPointer binary(16), @DataIndex int, @DeleteLength int, @Content image AS UPDATETEXT ReportServerTempDB.dbo.PersistedStream.Content @DataPointer @DataIndex @DeleteLength @Content GO GRANT EXECUTE ON [dbo].[WriteNextPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetFirstPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetFirstPortionPersistedStream] GO CREATE PROCEDURE [dbo].[GetFirstPortionPersistedStream] @SessionID varchar(32) AS SELECT TOP 1 TEXTPTR(P.Content), DATALENGTH(P.Content), P.[Index], P.[Name], P.MimeType, P.Extension, P.Encoding, P.Error FROM ReportServerTempDB.dbo.PersistedStream P WITH (XLOCK) WHERE P.SessionID = @SessionID GO GRANT EXECUTE ON [dbo].[GetFirstPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetPersistedStreamError]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetPersistedStreamError] GO CREATE PROCEDURE [dbo].[SetPersistedStreamError] @SessionID varchar(32), @Index int, @AllRows bit, @Error nvarchar(512) AS if @AllRows = 0 BEGIN UPDATE ReportServerTempDB.dbo.PersistedStream SET Error = @Error WHERE SessionID = @SessionID and [Index] = @Index END ELSE BEGIN UPDATE ReportServerTempDB.dbo.PersistedStream SET Error = @Error WHERE SessionID = @SessionID END GO GRANT EXECUTE ON [dbo].[SetPersistedStreamError] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetNextPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetNextPortionPersistedStream] GO CREATE PROCEDURE [dbo].[GetNextPortionPersistedStream] @DataPointer binary(16), @DataIndex int, @Length int AS READTEXT ReportServerTempDB.dbo.PersistedStream.Content @DataPointer @DataIndex @Length GO GRANT EXECUTE ON [dbo].[GetNextPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapshotChunks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapshotChunks] GO CREATE PROCEDURE [dbo].[GetSnapshotChunks] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit AS IF @IsPermanentSnapshot != 0 BEGIN SELECT ChunkName, ChunkType, ChunkFlags, MimeType, Version, datalength(Content) FROM ChunkData WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN SELECT ChunkName, ChunkType, ChunkFlags, MimeType, Version, datalength(Content) FROM ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[GetSnapshotChunks] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetDrillthroughReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetDrillthroughReports] GO CREATE PROCEDURE [dbo].[SetDrillthroughReports] @ReportID uniqueidentifier, @ModelID uniqueidentifier, @ModelItemID nvarchar(425), @Type tinyint AS INSERT INTO ModelDrill (ModelDrillID, ModelID, ReportID, ModelItemID, [Type]) VALUES (newid(), @ModelID, @ReportID, @ModelItemID, @Type) GO GRANT EXECUTE ON [dbo].[SetDrillthroughReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteDrillthroughReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteDrillthroughReports] GO CREATE PROCEDURE [dbo].[DeleteDrillthroughReports] @ModelID uniqueidentifier, @ModelItemID nvarchar(425) AS DELETE ModelDrill WHERE ModelID = @ModelID and ModelItemID = @ModelItemID GO GRANT EXECUTE ON [dbo].[DeleteDrillthroughReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDrillthroughReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDrillthroughReports] GO CREATE PROCEDURE [dbo].[GetDrillthroughReports] @ModelID uniqueidentifier, @ModelItemID nvarchar(425) AS SELECT ModelDrill.Type, Catalog.Path FROM ModelDrill INNER JOIN Catalog ON ModelDrill.ReportID = Catalog.ItemID WHERE ModelID = @ModelID AND ModelItemID = @ModelItemID GO GRANT EXECUTE ON [dbo].[GetDrillthroughReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDrillthroughReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDrillthroughReport] GO CREATE PROCEDURE [dbo].[GetDrillthroughReport] @ModelPath nvarchar(425), @ModelItemID nvarchar(425), @Type tinyint AS SELECT CatRep.Path FROM ModelDrill INNER JOIN Catalog CatMod ON ModelDrill.ModelID = CatMod.ItemID INNER JOIN Catalog CatRep ON ModelDrill.ReportID = CatRep.ItemID WHERE CatMod.Path = @ModelPath AND ModelItemID = @ModelItemID AND ModelDrill.[Type] = @Type GO GRANT EXECUTE ON [dbo].[GetDrillthroughReport] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUpgradeItems]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUpgradeItems] GO CREATE PROCEDURE [dbo].[GetUpgradeItems] AS SELECT [Item], [Status] FROM [UpgradeInfo] GO GRANT EXECUTE ON [dbo].[GetUpgradeItems] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetUpgradeItemStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetUpgradeItemStatus] GO CREATE PROCEDURE [dbo].[SetUpgradeItemStatus] @ItemName nvarchar(260), @Status nvarchar(512) AS UPDATE [UpgradeInfo] SET [Status] = @Status WHERE [Item] = @ItemName GO GRANT EXECUTE ON [dbo].[SetUpgradeItemStatus] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPolicyRoots]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPolicyRoots] GO CREATE PROCEDURE [dbo].[GetPolicyRoots] AS SELECT [Path], [Type] FROM [Catalog] WHERE [PolicyRoot] = 1 GO GRANT EXECUTE ON [dbo].[GetPolicyRoots] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDataSourceForUpgrade]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDataSourceForUpgrade] GO CREATE PROCEDURE [dbo].[GetDataSourceForUpgrade] @CurrentVersion int AS SELECT [DSID] FROM [DataSource] WHERE [Version] != @CurrentVersion GO GRANT EXECUTE ON [dbo].[GetDataSourceForUpgrade] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSubscriptionsForUpgrade]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSubscriptionsForUpgrade] GO CREATE PROCEDURE [dbo].[GetSubscriptionsForUpgrade] @CurrentVersion int AS SELECT [SubscriptionID] FROM [Subscriptions] WHERE [Version] != @CurrentVersion GO GRANT EXECUTE ON [dbo].[GetSubscriptionsForUpgrade] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[StoreServerParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[StoreServerParameters] GO CREATE PROCEDURE [dbo].[StoreServerParameters] @ServerParametersID nvarchar(32), @Path nvarchar(425), @CurrentDate datetime, @Timeout int, @Expiration datetime, @ParametersValues image, @ParentParametersID nvarchar(32) = NULL AS DECLARE @ExistingServerParametersID as nvarchar(32) SET @ExistingServerParametersID = (SELECT ServerParametersID from [dbo].[ServerParametersInstance] WHERE ServerParametersID = @ServerParametersID) IF @ExistingServerParametersID IS NULL -- new row BEGIN INSERT INTO [dbo].[ServerParametersInstance] (ServerParametersID, ParentID, Path, CreateDate, ModifiedDate, Timeout, Expiration, ParametersValues) VALUES (@ServerParametersID, @ParentParametersID, @Path, @CurrentDate, @CurrentDate, @Timeout, @Expiration, @ParametersValues) END ELSE BEGIN UPDATE [dbo].[ServerParametersInstance] SET Timeout = @Timeout, Expiration = @Expiration, ParametersValues = @ParametersValues, ModifiedDate = @CurrentDate, Path = @Path, ParentID = @ParentParametersID WHERE ServerParametersID = @ServerParametersID END GO GRANT EXECUTE ON [dbo].[StoreServerParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetServerParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetServerParameters] GO CREATE PROCEDURE [dbo].[GetServerParameters] @ServerParametersID nvarchar(32) AS DECLARE @now as DATETIME SET @now = GETDATE() SELECT Child.Path, Child.ParametersValues, Parent.ParametersValues FROM [dbo].[ServerParametersInstance] Child LEFT OUTER JOIN [dbo].[ServerParametersInstance] Parent ON Child.ParentID = Parent.ServerParametersID WHERE Child.ServerParametersID = @ServerParametersID AND Child.Expiration > @now GO GRANT EXECUTE ON [dbo].[GetServerParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredServerParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredServerParameters] GO CREATE PROCEDURE [dbo].[CleanExpiredServerParameters] @ParametersCleaned INT OUTPUT AS DECLARE @now as DATETIME SET @now = GETDATE() DELETE FROM [dbo].[ServerParametersInstance] WHERE ServerParametersID IN ( SELECT TOP 20 ServerParametersID FROM [dbo].[ServerParametersInstance] WHERE Expiration < @now ) SET @ParametersCleaned = @@ROWCOUNT GO GRANT EXECUTE ON [dbo].[CleanExpiredServerParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CopyChunks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CopyChunks] GO -- TODO: Modify to support segmented chunks CREATE PROCEDURE [dbo].[CopyChunks] @OldSnapshotId UNIQUEIDENTIFIER, @NewSnapshotId UNIQUEIDENTIFIER, @IsPermanentSnapshot BIT AS BEGIN IF(@IsPermanentSnapshot = 1) BEGIN -- copy non-segmented chunks INSERT [dbo].[ChunkData] ( ChunkId, SnapshotDataId, ChunkFlags, ChunkName, ChunkType, Version, MimeType, Content ) SELECT NEWID(), @NewSnapshotId, [c].[ChunkFlags], [c].[ChunkName], [c].[ChunkType], [c].[Version], [c].[MimeType], [c].[Content] FROM [dbo].[ChunkData] [c] WHERE [c].[SnapshotDataId] = @OldSnapshotId -- copy segmented chunks... real easy just add the mapping INSERT [dbo].[SegmentedChunk]( ChunkId, SnapshotDataId, ChunkName, ChunkType, Version, MimeType, ChunkFlags ) SELECT ChunkId, @NewSnapshotId, ChunkName, ChunkType, Version, MimeType, ChunkFlags FROM [dbo].[SegmentedChunk] WHERE [SnapshotDataId] = @OldSnapshotId END ELSE BEGIN -- copy non-segmented chunks INSERT ReportServerTempDB.dbo.[ChunkData] ( ChunkId, SnapshotDataId, ChunkFlags, ChunkName, ChunkType, Version, MimeType, Content ) SELECT NEWID(), @NewSnapshotId, [c].[ChunkFlags], [c].[ChunkName], [c].[ChunkType], [c].[Version], [c].[MimeType], [c].[Content] FROM ReportServerTempDB.dbo.[ChunkData] [c] WHERE [c].[SnapshotDataId] = @OldSnapshotId -- copy segmented chunks... real easy just add the mapping INSERT ReportServerTempDB.[dbo].[SegmentedChunk]( ChunkId, SnapshotDataId, ChunkName, ChunkType, Version, MimeType, ChunkFlags, Machine ) SELECT ChunkId, @NewSnapshotId, ChunkName, ChunkType, Version, MimeType, ChunkFlags, Machine FROM ReportServerTempDB.dbo.[SegmentedChunk] WHERE [SnapshotDataId] = @OldSnapshotId END END GO GRANT EXECUTE ON [dbo].[CopyChunks] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateNewSnapshotVersion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateNewSnapshotVersion] GO CREATE PROCEDURE [dbo].[CreateNewSnapshotVersion] @OldSnapshotId UNIQUEIDENTIFIER, @NewSnapshotId UNIQUEIDENTIFIER, @IsPermanentSnapshot BIT, @Machine NVARCHAR(512) AS BEGIN IF(@IsPermanentSnapshot = 1) BEGIN INSERT [dbo].[SnapshotData] ( SnapshotDataId, CreatedDate, ParamsHash, QueryParams, EffectiveParams, Description, DependsOnUser, PermanentRefCount, TransientRefCount, ExpirationDate, PageCount, HasDocMap, PaginationMode, ProcessingFlags ) SELECT @NewSnapshotId, [sn].CreatedDate, [sn].ParamsHash, [sn].QueryParams, [sn].EffectiveParams, [sn].Description, [sn].DependsOnUser, 0, 1, -- always create with transient refcount of 1 [sn].ExpirationDate, [sn].PageCount, [sn].HasDocMap, [sn].PaginationMode, [sn].ProcessingFlags FROM [dbo].[SnapshotData] [sn] WHERE [sn].SnapshotDataId = @OldSnapshotId END ELSE BEGIN INSERT ReportServerTempDB.dbo.[SnapshotData] ( SnapshotDataId, CreatedDate, ParamsHash, QueryParams, EffectiveParams, Description, DependsOnUser, PermanentRefCount, TransientRefCount, ExpirationDate, PageCount, HasDocMap, PaginationMode, ProcessingFlags, Machine, IsCached ) SELECT @NewSnapshotId, [sn].CreatedDate, [sn].ParamsHash, [sn].QueryParams, [sn].EffectiveParams, [sn].Description, [sn].DependsOnUser, 0, 1, -- always create with transient refcount of 1 [sn].ExpirationDate, [sn].PageCount, [sn].HasDocMap, [sn].PaginationMode, [sn].ProcessingFlags, @Machine, [sn].IsCached FROM ReportServerTempDB.dbo.[SnapshotData] [sn] WHERE [sn].SnapshotDataId = @OldSnapshotId END EXEC [dbo].[CopyChunks] @OldSnapshotId = @OldSnapshotId, @NewSnapshotId = @NewSnapshotId, @IsPermanentSnapshot = @IsPermanentSnapshot END GO GRANT EXECUTE ON [dbo].[CreateNewSnapshotVersion] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSnapshotReferences]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSnapshotReferences] GO CREATE PROCEDURE [dbo].[UpdateSnapshotReferences] @OldSnapshotId UNIQUEIDENTIFIER, @NewSnapshotId UNIQUEIDENTIFIER, @IsPermanentSnapshot BIT, @TransientRefCountModifier INT, @UpdatedReferences INT OUTPUT AS BEGIN SET @UpdatedReferences = 0 IF(@IsPermanentSnapshot = 1) BEGIN -- Update Snapshot Executions UPDATE [dbo].[Catalog] SET [SnapshotDataID] = @NewSnapshotId WHERE [SnapshotDataID] = @OldSnapshotId SELECT @UpdatedReferences = @UpdatedReferences + @@ROWCOUNT -- Update History UPDATE [dbo].[History] SET [SnapshotDataID] = @NewSnapshotId WHERE [SnapshotDataID] = @OldSnapshotId SELECT @UpdatedReferences = @UpdatedReferences + @@ROWCOUNT UPDATE [dbo].[SnapshotData] SET [PermanentRefcount] = [PermanentRefcount] - @UpdatedReferences, [TransientRefcount] = [TransientRefcount] + @TransientRefCountModifier WHERE [SnapshotDataID] = @OldSnapshotId UPDATE [dbo].[SnapshotData] SET [PermanentRefcount] = [PermanentRefcount] + @UpdatedReferences WHERE [SnapshotDataID] = @NewSnapshotId END ELSE BEGIN -- Update Execution Cache UPDATE ReportServerTempDB.dbo.[ExecutionCache] SET [SnapshotDataID] = @NewSnapshotId WHERE [SnapshotDataID] = @OldSnapshotId SELECT @UpdatedReferences = @UpdatedReferences + @@ROWCOUNT UPDATE ReportServerTempDB.dbo.[SnapshotData] SET [PermanentRefcount] = [PermanentRefcount] - @UpdatedReferences, [TransientRefcount] = [TransientRefcount] + @TransientRefCountModifier WHERE [SnapshotDataID] = @OldSnapshotId UPDATE ReportServerTempDB.dbo.[SnapshotData] SET [PermanentRefcount] = [PermanentRefcount] + @UpdatedReferences WHERE [SnapshotDataID] = @NewSnapshotId END END GO GRANT EXECUTE ON [dbo].[UpdateSnapshotReferences] TO RSExecRole GO -------------------------------------------------- ------------- Segmented Chunk Infrastructure -------------------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[OpenSegmentedChunk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[OpenSegmentedChunk] GO create proc [dbo].[OpenSegmentedChunk] @SnapshotId uniqueidentifier, @IsPermanent bit, @ChunkName nvarchar(260), @ChunkType int as begin -- Note that we use NOLOCK for everything. This is correct -- due to the fact that we only modify chunks for snapshots -- which are session snapshots, and those are protected by session lock. -- other snapshots are duplicated on write which maintains consistency -- in a lock-free manner from the chunk perspective if (@IsPermanent = 1) begin select chunk.ChunkId, chunk.ChunkFlags, seg.SegmentId, seg.LogicalByteCount as LogicalSegmentLength, convert(int, datalength(Content)) as ActualSegmentLength from dbo.SegmentedChunk chunk with (NOLOCK) join ChunkSegmentMapping csm with (NOLOCK) on (chunk.ChunkId = csm.ChunkId) join Segment seg with (NOLOCK) on (seg.SegmentId = csm.SegmentId) where chunk.SnapshotDataId = @SnapshotId and chunk.ChunkName = @ChunkName and chunk.ChunkType = @ChunkType order by csm.StartByte asc end else begin select chunk.ChunkId, chunk.ChunkFlags, seg.SegmentId, seg.LogicalByteCount as LogicalSegmentLength, convert(int, datalength(Content)) as ActualSegmentLength from ReportServerTempDB.dbo.SegmentedChunk chunk with (NOLOCK) join ReportServerTempDB.dbo.ChunkSegmentMapping csm with(NOLOCK) on (chunk.ChunkId = csm.ChunkId) join ReportServerTempDB.dbo.Segment seg with (NOLOCK) on (seg.SegmentId = csm.SegmentId) where chunk.SnapshotDataId = @SnapshotId and chunk.ChunkName = @ChunkName and chunk.ChunkType = @ChunkType order by csm.StartByte asc end end GO GRANT EXECUTE ON [dbo].[OpenSegmentedChunk] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateSegmentedChunk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateSegmentedChunk] GO create proc [dbo].[CreateSegmentedChunk] @SnapshotId uniqueidentifier, @IsPermanent bit, @ChunkName nvarchar(260), @ChunkFlags tinyint, @ChunkType int, @Version smallint, @MimeType nvarchar(260) = null, @Machine nvarchar(512), @ChunkId uniqueidentifier out as begin select @ChunkId = newid() ; if (@IsPermanent = 1) begin delete SegmentedChunk where SnapshotDataId = @SnapshotId and ChunkName = @ChunkName and ChunkType = @ChunkType delete ChunkData where SnapshotDataID = @SnapshotId and ChunkName = @ChunkName and ChunkType = @ChunkType insert SegmentedChunk(SnapshotDataId, ChunkId, ChunkFlags, ChunkName, ChunkType, Version, MimeType) values (@SnapshotId, @ChunkId, @ChunkFlags, @ChunkName, @ChunkType, @Version, @MimeType) ; end else begin delete ReportServerTempDB.dbo.SegmentedChunk where SnapshotDataId = @SnapshotId and ChunkName = @ChunkName and ChunkType = @ChunkType delete ReportServerTempDB.dbo.ChunkData where SnapshotDataID = @SnapshotId and ChunkName = @ChunkName and ChunkType = @ChunkType insert ReportServerTempDB.dbo.SegmentedChunk(SnapshotDataId, ChunkId, ChunkFlags, ChunkName, ChunkType, Version, MimeType, Machine) values (@SnapshotId, @ChunkId, @ChunkFlags, @ChunkName, @ChunkType, @Version, @MimeType, @Machine) ; end end GO GRANT EXECUTE ON [dbo].[CreateSegmentedChunk] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadChunkSegment]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadChunkSegment] GO create proc [dbo].[ReadChunkSegment] @ChunkId uniqueidentifier, @SegmentId uniqueidentifier, @IsPermanent bit, @DataIndex int, @Length int as begin if(@IsPermanent = 1) begin select substring(seg.Content, @DataIndex + 1, @Length) as [Content] from Segment seg join ChunkSegmentMapping csm on (csm.SegmentId = seg.SegmentId) where csm.ChunkId = @ChunkId and csm.SegmentId = @SegmentId end else begin select substring(seg.Content, @DataIndex + 1, @Length) as [Content] from ReportServerTempDB.dbo.Segment seg join ReportServerTempDB.dbo.ChunkSegmentMapping csm on (csm.SegmentId = seg.SegmentId) where csm.ChunkId = @ChunkId and csm.SegmentId = @SegmentId end end GO GRANT EXECUTE ON [dbo].[ReadChunkSegment] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteChunkSegment]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteChunkSegment] GO create proc [dbo].[WriteChunkSegment] @ChunkId uniqueidentifier, @IsPermanent bit, @SegmentId uniqueidentifier, @DataIndex int, @Length int, @LogicalByteCount int, @Content varbinary(max) as begin if(@IsPermanent = 1) begin update Segment set LogicalByteCount = @LogicalByteCount, Content.write( substring(@Content, 1, @Length), @DataIndex, @Length ) from ChunkSegmentMapping csm where Segment.SegmentId = csm.SegmentId and csm.ChunkId = @ChunkId and csm.SegmentId = @SegmentId ; end else begin update ReportServerTempDB.dbo.Segment set LogicalByteCount = @LogicalByteCount, Content.write( substring(@Content, 1, @Length), @DataIndex, @Length ) from ReportServerTempDB.dbo.ChunkSegmentMapping csm where ReportServerTempDB.dbo.Segment.SegmentId = csm.SegmentId and csm.ChunkId = @ChunkId and csm.SegmentId = @SegmentId ; end if(@@rowcount <> 1) raiserror('unexpected # of segments update', 16, 1) end GO GRANT EXECUTE ON [dbo].[WriteChunkSegment] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateChunkSegment]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateChunkSegment] GO create proc [dbo].[CreateChunkSegment] @SnapshotId uniqueidentifier, @IsPermanent bit, @ChunkId uniqueidentifier, @Content varbinary(max) = 0x0, @StartByte bigint, @Length int = 0, @LogicalByteCount int = 0, @SegmentId uniqueidentifier out as begin select @SegmentId = newid() ; if(@IsPermanent = 1) begin insert Segment(SegmentId, LogicalByteCount, Content) values (@SegmentId, @LogicalByteCount, substring(@Content, 1, @Length)) ; insert ChunkSegmentMapping(ChunkId, SegmentId, StartByte) values (@ChunkId, @SegmentId, @StartByte) ; end else begin insert ReportServerTempDB.dbo.Segment(SegmentId, LogicalByteCount, Content) values (@SegmentId, @LogicalByteCount, substring(@Content, 1, @Length)) ; insert ReportServerTempDB.dbo.ChunkSegmentMapping(ChunkId, SegmentId, StartByte) values (@ChunkId, @SegmentId, @StartByte) ; end end GO GRANT EXECUTE ON [dbo].[CreateChunkSegment] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[IsSegmentedChunk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[IsSegmentedChunk] GO create proc [dbo].[IsSegmentedChunk] @SnapshotId uniqueidentifier, @IsPermanent bit, @ChunkName nvarchar(260), @ChunkType int, @IsSegmented bit out as begin -- segmented chunks are read w/nolock -- we don't really care about locking in this scenario -- we just need to get some metadata which never changes (if it is segmented or not) if (@IsPermanent = 1) begin select top 1 @IsSegmented = IsSegmented from ( select convert(bit, 0) from [ChunkData] c where c.ChunkName = @ChunkName and c.ChunkType = @ChunkType and c.SnapshotDataId = @SnapshotId union all select convert(bit, 1) from [SegmentedChunk] c WITH(NOLOCK) where c.ChunkName = @ChunkName and c.ChunkType = @ChunkType and c.SnapshotDataId = @SnapshotId ) A(IsSegmented) end else begin select top 1 @IsSegmented = IsSegmented from ( select convert(bit, 0) from ReportServerTempDB.dbo.[ChunkData] c where c.ChunkName = @ChunkName and c.ChunkType = @ChunkType and c.SnapshotDataId = @SnapshotId union all select convert(bit, 1) from ReportServerTempDB.dbo.[SegmentedChunk] c WITH(NOLOCK) where c.ChunkName = @ChunkName and c.ChunkType = @ChunkType and c.SnapshotDataId = @SnapshotId ) A(IsSegmented) end end GO GRANT EXECUTE ON [dbo].[IsSegmentedChunk] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ShallowCopyChunk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ShallowCopyChunk] GO create proc [dbo].[ShallowCopyChunk] @SnapshotId uniqueidentifier, @ChunkId uniqueidentifier, @IsPermanent bit, @Machine nvarchar(512), @NewChunkId uniqueidentifier out as begin -- @SnapshotId & @ChunkId are the old identifiers -- build the chunksegmentmapping first to prevent race -- condition with cleaning it up select @NewChunkId = newid() ; if (@IsPermanent = 1) begin insert ChunkSegmentMapping (ChunkId, SegmentId, StartByte) select @NewChunkId, SegmentId, StartByte from ChunkSegmentMapping where ChunkId = @ChunkId ; update SegmentedChunk set ChunkId = @NewChunkId where ChunkId = @ChunkId and SnapshotDataId = @SnapshotId end else begin insert ReportServerTempDB.dbo.ChunkSegmentMapping (ChunkId, SegmentId, StartByte) select @NewChunkId, SegmentId, StartByte from ReportServerTempDB.dbo.ChunkSegmentMapping where ChunkId = @ChunkId ; -- update the machine name also, this is only really useful -- for file system chunks, in which case the snapshot should -- have been versioned on the initial update update ReportServerTempDB.dbo.SegmentedChunk set ChunkId = @NewChunkId, Machine = @Machine where ChunkId = @ChunkId and SnapshotDataId = @SnapshotId end end GO GRANT EXECUTE ON [dbo].[ShallowCopyChunk] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeepCopySegment]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeepCopySegment] GO create proc [dbo].[DeepCopySegment] @ChunkId uniqueidentifier, @IsPermanent bit, @SegmentId uniqueidentifier, @NewSegmentId uniqueidentifier out as begin select @NewSegmentId = newid() ; if (@IsPermanent = 1) begin insert Segment(SegmentId, LogicalByteCount, Content) select @NewSegmentId, seg.LogicalByteCount, seg.Content from Segment seg where seg.SegmentId = @SegmentId ; update ChunkSegmentMapping set SegmentId = @NewSegmentId where ChunkId = @ChunkId and SegmentId = @SegmentId ; end else begin insert ReportServerTempDB.dbo.Segment(SegmentId, LogicalByteCount, Content) select @NewSegmentId, seg.LogicalByteCount, seg.Content from ReportServerTempDB.dbo.Segment seg where seg.SegmentId = @SegmentId ; update ReportServerTempDB.dbo.ChunkSegmentMapping set SegmentId = @NewSegmentId where ChunkId = @ChunkId and SegmentId = @SegmentId ; end end GO GRANT EXECUTE ON [dbo].[DeepCopySegment] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSegmentMapCleanupCandidates]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSegmentMapCleanupCandidates] GO create proc [dbo].[GetSegmentMapCleanupCandidates] @Machine nvarchar(512) as begin SET DEADLOCK_PRIORITY LOW -- query run with no locks since this is only deletion candidates -- we will confirm that the item is not locked when we actually -- GO to delete it select cast(1 as bit) as IsPermanent, CSM.ChunkId from ChunkSegmentMapping CSM with (NOLOCK) where not exists ( select 1 from SegmentedChunk SC with (NOLOCK) where CSM.ChunkId = SC.ChunkId ) group by CSM.ChunkId union all -- select any ChunkIds which are not referenced in the SegmentedChunk table select cast(0 as bit) as IsPermanent, CSM.ChunkId from ReportServerTempDB.dbo.ChunkSegmentMapping CSM with (NOLOCK) where not exists ( select 1 from ReportServerTempDB.dbo.SegmentedChunk SC with (NOLOCK) where CSM.ChunkId = SC.ChunkId ) group by CSM.ChunkId union all -- select ChunkIds which are refernced in the SegmentedChunk table -- but the snapshot no longer exists... note that this should -- only happen in the Temp catalog since FK operation cleans them -- up in the permanent catalog select cast(0 as bit) as IsPermanent, SC.ChunkId from ReportServerTempDB.dbo.SegmentedChunk SC with (NOLOCK) where SC.Machine = @Machine and not exists ( select 1 from ReportServerTempDB.dbo.SnapshotData SD where SD.SnapshotDataID = SC.SnapshotDataId ) end GO GRANT EXECUTE ON [dbo].[GetSegmentMapCleanupCandidates] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSegmentCleanupCandidates]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSegmentCleanupCandidates] GO create proc [dbo].[GetSegmentCleanupCandidates] as begin SET DEADLOCK_PRIORITY LOW -- query run with no locks since this is only deletion candidates -- we will confirm that the item is not locked when we actually -- GO to delete it select cast(1 as bit) as IsPermanent, S.SegmentId from Segment S with (NOLOCK) where not exists ( select 1 from ChunkSegmentMapping CSM with (NOLOCK) where S.SegmentId = CSM.SegmentId ) union all select cast(0 as bit) as IsPermanent, S.SegmentId from ReportServerTempDB.dbo.Segment S with (NOLOCK) where not exists ( select 1 from ReportServerTempDB.dbo.ChunkSegmentMapping CSM with (NOLOCK) where S.SegmentId = CSM.SegmentId ) end GO GRANT EXECUTE ON [dbo].[GetSegmentCleanupCandidates] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RemoveSegmentedMapping]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RemoveSegmentedMapping] GO create proc [dbo].[RemoveSegmentedMapping] @ChunkId uniqueidentifier, @IsPermanent bit, @DidDelete bit out as begin SET DEADLOCK_PRIORITY LOW -- only deletes the chunk if it is actually unreferenced -- in the case that it is in the process of being referenced, locks -- should be held to prevent the row from being removed if (@IsPermanent = 1) begin delete top (1024) from ChunkSegmentMapping where ChunkId = @ChunkId and not exists (select 1 from SegmentedChunk SC where SC.ChunkId = @ChunkId) ; end else begin -- the chunk was found in the SegmentedChunk table, but it could not -- be mapped to a snapshot delete top (1024) from ReportServerTempDB.dbo.SegmentedChunk where ChunkId = @ChunkId and not exists ( select 1 from ReportServerTempDB.dbo.SnapshotData SD where ReportServerTempDB.dbo.SegmentedChunk.SnapshotDataId = SD.SnapshotDataID ) -- don't change DidDelete here... we only want to mark the chunk -- as being deleted when we remove its mappings, otherwise we can -- prematurely remove chunks from the file system cache, we only -- touch did delete when we remove the mappings for a chunk indicating -- that it is not used anywhere anymore -- clean up the mapping delete top (1024) from ReportServerTempDB.dbo.ChunkSegmentMapping where ChunkId = @ChunkId and not exists (select 1 from ReportServerTempDB.dbo.SegmentedChunk SC where SC.ChunkId = @ChunkId) ; end select @DidDelete = case when @DidDelete = CONVERT(BIT,1) then 1 when @@rowcount > 0 then 1 else 0 end ; end GO GRANT EXECUTE ON [dbo].[RemoveSegmentedMapping] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RemoveSegment]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RemoveSegment] GO create proc [dbo].[RemoveSegment] @SegmentId uniqueidentifier, @IsPermanent bit, @DidDelete bit out as begin SET DEADLOCK_PRIORITY LOW -- only delete the chunk if it is not being referenced if (@IsPermanent = 1) begin delete from Segment where SegmentId = @SegmentId and not exists (select 1 from ChunkSegmentMapping CSM where CSM.SegmentId = @SegmentId) ; end else begin delete from ReportServerTempDB.dbo.Segment where SegmentId = @SegmentId and not exists (select 1 from ReportServerTempDB.dbo.ChunkSegmentMapping CSM where CSM.SegmentId = @SegmentId) ; end select @DidDelete = case when @@rowcount > 0 then 1 else 0 end ; end GO GRANT EXECUTE ON [dbo].[RemoveSegment] TO RSExecRole GO -- END STORED PROCEDURESPASET ANSI_NULLS ON GO SET ANSI_PADDING ON GO SET ANSI_WARNINGS ON GO SET ARITHABORT ON GO SET CONCAT_NULL_YIELDS_NULL ON GO SET NUMERIC_ROUNDABORT OFF GO SET QUOTED_IDENTIFIER ON GO -- START STORED PROCEDURES if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetKeysForInstallation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetKeysForInstallation] GO CREATE PROCEDURE [dbo].[SetKeysForInstallation] @InstallationID uniqueidentifier, @SymmetricKey image = NULL, @PublicKey image AS update [dbo].[Keys] set [SymmetricKey] = @SymmetricKey, [PublicKey] = @PublicKey where [InstallationID] = @InstallationID and [Client] = 1 GO GRANT EXECUTE ON [dbo].[SetKeysForInstallation] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAnnouncedKey]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAnnouncedKey] GO CREATE PROCEDURE [dbo].[GetAnnouncedKey] @InstallationID uniqueidentifier AS select PublicKey, MachineName, InstanceName from Keys where InstallationID = @InstallationID and Client = 1 GO GRANT EXECUTE ON [dbo].[GetAnnouncedKey] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AnnounceOrGetKey]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AnnounceOrGetKey] GO CREATE PROCEDURE [dbo].[AnnounceOrGetKey] @MachineName nvarchar(256), @InstanceName nvarchar(32), @InstallationID uniqueidentifier, @PublicKey image, @NumAnnouncedServices int OUTPUT AS -- Acquire lock IF NOT EXISTS (SELECT * FROM [dbo].[Keys] WITH(XLOCK) WHERE [Client] < 0) BEGIN RAISERROR('Keys lock row not found', 16, 1) RETURN END -- Get the number of services that have already announced their presence SELECT @NumAnnouncedServices = count(*) FROM [dbo].[Keys] WHERE [Client] = 1 DECLARE @StoredInstallationID uniqueidentifier DECLARE @StoredInstanceName nvarchar(32) SELECT @StoredInstallationID = [InstallationID], @StoredInstanceName = [InstanceName] FROM [dbo].[Keys] WHERE [InstallationID] = @InstallationID AND [Client] = 1 IF @StoredInstallationID IS NULL -- no record present BEGIN INSERT INTO [dbo].[Keys] ([MachineName], [InstanceName], [InstallationID], [Client], [PublicKey], [SymmetricKey]) VALUES (@MachineName, @InstanceName, @InstallationID, 1, @PublicKey, null) END ELSE BEGIN IF @StoredInstanceName IS NULL BEGIN UPDATE [dbo].[Keys] SET [InstanceName] = @InstanceName WHERE [InstallationID] = @InstallationID AND [Client] = 1 END END SELECT [MachineName], [SymmetricKey], [PublicKey] FROM [Keys] WHERE [InstallationID] = @InstallationID and [Client] = 1 GO GRANT EXECUTE ON [dbo].[AnnounceOrGetKey] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetMachineName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetMachineName] GO CREATE PROCEDURE [dbo].[SetMachineName] @MachineName nvarchar(256), @InstallationID uniqueidentifier AS UPDATE [dbo].[Keys] SET MachineName = @MachineName WHERE [InstallationID] = @InstallationID and [Client] = 1 GO GRANT EXECUTE ON [dbo].[SetMachineName] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListInstallations]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListInstallations] GO CREATE PROCEDURE [dbo].[ListInstallations] AS SELECT [MachineName], [InstanceName], [InstallationID], CASE WHEN [SymmetricKey] IS null THEN 0 ELSE 1 END FROM [dbo].[Keys] WHERE [Client] = 1 GO GRANT EXECUTE ON [dbo].[ListInstallations] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListInfoForReencryption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListInfoForReencryption] GO CREATE PROCEDURE [dbo].[ListInfoForReencryption] AS SELECT [DSID] FROM [dbo].[DataSource] WITH (XLOCK, TABLOCK) SELECT [SubscriptionID] FROM [dbo].[Subscriptions] WITH (XLOCK, TABLOCK) SELECT [InstallationID], [PublicKey] FROM [dbo].[Keys] WITH (XLOCK, TABLOCK) WHERE [Client] = 1 AND ([SymmetricKey] IS NOT NULL) GO GRANT EXECUTE ON [dbo].[ListInfoForReencryption] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDatasourceInfoForReencryption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDatasourceInfoForReencryption] GO CREATE PROCEDURE [dbo].[GetDatasourceInfoForReencryption] @DSID as uniqueidentifier AS SELECT [ConnectionString], [OriginalConnectionString], [UserName], [Password], [CredentialRetrieval], [Version] FROM [dbo].[DataSource] WHERE [DSID] = @DSID GO GRANT EXECUTE ON [dbo].[GetDatasourceInfoForReencryption] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetReencryptedDatasourceInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetReencryptedDatasourceInfo] GO CREATE PROCEDURE [dbo].[SetReencryptedDatasourceInfo] @DSID uniqueidentifier, @ConnectionString image = NULL, @OriginalConnectionString image = NULL, @UserName image = NULL, @Password image = NULL, @CredentialRetrieval int, @Version int AS UPDATE [dbo].[DataSource] SET [ConnectionString] = @ConnectionString, [OriginalConnectionString] = @OriginalConnectionString, [UserName] = @UserName, [Password] = @Password, [CredentialRetrieval] = @CredentialRetrieval, [Version] = @Version WHERE [DSID] = @DSID GO GRANT EXECUTE ON [dbo].[SetReencryptedDatasourceInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSubscriptionInfoForReencryption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSubscriptionInfoForReencryption] GO CREATE PROCEDURE [dbo].[GetSubscriptionInfoForReencryption] @SubscriptionID as uniqueidentifier AS SELECT [DeliveryExtension], [ExtensionSettings], [Version] FROM [dbo].[Subscriptions] WHERE [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetSubscriptionInfoForReencryption] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetReencryptedSubscriptionInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetReencryptedSubscriptionInfo] GO CREATE PROCEDURE [dbo].[SetReencryptedSubscriptionInfo] @SubscriptionID as uniqueidentifier, @ExtensionSettings as ntext = NULL, @Version as int AS UPDATE [dbo].[Subscriptions] SET [ExtensionSettings] = @ExtensionSettings, [Version] = @Version WHERE [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[SetReencryptedSubscriptionInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteEncryptedContent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteEncryptedContent] GO CREATE PROCEDURE [dbo].[DeleteEncryptedContent] AS -- Remove the encryption keys delete from keys where client >= 0 -- Remove the encrypted content update datasource set CredentialRetrieval = 1, -- CredentialRetrieval.Prompt ConnectionString = null, OriginalConnectionString = null, UserName = null, Password = null GO GRANT EXECUTE ON [dbo].[DeleteEncryptedContent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteKey]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteKey] GO CREATE PROCEDURE [dbo].[DeleteKey] @InstallationID uniqueidentifier AS if (@InstallationID = '00000000-0000-0000-0000-000000000000') RAISERROR('Cannot delete reserved key', 16, 1) -- Remove the encryption keys delete from keys where InstallationID = @InstallationID and Client = 1 GO GRANT EXECUTE ON [dbo].[DeleteKey] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAllConfigurationInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAllConfigurationInfo] GO CREATE PROCEDURE [dbo].[GetAllConfigurationInfo] AS SELECT [Name], [Value] FROM [ConfigurationInfo] GO GRANT EXECUTE ON [dbo].[GetAllConfigurationInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetOneConfigurationInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetOneConfigurationInfo] GO CREATE PROCEDURE [dbo].[GetOneConfigurationInfo] @Name nvarchar (260) AS SELECT [Value] FROM [ConfigurationInfo] WHERE [Name] = @Name GO GRANT EXECUTE ON [dbo].[GetOneConfigurationInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetConfigurationInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetConfigurationInfo] GO CREATE PROCEDURE [dbo].[SetConfigurationInfo] @Name nvarchar (260), @Value ntext AS DELETE FROM [ConfigurationInfo] WHERE [Name] = @Name IF @Value is not null BEGIN INSERT INTO ConfigurationInfo VALUES ( newid(), @Name, @Value ) END GO GRANT EXECUTE ON [dbo].[SetConfigurationInfo] TO RSExecRole if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddEvent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddEvent] GO CREATE PROCEDURE [dbo].[AddEvent] @EventType nvarchar (260), @EventData nvarchar (260) AS insert into [Event] ([EventID], [EventType], [EventData], [TimeEntered], [ProcessStart], [BatchID]) values (NewID(), @EventType, @EventData, GETUTCDATE(), NULL, NULL) GO GRANT EXECUTE ON [dbo].[AddEvent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteEvent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteEvent] GO CREATE PROCEDURE [dbo].[DeleteEvent] @ID uniqueidentifier AS delete from [Event] where [EventID] = @ID GO GRANT EXECUTE ON [dbo].[DeleteEvent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanEventRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanEventRecords] GO CREATE PROCEDURE [dbo].[CleanEventRecords] @MaxAgeMinutes int AS -- Reset all notifications which have been add over n minutes ago Update [Event] set [ProcessStart] = NULL, [ProcessHeartbeat] = NULL where [EventID] in ( SELECT [EventID] FROM [Event] WHERE [ProcessHeartbeat] < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) ) GO GRANT EXECUTE ON [dbo].[CleanEventRecords] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddExecutionLogEntry]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddExecutionLogEntry] GO CREATE PROCEDURE [dbo].[AddExecutionLogEntry] @InstanceName nvarchar(38), @Report nvarchar(260), @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @RequestType bit, @Format nvarchar(26), @Parameters ntext, @TimeStart DateTime, @TimeEnd DateTime, @TimeDataRetrieval int, @TimeProcessing int, @TimeRendering int, @Source tinyint, @Status nvarchar(32), @ByteCount bigint, @RowCount bigint, @ExecutionId nvarchar(64) = null, @ReportAction tinyint, @AdditionalInfo xml = null AS -- Unless is is specifically 'False', it's true if exists (select * from ConfigurationInfo where [Name] = 'EnableExecutionLogging' and [Value] like 'False') begin return end Declare @ReportID uniqueidentifier select @ReportID = ItemID from Catalog with (nolock) where Path = @Report insert into ExecutionLogStorage (InstanceName, ReportID, UserName, ExecutionId, RequestType, [Format], Parameters, ReportAction, TimeStart, TimeEnd, TimeDataRetrieval, TimeProcessing, TimeRendering, Source, Status, ByteCount, [RowCount], AdditionalInfo) Values (@InstanceName, @ReportID, @UserName, @ExecutionId, @RequestType, @Format, @Parameters, @ReportAction, @TimeStart, @TimeEnd, @TimeDataRetrieval, @TimeProcessing, @TimeRendering, @Source, @Status, @ByteCount, @RowCount, @AdditionalInfo) GO GRANT EXECUTE ON [dbo].[AddExecutionLogEntry] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ExpireExecutionLogEntries]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ExpireExecutionLogEntries] GO CREATE PROCEDURE [dbo].[ExpireExecutionLogEntries] AS SET NOCOUNT OFF -- -1 means no expiration if exists (select * from ConfigurationInfo where [Name] = 'ExecutionLogDaysKept' and CAST(CAST(Value as nvarchar) as integer) = -1) begin return end delete from ExecutionLogStorage where DateDiff(day, TimeStart, getdate()) >= (select CAST(CAST(Value as nvarchar) as integer) from ConfigurationInfo where [Name] = 'ExecutionLogDaysKept') GO GRANT EXECUTE ON [dbo].[ExpireExecutionLogEntries] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUserIDBySid]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUserIDBySid] GO -- looks up any user name by its SID, if not it creates a regular user CREATE PROCEDURE [dbo].[GetUserIDBySid] @UserSid varbinary(85), @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS SELECT @UserID = (SELECT UserID FROM Users WHERE Sid = @UserSid AND AuthType = @AuthType) IF @UserID IS NULL BEGIN SET @UserID = newid() INSERT INTO Users (UserID, Sid, UserType, AuthType, UserName) VALUES (@UserID, @UserSid, 0, @AuthType, @UserName) END GO GRANT EXECUTE ON [dbo].[GetUserIDBySid] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUserIDByName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUserIDByName] GO -- looks up any user name by its User Name, if not it creates a regular user CREATE PROCEDURE [dbo].[GetUserIDByName] @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS SELECT @UserID = (SELECT UserID FROM Users WHERE UserName = @UserName AND AuthType = @AuthType) IF @UserID IS NULL BEGIN SET @UserID = newid() INSERT INTO Users (UserID, Sid, UserType, AuthType, UserName) VALUES (@UserID, NULL, 0, @AuthType, @UserName) END GO GRANT EXECUTE ON [dbo].[GetUserIDByName] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUserID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUserID] GO -- looks up any user name, if not it creates a regular user - uses Sid CREATE PROCEDURE [dbo].[GetUserID] @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS IF @AuthType = 1 -- Windows BEGIN EXEC GetUserIDBySid @UserSid, @UserName, @AuthType, @UserID OUTPUT END ELSE BEGIN EXEC GetUserIDByName @UserName, @AuthType, @UserID OUTPUT END GO GRANT EXECUTE ON [dbo].[GetUserID] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPrincipalID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPrincipalID] GO -- looks up a principal, if not there looks up regular users and turns them into principals -- if not, it creates a principal CREATE PROCEDURE [dbo].[GetPrincipalID] @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS -- windows auth IF @AuthType = 1 BEGIN -- is this a principal? SELECT @UserID = (SELECT UserID FROM Users WHERE Sid = @UserSid AND UserType = 1 AND AuthType = @AuthType) END ELSE BEGIN -- is this a principal? SELECT @UserID = (SELECT UserID FROM Users WHERE UserName = @UserName AND UserType = 1 AND AuthType = @AuthType) END IF @UserID IS NULL BEGIN IF @AuthType = 1 -- Windows BEGIN -- Is this a regular user SELECT @UserID = (SELECT UserID FROM Users WHERE Sid = @UserSid AND UserType = 0 AND AuthType = @AuthType) END ELSE BEGIN -- Is this a regular user SELECT @UserID = (SELECT UserID FROM Users WHERE UserName = @UserName AND UserType = 0 AND AuthType = @AuthType) END -- No, create a new principal IF @UserID IS NULL BEGIN SET @UserID = newid() INSERT INTO Users (UserID, Sid, UserType, AuthType, UserName) VALUES (@UserID, @UserSid, 1, @AuthType, @UserName) END ELSE BEGIN UPDATE Users SET UserType = 1 WHERE UserID = @UserID END END GO GRANT EXECUTE ON [dbo].[GetPrincipalID] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateSubscription] GO CREATE PROCEDURE [dbo].[CreateSubscription] @id uniqueidentifier, @Locale nvarchar (128), @Report_Name nvarchar (425), @OwnerSid varbinary (85) = NULL, @OwnerName nvarchar(260), @OwnerAuthType int, @DeliveryExtension nvarchar (260) = NULL, @InactiveFlags int, @ExtensionSettings ntext = NULL, @ModifiedBySid varbinary (85) = NULL, @ModifiedByName nvarchar(260), @ModifiedByAuthType int, @ModifiedDate datetime, @Description nvarchar(512) = NULL, @LastStatus nvarchar(260) = NULL, @EventType nvarchar(260), @MatchData ntext = NULL, @Parameters ntext = NULL, @DataSettings ntext = NULL, @Version int AS -- Create a subscription with the given data. The name must match a name in the -- Catalog table and it must be a report type (2) or linked report (4) DECLARE @Report_OID uniqueidentifier DECLARE @OwnerID uniqueidentifier DECLARE @ModifiedByID uniqueidentifier DECLARE @TempDeliveryID uniqueidentifier --Get the report id for this subscription select @Report_OID = (select [ItemID] from [Catalog] where [Catalog].[Path] = @Report_Name and ([Catalog].[Type] = 2 or [Catalog].[Type] = 4)) EXEC GetUserID @OwnerSid, @OwnerName, @OwnerAuthType, @OwnerID OUTPUT EXEC GetUserID @ModifiedBySid, @ModifiedByName, @ModifiedByAuthType, @ModifiedByID OUTPUT if (@Report_OID is NULL) begin RAISERROR('Report Not Found', 16, 1) return end Insert into Subscriptions ( [SubscriptionID], [OwnerID], [Report_OID], [Locale], [DeliveryExtension], [InactiveFlags], [ExtensionSettings], [ModifiedByID], [ModifiedDate], [Description], [LastStatus], [EventType], [MatchData], [LastRunTime], [Parameters], [DataSettings], [Version] ) values (@id, @OwnerID, @Report_OID, @Locale, @DeliveryExtension, @InactiveFlags, @ExtensionSettings, @ModifiedByID, @ModifiedDate, @Description, @LastStatus, @EventType, @MatchData, NULL, @Parameters, @DataSettings, @Version) GO GRANT EXECUTE ON [dbo].[CreateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeliveryRemovedInactivateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeliveryRemovedInactivateSubscription] GO CREATE PROCEDURE [dbo].[DeliveryRemovedInactivateSubscription] @DeliveryExtension nvarchar(260), @Status nvarchar(260) AS update Subscriptions set [DeliveryExtension] = '', [InactiveFlags] = [InactiveFlags] | 1, -- Delivery Provider Removed Flag == 1 [LastStatus] = @Status where [DeliveryExtension] = @DeliveryExtension GO GRANT EXECUTE ON [dbo].[DeliveryRemovedInactivateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddSubscriptionToBeingDeleted]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddSubscriptionToBeingDeleted] GO CREATE PROCEDURE [dbo].[AddSubscriptionToBeingDeleted] @SubscriptionID uniqueidentifier AS -- Delete subscription if it is already in this table -- Delete orphaned subscriptions, based on the age criteria: > 10 minutes delete from [SubscriptionsBeingDeleted] where (SubscriptionID = @SubscriptionID) or (DATEDIFF( minute, [CreationDate], GetUtcDate() ) > 10) -- Add subscription being deleted into the DeletedSubscription table insert into [SubscriptionsBeingDeleted] VALUES(@SubscriptionID, GetUtcDate()) GO GRANT EXECUTE ON [dbo].[AddSubscriptionToBeingDeleted] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RemoveSubscriptionFromBeingDeleted]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RemoveSubscriptionFromBeingDeleted] GO CREATE PROCEDURE [dbo].[RemoveSubscriptionFromBeingDeleted] @SubscriptionID uniqueidentifier AS delete from [SubscriptionsBeingDeleted] where SubscriptionID = @SubscriptionID GO GRANT EXECUTE ON [dbo].[RemoveSubscriptionFromBeingDeleted] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteSubscription] GO CREATE PROCEDURE [dbo].[DeleteSubscription] @SubscriptionID uniqueidentifier AS -- Delete the subscription delete from [Subscriptions] where [SubscriptionID] = @SubscriptionID -- Delete it from the SubscriptionsBeingDeleted EXEC RemoveSubscriptionFromBeingDeleted @SubscriptionID GO GRANT EXECUTE ON [dbo].[DeleteSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSubscription] GO CREATE PROCEDURE [dbo].[GetSubscription] @SubscriptionID uniqueidentifier AS -- Grab all of the-- subscription properties given a id select S.[SubscriptionID], S.[Report_OID], S.[Locale], S.[InactiveFlags], S.[DeliveryExtension], S.[ExtensionSettings], SUSER_SNAME(Modified.[Sid]), Modified.[UserName], S.[ModifiedDate], S.[Description], S.[LastStatus], S.[EventType], S.[MatchData], S.[Parameters], S.[DataSettings], A.[TotalNotifications], A.[TotalSuccesses], A.[TotalFailures], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], CAT.[Path], S.[LastRunTime], CAT.[Type], SD.NtSecDescPrimary, S.[Version], Owner.[AuthType] from [Subscriptions] S inner join [Catalog] CAT on S.[Report_OID] = CAT.[ItemID] inner join [Users] Owner on S.OwnerID = Owner.UserID inner join [Users] Modified on S.ModifiedByID = Modified.UserID left outer join [SecData] SD on CAT.PolicyID = SD.PolicyID AND SD.AuthType = Owner.AuthType left outer join [ActiveSubscriptions] A with (NOLOCK) on S.[SubscriptionID] = A.[SubscriptionID] where S.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListSubscriptionsUsingDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListSubscriptionsUsingDataSource] GO CREATE PROCEDURE [dbo].[ListSubscriptionsUsingDataSource] @DataSourceName nvarchar(450) AS select S.[SubscriptionID], S.[Report_OID], S.[Locale], S.[InactiveFlags], S.[DeliveryExtension], S.[ExtensionSettings], SUSER_SNAME(Modified.[Sid]), Modified.[UserName], S.[ModifiedDate], S.[Description], S.[LastStatus], S.[EventType], S.[MatchData], S.[Parameters], S.[DataSettings], A.[TotalNotifications], A.[TotalSuccesses], A.[TotalFailures], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], CAT.[Path], S.[LastRunTime], CAT.[Type], SD.NtSecDescPrimary, S.[Version], Owner.[AuthType] from [DataSource] DS inner join Catalog C on C.ItemID = DS.Link inner join Subscriptions S on S.[SubscriptionID] = DS.[SubscriptionID] inner join [Catalog] CAT on S.[Report_OID] = CAT.[ItemID] inner join [Users] Owner on S.OwnerID = Owner.UserID inner join [Users] Modified on S.ModifiedByID = Modified.UserID left join [SecData] SD on SD.[PolicyID] = CAT.[PolicyID] AND SD.AuthType = Owner.AuthType left outer join [ActiveSubscriptions] A with (NOLOCK) on S.[SubscriptionID] = A.[SubscriptionID] where C.Path = @DataSourceName GO GRANT EXECUTE ON [dbo].[ListSubscriptionsUsingDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSubscriptionStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSubscriptionStatus] GO CREATE PROCEDURE [dbo].[UpdateSubscriptionStatus] @SubscriptionID uniqueidentifier, @Status nvarchar(260) AS update Subscriptions set [LastStatus] = @Status where [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[UpdateSubscriptionStatus] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSubscription] GO CREATE PROCEDURE [dbo].[UpdateSubscription] @id uniqueidentifier, @Locale nvarchar(260), @OwnerSid varbinary(85) = NULL, @OwnerName nvarchar(260), @OwnerAuthType int, @DeliveryExtension nvarchar(260), @InactiveFlags int, @ExtensionSettings ntext = NULL, @ModifiedBySid varbinary(85) = NULL, @ModifiedByName nvarchar(260), @ModifiedByAuthType int, @ModifiedDate datetime, @Description nvarchar(512) = NULL, @LastStatus nvarchar(260) = NULL, @EventType nvarchar(260), @MatchData ntext = NULL, @Parameters ntext = NULL, @DataSettings ntext = NULL, @Version int AS -- Update a subscription's information. DECLARE @ModifiedByID uniqueidentifier DECLARE @OwnerID uniqueidentifier EXEC GetUserID @ModifiedBySid, @ModifiedByName, @ModifiedByAuthType, @ModifiedByID OUTPUT EXEC GetUserID @OwnerSid, @OwnerName, @OwnerAuthType, @OwnerID OUTPUT -- Make sure there is a valid provider update Subscriptions set [DeliveryExtension] = @DeliveryExtension, [Locale] = @Locale, [OwnerID] = @OwnerID, [InactiveFlags] = @InactiveFlags, [ExtensionSettings] = @ExtensionSettings, [ModifiedByID] = @ModifiedByID, [ModifiedDate] = @ModifiedDate, [Description] = @Description, [LastStatus] = @LastStatus, [EventType] = @EventType, [MatchData] = @MatchData, [Parameters] = @Parameters, [DataSettings] = @DataSettings, [Version] = @Version where [SubscriptionID] = @id GO GRANT EXECUTE ON [dbo].[UpdateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[InvalidateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[InvalidateSubscription] GO CREATE PROCEDURE [dbo].[InvalidateSubscription] @SubscriptionID uniqueidentifier, @Flags int, @LastStatus nvarchar(260) AS -- Mark all subscriptions for this report as inactive for the given flags update Subscriptions set [InactiveFlags] = S.[InactiveFlags] | @Flags, [LastStatus] = @LastStatus from Subscriptions S where SubscriptionID = @SubscriptionID GO GRANT EXECUTE ON [dbo].[InvalidateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanNotificationRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanNotificationRecords] GO CREATE PROCEDURE [dbo].[CleanNotificationRecords] @MaxAgeMinutes int AS -- Reset all notifications which have been add over n minutes ago Update [Notifications] set [ProcessStart] = NULL, [ProcessHeartbeat] = NULL, [Attempt] = 1 where [NotificationID] in ( SELECT [NotificationID] FROM [Notifications] WHERE [ProcessHeartbeat] < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) and [Attempt] is NULL ) Update [Notifications] set [ProcessStart] = NULL, [ProcessHeartbeat] = NULL, [Attempt] = [Attempt] + 1 where [NotificationID] in ( SELECT [NotificationID] FROM [Notifications] WHERE [ProcessHeartbeat] < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) and [Attempt] is not NULL ) GO GRANT EXECUTE ON [dbo].[CleanNotificationRecords] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateSnapShotNotifications]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateSnapShotNotifications] GO CREATE PROCEDURE [dbo].[CreateSnapShotNotifications] @HistoryID uniqueidentifier, @LastRunTime datetime AS update [Subscriptions] set [LastRunTime] = @LastRunTime from History SS inner join [Subscriptions] S on S.[Report_OID] = SS.[ReportID] where SS.[HistoryID] = @HistoryID and S.EventType = 'ReportHistorySnapshotCreated' and InactiveFlags = 0 -- Find all valid subscriptions for the given report and create a new notification row for -- each subscription insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) select NewID(), S.[SubscriptionID], NULL, S.[Report_OID], NULL, S.[ExtensionSettings], S.[Locale], S.[Parameters], GETUTCDATE(), S.[LastRunTime], S.[DeliveryExtension], S.[OwnerID], 0, S.[Version] from [Subscriptions] S with (READPAST) inner join History H on S.[Report_OID] = H.[ReportID] where H.[HistoryID] = @HistoryID and S.EventType = 'ReportHistorySnapshotCreated' and InactiveFlags = 0 and S.[DataSettings] is null -- Create any data driven subscription by creating a data driven event insert into [Event] ( [EventID], [EventType], [EventData], [TimeEntered] ) select NewID(), 'DataDrivenSubscription', S.SubscriptionID, GETUTCDATE() from [Subscriptions] S with (READPAST) inner join History H on S.[Report_OID] = H.[ReportID] where H.[HistoryID] = @HistoryID and S.EventType = 'ReportHistorySnapshotCreated' and InactiveFlags = 0 and S.[DataSettings] is not null GO GRANT EXECUTE ON [dbo].[CreateSnapShotNotifications] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateDataDrivenNotification]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateDataDrivenNotification] GO CREATE PROCEDURE [dbo].[CreateDataDrivenNotification] @SubscriptionID uniqueidentifier, @ActiveationID uniqueidentifier, @ReportID uniqueidentifier, @ExtensionSettings ntext, @Locale nvarchar(128), @Parameters ntext, @LastRunTime datetime, @DeliveryExtension nvarchar(260), @OwnerSid varbinary (85) = null, @OwnerName nvarchar(260), @OwnerAuthType int, @Version int AS declare @OwnerID as uniqueidentifier EXEC GetUserID @OwnerSid,@OwnerName, @OwnerAuthType, @OwnerID OUTPUT -- Verify if subscription is being deleted if exists (select 1 from [dbo].[SubscriptionsBeingDeleted] where [SubscriptionID]=@SubscriptionID) BEGIN RAISERROR( N'The subscription is being deleted', 16, 1) return; END -- Insert into the notification table insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) values ( NewID(), @SubscriptionID, @ActiveationID, @ReportID, NULL, @ExtensionSettings, @Locale, @Parameters, GETUTCDATE(), @LastRunTime, @DeliveryExtension, @OwnerID, 1, @Version ) GO GRANT EXECUTE ON [dbo].[CreateDataDrivenNotification] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateNewActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateNewActiveSubscription] GO CREATE PROCEDURE [dbo].[CreateNewActiveSubscription] @ActiveID uniqueidentifier, @SubscriptionID uniqueidentifier AS -- Insert into the activesubscription table insert into [ActiveSubscriptions] ( [ActiveID], [SubscriptionID], [TotalNotifications], [TotalSuccesses], [TotalFailures] ) values ( @ActiveID, @SubscriptionID, NULL, 0, 0 ) GO GRANT EXECUTE ON [dbo].[CreateNewActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateActiveSubscription] GO CREATE PROCEDURE [dbo].[UpdateActiveSubscription] @ActiveID uniqueidentifier, @TotalNotifications int = NULL, @TotalSuccesses int = NULL, @TotalFailures int = NULL AS if @TotalNotifications is not NULL begin update ActiveSubscriptions set TotalNotifications = @TotalNotifications where ActiveID = @ActiveID end if @TotalSuccesses is not NULL begin update ActiveSubscriptions set TotalSuccesses = @TotalSuccesses where ActiveID = @ActiveID end if @TotalFailures is not NULL begin update ActiveSubscriptions set TotalFailures = @TotalFailures where ActiveID = @ActiveID end GO GRANT EXECUTE ON [dbo].[UpdateActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteActiveSubscription] GO CREATE PROCEDURE [dbo].[DeleteActiveSubscription] @ActiveID uniqueidentifier AS delete from ActiveSubscriptions where ActiveID = @ActiveID GO GRANT EXECUTE ON [dbo].[DeleteActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAndHoldLockActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAndHoldLockActiveSubscription] GO CREATE PROCEDURE [dbo].[GetAndHoldLockActiveSubscription] @ActiveID uniqueidentifier AS select TotalNotifications, TotalSuccesses, TotalFailures from ActiveSubscriptions with (XLOCK) where ActiveID = @ActiveID GO GRANT EXECUTE ON [dbo].[GetAndHoldLockActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateCacheUpdateNotifications]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateCacheUpdateNotifications] GO CREATE PROCEDURE [dbo].[CreateCacheUpdateNotifications] @ReportID uniqueidentifier, @LastRunTime datetime AS update [Subscriptions] set [LastRunTime] = @LastRunTime from [Subscriptions] S where S.[Report_OID] = @ReportID and S.EventType = 'SnapshotUpdated' and InactiveFlags = 0 -- Find all valid subscriptions for the given report and create a new notification row for -- each subscription insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) select NewID(), S.[SubscriptionID], NULL, S.[Report_OID], NULL, S.[ExtensionSettings], S.[Locale], S.[Parameters], GETUTCDATE(), S.[LastRunTime], S.[DeliveryExtension], S.[OwnerID], 0, S.[Version] from [Subscriptions] S inner join Catalog C on S.[Report_OID] = C.[ItemID] where C.[ItemID] = @ReportID and S.EventType = 'SnapshotUpdated' and InactiveFlags = 0 and S.[DataSettings] is null -- Create any data driven subscription by creating a data driven event insert into [Event] ( [EventID], [EventType], [EventData], [TimeEntered] ) select NewID(), 'DataDrivenSubscription', S.SubscriptionID, GETUTCDATE() from [Subscriptions] S inner join Catalog C on S.[Report_OID] = C.[ItemID] where C.[ItemID] = @ReportID and S.EventType = 'SnapshotUpdated' and InactiveFlags = 0 and S.[DataSettings] is not null GO GRANT EXECUTE ON [dbo].[CreateCacheUpdateNotifications] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCacheSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetCacheSchedule] GO CREATE PROCEDURE [dbo].[GetCacheSchedule] @ReportID uniqueidentifier AS SELECT S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], Owner.[AuthType], RS.ReportAction FROM Schedule S with (XLOCK) inner join ReportSchedule RS on S.ScheduleID = RS.ScheduleID inner join [Users] Owner on S.[CreatedById] = Owner.[UserID] WHERE (RS.ReportAction = 1 or RS.ReportAction = 3) and -- 1 == UpdateCache, 3 == Invalidate cache RS.[ReportID] = @ReportID GO GRANT EXECUTE ON [dbo].[GetCacheSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteNotification]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteNotification] GO CREATE PROCEDURE [dbo].[DeleteNotification] @ID uniqueidentifier AS delete from [Notifications] where [NotificationID] = @ID GO GRANT EXECUTE ON [dbo].[DeleteNotification] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetNotificationAttempt]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetNotificationAttempt] GO CREATE PROCEDURE [dbo].[SetNotificationAttempt] @Attempt int, @SecondsToAdd int, @NotificationID uniqueidentifier AS update [Notifications] set [ProcessStart] = NULL, [Attempt] = @Attempt, [ProcessAfter] = DateAdd(second, @SecondsToAdd, GetUtcDate()) where [NotificationID] = @NotificationID GO GRANT EXECUTE ON [dbo].[SetNotificationAttempt] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateTimeBasedSubscriptionNotification]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateTimeBasedSubscriptionNotification] GO CREATE PROCEDURE [dbo].[CreateTimeBasedSubscriptionNotification] @SubscriptionID uniqueidentifier, @LastRunTime datetime as insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) select NewID(), S.[SubscriptionID], NULL, S.[Report_OID], NULL, S.[ExtensionSettings], S.[Locale], S.[Parameters], GETUTCDATE(), @LastRunTime, S.[DeliveryExtension], S.[OwnerID], 0, S.[Version] from [Subscriptions] S where S.[SubscriptionID] = @SubscriptionID and InactiveFlags = 0 and S.[DataSettings] is null -- Create any data driven subscription by creating a data driven event insert into [Event] ( [EventID], [EventType], [EventData], [TimeEntered] ) select NewID(), 'DataDrivenSubscription', S.SubscriptionID, GETUTCDATE() from [Subscriptions] S where S.[SubscriptionID] = @SubscriptionID and InactiveFlags = 0 and S.[DataSettings] is not null update [Subscriptions] set [LastRunTime] = @LastRunTime where [SubscriptionID] = @SubscriptionID and InactiveFlags = 0 GO GRANT EXECUTE ON [dbo].[CreateTimeBasedSubscriptionNotification] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteTimeBasedSubscriptionSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteTimeBasedSubscriptionSchedule] GO CREATE PROCEDURE [dbo].[DeleteTimeBasedSubscriptionSchedule] @SubscriptionID as uniqueidentifier as delete ReportSchedule from ReportSchedule RS inner join Subscriptions S on S.[SubscriptionID] = RS.[SubscriptionID] where S.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[DeleteTimeBasedSubscriptionSchedule] TO RSExecRole GO -------------------------------------------------- ------------- Provider Info if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListUsedDeliveryProviders]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListUsedDeliveryProviders] GO CREATE PROCEDURE [dbo].[ListUsedDeliveryProviders] AS select distinct [DeliveryExtension] from Subscriptions where [DeliveryExtension] <> '' GO GRANT EXECUTE ON [dbo].[ListUsedDeliveryProviders] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id('[dbo].[AddBatchRecord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddBatchRecord] GO CREATE PROCEDURE [dbo].[AddBatchRecord] @BatchID uniqueidentifier, @UserName nvarchar(260), @Action varchar(32), @Item nvarchar(425) = NULL, @Parent nvarchar(425) = NULL, @Param nvarchar(425) = NULL, @BoolParam bit = NULL, @Content image = NULL, @Properties ntext = NULL AS IF @Action='BatchStart' BEGIN INSERT INTO [Batch] (BatchID, AddedOn, [Action], Item, Parent, Param, BoolParam, Content, Properties) VALUES (@BatchID, GETUTCDATE(), @Action, @UserName, @Parent, @Param, @BoolParam, @Content, @Properties) END ELSE BEGIN IF EXISTS (SELECT * FROM Batch WHERE BatchID = @BatchID AND [Action] = 'BatchStart' AND Item = @UserName) BEGIN INSERT INTO [Batch] (BatchID, AddedOn, [Action], Item, Parent, Param, BoolParam, Content, Properties) VALUES (@BatchID, GETUTCDATE(), @Action, @Item, @Parent, @Param, @BoolParam, @Content, @Properties) END ELSE BEGIN RAISERROR( 'Batch does not exist', 16, 1 ) END END GO GRANT EXECUTE ON [dbo].[AddBatchRecord] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[GetBatchRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetBatchRecords] GO CREATE PROCEDURE [dbo].[GetBatchRecords] @BatchID uniqueidentifier AS SELECT [Action], Item, Parent, Param, BoolParam, Content, Properties FROM [Batch] WHERE BatchID = @BatchID ORDER BY AddedOn GO GRANT EXECUTE ON [dbo].[GetBatchRecords] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteBatchRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteBatchRecords] GO CREATE PROCEDURE [dbo].[DeleteBatchRecords] @BatchID uniqueidentifier AS SET NOCOUNT OFF DELETE FROM [Batch] WHERE BatchID = @BatchID GO GRANT EXECUTE ON [dbo].[DeleteBatchRecords] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanBatchRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanBatchRecords] GO CREATE PROCEDURE [dbo].[CleanBatchRecords] @MaxAgeMinutes int AS SET NOCOUNT OFF DELETE FROM [Batch] where BatchID in ( SELECT BatchID FROM [Batch] WHERE AddedOn < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) ) GO GRANT EXECUTE ON [dbo].[CleanBatchRecords] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanOrphanedPolicies]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanOrphanedPolicies] GO -- Cleaning orphan policies CREATE PROCEDURE [dbo].[CleanOrphanedPolicies] AS SET NOCOUNT OFF DELETE [Policies] WHERE [Policies].[PolicyFlag] = 0 AND NOT EXISTS (SELECT ItemID FROM [Catalog] WHERE [Catalog].[PolicyID] = [Policies].[PolicyID]) DELETE [Policies] FROM [Policies] INNER JOIN [ModelItemPolicy] ON [ModelItemPolicy].[PolicyID] = [Policies].[PolicyID] WHERE NOT EXISTS (SELECT ItemID FROM [Catalog] WHERE [Catalog].[ItemID] = [ModelItemPolicy].[CatalogItemID]) GO GRANT EXECUTE ON [dbo].[CleanOrphanedPolicies] TO RSExecRole GO -------------------------------------------------- ------------- Snapshot manipulation if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[IncreaseTransientSnapshotRefcount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[IncreaseTransientSnapshotRefcount] GO CREATE PROCEDURE [dbo].[IncreaseTransientSnapshotRefcount] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @ExpirationMinutes as int AS SET NOCOUNT OFF DECLARE @soon AS datetime SET @soon = DATEADD(n, @ExpirationMinutes, GETDATE()) if @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET ExpirationDate = @soon, TransientRefcount = TransientRefcount + 1 WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET ExpirationDate = @soon, TransientRefcount = TransientRefcount + 1 WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[IncreaseTransientSnapshotRefcount] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DecreaseTransientSnapshotRefcount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DecreaseTransientSnapshotRefcount] GO CREATE PROCEDURE [dbo].[DecreaseTransientSnapshotRefcount] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS SET NOCOUNT OFF if @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET TransientRefcount = TransientRefcount - 1 WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET TransientRefcount = TransientRefcount - 1 WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[DecreaseTransientSnapshotRefcount] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[MarkSnapshotAsDependentOnUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[MarkSnapshotAsDependentOnUser] GO CREATE PROCEDURE [dbo].[MarkSnapshotAsDependentOnUser] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS SET NOCOUNT OFF if @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET DependsOnUser = 1 WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET DependsOnUser = 1 WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[MarkSnapshotAsDependentOnUser] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSnapshotProcessingFlags]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSnapshotProcessingFlags] GO CREATE PROCEDURE [dbo].[SetSnapshotProcessingFlags] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @ProcessingFlags int AS if @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET ProcessingFlags = @ProcessingFlags WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET ProcessingFlags = @ProcessingFlags WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[SetSnapshotProcessingFlags] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSnapshotChunksVersion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSnapshotChunksVersion] GO CREATE PROCEDURE [dbo].[SetSnapshotChunksVersion] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @Version as smallint AS declare @affectedRows int set @affectedRows = 0 if @IsPermanentSnapshot = 1 BEGIN if @Version > 0 BEGIN UPDATE ChunkData SET Version = @Version WHERE SnapshotDataID = @SnapshotDataID SELECT @affectedRows = @affectedRows + @@rowcount UPDATE SegmentedChunk SET Version = @Version WHERE SnapshotDataId = @SnapshotDataID SELECT @affectedRows = @affectedRows + @@rowcount END ELSE BEGIN UPDATE ChunkData SET Version = Version WHERE SnapshotDataID = @SnapshotDataID SELECT @affectedRows = @affectedRows + @@rowcount UPDATE SegmentedChunk SET Version = Version WHERE SnapshotDataId = @SnapshotDataID SELECT @affectedRows = @affectedRows + @@rowcount END END ELSE BEGIN if @Version > 0 BEGIN UPDATE ReportServerTempDB.dbo.ChunkData SET Version = @Version WHERE SnapshotDataID = @SnapshotDataID SELECT @affectedRows = @affectedRows + @@rowcount UPDATE ReportServerTempDB.dbo.SegmentedChunk SET Version = @Version WHERE SnapshotDataId = @SnapshotDataID SELECT @affectedRows = @affectedRows + @@rowcount END ELSE BEGIN UPDATE ReportServerTempDB.dbo.ChunkData SET Version = Version WHERE SnapshotDataID = @SnapshotDataID SELECT @affectedRows = @affectedRows + @@rowcount UPDATE ReportServerTempDB.dbo.SegmentedChunk SET Version = Version WHERE SnapshotDataId = @SnapshotDataID SELECT @affectedRows = @affectedRows + @@rowcount END END SELECT @affectedRows GO GRANT EXECUTE ON [dbo].[SetSnapshotChunksVersion] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[LockSnapshotForUpgrade]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[LockSnapshotForUpgrade] GO CREATE PROCEDURE [dbo].[LockSnapshotForUpgrade] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS if @IsPermanentSnapshot = 1 BEGIN SELECT ChunkName from ChunkData with (XLOCK) WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN SELECT ChunkName from ReportServerTempDB.dbo.ChunkData with (XLOCK) WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[LockSnapshotForUpgrade] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[InsertUnreferencedSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[InsertUnreferencedSnapshot] GO CREATE PROCEDURE [dbo].[InsertUnreferencedSnapshot] @ReportID as uniqueidentifier = NULL, @EffectiveParams as ntext = NULL, @QueryParams as ntext = NULL, @ParamsHash as int = NULL, @CreatedDate as datetime, @Description as nvarchar(512) = NULL, @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @ProcessingFlags as int, @SnapshotTimeoutMinutes as int, @Machine as nvarchar(512) = NULL AS DECLARE @now datetime SET @now = GETDATE() IF @IsPermanentSnapshot = 1 BEGIN INSERT INTO SnapshotData (SnapshotDataID, CreatedDate, EffectiveParams, QueryParams, ParamsHash, Description, PermanentRefcount, TransientRefcount, ExpirationDate, ProcessingFlags) VALUES (@SnapshotDataID, @CreatedDate, @EffectiveParams, @QueryParams, @ParamsHash, @Description, 0, 1, DATEADD(n, @SnapshotTimeoutMinutes, @now), @ProcessingFlags) END ELSE BEGIN INSERT INTO ReportServerTempDB.dbo.SnapshotData (SnapshotDataID, CreatedDate, EffectiveParams, QueryParams, ParamsHash, Description, PermanentRefcount, TransientRefcount, ExpirationDate, Machine, ProcessingFlags) VALUES (@SnapshotDataID, @CreatedDate, @EffectiveParams, @QueryParams, @ParamsHash, @Description, 0, 1, DATEADD(n, @SnapshotTimeoutMinutes, @now), @Machine, @ProcessingFlags) END GO GRANT EXECuTE ON [dbo].[InsertUnreferencedSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[PromoteSnapshotInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[PromoteSnapshotInfo] GO CREATE PROCEDURE [dbo].[PromoteSnapshotInfo] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @PageCount as int, @HasDocMap as bit, @PaginationMode as smallint, @ProcessingFlags as int AS -- HasDocMap: Processing engine may not -- compute this flag in all cases, which -- can lead to it being false when passed into -- this proc, however the server needs this -- flag to be true if it was ever set to be -- true in order to communicate that there is a -- document map to the viewer control. IF @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET PageCount = @PageCount, HasDocMap = COALESCE(@HasDocMap | HasDocMap, @HasDocMap), PaginationMode = @PaginationMode, ProcessingFlags = @ProcessingFlags WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET PageCount = @PageCount, HasDocMap = COALESCE(@HasDocMap | HasDocMap, @HasDocMap), PaginationMode = @PaginationMode, ProcessingFlags = @ProcessingFlags WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[PromoteSnapshotInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSnapshotPaginationInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSnapshotPaginationInfo] GO CREATE PROCEDURE [dbo].[UpdateSnapshotPaginationInfo] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @PageCount as int, @PaginationMode as smallint AS IF @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET PageCount = @PageCount, PaginationMode = @PaginationMode WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET PageCount = @PageCount, PaginationMode = @PaginationMode WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[UpdateSnapshotPaginationInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapshotPromotedInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapshotPromotedInfo] GO CREATE PROCEDURE [dbo].[GetSnapshotPromotedInfo] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS -- We don't want to hold shared locks if even if we are in a repeatable -- read transaction, so explicitly use READCOMMITTED lock hint IF @IsPermanentSnapshot = 1 BEGIN SELECT PageCount, HasDocMap, PaginationMode, ProcessingFlags FROM SnapshotData WITH (READCOMMITTED) WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN SELECT PageCount, HasDocMap, PaginationMode, ProcessingFlags FROM ReportServerTempDB.dbo.SnapshotData WITH (READCOMMITTED) WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[GetSnapshotPromotedInfo] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[AddHistoryRecord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddHistoryRecord] GO -- add new record to History table CREATE PROCEDURE [dbo].[AddHistoryRecord] @HistoryID uniqueidentifier, @ReportID uniqueidentifier, @SnapshotDate datetime, @SnapshotDataID uniqueidentifier, @SnapshotTransientRefcountChange int AS INSERT INTO History (HistoryID, ReportID, SnapshotDataID, SnapshotDate) VALUES (@HistoryID, @ReportID, @SnapshotDataID, @SnapshotDate) IF @@ERROR = 0 BEGIN UPDATE SnapshotData -- Snapshots, when created, have transient refcount set to 1. Here create permanent reference -- here so we need to increase permanent refcount and decrease transient refcount. However, -- if it was already referenced by the execution snapshot, transient refcount was already -- decreased. Hence, there's a parameter @SnapshotTransientRefcountChange that is 0 or -1. SET PermanentRefcount = PermanentRefcount + 1, TransientRefcount = TransientRefcount + @SnapshotTransientRefcountChange WHERE SnapshotData.SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[AddHistoryRecord] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[SetHistoryLimit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetHistoryLimit] GO CREATE PROCEDURE [dbo].[SetHistoryLimit] @Path nvarchar (425), @SnapshotLimit int = NULL AS UPDATE Catalog SET SnapshotLimit=@SnapshotLimit WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[SetHistoryLimit] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[ListHistory]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListHistory] GO -- list all historical snapshots for a specific report CREATE PROCEDURE [dbo].[ListHistory] @ReportID uniqueidentifier AS SELECT S.SnapshotDate, ISNULL((SELECT SUM(DATALENGTH( CD.Content ) ) FROM ChunkData AS CD WHERE CD.SnapshotDataID = S.SnapshotDataID ), 0) + ISNULL( ( SELECT SUM(DATALENGTH( SEG.Content) ) FROM Segment SEG WITH(NOLOCK) JOIN ChunkSegmentMapping CSM WITH(NOLOCK) ON (CSM.SegmentId = SEG.SegmentId) JOIN SegmentedChunk C WITH(NOLOCK) ON (C.ChunkId = CSM.ChunkId AND C.SnapshotDataId = S.SnapshotDataId) ), 0) FROM History AS S -- skipping intermediate table SnapshotData WHERE S.ReportID = @ReportID GO GRANT EXECUTE ON [dbo].[ListHistory] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanHistoryForReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanHistoryForReport] GO -- delete snapshots exceeding # of snapshots. won't work if @SnapshotLimit = 0 CREATE PROCEDURE [dbo].[CleanHistoryForReport] @SnapshotLimit int, @ReportID uniqueidentifier AS SET NOCOUNT OFF DELETE FROM History WHERE ReportID = @ReportID and SnapshotDate < (SELECT MIN(SnapshotDate) FROM (SELECT TOP (@SnapshotLimit) SnapshotDate FROM History WHERE ReportID = @ReportID ORDER BY SnapshotDate DESC ) AS TopSnapshots ) GO GRANT EXECUTE ON [dbo].[CleanHistoryForReport] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanAllHistories]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanAllHistories] GO -- delete snapshots exceeding # of snapshots for the whole system CREATE PROCEDURE [dbo].[CleanAllHistories] @SnapshotLimit int AS SET NOCOUNT OFF DELETE FROM History WHERE HistoryID in (SELECT HistoryID FROM History JOIN Catalog AS ReportJoinSnapshot ON ItemID = ReportID WHERE SnapshotLimit IS NULL and SnapshotDate < (SELECT MIN(SnapshotDate) FROM (SELECT TOP (@SnapshotLimit) SnapshotDate FROM History AS InnerSnapshot WHERE InnerSnapshot.ReportID = ReportJoinSnapshot.ItemID ORDER BY SnapshotDate DESC ) AS TopSnapshots ) ) GO GRANT EXECUTE ON [dbo].[CleanAllHistories] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteHistoryRecord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteHistoryRecord] GO -- delete one historical snapshot CREATE PROCEDURE [dbo].[DeleteHistoryRecord] @ReportID uniqueidentifier, @SnapshotDate DateTime AS SET NOCOUNT OFF DELETE FROM History WHERE ReportID = @ReportID AND SnapshotDate = @SnapshotDate GO GRANT EXECUTE ON [dbo].[DeleteHistoryRecord] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteAllHistoryForReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteAllHistoryForReport] GO -- delete all snapshots for a report CREATE PROCEDURE [dbo].[DeleteAllHistoryForReport] @ReportID uniqueidentifier AS SET NOCOUNT OFF DELETE FROM History WHERE HistoryID in (SELECT HistoryID FROM History JOIN Catalog on ItemID = ReportID WHERE ReportID = @ReportID ) GO GRANT EXECUTE ON [dbo].[DeleteAllHistoryForReport] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteHistoriesWithNoPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteHistoriesWithNoPolicy] GO -- delete all snapshots for all reports that inherit system History policy CREATE PROCEDURE [dbo].[DeleteHistoriesWithNoPolicy] AS SET NOCOUNT OFF DELETE FROM History WHERE HistoryID in (SELECT HistoryID FROM History JOIN Catalog on ItemID = ReportID WHERE SnapshotLimit is null ) GO GRANT EXECUTE ON [dbo].[DeleteHistoriesWithNoPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Get_sqlagent_job_status]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[Get_sqlagent_job_status] GO CREATE PROCEDURE [dbo].[Get_sqlagent_job_status] -- Individual job parameters @job_id UNIQUEIDENTIFIER = NULL, -- If provided will only return info about this job -- Note: Only @job_id or @job_name needs to be provided @job_name sysname = NULL, -- If provided will only return info about this job @owner_login_name sysname = NULL -- If provided will only return jobs for this owner AS BEGIN DECLARE @retval INT DECLARE @job_owner_sid VARBINARY(85) DECLARE @is_sysadmin INT SET NOCOUNT ON -- Remove any leading/trailing spaces from parameters (except @owner_login_name) SELECT @job_name = LTRIM(RTRIM(@job_name)) -- Turn [nullable] empty string parameters into NULLs IF (@job_name = N'') SELECT @job_name = NULL -- Verify the job if supplied. This also checks if the caller has rights to view the job IF ((@job_id IS NOT NULL) OR (@job_name IS NOT NULL)) BEGIN EXECUTE @retval = msdb..sp_verify_job_identifiers '@job_name', '@job_id', @job_name OUTPUT, @job_id OUTPUT IF (@retval <> 0) RETURN(1) -- Failure END -- If the login name isn't given, set it to the job owner or the current caller IF(@owner_login_name IS NULL) BEGIN SET @owner_login_name = (SELECT SUSER_SNAME(sj.owner_sid) FROM msdb.dbo.sysjobs sj where sj.job_id = @job_id) SET @is_sysadmin = ISNULL(IS_SRVROLEMEMBER(N'sysadmin', @owner_login_name), 0) END ELSE BEGIN -- Check owner IF (SUSER_SID(@owner_login_name) IS NULL) BEGIN RAISERROR(14262, -1, -1, '@owner_login_name', @owner_login_name) RETURN(1) -- Failure END --only allow sysadmin types to specify the owner IF ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1) AND (ISNULL(IS_MEMBER(N'SQLAgentAdminRole'), 0) = 1) AND (SUSER_SNAME() <> @owner_login_name)) BEGIN --TODO: RAISERROR(14525, -1, -1) RETURN(1) -- Failure END SET @is_sysadmin = 0 END IF (@job_id IS NOT NULL) BEGIN -- Individual job... EXECUTE @retval = master.dbo.xp_sqlagent_enum_jobs @is_sysadmin, @owner_login_name, @job_id IF (@retval <> 0) RETURN(1) -- Failure END ELSE BEGIN -- Set of jobs... EXECUTE @retval = master.dbo.xp_sqlagent_enum_jobs @is_sysadmin, @owner_login_name IF (@retval <> 0) RETURN(1) -- Failure END RETURN(0) -- Success END GO GRANT EXECUTE ON [dbo].[Get_sqlagent_job_status] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateTask] GO CREATE PROCEDURE [dbo].[CreateTask] @ScheduleID uniqueidentifier, @Name nvarchar (260), @StartDate datetime, @Flags int, @NextRunTime datetime = NULL, @LastRunTime datetime = NULL, @EndDate datetime = NULL, @RecurrenceType int = NULL, @MinutesInterval int = NULL, @DaysInterval int = NULL, @WeeksInterval int = NULL, @DaysOfWeek int = NULL, @DaysOfMonth int = NULL, @Month int = NULL, @MonthlyWeek int = NULL, @State int = NULL, @LastRunStatus nvarchar (260) = NULL, @ScheduledRunTimeout int = NULL, @UserSid varbinary (85) = null, @UserName nvarchar(260), @AuthType int, @EventType nvarchar (260), @EventData nvarchar (260), @Type int , @Path nvarchar (425) = NULL AS DECLARE @UserID uniqueidentifier EXEC GetUserID @UserSid, @UserName, @AuthType, @UserID OUTPUT -- Create a task with the given data. Insert into Schedule ( [ScheduleID], [Name], [StartDate], [Flags], [NextRunTime], [LastRunTime], [EndDate], [RecurrenceType], [MinutesInterval], [DaysInterval], [WeeksInterval], [DaysOfWeek], [DaysOfMonth], [Month], [MonthlyWeek], [State], [LastRunStatus], [ScheduledRunTimeout], [CreatedById], [EventType], [EventData], [Type], [Path] ) values (@ScheduleID, @Name, @StartDate, @Flags, @NextRunTime, @LastRunTime, @EndDate, @RecurrenceType, @MinutesInterval, @DaysInterval, @WeeksInterval, @DaysOfWeek, @DaysOfMonth, @Month, @MonthlyWeek, @State, @LastRunStatus, @ScheduledRunTimeout, @UserID, @EventType, @EventData, @Type, @Path) GO GRANT EXECUTE ON [dbo].[CreateTask] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateTask] GO CREATE PROCEDURE [dbo].[UpdateTask] @ScheduleID uniqueidentifier, @Name nvarchar (260), @StartDate datetime, @Flags int, @NextRunTime datetime = NULL, @LastRunTime datetime = NULL, @EndDate datetime = NULL, @RecurrenceType int = NULL, @MinutesInterval int = NULL, @DaysInterval int = NULL, @WeeksInterval int = NULL, @DaysOfWeek int = NULL, @DaysOfMonth int = NULL, @Month int = NULL, @MonthlyWeek int = NULL, @State int = NULL, @LastRunStatus nvarchar (260) = NULL, @ScheduledRunTimeout int = NULL AS -- Update a tasks values. ScheduleID and Report information can not be updated Update Schedule set [StartDate] = @StartDate, [Name] = @Name, [Flags] = @Flags, [NextRunTime] = @NextRunTime, [LastRunTime] = @LastRunTime, [EndDate] = @EndDate, [RecurrenceType] = @RecurrenceType, [MinutesInterval] = @MinutesInterval, [DaysInterval] = @DaysInterval, [WeeksInterval] = @WeeksInterval, [DaysOfWeek] = @DaysOfWeek, [DaysOfMonth] = @DaysOfMonth, [Month] = @Month, [MonthlyWeek] = @MonthlyWeek, [State] = @State, [LastRunStatus] = @LastRunStatus, [ScheduledRunTimeout] = @ScheduledRunTimeout where [ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[UpdateTask] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateScheduleNextRunTime]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateScheduleNextRunTime] GO CREATE PROCEDURE [dbo].[UpdateScheduleNextRunTime] @ScheduleID as uniqueidentifier, @NextRunTime as datetime as update Schedule set [NextRunTime] = @NextRunTime where [ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[UpdateScheduleNextRunTime] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListScheduledReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListScheduledReports] GO CREATE PROCEDURE [dbo].[ListScheduledReports] @ScheduleID uniqueidentifier AS -- List all reports for a schedule select RS.[ReportAction], RS.[ScheduleID], RS.[ReportID], RS.[SubscriptionID], C.[Path], C.[Name], C.[Description], C.[ModifiedDate], SUSER_SNAME(U.[Sid]), U.[UserName], DATALENGTH( C.Content ), C.ExecutionTime, S.[Type], SD.[NtSecDescPrimary] from [ReportSchedule] RS Inner join [Catalog] C on RS.[ReportID] = C.[ItemID] Inner join [Schedule] S on RS.[ScheduleID] = S.[ScheduleID] Inner join [Users] U on C.[ModifiedByID] = U.UserID left outer join [SecData] SD on SD.[PolicyID] = C.[PolicyID] AND SD.AuthType = U.AuthType where RS.[ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[ListScheduledReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListTasks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListTasks] GO CREATE PROCEDURE [dbo].[ListTasks] @Path nvarchar (425) = NULL, @Prefix nvarchar (425) = NULL AS select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], Owner.[AuthType], (select count(*) from ReportSchedule where ReportSchedule.ScheduleID = S.ScheduleID) from [Schedule] S inner join [Users] Owner on S.[CreatedById] = Owner.UserID where S.[Type] = 0 /*Type 0 is shared schedules*/ and ((@Path is null) OR (S.Path = @Path) or (S.Path like @Prefix escape '*')) GO GRANT EXECUTE ON [dbo].[ListTasks] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListTasksForMaintenance]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListTasksForMaintenance] GO CREATE PROCEDURE [dbo].[ListTasksForMaintenance] AS declare @date datetime set @date = GETUTCDATE() update [Schedule] set [ConsistancyCheck] = @date from ( SELECT TOP 20 [ScheduleID] FROM [Schedule] WITH(UPDLOCK) WHERE [ConsistancyCheck] is NULL ) AS t1 WHERE [Schedule].[ScheduleID] = t1.[ScheduleID] select top 20 S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path] from [Schedule] S where [ConsistancyCheck] = @date GO GRANT EXECUTE ON [dbo].[ListTasksForMaintenance] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ClearScheduleConsistancyFlags]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ClearScheduleConsistancyFlags] GO CREATE PROCEDURE [dbo].[ClearScheduleConsistancyFlags] AS update [Schedule] with (tablock, xlock) set [ConsistancyCheck] = NULL GO GRANT EXECUTE ON [dbo].[ClearScheduleConsistancyFlags] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAReportsReportAction]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAReportsReportAction] GO CREATE PROCEDURE [dbo].[GetAReportsReportAction] @ReportID uniqueidentifier, @ReportAction int AS select RS.[ReportAction], RS.[ScheduleID], RS.[ReportID], RS.[SubscriptionID], C.[Path] from [ReportSchedule] RS Inner join [Catalog] C on RS.[ReportID] = C.[ItemID] where C.ItemID = @ReportID and RS.[ReportAction] = @ReportAction GO GRANT EXECUTE ON [dbo].[GetAReportsReportAction] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetTimeBasedSubscriptionReportAction]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetTimeBasedSubscriptionReportAction] GO CREATE PROCEDURE [dbo].[GetTimeBasedSubscriptionReportAction] @SubscriptionID uniqueidentifier AS select RS.[ReportAction], RS.[ScheduleID], RS.[ReportID], RS.[SubscriptionID], C.[Path] from [ReportSchedule] RS Inner join [Catalog] C on RS.[ReportID] = C.[ItemID] where RS.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetTimeBasedSubscriptionReportAction] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetTaskProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetTaskProperties] GO CREATE PROCEDURE [dbo].[GetTaskProperties] @ScheduleID uniqueidentifier AS -- Grab all of a tasks properties given a task id select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], Owner.[AuthType] from [Schedule] S with (XLOCK) Inner join [Users] Owner on S.[CreatedById] = Owner.UserID where S.[ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[GetTaskProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteTask] GO CREATE PROCEDURE [dbo].[DeleteTask] @ScheduleID uniqueidentifier AS SET NOCOUNT OFF -- Delete the task with the given task id DELETE FROM Schedule WHERE [ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[DeleteTask] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSchedulesReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSchedulesReports] GO CREATE PROCEDURE [dbo].[GetSchedulesReports] @ID uniqueidentifier AS select C.Path from ReportSchedule RS inner join Catalog C on (C.ItemID = RS.ReportID) where ScheduleID = @ID GO GRANT EXECUTE ON [dbo].[GetSchedulesReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddReportSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddReportSchedule] GO CREATE PROCEDURE [dbo].[AddReportSchedule] @ScheduleID uniqueidentifier, @ReportID uniqueidentifier, @SubscriptionID uniqueidentifier = NULL, @Action int AS -- VSTS #139366: SQL Deadlock in AddReportSchedule stored procedure -- Hold lock on [Schedule].[ScheduleID] to prevent deadlock -- with Schedule_UpdateExpiration Schedule's after update trigger select 1 from [Schedule] with (HOLDLOCK) where [Schedule].[ScheduleID] = @ScheduleID Insert into ReportSchedule ([ScheduleID], [ReportID], [SubscriptionID], [ReportAction]) values (@ScheduleID, @ReportID, @SubscriptionID, @Action) GO GRANT EXECUTE ON [dbo].[AddReportSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteReportSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteReportSchedule] GO CREATE PROCEDURE [dbo].[DeleteReportSchedule] @ScheduleID uniqueidentifier, @ReportID uniqueidentifier, @SubscriptionID uniqueidentifier = NULL, @ReportAction int AS IF @SubscriptionID is NULL BEGIN delete from ReportSchedule where ScheduleID = @ScheduleID and ReportID = @ReportID and ReportAction = @ReportAction END ELSE BEGIN delete from ReportSchedule where ScheduleID = @ScheduleID and ReportID = @ReportID and ReportAction = @ReportAction and SubscriptionID = @SubscriptionID END GO GRANT EXECUTE ON [dbo].[DeleteReportSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapShotSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapShotSchedule] GO CREATE PROCEDURE [dbo].[GetSnapShotSchedule] @ReportID uniqueidentifier AS select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], Owner.[AuthType] from Schedule S with (XLOCK) inner join ReportSchedule RS on S.ScheduleID = RS.ScheduleID inner join [Users] Owner on S.[CreatedById] = Owner.[UserID] where RS.ReportAction = 2 and -- 2 == create snapshot RS.ReportID = @ReportID GO GRANT EXECUTE ON [dbo].[GetSnapShotSchedule] TO RSExecRole GO -------------------------------------------------- ------------- Time based subscriptions if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateTimeBasedSubscriptionSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateTimeBasedSubscriptionSchedule] GO CREATE PROCEDURE [dbo].[CreateTimeBasedSubscriptionSchedule] @SubscriptionID as uniqueidentifier, @ScheduleID uniqueidentifier, @Schedule_Name nvarchar (260), @Report_Name nvarchar (425), @StartDate datetime, @Flags int, @NextRunTime datetime = NULL, @LastRunTime datetime = NULL, @EndDate datetime = NULL, @RecurrenceType int = NULL, @MinutesInterval int = NULL, @DaysInterval int = NULL, @WeeksInterval int = NULL, @DaysOfWeek int = NULL, @DaysOfMonth int = NULL, @Month int = NULL, @MonthlyWeek int = NULL, @State int = NULL, @LastRunStatus nvarchar (260) = NULL, @ScheduledRunTimeout int = NULL, @UserSid varbinary (85) = NULL, @UserName nvarchar(260), @AuthType int, @EventType nvarchar (260), @EventData nvarchar (260), @Path nvarchar (425) = NULL AS EXEC CreateTask @ScheduleID, @Schedule_Name, @StartDate, @Flags, @NextRunTime, @LastRunTime, @EndDate, @RecurrenceType, @MinutesInterval, @DaysInterval, @WeeksInterval, @DaysOfWeek, @DaysOfMonth, @Month, @MonthlyWeek, @State, @LastRunStatus, @ScheduledRunTimeout, @UserSid, @UserName, @AuthType, @EventType, @EventData, 1 /*scoped type*/, @Path if @@ERROR = 0 begin -- add a row to the reportSchedule table declare @Report_OID uniqueidentifier select @Report_OID = (select [ItemID] from [Catalog] with (HOLDLOCK) where [Catalog].[Path] = @Report_Name and ([Catalog].[Type] = 2 or [Catalog].[Type] = 4)) EXEC AddReportSchedule @ScheduleID, @Report_OID, @SubscriptionID, 4 -- TimedSubscription action end GO GRANT EXECUTE ON [dbo].[CreateTimeBasedSubscriptionSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetTimeBasedSubscriptionSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetTimeBasedSubscriptionSchedule] GO CREATE PROCEDURE [dbo].[GetTimeBasedSubscriptionSchedule] @SubscriptionID as uniqueidentifier AS select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], Owner.[AuthType] from [ReportSchedule] R inner join Schedule S with (XLOCK) on R.[ScheduleID] = S.[ScheduleID] Inner join [Users] Owner on S.[CreatedById] = Owner.UserID where R.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetTimeBasedSubscriptionSchedule] TO RSExecRole GO -------------------------------------------------- ------------- Running Jobs if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddRunningJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddRunningJob] GO CREATE PROCEDURE [dbo].[AddRunningJob] @JobID as nvarchar(32), @StartDate as datetime, @ComputerName as nvarchar(32), @RequestName as nvarchar(425), @RequestPath as nvarchar(425), @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @Description as ntext = NULL, @Timeout as int, @JobAction as smallint, @JobType as smallint, @JobStatus as smallint AS SET NOCOUNT OFF DECLARE @UserID uniqueidentifier EXEC GetUserID @UserSid, @UserName, @AuthType, @UserID OUTPUT INSERT INTO RunningJobs (JobID, StartDate, ComputerName, RequestName, RequestPath, UserID, Description, Timeout, JobAction, JobType, JobStatus ) VALUES (@JobID, @StartDate, @ComputerName, @RequestName, @RequestPath, @UserID, @Description, @Timeout, @JobAction, @JobType, @JobStatus) GO GRANT EXECUTE ON [dbo].[AddRunningJob] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RemoveRunningJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RemoveRunningJob] GO CREATE PROCEDURE [dbo].[RemoveRunningJob] @JobID as nvarchar(32) AS SET NOCOUNT OFF DELETE FROM RunningJobs WHERE JobID = @JobID GO GRANT EXECUTE ON [dbo].[RemoveRunningJob] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateRunningJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateRunningJob] GO CREATE PROCEDURE [dbo].[UpdateRunningJob] @JobID as nvarchar(32), @JobStatus as smallint AS SET NOCOUNT OFF UPDATE RunningJobs SET JobStatus = @JobStatus WHERE JobID = @JobID GO GRANT EXECUTE ON [dbo].[UpdateRunningJob] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetMyRunningJobs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetMyRunningJobs] GO CREATE PROCEDURE [dbo].[GetMyRunningJobs] @ComputerName as nvarchar(32), @JobType as smallint AS SELECT JobID, StartDate, ComputerName, RequestName, RequestPath, SUSER_SNAME(Users.[Sid]), Users.[UserName], Description, Timeout, JobAction, JobType, JobStatus, Users.[AuthType] FROM RunningJobs INNER JOIN Users ON RunningJobs.UserID = Users.UserID WHERE ComputerName = @ComputerName AND JobType = @JobType GO GRANT EXECUTE ON [dbo].[GetMyRunningJobs] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListRunningJobs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListRunningJobs] GO CREATE PROCEDURE [dbo].[ListRunningJobs] AS SELECT JobID, StartDate, ComputerName, RequestName, RequestPath, SUSER_SNAME(Users.[Sid]), Users.[UserName], Description, Timeout, JobAction, JobType, JobStatus, Users.[AuthType] FROM RunningJobs INNER JOIN Users ON RunningJobs.UserID = Users.UserID GO GRANT EXECUTE ON [dbo].[ListRunningJobs] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredJobs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredJobs] GO CREATE PROCEDURE [dbo].[CleanExpiredJobs] AS SET NOCOUNT OFF DELETE FROM RunningJobs WHERE DATEADD(s, Timeout, StartDate) < GETDATE() GO GRANT EXECUTE ON [dbo].[CleanExpiredJobs] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateObject]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateObject] GO -- This SP should never be called with a policy ID unless it is guarenteed that -- the parent will not be deleted before the insert (such as while running this script) CREATE PROCEDURE [dbo].[CreateObject] @ItemID uniqueidentifier, @Name nvarchar (425), @Path nvarchar (425), @ParentID uniqueidentifier, @Type int, @Content image = NULL, @Intermediate uniqueidentifier = NULL, @LinkSourceID uniqueidentifier = NULL, @Property ntext = NULL, @Parameter ntext = NULL, @Description ntext = NULL, @Hidden bit = NULL, @CreatedBySid varbinary(85) = NULL, @CreatedByName nvarchar(260), @AuthType int, @CreationDate datetime, @ModificationDate datetime, @MimeType nvarchar (260) = NULL, @SnapshotLimit int = NULL, @PolicyRoot int = 0, @PolicyID uniqueidentifier = NULL, @ExecutionFlag int = 1 -- allow live execution, don't keep history AS DECLARE @CreatedByID uniqueidentifier EXEC GetUserID @CreatedBySid, @CreatedByName, @AuthType, @CreatedByID OUTPUT UPDATE Catalog with (XLOCK) SET ModifiedByID = @CreatedByID, ModifiedDate = @ModificationDate WHERE ItemID = @ParentID -- If no policyID, use the parent's IF @PolicyID is NULL BEGIN SET @PolicyID = (SELECT PolicyID FROM [dbo].[Catalog] WHERE Catalog.ItemID = @ParentID) END -- If there is no policy ID then we are guarenteed not to have a parent IF @PolicyID is NULL BEGIN RAISERROR ('Parent Not Found', 16, 1) return END INSERT INTO Catalog (ItemID, Path, Name, ParentID, Type, Content, Intermediate, LinkSourceID, Property, Description, Hidden, CreatedByID, CreationDate, ModifiedByID, ModifiedDate, MimeType, SnapshotLimit, [Parameter], PolicyID, PolicyRoot, ExecutionFlag ) VALUES (@ItemID, @Path, @Name, @ParentID, @Type, @Content, @Intermediate, @LinkSourceID, @Property, @Description, @Hidden, @CreatedByID, @CreationDate, @CreatedByID, @ModificationDate, @MimeType, @SnapshotLimit, @Parameter, @PolicyID, @PolicyRoot , @ExecutionFlag) IF @Intermediate IS NOT NULL AND @@ERROR = 0 BEGIN UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount + 1, TransientRefcount = TransientRefcount - 1 WHERE SnapshotData.SnapshotDataID = @Intermediate END GO GRANT EXECUTE ON [dbo].[CreateObject] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteObject]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteObject] GO CREATE PROCEDURE [dbo].[DeleteObject] @Path nvarchar (425), @Prefix nvarchar (850) AS SET NOCOUNT OFF -- Remove reference for intermediate formats UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 FROM Catalog AS R WITH (XLOCK) INNER JOIN [SnapshotData] AS SD ON R.Intermediate = SD.SnapshotDataID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Remove reference for execution snapshots UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 FROM Catalog AS R WITH (XLOCK) INNER JOIN [SnapshotData] AS SD ON R.SnapshotDataID = SD.SnapshotDataID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Remove history for deleted reports and linked report DELETE History FROM [Catalog] AS R INNER JOIN [History] AS S ON R.ItemID = S.ReportID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Remove model drill reports DELETE ModelDrill FROM [Catalog] AS C INNER JOIN [ModelDrill] AS M ON C.ItemID = M.ReportID WHERE (C.Path = @Path OR C.Path LIKE @Prefix ESCAPE '*') -- Adjust data sources UPDATE [DataSource] SET [Flags] = [Flags] & 0x7FFFFFFD, -- broken link [Link] = NULL FROM [Catalog] AS C INNER JOIN [DataSource] AS DS ON C.[ItemID] = DS.[Link] WHERE (C.Path = @Path OR C.Path LIKE @Prefix ESCAPE '*') -- Clean all data sources DELETE [DataSource] FROM [Catalog] AS R INNER JOIN [DataSource] AS DS ON R.[ItemID] = DS.[ItemID] WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Update linked reports UPDATE LR SET LR.LinkSourceID = NULL FROM [Catalog] AS R INNER JOIN [Catalog] AS LR ON R.ItemID = LR.LinkSourceID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') AND (LR.Path NOT LIKE @Prefix ESCAPE '*') -- Remove references for cache entries UPDATE SN SET PermanentRefcount = PermanentRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC on SN.SnapshotDataID = EC.SnapshotDataID INNER JOIN Catalog AS C ON EC.ReportID = C.ItemID WHERE (Path = @Path OR Path LIKE @Prefix ESCAPE '*') -- Clean cache entries for items to be deleted DELETE EC FROM ReportServerTempDB.dbo.ExecutionCache AS EC INNER JOIN Catalog AS C ON EC.ReportID = C.ItemID WHERE (Path = @Path OR Path LIKE @Prefix ESCAPE '*') -- Finally delete items DELETE FROM [Catalog] WHERE (Path = @Path OR Path LIKE @Prefix ESCAPE '*') EXEC CleanOrphanedPolicies GO GRANT EXECUTE ON [dbo].[DeleteObject] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindObjectsNonRecursive]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindObjectsNonRecursive] GO CREATE PROCEDURE [dbo].[FindObjectsNonRecursive] @Path nvarchar (425), @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.[UserName], SUSER_SNAME(MU.Sid), MU.[UserName], C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Catalog AS P ON C.ParentID = P.ItemID INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE P.Path = @Path GO GRANT EXECUTE ON [dbo].[FindObjectsNonRecursive] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindObjectsRecursive]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindObjectsRecursive] GO CREATE PROCEDURE [dbo].[FindObjectsRecursive] @Prefix nvarchar (850), @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.UserName, SUSER_SNAME(MU.Sid), MU.UserName, C.MimeType, C.ExecutionTime, C.Hidden from Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE C.Path LIKE @Prefix ESCAPE '*' GO GRANT EXECUTE ON [dbo].[FindObjectsRecursive] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindParents]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindParents] GO CREATE PROCEDURE [dbo].[FindParents] @Path nvarchar (425), @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.[UserName], SUSER_SNAME(MU.Sid), MU.[UserName], C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE @Path LIKE C.Path + '/%' ORDER BY DATALENGTH(C.Path) desc GO GRANT EXECUTE ON [dbo].[FindParents] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindObjectsByLink]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindObjectsByLink] GO CREATE PROCEDURE [dbo].[FindObjectsByLink] @Link uniqueidentifier, @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.UserName, SUSER_SNAME(MU.Sid), MU.UserName, C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE C.LinkSourceID = @Link GO GRANT EXECUTE ON [dbo].[FindObjectsByLink] TO RSExecRole GO -------------------------------------------------- ------------- Procedures used to update linked reports if exists (select * from sysobjects where id = object_id('[dbo].[GetIDPairsByLink]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetIDPairsByLink] GO CREATE PROCEDURE [dbo].[GetIDPairsByLink] @Link uniqueidentifier AS SELECT LinkSourceID, ItemID FROM Catalog WHERE LinkSourceID = @Link GO GRANT EXECUTE ON [dbo].[GetIDPairsByLink] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[GetChildrenBeforeDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetChildrenBeforeDelete] GO CREATE PROCEDURE [dbo].[GetChildrenBeforeDelete] @Prefix nvarchar (850), @AuthType int AS SELECT C.PolicyID, C.Type, SD.NtSecDescPrimary FROM Catalog AS C LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE C.Path LIKE @Prefix ESCAPE '*' -- return children only, not item itself GO GRANT EXECUTE ON [dbo].[GetChildrenBeforeDelete] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAllProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAllProperties] GO CREATE PROCEDURE [dbo].[GetAllProperties] @Path nvarchar (425), @AuthType int AS select Property, Description, Type, DATALENGTH( Content ), ItemID, SUSER_SNAME(C.Sid), C.UserName, CreationDate, SUSER_SNAME(M.Sid), M.UserName, ModifiedDate, MimeType, ExecutionTime, NtSecDescPrimary, [LinkSourceID], Hidden, ExecutionFlag, SnapshotLimit, [Name] FROM Catalog INNER JOIN Users C ON Catalog.CreatedByID = C.UserID INNER JOIN Users M ON Catalog.ModifiedByID = M.UserID LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[GetAllProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetParameters] GO CREATE PROCEDURE [dbo].[GetParameters] @Path nvarchar (425), @AuthType int AS SELECT Type, [Parameter], ItemID, SecData.NtSecDescPrimary, [LinkSourceID], [ExecutionFlag] FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[GetParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetObjectContent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetObjectContent] GO CREATE PROCEDURE [dbo].[GetObjectContent] @Path nvarchar (425), @AuthType int AS SELECT Type, Content, LinkSourceID, MimeType, SecData.NtSecDescPrimary, ItemID FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[GetObjectContent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[LoadForDefinitionCheck]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[LoadForDefinitionCheck] GO -- For loading compiled definitions to check for internal republishing, this is -- done before calling GetCompiledDefinition or GetReportForExecution CREATE PROCEDURE [dbo].[LoadForDefinitionCheck] @Path nvarchar(425), @AcquireUpdateLocks bit, @AuthType int AS IF(@AcquireUpdateLocks = 0) BEGIN SELECT CompiledDefinition.SnapshotDataID, CompiledDefinition.ProcessingFlags, SecData.NtSecDescPrimary FROM Catalog MainItem LEFT OUTER JOIN SecData ON (MainItem.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType) LEFT OUTER JOIN Catalog LinkTarget WITH (INDEX = PK_CATALOG) ON (MainItem.LinkSourceID = LinkTarget.ItemID) JOIN SnapshotData CompiledDefinition ON (CompiledDefinition.SnapshotDataID = COALESCE(LinkTarget.Intermediate, MainItem.Intermediate)) WHERE MainItem.Path = @Path AND (MainItem.Type = 2 /* Report */ OR MainItem.Type = 4 /* Linked Report */) END ELSE BEGIN -- acquire upgrade locks, this means that the check is being perform in a -- different transaction context which will be committed before trying to -- perform the actual load, to prevent deadlock in the case where we have to -- republish this new transaction will acquire and hold upgrade locks SELECT CompiledDefinition.SnapshotDataID, CompiledDefinition.ProcessingFlags, SecData.NtSecDescPrimary FROM Catalog MainItem WITH(UPDLOCK ROWLOCK) LEFT OUTER JOIN SecData ON (MainItem.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType) LEFT OUTER JOIN Catalog LinkTarget WITH (UPDLOCK ROWLOCK INDEX = PK_CATALOG) ON (MainItem.LinkSourceID = LinkTarget.ItemID) JOIN SnapshotData CompiledDefinition WITH(UPDLOCK ROWLOCK) ON (CompiledDefinition.SnapshotDataID = COALESCE(LinkTarget.Intermediate, MainItem.Intermediate)) WHERE MainItem.Path = @Path AND (MainItem.Type = 2 /* Report */ OR MainItem.Type = 4 /* Linked Report */) END GO GRANT EXECUTE ON [dbo].[LoadForDefinitionCheck] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[LoadForRepublishing]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[LoadForRepublishing] GO -- Loads a report's RDL for republishing CREATE PROCEDURE [dbo].[LoadForRepublishing] @Path nvarchar(425) AS SELECT COALESCE(LinkTarget.Content, MainItem.Content) AS [Content], CompiledDefinition.SnapshotDataID, CompiledDefinition.ProcessingFlags FROM Catalog MainItem LEFT OUTER JOIN Catalog LinkTarget WITH (INDEX = PK_CATALOG) ON (MainItem.LinkSourceID = LinkTarget.ItemID) JOIN SnapshotData CompiledDefinition ON (CompiledDefinition.SnapshotDataID = COALESCE(LinkTarget.Intermediate, MainItem.Intermediate)) WHERE MainItem.Path = @Path GO GRANT EXECUTE ON [dbo].[LoadForRepublishing] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateCompiledDefinition]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateCompiledDefinition] GO CREATE PROCEDURE [dbo].[UpdateCompiledDefinition] @Path NVARCHAR(425), @OldSnapshotId UNIQUEIDENTIFIER, @NewSnapshotId UNIQUEIDENTIFIER, @ItemId UNIQUEIDENTIFIER OUTPUT AS BEGIN -- we have a clustered unique index on [Path] which the QO -- should match for the filter UPDATE [dbo].[Catalog] SET [Intermediate] = @NewSnapshotId, @ItemId = [ItemID] WHERE [Path] = @Path AND ([Intermediate] = @OldSnapshotId OR (@OldSnapshotId IS NULL AND [Intermediate] IS NULL)); DECLARE @UpdatedReferences INT ; SELECT @UpdatedReferences = @@ROWCOUNT ; IF(@UpdatedReferences <> 0) BEGIN UPDATE [dbo].[SnapshotData] SET [PermanentRefcount] = [PermanentRefcount] + @UpdatedReferences, [TransientRefcount] = [TransientRefcount] - 1 WHERE [SnapshotDataID] = @NewSnapshotId ; UPDATE [dbo].[SnapshotData] SET [PermanentRefcount] = [PermanentRefcount] - @UpdatedReferences WHERE [SnapshotDataID] = @OldSnapshotId ; END END GRANT EXECUTE ON [dbo].[UpdateCompiledDefinition] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RebindDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RebindDataSource] GO -- Republishing generates new DSID and stores those in the object model, -- in order to resolve the data sources we need to rebind the old -- data source definition to the current DSID CREATE PROCEDURE [dbo].[RebindDataSource] @ItemId uniqueidentifier, @Name nvarchar(260), @NewDSID uniqueidentifier AS UPDATE DataSource SET DSID = @NewDSID WHERE ItemID = @ItemId AND [Name] = @Name GO GRANT EXECUTE ON [dbo].[RebindDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCompiledDefinition]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetCompiledDefinition] GO -- used to create snapshots CREATE PROCEDURE [dbo].[GetCompiledDefinition] @Path nvarchar (425), @AuthType int AS SELECT MainItem.Type, MainItem.Intermediate, MainItem.LinkSourceID, MainItem.Property, MainItem.Description, SecData.NtSecDescPrimary, MainItem.ItemID, MainItem.ExecutionFlag, LinkTarget.Intermediate, LinkTarget.Property, LinkTarget.Description, MainItem.[SnapshotDataID] FROM Catalog MainItem LEFT OUTER JOIN SecData ON MainItem.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog LinkTarget with (INDEX(PK_Catalog)) on MainItem.LinkSourceID = LinkTarget.ItemID WHERE MainItem.Path = @Path GO GRANT EXECUTE ON [dbo].[GetCompiledDefinition] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetReportForExecution]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetReportForExecution] GO -- gets either the intermediate format or snapshot from cache CREATE PROCEDURE [dbo].[GetReportForExecution] @Path nvarchar (425), @ParamsHash int, @AuthType int AS DECLARE @now AS datetime SET @now = GETDATE() IF ( NOT EXISTS ( SELECT TOP 1 1 FROM Catalog AS C INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON C.ItemID = EC.ReportID INNER JOIN ReportServerTempDB.dbo.SnapshotData AS SN ON EC.SnapshotDataID = SN.SnapshotDataID WHERE C.Path = @Path AND EC.AbsoluteExpiration > @now AND SN.ParamsHash = @ParamsHash ) ) BEGIN -- no cache SELECT Cat.Type, Cat.LinkSourceID, Cat2.Path, Cat.Property, Cat.Description, SecData.NtSecDescPrimary, Cat.ItemID, CAST (0 AS BIT), -- not found, Cat.Intermediate, Cat.ExecutionFlag, SD.SnapshotDataID, SD.DependsOnUser, Cat.ExecutionTime, (SELECT Schedule.NextRunTime FROM Schedule WITH (XLOCK) INNER JOIN ReportSchedule ON Schedule.ScheduleID = ReportSchedule.ScheduleID WHERE ReportSchedule.ReportID = Cat.ItemID AND ReportSchedule.ReportAction = 1), -- update snapshot (SELECT Schedule.ScheduleID FROM Schedule INNER JOIN ReportSchedule ON Schedule.ScheduleID = ReportSchedule.ScheduleID WHERE ReportSchedule.ReportID = Cat.ItemID AND ReportSchedule.ReportAction = 1), -- update snapshot (SELECT CachePolicy.ExpirationFlags FROM CachePolicy WHERE CachePolicy.ReportID = Cat.ItemID), Cat2.Intermediate, SD.ProcessingFlags FROM Catalog AS Cat LEFT OUTER JOIN SecData ON Cat.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog AS Cat2 on Cat.LinkSourceID = Cat2.ItemID LEFT OUTER JOIN SnapshotData AS SD ON Cat.SnapshotDataID = SD.SnapshotDataID WHERE Cat.Path = @Path END ELSE BEGIN -- use cache SELECT TOP 1 Cat.Type, Cat.LinkSourceID, Cat2.Path, Cat.Property, Cat.Description, SecData.NtSecDescPrimary, Cat.ItemID, CAST (1 AS BIT), -- found, SN.SnapshotDataID, SN.DependsOnUser, SN.EffectiveParams, SN.CreatedDate, EC.AbsoluteExpiration, (SELECT CachePolicy.ExpirationFlags FROM CachePolicy WHERE CachePolicy.ReportID = Cat.ItemID), (SELECT Schedule.ScheduleID FROM Schedule WITH (XLOCK) INNER JOIN ReportSchedule ON Schedule.ScheduleID = ReportSchedule.ScheduleID WHERE ReportSchedule.ReportID = Cat.ItemID AND ReportSchedule.ReportAction = 1), -- update snapshot SN.QueryParams, SN.ProcessingFlags FROM Catalog AS Cat INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON Cat.ItemID = EC.ReportID INNER JOIN ReportServerTempDB.dbo.SnapshotData AS SN ON EC.SnapshotDataID = SN.SnapshotDataID LEFT OUTER JOIN SecData ON Cat.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog AS Cat2 on Cat.LinkSourceID = Cat2.ItemID WHERE Cat.Path = @Path AND AbsoluteExpiration > @now AND SN.ParamsHash = @ParamsHash ORDER BY SN.CreatedDate DESC END GO GRANT EXECUTE ON [dbo].[GetReportForExecution] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetReportParametersForExecution]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetReportParametersForExecution] GO -- gets either the intermediate format or snapshot from cache CREATE PROCEDURE [dbo].[GetReportParametersForExecution] @Path nvarchar (425), @HistoryID DateTime = NULL, @AuthType int AS SELECT C.[ItemID], C.[Type], C.[ExecutionFlag], [SecData].[NtSecDescPrimary], C.[Parameter], C.[Intermediate], C.[SnapshotDataID], [History].[SnapshotDataID], L.[Intermediate], C.[LinkSourceID], C.[ExecutionTime] FROM [Catalog] AS C LEFT OUTER JOIN [SecData] ON C.[PolicyID] = [SecData].[PolicyID] AND [SecData].AuthType = @AuthType LEFT OUTER JOIN [History] ON ( C.[ItemID] = [History].[ReportID] AND [History].[SnapshotDate] = @HistoryID ) LEFT OUTER JOIN [Catalog] AS L WITH (INDEX(PK_Catalog)) ON C.[LinkSourceID] = L.[ItemID] WHERE C.[Path] = @Path GO GRANT EXECUTE ON [dbo].[GetReportParametersForExecution] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[MoveObject]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[MoveObject] GO CREATE PROCEDURE [dbo].[MoveObject] @OldPath nvarchar (425), @OldPrefix nvarchar (850), @NewName nvarchar (425), @NewPath nvarchar (425), @NewParentID uniqueidentifier, @RenameOnly as bit, @MaxPathLength as int AS DECLARE @LongPath nvarchar(425) SET @LongPath = (SELECT TOP 1 Path FROM Catalog WHERE LEN(Path)-LEN(@OldPath)+LEN(@NewPath) > @MaxPathLength AND Path LIKE @OldPrefix ESCAPE '*') IF @LongPath IS NOT NULL BEGIN SELECT @LongPath RETURN END IF @RenameOnly = 0 -- if this a full-blown move, not just a rename BEGIN -- adjust policies on the top item that gets moved DECLARE @OldInheritedPolicyID as uniqueidentifier SELECT @OldInheritedPolicyID = (SELECT PolicyID FROM Catalog with (XLOCK) WHERE Path = @OldPath AND PolicyRoot = 0) IF (@OldInheritedPolicyID IS NOT NULL) BEGIN -- this was not a policy root, change it to inherit from target folder DECLARE @NewPolicyID as uniqueidentifier SELECT @NewPolicyID = (SELECT PolicyID FROM Catalog with (XLOCK) WHERE ItemID = @NewParentID) -- update item and children that shared the old policy UPDATE Catalog SET PolicyID = @NewPolicyID WHERE Path = @OldPath UPDATE Catalog SET PolicyID = @NewPolicyID WHERE Path LIKE @OldPrefix ESCAPE '*' AND Catalog.PolicyID = @OldInheritedPolicyID END END -- Update item that gets moved (Path, Name, and ParentId) update Catalog set Name = @NewName, Path = @NewPath, ParentID = @NewParentID where Path = @OldPath -- Update all its children (Path only, Names and ParentIds stay the same) update Catalog set Path = STUFF(Path, 1, LEN(@OldPath), @NewPath ) where Path like @OldPrefix escape '*' GO GRANT EXECUTE ON [dbo].[MoveObject] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ObjectExists]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ObjectExists] GO CREATE PROCEDURE [dbo].[ObjectExists] @Path nvarchar (425), @AuthType int AS SELECT Type, ItemID, SnapshotLimit, NtSecDescPrimary, ExecutionFlag, Intermediate, [LinkSourceID] FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[ObjectExists] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetAllProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetAllProperties] GO CREATE PROCEDURE [dbo].[SetAllProperties] @Path nvarchar (425), @Property ntext, @Description ntext = NULL, @Hidden bit = NULL, @ModifiedBySid varbinary (85) = NULL, @ModifiedByName nvarchar(260), @AuthType int, @ModifiedDate DateTime AS DECLARE @ModifiedByID uniqueidentifier EXEC GetUserID @ModifiedBySid, @ModifiedByName, @AuthType, @ModifiedByID OUTPUT UPDATE Catalog SET Property = @Property, Description = @Description, Hidden = @Hidden, ModifiedByID = @ModifiedByID, ModifiedDate = @ModifiedDate WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[SetAllProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FlushReportFromCache]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FlushReportFromCache] GO CREATE PROCEDURE [dbo].[FlushReportFromCache] @Path as nvarchar(425) AS SET DEADLOCK_PRIORITY LOW -- VSTS #139360: SQL Deadlock in GetReportForexecution stored procedure -- Use temporary table to keep the same order of accessing the ExecutionCache -- and SnapshotData tables as GetReportForExecution does, that is first -- delete from the ExecutionCache, then update the SnapshotData CREATE TABLE #tempSnapshot (SnapshotDataID uniqueidentifier) INSERT INTO #tempSnapshot SELECT SN.SnapshotDataID FROM ReportServerTempDB.dbo.SnapshotData AS SN WITH (UPDLOCK) INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC WITH (UPDLOCK) ON SN.SnapshotDataID = EC.SnapshotDataID INNER JOIN Catalog AS C ON EC.ReportID = C.ItemID WHERE C.Path = @Path DELETE EC FROM ReportServerTempDB.dbo.ExecutionCache AS EC INNER JOIN #tempSnapshot ON #tempSnapshot.SnapshotDataID = EC.SnapshotDataID UPDATE SN SET SN.PermanentRefcount = SN.PermanentRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN #tempSnapshot ON #tempSnapshot.SnapshotDataID = SN.SnapshotDataID GO GRANT EXECUTE ON [dbo].[FlushReportFromCache] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetParameters] GO CREATE PROCEDURE [dbo].[SetParameters] @Path nvarchar (425), @Parameter ntext AS UPDATE Catalog SET [Parameter] = @Parameter WHERE Path = @Path EXEC FlushReportFromCache @Path GO GRANT EXECUTE ON [dbo].[SetParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetObjectContent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetObjectContent] GO CREATE PROCEDURE [dbo].[SetObjectContent] @Path nvarchar (425), @Type int, @Content image = NULL, @Intermediate uniqueidentifier = NULL, @Parameter ntext = NULL, @LinkSourceID uniqueidentifier = NULL, @MimeType nvarchar (260) = NULL AS DECLARE @OldIntermediate as uniqueidentifier SET @OldIntermediate = (SELECT Intermediate FROM Catalog WITH (XLOCK) WHERE Path = @Path) UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 WHERE SnapshotData.SnapshotDataID = @OldIntermediate UPDATE Catalog SET Type=@Type, Content = @Content, Intermediate = @Intermediate, [Parameter] = @Parameter, LinkSourceID = @LinkSourceID, MimeType = @MimeType WHERE Path = @Path UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount + 1, TransientRefcount = TransientRefcount - 1 WHERE SnapshotData.SnapshotDataID = @Intermediate EXEC FlushReportFromCache @Path GO GRANT EXECUTE ON [dbo].[SetObjectContent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetLastModified]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetLastModified] GO CREATE PROCEDURE [dbo].[SetLastModified] @Path nvarchar (425), @ModifiedBySid varbinary (85) = NULL, @ModifiedByName nvarchar(260), @AuthType int, @ModifiedDate DateTime AS DECLARE @ModifiedByID uniqueidentifier EXEC GetUserID @ModifiedBySid, @ModifiedByName, @AuthType, @ModifiedByID OUTPUT UPDATE Catalog SET ModifiedByID = @ModifiedByID, ModifiedDate = @ModifiedDate WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[SetLastModified] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetNameById]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetNameById] GO CREATE PROCEDURE [dbo].[GetNameById] @ItemID uniqueidentifier AS SELECT Path FROM Catalog WHERE ItemID = @ItemID GO GRANT EXECUTE ON [dbo].[GetNameById] TO RSExecRole GO -------------------------------------------------- ------------- Data source procedures to store user names and passwords if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddDataSource] GO CREATE PROCEDURE [dbo].[AddDataSource] @DSID [uniqueidentifier], @ItemID [uniqueidentifier] = NULL, -- null for future suport dynamic delivery @SubscriptionID [uniqueidentifier] = NULL, @Name [nvarchar] (260) = NULL, -- only for scoped data sources, MUST be NULL for standalone!!! @Extension [nvarchar] (260) = NULL, @LinkID [uniqueidentifier] = NULL, -- link id is trusted, if it is provided - we use it @LinkPath [nvarchar] (425) = NULL, -- if LinkId is not provided we try to look up LinkPath @CredentialRetrieval [int], @Prompt [ntext] = NULL, @ConnectionString [image] = NULL, @OriginalConnectionString [image] = NULL, @OriginalConnectStringExpressionBased [bit] = NULL, @UserName [image] = NULL, @Password [image] = NULL, @Flags [int], @AuthType [int], @Version [int] AS DECLARE @ActualLinkID uniqueidentifier SET @ActualLinkID = NULL IF (@LinkID is NULL) AND (@LinkPath is not NULL) BEGIN SELECT Type, ItemID, NtSecDescPrimary FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @LinkPath SET @ActualLinkID = (SELECT ItemID FROM Catalog WHERE Path = @LinkPath) END ELSE BEGIN SET @ActualLinkID = @LinkID END INSERT INTO DataSource ([DSID], [ItemID], [SubscriptionID], [Name], [Extension], [Link], [CredentialRetrieval], [Prompt], [ConnectionString], [OriginalConnectionString], [OriginalConnectStringExpressionBased], [UserName], [Password], [Flags], [Version]) VALUES (@DSID, @ItemID, @SubscriptionID, @Name, @Extension, @ActualLinkID, @CredentialRetrieval, @Prompt, @ConnectionString, @OriginalConnectionString, @OriginalConnectStringExpressionBased, @UserName, @Password, @Flags, @Version) GO GRANT EXECUTE ON [dbo].[AddDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDataSources]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDataSources] GO CREATE PROCEDURE [dbo].[GetDataSources] @ItemID [uniqueidentifier], @AuthType int AS SELECT -- select data sources and their links (if they exist) DS.[DSID], -- 0 DS.[ItemID], -- 1 DS.[Name], -- 2 DS.[Extension], -- 3 DS.[Link], -- 4 DS.[CredentialRetrieval], -- 5 DS.[Prompt], -- 6 DS.[ConnectionString], -- 7 DS.[OriginalConnectionString], -- 8 DS.[UserName], -- 9 DS.[Password], -- 10 DS.[Flags], -- 11 DSL.[DSID], -- 12 DSL.[ItemID], -- 13 DSL.[Name], -- 14 DSL.[Extension], -- 15 DSL.[Link], -- 16 DSL.[CredentialRetrieval], -- 17 DSL.[Prompt], -- 18 DSL.[ConnectionString], -- 19 DSL.[UserName], -- 20 DSL.[Password], -- 21 DSL.[Flags], -- 22 C.Path, -- 23 SD.NtSecDescPrimary, -- 24 DS.[OriginalConnectStringExpressionBased], -- 25 DS.[Version], -- 26 DSL.[Version], -- 27 (SELECT 1 WHERE EXISTS (SELECT * from [ModelItemPolicy] AS MIP WHERE C.[ItemID] = MIP.[CatalogItemID])) -- 28 FROM [DataSource] AS DS LEFT OUTER JOIN ([DataSource] AS DSL INNER JOIN [Catalog] AS C ON DSL.[ItemID] = C.[ItemID] LEFT OUTER JOIN [SecData] AS SD ON C.[PolicyID] = SD.[PolicyID] AND SD.AuthType = @AuthType) ON DS.[Link] = DSL.[ItemID] WHERE DS.[ItemID] = @ItemID or DS.[SubscriptionID] = @ItemID GO GRANT EXECUTE ON [dbo].[GetDataSources] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteDataSources]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteDataSources] GO CREATE PROCEDURE [dbo].[DeleteDataSources] @ItemID [uniqueidentifier] AS DELETE FROM [DataSource] WHERE [ItemID] = @ItemID or [SubscriptionID] = @ItemID GO GRANT EXECUTE ON [dbo].[DeleteDataSources] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ChangeStateOfDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ChangeStateOfDataSource] GO CREATE PROCEDURE [dbo].[ChangeStateOfDataSource] @ItemID [uniqueidentifier], @Enable bit AS IF @Enable != 0 BEGIN UPDATE [DataSource] SET [Flags] = [Flags] | 1 WHERE [ItemID] = @ItemID END ELSE BEGIN UPDATE [DataSource] SET [Flags] = [Flags] & 0x7FFFFFFE WHERE [ItemID] = @ItemID END GO GRANT EXECUTE ON [dbo].[ChangeStateOfDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindItemsByDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindItemsByDataSource] GO CREATE PROCEDURE [dbo].[FindItemsByDataSource] @ItemID uniqueidentifier, @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.UserName, SUSER_SNAME(MU.Sid), MU.UserName, C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType INNER JOIN DataSource AS DS ON C.ItemID = DS.ItemID WHERE DS.Link = @ItemID GO GRANT EXECUTE ON [dbo].[FindItemsByDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateRole] GO CREATE PROCEDURE [dbo].[CreateRole] @RoleID as uniqueidentifier, @RoleName as nvarchar(260), @Description as nvarchar(512) = null, @TaskMask as nvarchar(32), @RoleFlags as tinyint AS INSERT INTO Roles (RoleID, RoleName, Description, TaskMask, RoleFlags) VALUES (@RoleID, @RoleName, @Description, @TaskMask, @RoleFlags) GO GRANT EXECUTE ON [dbo].[CreateRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetRoles]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetRoles] GO CREATE PROCEDURE [dbo].[GetRoles] @RoleFlags as tinyint = NULL AS SELECT RoleName, Description, TaskMask FROM Roles WHERE (@RoleFlags is NULL) OR (RoleFlags = @RoleFlags) GO GRANT EXECUTE ON [dbo].[GetRoles] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteRole] GO -- Delete all policies associated with this role CREATE PROCEDURE [dbo].[DeleteRole] @RoleName nvarchar(260) AS SET NOCOUNT OFF -- if you call this, you must delete/reconstruct all policies associated with this role DELETE FROM Roles WHERE RoleName = @RoleName GO GRANT EXECUTE ON [dbo].[DeleteRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadRoleProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadRoleProperties] GO CREATE PROCEDURE [dbo].[ReadRoleProperties] @RoleName as nvarchar(260) AS SELECT Description, TaskMask, RoleFlags FROM Roles WHERE RoleName = @RoleName GO GRANT EXECUTE ON [dbo].[ReadRoleProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetRoleProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetRoleProperties] GO CREATE PROCEDURE [dbo].[SetRoleProperties] @RoleName as nvarchar(260), @Description as nvarchar(512) = NULL, @TaskMask as nvarchar(32), @RoleFlags as tinyint AS SET NOCOUNT OFF DECLARE @ExistingRoleFlags as tinyint SET @ExistingRoleFlags = (SELECT RoleFlags FROM Roles WHERE RoleName = @RoleName) IF @ExistingRoleFlags IS NULL BEGIN RETURN END IF @ExistingRoleFlags <> @RoleFlags BEGIN RAISERROR ('Bad role flags', 16, 1) END UPDATE Roles SET Description = @Description, TaskMask = @TaskMask, RoleFlags = @RoleFlags WHERE RoleName = @RoleName GO GRANT EXECUTE ON [dbo].[SetRoleProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPoliciesForRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPoliciesForRole] GO CREATE PROCEDURE [dbo].[GetPoliciesForRole] @RoleName as nvarchar(260), @AuthType as int AS SELECT Policies.PolicyID, SecData.XmlDescription, Policies.PolicyFlag, Catalog.Type, Catalog.Path, ModelItemPolicy.CatalogItemID, ModelItemPolicy.ModelItemID, RelatedRoles.RoleID, RelatedRoles.RoleName, RelatedRoles.TaskMask, RelatedRoles.RoleFlags FROM Roles INNER JOIN PolicyUserRole ON Roles.RoleID = PolicyUserRole.RoleID INNER JOIN Policies ON PolicyUserRole.PolicyID = Policies.PolicyID INNER JOIN PolicyUserRole AS RelatedPolicyUserRole ON Policies.PolicyID = RelatedPolicyUserRole.PolicyID INNER JOIN Roles AS RelatedRoles ON RelatedPolicyUserRole.RoleID = RelatedRoles.RoleID LEFT OUTER JOIN SecData ON Policies.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog ON Policies.PolicyID = Catalog.PolicyID AND Catalog.PolicyRoot = 1 LEFT OUTER JOIN ModelItemPolicy ON Policies.PolicyID = ModelItemPolicy.PolicyID WHERE Roles.RoleName = @RoleName ORDER BY Policies.PolicyID GO GRANT EXECUTE ON [dbo].[GetPoliciesForRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdatePolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdatePolicy] GO CREATE PROCEDURE [dbo].[UpdatePolicy] @PolicyID as uniqueidentifier, @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @AuthType int AS UPDATE SecData SET NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND SecData.AuthType = @AuthType GO GRANT EXECUTE ON [dbo].[UpdatePolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetPolicy] GO -- this assumes the item exists in the catalog CREATE PROCEDURE [dbo].[SetPolicy] @ItemName as nvarchar(425), @ItemNameLike as nvarchar(850), @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @XmlPolicy as ntext, @AuthType int, @PolicyID uniqueidentifier OUTPUT AS SELECT @PolicyID = (SELECT PolicyID FROM Catalog WHERE Path = @ItemName AND PolicyRoot = 1) IF (@PolicyID IS NULL) BEGIN -- this is not a policy root SET @PolicyID = newid() INSERT INTO Policies (PolicyID, PolicyFlag) VALUES (@PolicyID, 0) INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) DECLARE @OldPolicyID as uniqueidentifier SELECT @OldPolicyID = (SELECT PolicyID FROM Catalog WHERE Path = @ItemName) -- update item and children that shared the old policy UPDATE Catalog SET PolicyID = @PolicyID, PolicyRoot = 1 WHERE Path = @ItemName UPDATE Catalog SET PolicyID = @PolicyID WHERE Path LIKE @ItemNameLike ESCAPE '*' AND Catalog.PolicyID = @OldPolicyID END ELSE BEGIN UPDATE Policies SET PolicyFlag = 0 WHERE Policies.PolicyID = @PolicyID DECLARE @SecDataID as uniqueidentifier SELECT @SecDataID = (SELECT SecDataID FROM SecData WHERE PolicyID = @PolicyID and AuthType = @AuthType) IF (@SecDataID IS NULL) BEGIN -- insert new sec desc's INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription ,NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN -- update existing sec desc's UPDATE SecData SET XmlDescription = @XmlPolicy, NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND AuthType = @AuthType END END DELETE FROM PolicyUserRole WHERE PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[SetPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSystemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSystemPolicy] GO -- update the system policy CREATE PROCEDURE [dbo].[SetSystemPolicy] @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @XmlPolicy as ntext, @AuthType as int, @PolicyID uniqueidentifier OUTPUT AS SELECT @PolicyID = (SELECT PolicyID FROM Policies WHERE PolicyFlag = 1) IF (@PolicyID IS NULL) BEGIN SET @PolicyID = newid() INSERT INTO Policies (PolicyID, PolicyFlag) VALUES (@PolicyID, 1) INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN DECLARE @SecDataID as uniqueidentifier SELECT @SecDataID = (SELECT SecDataID FROM SecData WHERE PolicyID = @PolicyID and AuthType = @AuthType) IF (@SecDataID IS NULL) BEGIN -- insert new sec desc's INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN -- update existing sec desc's UPDATE SecData SET XmlDescription = @XmlPolicy, NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND AuthType = @AuthType END END DELETE FROM PolicyUserRole WHERE PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[SetSystemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetModelItemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetModelItemPolicy] GO -- update the system policy CREATE PROCEDURE [dbo].[SetModelItemPolicy] @CatalogItemID as uniqueidentifier, @ModelItemID as nvarchar(425), @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @XmlPolicy as ntext, @AuthType as int, @PolicyID uniqueidentifier OUTPUT AS SELECT @PolicyID = (SELECT PolicyID FROM ModelItemPolicy WHERE CatalogItemID = @CatalogItemID AND ModelItemID = @ModelItemID ) IF (@PolicyID IS NULL) BEGIN SET @PolicyID = newid() INSERT INTO Policies (PolicyID, PolicyFlag) VALUES (@PolicyID, 2) INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) INSERT INTO ModelItemPolicy (ID, CatalogItemID, ModelItemID, PolicyID) VALUES (newid(), @CatalogItemID, @ModelItemID, @PolicyID) END ELSE BEGIN DECLARE @SecDataID as uniqueidentifier SELECT @SecDataID = (SELECT SecDataID FROM SecData WHERE PolicyID = @PolicyID and AuthType = @AuthType) IF (@SecDataID IS NULL) BEGIN -- insert new sec desc's INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN -- update existing sec desc's UPDATE SecData SET XmlDescription = @XmlPolicy, NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND AuthType = @AuthType END END DELETE FROM PolicyUserRole WHERE PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[SetModelItemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdatePolicyPrincipal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdatePolicyPrincipal] GO CREATE PROCEDURE [dbo].[UpdatePolicyPrincipal] @PolicyID uniqueidentifier, @PrincipalSid varbinary(85) = NULL, @PrincipalName nvarchar(260), @PrincipalAuthType int, @RoleName nvarchar(260), @PrincipalID uniqueidentifier OUTPUT, @RoleID uniqueidentifier OUTPUT AS EXEC GetPrincipalID @PrincipalSid , @PrincipalName, @PrincipalAuthType, @PrincipalID OUTPUT SELECT @RoleID = (SELECT RoleID FROM Roles WHERE RoleName = @RoleName) INSERT INTO PolicyUserRole (ID, RoleID, UserID, PolicyID) VALUES (newid(), @RoleID, @PrincipalID, @PolicyID) GO GRANT EXECUTE ON [dbo].[UpdatePolicyPrincipal] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdatePolicyRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdatePolicyRole] GO CREATE PROCEDURE [dbo].[UpdatePolicyRole] @PolicyID uniqueidentifier, @PrincipalID uniqueidentifier, @RoleName nvarchar(260), @RoleID uniqueidentifier OUTPUT AS SELECT @RoleID = (SELECT RoleID FROM Roles WHERE RoleName = @RoleName) INSERT INTO PolicyUserRole (ID, RoleID, UserID, PolicyID) VALUES (newid(), @RoleID, @PrincipalID, @PolicyID) GO GRANT EXECUTE ON [dbo].[UpdatePolicyRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPolicy] GO CREATE PROCEDURE [dbo].[GetPolicy] @ItemName as nvarchar(425), @AuthType int AS SELECT SecData.XmlDescription, Catalog.PolicyRoot , SecData.NtSecDescPrimary, Catalog.Type FROM Catalog INNER JOIN Policies ON Catalog.PolicyID = Policies.PolicyID LEFT OUTER JOIN SecData ON Policies.PolicyID = SecData.PolicyID AND AuthType = @AuthType WHERE Catalog.Path = @ItemName AND PolicyFlag = 0 GO GRANT EXECUTE ON [dbo].[GetPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSystemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSystemPolicy] GO CREATE PROCEDURE [dbo].[GetSystemPolicy] @AuthType int AS SELECT SecData.NtSecDescPrimary, SecData.XmlDescription FROM Policies LEFT OUTER JOIN SecData ON Policies.PolicyID = SecData.PolicyID AND AuthType = @AuthType WHERE PolicyFlag = 1 GO GRANT EXECUTE ON [dbo].[GetSystemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeletePolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeletePolicy] GO CREATE PROCEDURE [dbo].[DeletePolicy] @ItemName as nvarchar(425) AS SET NOCOUNT OFF DECLARE @OldPolicyID uniqueidentifier SELECT @OldPolicyID = (SELECT PolicyID FROM Catalog WHERE Catalog.Path = @ItemName) UPDATE Catalog SET PolicyID = (SELECT Parent.PolicyID FROM Catalog Parent, Catalog WHERE Parent.ItemID = Catalog.ParentID AND Catalog.Path = @ItemName), PolicyRoot = 0 WHERE Catalog.PolicyID = @OldPolicyID DELETE Policies FROM Policies WHERE Policies.PolicyID = @OldPolicyID GO GRANT EXECUTE ON [dbo].[DeletePolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateSession]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateSession] GO -- Writes or updates session record CREATE PROCEDURE [dbo].[CreateSession] @SessionID as varchar(32), @CompiledDefinition as uniqueidentifier = NULL, @SnapshotDataID as uniqueidentifier = NULL, @IsPermanentSnapshot as bit = NULL, @ReportPath as nvarchar(440) = NULL, @Timeout as int, @AutoRefreshSeconds as int = NULL, @DataSourceInfo as image = NULL, @OwnerName as nvarchar (260), @OwnerSid as varbinary (85) = NULL, @AuthType as int, @EffectiveParams as ntext = NULL, @HistoryDate as datetime = NULL, @PageHeight as float = NULL, @PageWidth as float = NULL, @TopMargin as float = NULL, @BottomMargin as float = NULL, @LeftMargin as float = NULL, @RightMargin as float = NULL, @AwaitingFirstExecution as bit = NULL AS UPDATE PS SET PS.RefCount = 1 FROM ReportServerTempDB.dbo.PersistedStream as PS WHERE PS.SessionID = @SessionID UPDATE SN SET TransientRefcount = TransientRefcount + 1 FROM SnapshotData AS SN WHERE SN.SnapshotDataID = @SnapshotDataID UPDATE SN SET TransientRefcount = TransientRefcount + 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN WHERE SN.SnapshotDataID = @SnapshotDataID DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT DECLARE @now datetime SET @now = GETDATE() INSERT INTO ReportServerTempDB.dbo.SessionData ( SessionID, CompiledDefinition, SnapshotDataID, IsPermanentSnapshot, ReportPath, Timeout, AutoRefreshSeconds, Expiration, DataSourceInfo, OwnerID, EffectiveParams, CreationTime, HistoryDate, PageHeight, PageWidth, TopMargin, BottomMargin, LeftMargin, RightMargin, AwaitingFirstExecution ) VALUES ( @SessionID, @CompiledDefinition, @SnapshotDataID, @IsPermanentSnapshot, @ReportPath, @Timeout, @AutoRefreshSeconds, DATEADD(s, @Timeout, @now), @DataSourceInfo, @OwnerID, @EffectiveParams, @now, @HistoryDate, @PageHeight, @PageWidth, @TopMargin, @BottomMargin, @LeftMargin, @RightMargin, @AwaitingFirstExecution ) GO GRANT EXECUTE ON [dbo].[CreateSession] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteModelItemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteModelItemPolicy] GO CREATE PROCEDURE [dbo].[DeleteModelItemPolicy] @CatalogItemID as uniqueidentifier, @ModelItemID as nvarchar(425) AS SET NOCOUNT OFF DECLARE @PolicyID uniqueidentifier SELECT @PolicyID = (SELECT PolicyID FROM ModelItemPolicy WHERE CatalogItemID = @CatalogItemID AND ModelItemID = @ModelItemID) DELETE Policies FROM Policies WHERE Policies.PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[DeleteModelItemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteAllModelItemPolicies]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteAllModelItemPolicies] GO CREATE PROCEDURE [dbo].[DeleteAllModelItemPolicies] @Path as nvarchar(450) AS DELETE Policies FROM Policies AS P INNER JOIN ModelItemPolicy AS MIP ON P.PolicyID = MIP.PolicyID INNER JOIN Catalog AS C ON MIP.CatalogItemID = C.ItemID WHERE C.[Path] = @Path GO GRANT EXECUTE ON [dbo].[DeleteAllModelItemPolicies] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelItemInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelItemInfo] GO CREATE PROCEDURE [dbo].[GetModelItemInfo] @Path nvarchar (425), @UseUpdateLock bit AS IF(@UseUpdateLock = 0) BEGIN SELECT C.[Intermediate] FROM [Catalog] AS C WHERE C.[Path] = @Path END ELSE BEGIN -- acquire update lock, this means that the operation is being performed in a -- different transaction context which will be committed before trying to -- perform the actual load, to prevent deadlock in the case where we have to -- republish, this new transaction will acquire and hold upgrade locks SELECT C.[Intermediate] FROM [Catalog] AS C WITH(UPDLOCK ROWLOCK) WHERE C.[Path] = @Path END SELECT MIP.[ModelItemID], SD.[NtSecDescPrimary], SD.[XmlDescription] FROM [Catalog] AS C INNER JOIN [ModelItemPolicy] AS MIP ON C.[ItemID] = MIP.[CatalogItemID] LEFT OUTER JOIN [SecData] AS SD ON MIP.[PolicyID] = SD.[PolicyID] WHERE C.[Path] = @Path GO GRANT EXECUTE ON [dbo].[GetModelItemInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelDefinition]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelDefinition] GO CREATE PROCEDURE [dbo].[GetModelDefinition] @CatalogItemID as uniqueidentifier AS SELECT C.[Content] FROM [Catalog] AS C WHERE C.[ItemID] = @CatalogItemID GO GRANT EXECUTE ON [dbo].[GetModelDefinition] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddModelPerspective]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddModelPerspective] GO CREATE PROCEDURE [dbo].[AddModelPerspective] @ModelID as uniqueidentifier, @PerspectiveID as ntext, @PerspectiveName as ntext = null, @PerspectiveDescription as ntext = null AS INSERT INTO [ModelPerspective] ([ID], [ModelID], [PerspectiveID], [PerspectiveName], [PerspectiveDescription]) VALUES (newid(), @ModelID, @PerspectiveID, @PerspectiveName, @PerspectiveDescription) GO GRANT EXECUTE ON [dbo].[AddModelPerspective] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteModelPerspectives]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteModelPerspectives] GO CREATE PROCEDURE [dbo].[DeleteModelPerspectives] @ModelID as uniqueidentifier AS DELETE FROM [ModelPerspective] WHERE [ModelID] = @ModelID GO GRANT EXECUTE ON [dbo].[DeleteModelPerspectives] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelsAndPerspectives]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelsAndPerspectives] GO CREATE PROCEDURE [dbo].[GetModelsAndPerspectives] @AuthType int, @SitePathPrefix nvarchar(520) = '%' AS SELECT C.[PolicyID], SD.[NtSecDescPrimary], C.[ItemID], C.[Path], C.[Description], P.[PerspectiveID], P.[PerspectiveName], P.[PerspectiveDescription] FROM [Catalog] as C LEFT OUTER JOIN [ModelPerspective] as P ON C.[ItemID] = P.[ModelID] LEFT OUTER JOIN [SecData] AS SD ON C.[PolicyID] = SD.[PolicyID] AND SD.[AuthType] = @AuthType WHERE C.Path like @SitePathPrefix AND C.[Type] = 6 -- Model ORDER BY C.[Path] GO GRANT EXECUTE ON [dbo].[GetModelsAndPerspectives] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelPerspectives]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelPerspectives] GO CREATE PROCEDURE [dbo].[GetModelPerspectives] @Path nvarchar (425), @AuthType int AS SELECT C.[Type], SD.[NtSecDescPrimary], C.[Description] FROM [Catalog] as C LEFT OUTER JOIN [SecData] AS SD ON C.[PolicyID] = SD.[PolicyID] AND SD.[AuthType] = @AuthType WHERE [Path] = @Path SELECT P.[PerspectiveID], P.[PerspectiveName], P.[PerspectiveDescription] FROM [Catalog] as C INNER JOIN [ModelPerspective] as P ON C.[ItemID] = P.[ModelID] WHERE [Path] = @Path GO GRANT EXECUTE ON [dbo].[GetModelPerspectives] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DereferenceSessionSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DereferenceSessionSnapshot] GO CREATE PROCEDURE [dbo].[DereferenceSessionSnapshot] @SessionID as varchar(32), @OwnerID as uniqueidentifier AS UPDATE SN SET TransientRefcount = TransientRefcount - 1 FROM SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.SessionData AS SE ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID UPDATE SN SET TransientRefcount = TransientRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.SessionData AS SE ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[DereferenceSessionSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSessionData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSessionData] GO -- Writes or updates session record CREATE PROCEDURE [dbo].[SetSessionData] @SessionID as varchar(32), @ReportPath as nvarchar(440), @HistoryDate as datetime = NULL, @Timeout as int, @AutoRefreshSeconds as int = NULL, @EffectiveParams ntext = NULL, @OwnerSid as varbinary (85) = NULL, @OwnerName as nvarchar (260), @AuthType as int, @ShowHideInfo as image = NULL, @DataSourceInfo as image = NULL, @SnapshotDataID as uniqueidentifier = NULL, @IsPermanentSnapshot as bit = NULL, @SnapshotTimeoutSeconds as int = NULL, @HasInteractivity as bit, @SnapshotExpirationDate as datetime = NULL, @AwaitingFirstExecution as bit = NULL AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT DECLARE @now datetime SET @now = GETDATE() -- is there a session for the same report ? DECLARE @OldSnapshotDataID uniqueidentifier DECLARE @OldIsPermanentSnapshot bit DECLARE @OldSessionID varchar(32) SELECT @OldSessionID = SessionID, @OldSnapshotDataID = SnapshotDataID, @OldIsPermanentSnapshot = IsPermanentSnapshot FROM ReportServerTempDB.dbo.SessionData WITH (XLOCK) WHERE SessionID = @SessionID IF @OldSessionID IS NOT NULL BEGIN -- Yes, update it IF @OldSnapshotDataID != @SnapshotDataID or @SnapshotDataID is NULL BEGIN EXEC DereferenceSessionSnapshot @SessionID, @OwnerID END UPDATE ReportServerTempDB.dbo.SessionData SET SnapshotDataID = @SnapshotDataID, IsPermanentSnapshot = @IsPermanentSnapshot, Timeout = @Timeout, AutoRefreshSeconds = @AutoRefreshSeconds, SnapshotExpirationDate = @SnapshotExpirationDate, -- we want database session to expire later than in-memory session Expiration = DATEADD(s, @Timeout+10, @now), ShowHideInfo = @ShowHideInfo, DataSourceInfo = @DataSourceInfo, AwaitingFirstExecution = @AwaitingFirstExecution -- EffectiveParams = @EffectiveParams, -- no need to update user params as they are always same -- ReportPath = @ReportPath -- OwnerID = @OwnerID WHERE SessionID = @SessionID -- update expiration date on a snapshot that we reference IF @IsPermanentSnapshot != 0 BEGIN UPDATE SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutSeconds, @now) WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutSeconds, @now) WHERE SnapshotDataID = @SnapshotDataID END END ELSE BEGIN -- no, insert it UPDATE PS SET PS.RefCount = 1 FROM ReportServerTempDB.dbo.PersistedStream as PS WHERE PS.SessionID = @SessionID INSERT INTO ReportServerTempDB.dbo.SessionData (SessionID, SnapshotDataID, IsPermanentSnapshot, ReportPath, EffectiveParams, Timeout, AutoRefreshSeconds, Expiration, ShowHideInfo, DataSourceInfo, OwnerID, CreationTime, HasInteractivity, SnapshotExpirationDate, HistoryDate, AwaitingFirstExecution) VALUES (@SessionID, @SnapshotDataID, @IsPermanentSnapshot, @ReportPath, @EffectiveParams, @Timeout, @AutoRefreshSeconds, DATEADD(s, @Timeout, @now), @ShowHideInfo, @DataSourceInfo, @OwnerID, @now, @HasInteractivity, @SnapshotExpirationDate, @HistoryDate, @AwaitingFirstExecution) END GO GRANT EXECUTE ON [dbo].[SetSessionData] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteLockSession]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteLockSession] GO CREATE PROCEDURE [dbo].[WriteLockSession] @SessionID as varchar(32) AS INSERT INTO ReportServerTempDB.dbo.SessionLock WITH (ROWLOCK) (SessionID) VALUES (@SessionID) GO GRANT EXECUTE ON [dbo].[WriteLockSession] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CheckSessionLock]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CheckSessionLock] GO CREATE PROCEDURE [dbo].[CheckSessionLock] @SessionID as varchar(32) AS DECLARE @Selected nvarchar(32) SELECT @Selected=SessionID FROM ReportServerTempDB.dbo.SessionLock WITH (ROWLOCK) WHERE SessionID = @SessionID GO GRANT EXECUTE ON [dbo].[CheckSessionLock] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadLockSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadLockSnapshot] GO CREATE PROCEDURE [dbo].[ReadLockSnapshot] @SnapshotDataID as uniqueidentifier AS SELECT SnapshotDataID FROM SnapshotData WITH (REPEATABLEREAD, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID GO GRANT EXECUTE ON [dbo].[ReadLockSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSessionData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSessionData] GO -- Get record from session data, update session and snapshot CREATE PROCEDURE [dbo].[GetSessionData] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @SnapshotTimeoutMinutes as int AS DECLARE @now as datetime SET @now = GETDATE() DECLARE @DBSessionID varchar(32) DECLARE @SnapshotDataID uniqueidentifier DECLARE @IsPermanentSnapshot bit EXEC CheckSessionLock @SessionID = @SessionID DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT SELECT @DBSessionID = SE.SessionID, @SnapshotDataID = SE.SnapshotDataID, @IsPermanentSnapshot = SE.IsPermanentSnapshot FROM ReportServerTempDB.dbo.SessionData AS SE WITH (XLOCK) WHERE SE.OwnerID = @OwnerID AND SE.SessionID = @SessionID AND SE.Expiration > @now -- We need this update to keep session around while we process it. -- TODO: This assumes that it will be processed within the session timeout. UPDATE SE SET Expiration = DATEADD(s, Timeout, @now) FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @DBSessionID -- Update snapshot expiration to prevent early deletion -- If session uses snapshot, it is already refcounted. However, if session lasts for too long, -- snapshot may expire. Therefore, every time we touch snapshot we should change expiration. IF (@DBSessionID IS NOT NULL) BEGIN -- We return something only if session is present IF @IsPermanentSnapshot != 0 BEGIN -- If session has snapshot and it is permanent SELECT SN.SnapshotDataID, SE.ShowHideInfo, SE.DataSourceInfo, SN.Description, SE.EffectiveParams, SN.CreatedDate, SE.IsPermanentSnapshot, SE.CreationTime, SE.HasInteractivity, SE.Timeout, SE.SnapshotExpirationDate, SE.ReportPath, SE.HistoryDate, SE.CompiledDefinition, SN.PageCount, SN.HasDocMap, SE.Expiration, SN.EffectiveParams, SE.PageHeight, SE.PageWidth, SE.TopMargin, SE.BottomMargin, SE.LeftMargin, SE.RightMargin, SE.AutoRefreshSeconds, SE.AwaitingFirstExecution, SN.[DependsOnUser], SN.PaginationMode, SN.ProcessingFlags, NULL, -- No compiled definition in tempdb to get flags from CONVERT(BIT, 0) AS [FoundInCache] -- permanent snapshot is never from Cache FROM ReportServerTempDB.dbo.SessionData AS SE INNER JOIN SnapshotData AS SN ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @DBSessionID UPDATE SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutMinutes, @now) WHERE SnapshotDataID = @SnapshotDataID END ELSE IF @IsPermanentSnapshot = 0 BEGIN -- If session has snapshot and it is temporary SELECT SN.SnapshotDataID, SE.ShowHideInfo, SE.DataSourceInfo, SN.Description, SE.EffectiveParams, SN.CreatedDate, SE.IsPermanentSnapshot, SE.CreationTime, SE.HasInteractivity, SE.Timeout, SE.SnapshotExpirationDate, SE.ReportPath, SE.HistoryDate, SE.CompiledDefinition, SN.PageCount, SN.HasDocMap, SE.Expiration, SN.EffectiveParams, SE.PageHeight, SE.PageWidth, SE.TopMargin, SE.BottomMargin, SE.LeftMargin, SE.RightMargin, SE.AutoRefreshSeconds, SE.AwaitingFirstExecution, SN.[DependsOnUser], SN.PaginationMode, SN.ProcessingFlags, COMP.ProcessingFlags, -- If we are AwaitingFirstExecution, then we haven't executed a -- report and therefore have not been bound to a cached snapshot -- because that binding only happens at report execution time. CASE SE.AwaitingFirstExecution WHEN 1 THEN CONVERT(BIT, 0) ELSE SN.IsCached END FROM ReportServerTempDB.dbo.SessionData AS SE INNER JOIN ReportServerTempDB.dbo.SnapshotData AS SN ON SN.SnapshotDataID = SE.SnapshotDataID LEFT OUTER JOIN ReportServerTempDB.dbo.SnapshotData AS COMP ON SE.CompiledDefinition = COMP.SnapshotDataID WHERE SE.SessionID = @DBSessionID UPDATE ReportServerTempDB.dbo.SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutMinutes, @now) WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN -- If session doesn't have snapshot SELECT null, SE.ShowHideInfo, SE.DataSourceInfo, null, SE.EffectiveParams, null, SE.IsPermanentSnapshot, SE.CreationTime, SE.HasInteractivity, SE.Timeout, SE.SnapshotExpirationDate, SE.ReportPath, SE.HistoryDate, SE.CompiledDefinition, null, null, SE.Expiration, null, SE.PageHeight, SE.PageWidth, SE.TopMargin, SE.BottomMargin, SE.LeftMargin, SE.RightMargin, SE.AutoRefreshSeconds, SE.AwaitingFirstExecution, null, null, null, COMP.ProcessingFlags, CONVERT(BIT, 0) AS [FoundInCache] -- no snapshot, so it can't be from the cache FROM ReportServerTempDB.dbo.SessionData AS SE LEFT OUTER JOIN ReportServerTempDB.dbo.SnapshotData AS COMP ON (SE.CompiledDefinition = COMP.SnapshotDataID) WHERE SE.SessionID = @DBSessionID END END GO GRANT EXECUTE ON [dbo].[GetSessionData] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapshotFromHistory]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapshotFromHistory] GO CREATE PROCEDURE [dbo].[GetSnapshotFromHistory] @Path nvarchar (425), @SnapshotDate datetime, @AuthType int AS SELECT Catalog.ItemID, Catalog.Type, SnapshotData.SnapshotDataID, SnapshotData.DependsOnUser, SnapshotData.Description, SecData.NtSecDescPrimary, Catalog.[Property], SnapshotData.ProcessingFlags FROM SnapshotData INNER JOIN History ON History.SnapshotDataID = SnapshotData.SnapshotDataID INNER JOIN Catalog ON History.ReportID = Catalog.ItemID LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Catalog.Path = @Path AND History.SnapshotDate = @SnapshotDate GO GRANT EXECUTE ON [dbo].[GetSnapshotFromHistory] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredSessions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredSessions] GO CREATE PROCEDURE [dbo].[CleanExpiredSessions] @SessionsCleaned int OUTPUT AS SET DEADLOCK_PRIORITY LOW DECLARE @now as datetime SET @now = GETDATE() CREATE TABLE #tempSession (SessionID varchar(32) COLLATE Latin1_General_CI_AS_KS_WS, SnapshotDataID uniqueidentifier, CompiledDefinition uniqueidentifier) INSERT INTO #tempSession SELECT TOP 20 SessionID, SnapshotDataID, CompiledDefinition FROM ReportServerTempDB.dbo.SessionData WITH (XLOCK) WHERE Expiration < @now SET @SessionsCleaned = @@ROWCOUNT IF @SessionsCleaned = 0 RETURN -- Mark persisted streams for this session to be deleted UPDATE PS SET RefCount = 0, ExpirationDate = GETDATE() FROM ReportServerTempDB.dbo.PersistedStream AS PS INNER JOIN #tempSession on PS.SessionID = #tempsession.SessionID DELETE SE FROM ReportServerTempDB.dbo.SessionData AS SE INNER JOIN #tempSession on SE.SessionID = #tempsession.SessionID UPDATE SN SET TransientRefcount = TransientRefcount-1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN #tempSession AS SE ON SN.SnapshotDataID = SE.CompiledDefinition UPDATE SN SET TransientRefcount = TransientRefcount- (SELECT COUNT(*) FROM #tempSession AS SE1 WHERE SE1.SnapshotDataID = SN.SnapshotDataID) FROM SnapshotData AS SN INNER JOIN #tempSession AS SE ON SN.SnapshotDataID = SE.SnapshotDataID UPDATE SN SET TransientRefcount = TransientRefcount- (SELECT COUNT(*) FROM #tempSession AS SE1 WHERE SE1.SnapshotDataID = SN.SnapshotDataID) FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN #tempSession AS SE ON SN.SnapshotDataID = SE.SnapshotDataID GO GRANT EXECUTE ON [dbo].[CleanExpiredSessions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredCache]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredCache] GO CREATE PROCEDURE [dbo].[CleanExpiredCache] AS SET NOCOUNT OFF DECLARE @now as datetime SET @now = DATEADD(minute, -1, GETDATE()) UPDATE SN SET PermanentRefcount = PermanentRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON SN.SnapshotDataID = EC.SnapshotDataID WHERE EC.AbsoluteExpiration < @now DELETE EC FROM ReportServerTempDB.dbo.ExecutionCache AS EC WHERE EC.AbsoluteExpiration < @now GO GRANT EXECUTE ON [dbo].[CleanExpiredCache] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSessionCredentials]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSessionCredentials] GO CREATE PROCEDURE [dbo].[SetSessionCredentials] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @DataSourceInfo as image = NULL, @Expiration as datetime, @EffectiveParams as ntext = NULL AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT EXEC DereferenceSessionSnapshot @SessionID, @OwnerID UPDATE SE SET SE.DataSourceInfo = @DataSourceInfo, SE.SnapshotDataID = null, SE.IsPermanentSnapshot = null, SE.SnapshotExpirationDate = null, SE.ShowHideInfo = null, SE.HasInteractivity = null, SE.AutoRefreshSeconds = null, SE.Expiration = @Expiration, SE.EffectiveParams = @EffectiveParams, SE.AwaitingFirstExecution = 1 FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[SetSessionCredentials] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSessionParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSessionParameters] GO CREATE PROCEDURE [dbo].[SetSessionParameters] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @EffectiveParams as ntext = NULL AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT UPDATE SE SET SE.EffectiveParams = @EffectiveParams, SE.AwaitingFirstExecution = 1 FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[SetSessionParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ClearSessionSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ClearSessionSnapshot] GO CREATE PROCEDURE [dbo].[ClearSessionSnapshot] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @Expiration as datetime AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT EXEC DereferenceSessionSnapshot @SessionID, @OwnerID UPDATE SE SET SE.SnapshotDataID = null, SE.IsPermanentSnapshot = null, SE.SnapshotExpirationDate = null, SE.ShowHideInfo = null, SE.HasInteractivity = null, SE.AutoRefreshSeconds = null, SE.Expiration = @Expiration FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[ClearSessionSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RemoveReportFromSession]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RemoveReportFromSession] GO CREATE PROCEDURE [dbo].[RemoveReportFromSession] @SessionID as varchar(32), @ReportPath as nvarchar(440), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT EXEC DereferenceSessionSnapshot @SessionID, @OwnerID DELETE SE FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.ReportPath = @ReportPath AND SE.OwnerID = @OwnerID -- Delete any persisted streams associated with this session UPDATE PS SET PS.RefCount = 0, PS.ExpirationDate = GETDATE() FROM ReportServerTempDB.dbo.PersistedStream AS PS WHERE PS.SessionID = @SessionID GO GRANT EXECUTE ON [dbo].[RemoveReportFromSession] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanBrokenSnapshots]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanBrokenSnapshots] GO CREATE PROCEDURE [dbo].[CleanBrokenSnapshots] @Machine nvarchar(512), @SnapshotsCleaned int OUTPUT, @ChunksCleaned int OUTPUT, @TempSnapshotID uniqueidentifier OUTPUT AS SET DEADLOCK_PRIORITY LOW DECLARE @now AS datetime SELECT @now = GETDATE() CREATE TABLE #tempSnapshot (SnapshotDataID uniqueidentifier) INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM SnapshotData WITH (NOLOCK) where SnapshotData.PermanentRefcount <= 0 AND ExpirationDate < @now SET @SnapshotsCleaned = @@ROWCOUNT DELETE ChunkData FROM ChunkData INNER JOIN #tempSnapshot ON ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @@ROWCOUNT DELETE SnapshotData FROM SnapshotData INNER JOIN #tempSnapshot ON SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID TRUNCATE TABLE #tempSnapshot INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM ReportServerTempDB.dbo.SnapshotData WITH (NOLOCK) where ReportServerTempDB.dbo.SnapshotData.PermanentRefcount <= 0 AND ReportServerTempDB.dbo.SnapshotData.ExpirationDate < @now AND ReportServerTempDB.dbo.SnapshotData.Machine = @Machine SET @SnapshotsCleaned = @SnapshotsCleaned + @@ROWCOUNT SELECT @TempSnapshotID = (SELECT SnapshotDataID FROM #tempSnapshot) DELETE ReportServerTempDB.dbo.ChunkData FROM ReportServerTempDB.dbo.ChunkData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @ChunksCleaned + @@ROWCOUNT DELETE ReportServerTempDB.dbo.SnapshotData FROM ReportServerTempDB.dbo.SnapshotData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID GO GRANT EXECUTE ON [dbo].[CleanBrokenSnapshots] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanOrphanedSnapshots]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanOrphanedSnapshots] GO CREATE PROCEDURE [dbo].[CleanOrphanedSnapshots] @Machine nvarchar(512), @SnapshotsCleaned int OUTPUT, @ChunksCleaned int OUTPUT, @TempSnapshotID uniqueidentifier OUTPUT AS SET DEADLOCK_PRIORITY LOW CREATE TABLE #tempSnapshot (SnapshotDataID uniqueidentifier) INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM SnapshotData WITH (NOLOCK) where SnapshotData.PermanentRefcount = 0 AND SnapshotData.TransientRefcount = 0 SET @SnapshotsCleaned = @@ROWCOUNT DELETE ChunkData FROM ChunkData INNER JOIN #tempSnapshot ON ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @@ROWCOUNT DELETE SnapshotData FROM SnapshotData INNER JOIN #tempSnapshot ON SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID TRUNCATE TABLE #tempSnapshot INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM ReportServerTempDB.dbo.SnapshotData WITH (NOLOCK) where ReportServerTempDB.dbo.SnapshotData.PermanentRefcount = 0 AND ReportServerTempDB.dbo.SnapshotData.TransientRefcount = 0 AND ReportServerTempDB.dbo.SnapshotData.Machine = @Machine SET @SnapshotsCleaned = @SnapshotsCleaned + @@ROWCOUNT SELECT @TempSnapshotID = (SELECT SnapshotDataID FROM #tempSnapshot) DELETE ReportServerTempDB.dbo.ChunkData FROM ReportServerTempDB.dbo.ChunkData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @ChunksCleaned + @@ROWCOUNT DELETE ReportServerTempDB.dbo.SnapshotData FROM ReportServerTempDB.dbo.SnapshotData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID GO GRANT EXECUTE ON [dbo].[CleanOrphanedSnapshots] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetCacheOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetCacheOptions] GO CREATE PROCEDURE [dbo].[SetCacheOptions] @Path as nvarchar(425), @CacheReport as bit, @ExpirationFlags as int, @CacheExpiration as int = NULL AS DECLARE @CachePolicyID as uniqueidentifier SELECT @CachePolicyID = (SELECT CachePolicyID FROM CachePolicy with (XLOCK) INNER JOIN Catalog ON Catalog.ItemID = CachePolicy.ReportID WHERE Catalog.Path = @Path) IF @CachePolicyID IS NULL -- no policy exists BEGIN IF @CacheReport = 1 -- create a new one BEGIN INSERT INTO CachePolicy (CachePolicyID, ReportID, ExpirationFlags, CacheExpiration) (SELECT NEWID(), ItemID, @ExpirationFlags, @CacheExpiration FROM Catalog WHERE Catalog.Path = @Path) END -- ELSE if it has no policy and we want to remove its policy do nothing END ELSE -- existing policy BEGIN IF @CacheReport = 1 BEGIN UPDATE CachePolicy SET ExpirationFlags = @ExpirationFlags, CacheExpiration = @CacheExpiration WHERE CachePolicyID = @CachePolicyID EXEC FlushReportFromCache @Path END ELSE BEGIN DELETE FROM CachePolicy WHERE CachePolicyID = @CachePolicyID EXEC FlushReportFromCache @Path END END GO GRANT EXECUTE ON [dbo].[SetCacheOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCacheOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetCacheOptions] GO CREATE PROCEDURE [dbo].[GetCacheOptions] @Path as nvarchar(425) AS SELECT ExpirationFlags, CacheExpiration, S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path] FROM CachePolicy INNER JOIN Catalog ON Catalog.ItemID = CachePolicy.ReportID LEFT outer join reportschedule rs on catalog.itemid = rs.reportid and rs.reportaction = 3 LEFT OUTER JOIN [Schedule] S ON S.ScheduleID = rs.ScheduleID LEFT OUTER JOIN [Users] Owner on Owner.UserID = S.[CreatedById] WHERE Catalog.Path = @Path GO GRANT EXECUTE ON [dbo].[GetCacheOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddReportToCache]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddReportToCache] GO CREATE PROCEDURE [dbo].[AddReportToCache] @ReportID as uniqueidentifier, @ExecutionDate datetime, @SnapshotDataID uniqueidentifier, @ExpirationDate datetime OUTPUT, @ScheduleID uniqueidentifier OUTPUT AS DECLARE @ExpirationFlags as int DECLARE @Timeout as int SET @ExpirationDate = NULL SET @ScheduleID = NULL SET @ExpirationFlags = (SELECT ExpirationFlags FROM CachePolicy WHERE ReportID = @ReportID) IF @ExpirationFlags = 1 -- timeout based BEGIN SET @Timeout = (SELECT CacheExpiration FROM CachePolicy WHERE ReportID = @ReportID) SET @ExpirationDate = DATEADD(n, @Timeout, @ExecutionDate) END ELSE IF @ExpirationFlags = 2 -- schedule based BEGIN SELECT @ScheduleID=s.ScheduleID, @ExpirationDate=s.NextRunTime FROM Schedule s WITH(UPDLOCK) INNER JOIN ReportSchedule rs ON rs.ScheduleID = s.ScheduleID and rs.ReportAction = 3 WHERE rs.ReportID = @ReportID END ELSE BEGIN -- Ignore NULL case. It means that a user set the Report not to be cached after the report execution fired. IF @ExpirationFlags IS NOT NULL BEGIN RAISERROR('Invalid cache flags', 16, 1) END RETURN END -- and to the report cache INSERT INTO ReportServerTempDB.dbo.ExecutionCache (ExecutionCacheID, ReportID, ExpirationFlags, AbsoluteExpiration, RelativeExpiration, SnapshotDataID) VALUES (newid(), @ReportID, @ExpirationFlags, @ExpirationDate, @Timeout, @SnapshotDataID ) UPDATE ReportServerTempDB.dbo.SnapshotData SET PermanentRefcount = PermanentRefcount + 1, IsCached = CONVERT(BIT, 1) WHERE SnapshotDataID = @SnapshotDataID; GO GRANT EXECUTE ON [dbo].[AddReportToCache] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetExecutionOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetExecutionOptions] GO CREATE PROCEDURE [dbo].[GetExecutionOptions] @Path nvarchar(425) AS SELECT ExecutionFlag, S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path] FROM Catalog LEFT OUTER JOIN ReportSchedule ON Catalog.ItemID = ReportSchedule.ReportID AND ReportSchedule.ReportAction = 1 LEFT OUTER JOIN [Schedule] S ON S.ScheduleID = ReportSchedule.ScheduleID LEFT OUTER JOIN [Users] Owner on Owner.UserID = S.[CreatedById] WHERE Catalog.Path = @Path GO GRANT EXECUTE ON [dbo].[GetExecutionOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetExecutionOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetExecutionOptions] GO CREATE PROCEDURE [dbo].[SetExecutionOptions] @Path as nvarchar(425), @ExecutionFlag as int, @ExecutionChanged as bit = 0 AS IF @ExecutionChanged = 0 BEGIN UPDATE Catalog SET ExecutionFlag = @ExecutionFlag WHERE Catalog.Path = @Path END ELSE BEGIN IF (@ExecutionFlag & 3) = 2 BEGIN -- set it to snapshot, flush cache EXEC FlushReportFromCache @Path DELETE CachePolicy FROM CachePolicy INNER JOIN Catalog ON CachePolicy.ReportID = Catalog.ItemID WHERE Catalog.Path = @Path END -- now clean existing snapshot and execution time if any UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 FROM SnapshotData INNER JOIN Catalog ON SnapshotData.SnapshotDataID = Catalog.SnapshotDataID WHERE Catalog.Path = @Path UPDATE Catalog SET ExecutionFlag = @ExecutionFlag, SnapshotDataID = NULL, ExecutionTime = NULL WHERE Catalog.Path = @Path END GO GRANT EXECUTE ON [dbo].[SetExecutionOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSnapshot] GO CREATE PROCEDURE [dbo].[UpdateSnapshot] @Path as nvarchar(425), @SnapshotDataID as uniqueidentifier, @executionDate as datetime AS DECLARE @OldSnapshotDataID uniqueidentifier SET @OldSnapshotDataID = (SELECT SnapshotDataID FROM Catalog WITH (XLOCK) WHERE Catalog.Path = @Path) -- update reference count in snapshot table UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount-1 WHERE SnapshotData.SnapshotDataID = @OldSnapshotDataID -- update catalog to point to the new execution snapshot UPDATE Catalog SET SnapshotDataID = @SnapshotDataID, ExecutionTime = @executionDate WHERE Catalog.Path = @Path UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount+1, TransientRefcount = TransientRefcount-1 WHERE SnapshotData.SnapshotDataID = @SnapshotDataID GO GRANT EXECUTE ON [dbo].[UpdateSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateChunkAndGetPointer]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateChunkAndGetPointer] GO CREATE PROCEDURE [dbo].[CreateChunkAndGetPointer] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int, @MimeType nvarchar(260) = NULL, @Version smallint, @Content image, @ChunkFlags tinyint = NULL, @ChunkPointer binary(16) OUTPUT AS DECLARE @ChunkID uniqueidentifier SET @ChunkID = NEWID() IF @IsPermanentSnapshot != 0 BEGIN DELETE ChunkData WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType INSERT INTO ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) VALUES (@ChunkID, @SnapshotDataID, @ChunkName, @ChunkType, @MimeType, @Version, @ChunkFlags, @Content) SELECT @ChunkPointer = TEXTPTR(Content) FROM ChunkData WHERE ChunkData.ChunkID = @ChunkID END ELSE BEGIN DELETE ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType INSERT INTO ReportServerTempDB.dbo.ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) VALUES (@ChunkID, @SnapshotDataID, @ChunkName, @ChunkType, @MimeType, @Version, @ChunkFlags, @Content) SELECT @ChunkPointer = TEXTPTR(Content) FROM ReportServerTempDB.dbo.ChunkData AS CH WHERE CH.ChunkID = @ChunkID END GO GRANT EXECUTE ON [dbo].[CreateChunkAndGetPointer] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteChunkPortion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteChunkPortion] GO CREATE PROCEDURE [dbo].[WriteChunkPortion] @ChunkPointer binary(16), @IsPermanentSnapshot bit, @DataIndex int = NULL, @DeleteLength int = NULL, @Content image AS IF @IsPermanentSnapshot != 0 BEGIN UPDATETEXT ChunkData.Content @ChunkPointer @DataIndex @DeleteLength @Content END ELSE BEGIN UPDATETEXT ReportServerTempDB.dbo.ChunkData.Content @ChunkPointer @DataIndex @DeleteLength @Content END GO GRANT EXECUTE ON [dbo].[WriteChunkPortion] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetChunkPointerAndLength]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetChunkPointerAndLength] GO CREATE PROCEDURE [dbo].[GetChunkPointerAndLength] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int AS IF @IsPermanentSnapshot != 0 BEGIN SELECT TEXTPTR(Content), DATALENGTH(Content), MimeType, ChunkFlags, Version FROM ChunkData AS CH WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END ELSE BEGIN SELECT TEXTPTR(Content), DATALENGTH(Content), MimeType, ChunkFlags, Version FROM ReportServerTempDB.dbo.ChunkData AS CH WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END GO GRANT EXECUTE ON [dbo].[GetChunkPointerAndLength] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetChunkInformation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetChunkInformation] GO CREATE PROCEDURE [dbo].[GetChunkInformation] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int AS IF @IsPermanentSnapshot != 0 BEGIN SELECT MimeType FROM ChunkData AS CH WITH (HOLDLOCK, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END ELSE BEGIN SELECT MimeType FROM ReportServerTempDB.dbo.ChunkData AS CH WITH (HOLDLOCK, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END GO GRANT EXECUTE ON [dbo].[GetChunkInformation] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadChunkPortion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadChunkPortion] GO CREATE PROCEDURE [dbo].[ReadChunkPortion] @ChunkPointer binary(16), @IsPermanentSnapshot bit, @DataIndex int, @Length int AS IF @IsPermanentSnapshot != 0 BEGIN READTEXT ChunkData.Content @ChunkPointer @DataIndex @Length END ELSE BEGIN READTEXT ReportServerTempDB.dbo.ChunkData.Content @ChunkPointer @DataIndex @Length END GO GRANT EXECUTE ON [dbo].[ReadChunkPortion] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CopyChunksOfType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CopyChunksOfType] GO CREATE PROCEDURE [dbo].[CopyChunksOfType] @FromSnapshotID uniqueidentifier, @FromIsPermanent bit, @ToSnapshotID uniqueidentifier, @ToIsPermanent bit, @ChunkType int, @ChunkName nvarchar(260) = NULL, @TargetChunkName nvarchar(260) = NULL AS DECLARE @Machine nvarchar(512) IF @FromIsPermanent != 0 AND @ToIsPermanent = 0 BEGIN -- copy the contiguous chunks INSERT INTO ReportServerTempDB.dbo.ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) SELECT newid(), @ToSnapshotID, COALESCE(@TargetChunkName, S.ChunkName), S.ChunkType, S.MimeType, S.Version, S.ChunkFlags, S.Content FROM ChunkData AS S WHERE S.SnapshotDataID = @FromSnapshotID AND (S.ChunkType = @ChunkType OR @ChunkType IS NULL) AND (S.ChunkName = @ChunkName OR @ChunkName IS NUll) AND NOT EXISTS( SELECT T.ChunkName FROM ReportServerTempDB.dbo.ChunkData AS T -- exclude the ones in the target WHERE T.ChunkName = COALESCE(@TargetChunkName, S.ChunkName) AND T.ChunkType = S.ChunkType AND T.SnapshotDataID = @ToSnapshotID) -- copying a segmented chunk from permanent to temp database -- requires doing a deep copy and updating all of the -- mapping tables DECLARE @CopiedChunkMetadata TABLE ( NewChunkId uniqueidentifier default newsequentialid() not null, OldChunkId uniqueidentifier not null ) -- find chunks which we need to copy -- @CopiedChunkMetadata will be already be filtered for chunks -- which already exist in the target snapshot INSERT INTO @CopiedChunkMetadata (OldChunkId) SELECT SC.ChunkId FROM SegmentedChunk SC -- JOIN SnapshotChunkMapping SCM ON (SCM.ChunkId = SC.ChunkId) WHERE SC.SnapshotDataId = @FromSnapshotID AND (SC.ChunkType = @ChunkType OR @ChunkType IS NULL) AND (SC.ChunkName = @ChunkName OR @ChunkName IS NULL) AND NOT EXISTS( -- exclude chunks already in the target SELECT TSC.ChunkName FROM ReportServerTempDB.dbo.SegmentedChunk TSC -- JOIN ReportServerTempDB.dbo.SnapshotChunkMapping TSCM ON (TSC.ChunkId = TSCM.ChunkId) WHERE TSC.ChunkName = COALESCE(@TargetChunkName, SC.ChunkName) AND TSC.ChunkType = SC.ChunkType AND TSC.SnapshotDataId = @ToSnapshotID ) -- insert those chunks -- the chunks will be cleaned up by the machine in which they are being allocated to select @Machine = Machine from ReportServerTempDB.dbo.SnapshotData SD where SD.SnapshotDataID = @ToSnapshotID INSERT INTO ReportServerTempDB.dbo.SegmentedChunk (SnapshotDataId, ChunkId, ChunkFlags, ChunkName, ChunkType, Version, MimeType, Machine) SELECT @ToSnapshotID, CCM.NewChunkId, SC.ChunkFlags, COALESCE(@TargetChunkName, SC.ChunkName), SC.ChunkType, SC.Version, SC.MimeType, @Machine FROM SegmentedChunk SC JOIN @CopiedChunkMetadata CCM ON (CCM.OldChunkId = SC.ChunkId AND SC.SnapshotDataId = @FromSnapshotID) DECLARE @CopiedSegmentMetadata TABLE ( NewChunkId uniqueidentifier not null, OldChunkId uniqueidentifier not null, NewSegmentId uniqueidentifier default newsequentialid() not null, OldSegmentId uniqueidentifier not null, StartByte bigint not null ) INSERT INTO @CopiedSegmentMetadata (NewChunkId, OldChunkId, OldSegmentId, CSM.StartByte) SELECT CCM.NewChunkId, CCM.OldChunkId, S.SegmentId, CSM.StartByte FROM Segment S JOIN ChunkSegmentMapping CSM ON (S.SegmentId = CSM.SegmentId) JOIN @CopiedChunkMetadata CCM ON (CSM.ChunkId = CCM.OldChunkId) -- now copy the actual segment data into the tempdb INSERT INTO ReportServerTempDB.dbo.Segment (SegmentId, LogicalByteCount, Content) SELECT CSMETA.NewSegmentId, S.LogicalByteCount, S.Content FROM Segment S JOIN @CopiedSegmentMetadata CSMETA ON (S.SegmentId = CSMETA.OldSegmentId) -- now build the chunk->segment mapping INSERT INTO ReportServerTempDB.dbo.ChunkSegmentMapping (ChunkId, SegmentId, StartByte) SELECT CSMETA.NewChunkId, CSMETA.NewSegmentId, CSMETA.StartByte FROM @CopiedSegmentMetadata CSMETA END ELSE IF @FromIsPermanent = 0 AND @ToIsPermanent = 0 BEGIN -- the chunks exist on the node in which they were originally allocated on, they should -- be cleaned up by that node select @Machine = Machine from ReportServerTempDB.dbo.SnapshotData SD where SD.SnapshotDataID = @FromSnapshotID INSERT INTO ReportServerTempDB.dbo.ChunkData (ChunkId, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) SELECT newid(), @ToSnapshotID, COALESCE(@TargetChunkName, S.ChunkName), S.ChunkType, S.MimeType, S.Version, S.ChunkFlags, S.Content FROM ReportServerTempDB.dbo.ChunkData AS S WHERE S.SnapshotDataID = @FromSnapshotID AND (S.ChunkType = @ChunkType OR @ChunkType IS NULL) AND (S.ChunkName = @ChunkName OR @ChunkName IS NULL) AND NOT EXISTS( SELECT T.ChunkName FROM ReportServerTempDB.dbo.ChunkData AS T -- exclude the ones in the target WHERE T.ChunkName = COALESCE(@TargetChunkName, S.ChunkName) AND T.ChunkType = S.ChunkType AND T.SnapshotDataID = @ToSnapshotID) -- copy the segmented chunks, copying the segmented -- chunks really just needs to update the mappings INSERT INTO ReportServerTempDB.dbo.SegmentedChunk (SnapshotDataId, ChunkId, ChunkName, ChunkType, Version, ChunkFlags, MimeType, Machine) SELECT @ToSnapshotID, ChunkId, COALESCE(@TargetChunkName, C.ChunkName), C.ChunkType, C.Version, C.ChunkFlags, C.MimeType, @Machine -- FROM ReportServerTempDB.dbo.SnapshotChunkMapping SCM FROM ReportServerTempDB.dbo.SegmentedChunk C WHERE C.SnapshotDataId = @FromSnapshotID AND (C.ChunkType = @ChunkType OR @ChunkType IS NULL) AND (C.ChunkName = @ChunkName OR @ChunkName IS NULL) AND NOT EXISTS( -- exclude chunks that are already mapped into this snapshot SELECT T.ChunkId FROM ReportServerTempDB.dbo.SegmentedChunk T WHERE T.SnapshotDataId = @ToSnapshotID and T.ChunkName = COALESCE(@TargetChunkName, C.ChunkName) and T.ChunkType = C.ChunkType ) END ELSE IF @FromIsPermanent != 0 AND @ToIsPermanent != 0 BEGIN INSERT INTO ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) SELECT newid(), @ToSnapshotID, COALESCE(@TargetChunkName, S.ChunkName), S.ChunkType, S.MimeType, S.Version, S.ChunkFlags, S.Content FROM ChunkData AS S WHERE S.SnapshotDataID = @FromSnapshotID AND (S.ChunkType = @ChunkType OR @ChunkType IS NULL) AND (S.ChunkName = @ChunkName OR @ChunkName IS NULL) AND NOT EXISTS( SELECT T.ChunkName FROM ChunkData AS T -- exclude the ones in the target WHERE T.ChunkName = COALESCE(@TargetChunkName, S.ChunkName) AND T.ChunkType = S.ChunkType AND T.SnapshotDataID = @ToSnapshotID) -- copy the segmented chunks, copying the segmented -- chunks really just needs to update the mappings INSERT INTO SegmentedChunk (SnapshotDataId, ChunkId, ChunkName, ChunkType, Version, ChunkFlags, C.MimeType) SELECT @ToSnapshotID, ChunkId, COALESCE(@TargetChunkName, C.ChunkName), C.ChunkType, C.Version, C.ChunkFlags, C.MimeType -- FROM ReportServerTempDB.dbo.SnapshotChunkMapping SCM FROM SegmentedChunk C WHERE C.SnapshotDataId = @FromSnapshotID AND (C.ChunkType = @ChunkType OR @ChunkType IS NULL) AND (C.ChunkName = @ChunkName OR @ChunkName IS NULL) AND NOT EXISTS( -- exclude chunks that are already mapped into this snapshot SELECT T.ChunkId FROM SegmentedChunk T WHERE T.SnapshotDataId = @ToSnapshotID and T.ChunkName = COALESCE(@TargetChunkName, C.ChunkName) and T.ChunkType = C.ChunkType ) END ELSE BEGIN RAISERROR('Unsupported chunk copy', 16, 1) END GO GRANT EXECUTE ON [dbo].[CopyChunksOfType] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteSnapshotAndChunks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteSnapshotAndChunks] GO CREATE PROCEDURE [dbo].[DeleteSnapshotAndChunks] @SnapshotID uniqueidentifier, @IsPermanentSnapshot bit AS -- Deleting from SnapshotData will cascade -- the deletion to the SegmentedChunk -- we will then lazily clean up the SegmentedChunk metadata -- along with the actual segment data IF @IsPermanentSnapshot != 0 BEGIN DELETE ChunkData WHERE ChunkData.SnapshotDataID = @SnapshotID DELETE SnapshotData WHERE SnapshotData.SnapshotDataID = @SnapshotID END ELSE BEGIN DELETE ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotID DELETE ReportServerTempDB.dbo.SnapshotData WHERE SnapshotDataID = @SnapshotID END GO GRANT EXECUTE ON [dbo].[DeleteSnapshotAndChunks] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteOneChunk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteOneChunk] GO CREATE PROCEDURE [dbo].[DeleteOneChunk] @SnapshotID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int AS SET NOCOUNT OFF -- for segmented chunks we just need to -- remove the mapping, the cleanup thread -- will pick up the rest of the pieces IF @IsPermanentSnapshot != 0 BEGIN DELETE ChunkData WHERE SnapshotDataID = @SnapshotID AND ChunkName = @ChunkName AND ChunkType = @ChunkType DELETE SegmentedChunk WHERE SnapshotDataId = @SnapshotID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END ELSE BEGIN DELETE ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotID AND ChunkName = @ChunkName AND ChunkType = @ChunkType DELETE ReportServerTempDB.dbo.SegmentedChunk WHERE SnapshotDataId = @SnapshotID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END GO GRANT EXECUTE ON [dbo].[DeleteOneChunk] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateRdlChunk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateRdlChunk] GO CREATE PROCEDURE [dbo].[CreateRdlChunk] @ItemId UNIQUEIDENTIFIER, @SnapshotId UNIQUEIDENTIFIER, @IsPermanentSnapshot BIT, @ChunkName NVARCHAR(260), @ChunkFlags TINYINT, @ChunkType INT, @Version SMALLINT, @MimeType NVARCHAR(260) = NULL AS BEGIN -- If the chunk already exists then bail out early IF EXISTS ( SELECT 1 FROM [SegmentedChunk] WHERE SnapshotDataId = @SnapshotId AND ChunkName = @ChunkName AND ChunkType = @ChunkType ) RETURN ; -- This is a 3-step process. First we need to get the RDL out of the Catalog -- table where it is stored in the Content row. Note the join to make sure -- that if ItemId is a Linked Report we go back to the main report to get the RDL. -- Once we have the RDL stored in @SegmentData, we then invoke the CreateSegmentedChunk -- stored proc which will create an empty segmented chunk for us and return the ChunkId. -- finally, once we have a ChunkId, we can invoke CreateChunkSegment to actually put the -- content into the chunk. Note that we do not every actually break the chunk into multiple -- sgements but instead we always use one. DECLARE @SegmentData VARBINARY(MAX) ; DECLARE @SegmentByteCount INT ; SELECT @SegmentData = CONVERT(VARBINARY(MAX), ISNULL(Linked.Content, Original.Content)) FROM [Catalog] Original LEFT OUTER JOIN [Catalog] Linked WITH (INDEX(PK_Catalog)) ON (Original.LinkSourceId = Linked.ItemId) WHERE [Original].[ItemId] = @ItemId ; SELECT @SegmentByteCount = DATALENGTH(@SegmentData) ; DECLARE @ChunkId UNIQUEIDENTIFIER ; EXEC [CreateSegmentedChunk] @SnapshotId = @SnapshotId, @IsPermanent = @IsPermanentSnapshot, @ChunkName = @ChunkName, @ChunkFlags = @ChunkFlags, @ChunkType = @ChunkType, @Version = @Version, @MimeType = @MimeType, @Machine = NULL, @ChunkId = @ChunkId out ; DECLARE @SegmentId UNIQUEIDENTIFIER ; EXEC [CreateChunkSegment] @SnapshotId = @SnapshotId, @IsPermanent = @IsPermanentSnapshot, @ChunkId = @ChunkId, @Content = @SegmentData, @StartByte = 0, @Length = @SegmentByteCount, @LogicalByteCount = @SegmentByteCount, @SegmentId = @SegmentId out END GO GRANT EXECUTE ON [dbo].[CreateRdlChunk] TO RSExecRole GO -------------------------------------------------- ------------- Persisted stream SPs if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeletePersistedStreams]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeletePersistedStreams] GO CREATE PROCEDURE [dbo].[DeletePersistedStreams] @SessionID varchar(32) AS SET NOCOUNT OFF delete ReportServerTempDB.dbo.PersistedStream from (select top 1 * from ReportServerTempDB.dbo.PersistedStream PS2 where PS2.SessionID = @SessionID) as e1 where e1.SessionID = ReportServerTempDB.dbo.PersistedStream.[SessionID] and e1.[Index] = ReportServerTempDB.dbo.PersistedStream.[Index] GO GRANT EXECUTE ON [dbo].[DeletePersistedStreams] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteExpiredPersistedStreams]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteExpiredPersistedStreams] GO CREATE PROCEDURE [dbo].[DeleteExpiredPersistedStreams] AS SET NOCOUNT OFF SET DEADLOCK_PRIORITY LOW DELETE ReportServerTempDB.dbo.PersistedStream FROM (SELECT TOP 1 * FROM ReportServerTempDB.dbo.PersistedStream PS2 WHERE PS2.RefCount = 0 AND GETDATE() > PS2.ExpirationDate) AS e1 WHERE e1.SessionID = ReportServerTempDB.dbo.PersistedStream.[SessionID] AND e1.[Index] = ReportServerTempDB.dbo.PersistedStream.[Index] GO GRANT EXECUTE ON [dbo].[DeleteExpiredPersistedStreams] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeletePersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeletePersistedStream] GO CREATE PROCEDURE [dbo].[DeletePersistedStream] @SessionID varchar(32), @Index int AS delete from ReportServerTempDB.dbo.PersistedStream where SessionID = @SessionID and [Index] = @Index GO GRANT EXECUTE ON [dbo].[DeletePersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddPersistedStream] GO CREATE PROCEDURE [dbo].[AddPersistedStream] @SessionID varchar(32), @Index int AS DECLARE @RefCount int DECLARE @id varchar(32) DECLARE @ExpirationDate datetime set @RefCount = 0 set @ExpirationDate = DATEADD(day, 2, GETDATE()) set @id = (select SessionID from ReportServerTempDB.dbo.SessionData where SessionID = @SessionID) if @id is not null begin set @RefCount = 1 end INSERT INTO ReportServerTempDB.dbo.PersistedStream (SessionID, [Index], [RefCount], [ExpirationDate]) VALUES (@SessionID, @Index, @RefCount, @ExpirationDate) GO GRANT EXECUTE ON [dbo].[AddPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[LockPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[LockPersistedStream] GO CREATE PROCEDURE [dbo].[LockPersistedStream] @SessionID varchar(32), @Index int AS SELECT [Index] FROM ReportServerTempDB.dbo.PersistedStream WITH (XLOCK) WHERE SessionID = @SessionID AND [Index] = @Index GO GRANT EXECUTE ON [dbo].[LockPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteFirstPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteFirstPortionPersistedStream] GO CREATE PROCEDURE [dbo].[WriteFirstPortionPersistedStream] @SessionID varchar(32), @Index int, @Name nvarchar(260) = NULL, @MimeType nvarchar(260) = NULL, @Extension nvarchar(260) = NULL, @Encoding nvarchar(260) = NULL, @Content image AS UPDATE ReportServerTempDB.dbo.PersistedStream set Content = @Content, [Name] = @Name, MimeType = @MimeType, Extension = @Extension WHERE SessionID = @SessionID AND [Index] = @Index SELECT TEXTPTR(Content) FROM ReportServerTempDB.dbo.PersistedStream WHERE SessionID = @SessionID AND [Index] = @Index GO GRANT EXECUTE ON [dbo].[WriteFirstPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteNextPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteNextPortionPersistedStream] GO CREATE PROCEDURE [dbo].[WriteNextPortionPersistedStream] @DataPointer binary(16), @DataIndex int, @DeleteLength int, @Content image AS UPDATETEXT ReportServerTempDB.dbo.PersistedStream.Content @DataPointer @DataIndex @DeleteLength @Content GO GRANT EXECUTE ON [dbo].[WriteNextPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetFirstPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetFirstPortionPersistedStream] GO CREATE PROCEDURE [dbo].[GetFirstPortionPersistedStream] @SessionID varchar(32) AS SELECT TOP 1 TEXTPTR(P.Content), DATALENGTH(P.Content), P.[Index], P.[Name], P.MimeType, P.Extension, P.Encoding, P.Error FROM ReportServerTempDB.dbo.PersistedStream P WITH (XLOCK) WHERE P.SessionID = @SessionID GO GRANT EXECUTE ON [dbo].[GetFirstPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetPersistedStreamError]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetPersistedStreamError] GO CREATE PROCEDURE [dbo].[SetPersistedStreamError] @SessionID varchar(32), @Index int, @AllRows bit, @Error nvarchar(512) AS if @AllRows = 0 BEGIN UPDATE ReportServerTempDB.dbo.PersistedStream SET Error = @Error WHERE SessionID = @SessionID and [Index] = @Index END ELSE BEGIN UPDATE ReportServerTempDB.dbo.PersistedStream SET Error = @Error WHERE SessionID = @SessionID END GO GRANT EXECUTE ON [dbo].[SetPersistedStreamError] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetNextPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetNextPortionPersistedStream] GO CREATE PROCEDURE [dbo].[GetNextPortionPersistedStream] @DataPointer binary(16), @DataIndex int, @Length int AS READTEXT ReportServerTempDB.dbo.PersistedStream.Content @DataPointer @DataIndex @Length GO GRANT EXECUTE ON [dbo].[GetNextPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapshotChunks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapshotChunks] GO CREATE PROCEDURE [dbo].[GetSnapshotChunks] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit AS IF @IsPermanentSnapshot != 0 BEGIN SELECT ChunkName, ChunkType, ChunkFlags, MimeType, Version, datalength(Content) FROM ChunkData WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN SELECT ChunkName, ChunkType, ChunkFlags, MimeType, Version, datalength(Content) FROM ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[GetSnapshotChunks] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetDrillthroughReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetDrillthroughReports] GO CREATE PROCEDURE [dbo].[SetDrillthroughReports] @ReportID uniqueidentifier, @ModelID uniqueidentifier, @ModelItemID nvarchar(425), @Type tinyint AS SET NOCOUNT OFF INSERT INTO ModelDrill (ModelDrillID, ModelID, ReportID, ModelItemID, [Type]) VALUES (newid(), @ModelID, @ReportID, @ModelItemID, @Type) GO GRANT EXECUTE ON [dbo].[SetDrillthroughReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteDrillthroughReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteDrillthroughReports] GO CREATE PROCEDURE [dbo].[DeleteDrillthroughReports] @ModelID uniqueidentifier, @ModelItemID nvarchar(425) AS DELETE ModelDrill WHERE ModelID = @ModelID and ModelItemID = @ModelItemID GO GRANT EXECUTE ON [dbo].[DeleteDrillthroughReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDrillthroughReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDrillthroughReports] GO CREATE PROCEDURE [dbo].[GetDrillthroughReports] @ModelID uniqueidentifier, @ModelItemID nvarchar(425) AS SELECT ModelDrill.Type, Catalog.Path FROM ModelDrill INNER JOIN Catalog ON ModelDrill.ReportID = Catalog.ItemID WHERE ModelID = @ModelID AND ModelItemID = @ModelItemID GO GRANT EXECUTE ON [dbo].[GetDrillthroughReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDrillthroughReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDrillthroughReport] GO CREATE PROCEDURE [dbo].[GetDrillthroughReport] @ModelPath nvarchar(425), @ModelItemID nvarchar(425), @Type tinyint AS SELECT CatRep.Path FROM ModelDrill INNER JOIN Catalog CatMod ON ModelDrill.ModelID = CatMod.ItemID INNER JOIN Catalog CatRep ON ModelDrill.ReportID = CatRep.ItemID WHERE CatMod.Path = @ModelPath AND ModelItemID = @ModelItemID AND ModelDrill.[Type] = @Type GO GRANT EXECUTE ON [dbo].[GetDrillthroughReport] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUpgradeItems]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUpgradeItems] GO CREATE PROCEDURE [dbo].[GetUpgradeItems] AS SELECT [Item], [Status] FROM [UpgradeInfo] GO GRANT EXECUTE ON [dbo].[GetUpgradeItems] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetUpgradeItemStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetUpgradeItemStatus] GO CREATE PROCEDURE [dbo].[SetUpgradeItemStatus] @ItemName nvarchar(260), @Status nvarchar(512) AS UPDATE [UpgradeInfo] SET [Status] = @Status WHERE [Item] = @ItemName GO GRANT EXECUTE ON [dbo].[SetUpgradeItemStatus] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPolicyRoots]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPolicyRoots] GO CREATE PROCEDURE [dbo].[GetPolicyRoots] AS SELECT [Path], [Type] FROM [Catalog] WHERE [PolicyRoot] = 1 GO GRANT EXECUTE ON [dbo].[GetPolicyRoots] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDataSourceForUpgrade]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDataSourceForUpgrade] GO CREATE PROCEDURE [dbo].[GetDataSourceForUpgrade] @CurrentVersion int AS SELECT [DSID] FROM [DataSource] WHERE [Version] != @CurrentVersion GO GRANT EXECUTE ON [dbo].[GetDataSourceForUpgrade] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSubscriptionsForUpgrade]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSubscriptionsForUpgrade] GO CREATE PROCEDURE [dbo].[GetSubscriptionsForUpgrade] @CurrentVersion int AS SELECT [SubscriptionID] FROM [Subscriptions] WHERE [Version] != @CurrentVersion GO GRANT EXECUTE ON [dbo].[GetSubscriptionsForUpgrade] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[StoreServerParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[StoreServerParameters] GO CREATE PROCEDURE [dbo].[StoreServerParameters] @ServerParametersID nvarchar(32), @Path nvarchar(425), @CurrentDate datetime, @Timeout int, @Expiration datetime, @ParametersValues image, @ParentParametersID nvarchar(32) = NULL AS DECLARE @ExistingServerParametersID as nvarchar(32) SET @ExistingServerParametersID = (SELECT ServerParametersID from [dbo].[ServerParametersInstance] WHERE ServerParametersID = @ServerParametersID) IF @ExistingServerParametersID IS NULL -- new row BEGIN INSERT INTO [dbo].[ServerParametersInstance] (ServerParametersID, ParentID, Path, CreateDate, ModifiedDate, Timeout, Expiration, ParametersValues) VALUES (@ServerParametersID, @ParentParametersID, @Path, @CurrentDate, @CurrentDate, @Timeout, @Expiration, @ParametersValues) END ELSE BEGIN UPDATE [dbo].[ServerParametersInstance] SET Timeout = @Timeout, Expiration = @Expiration, ParametersValues = @ParametersValues, ModifiedDate = @CurrentDate, Path = @Path, ParentID = @ParentParametersID WHERE ServerParametersID = @ServerParametersID END GO GRANT EXECUTE ON [dbo].[StoreServerParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetServerParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetServerParameters] GO CREATE PROCEDURE [dbo].[GetServerParameters] @ServerParametersID nvarchar(32) AS DECLARE @now as DATETIME SET @now = GETDATE() SELECT Child.Path, Child.ParametersValues, Parent.ParametersValues FROM [dbo].[ServerParametersInstance] Child LEFT OUTER JOIN [dbo].[ServerParametersInstance] Parent ON Child.ParentID = Parent.ServerParametersID WHERE Child.ServerParametersID = @ServerParametersID AND Child.Expiration > @now GO GRANT EXECUTE ON [dbo].[GetServerParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredServerParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredServerParameters] GO CREATE PROCEDURE [dbo].[CleanExpiredServerParameters] @ParametersCleaned INT OUTPUT AS DECLARE @now as DATETIME SET @now = GETDATE() DELETE FROM [dbo].[ServerParametersInstance] WHERE ServerParametersID IN ( SELECT TOP 20 ServerParametersID FROM [dbo].[ServerParametersInstance] WHERE Expiration < @now ) SET @ParametersCleaned = @@ROWCOUNT GO GRANT EXECUTE ON [dbo].[CleanExpiredServerParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CopyChunks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CopyChunks] GO -- TODO: Modify to support segmented chunks CREATE PROCEDURE [dbo].[CopyChunks] @OldSnapshotId UNIQUEIDENTIFIER, @NewSnapshotId UNIQUEIDENTIFIER, @IsPermanentSnapshot BIT AS BEGIN IF(@IsPermanentSnapshot = 1) BEGIN -- copy non-segmented chunks INSERT [dbo].[ChunkData] ( ChunkId, SnapshotDataId, ChunkFlags, ChunkName, ChunkType, Version, MimeType, Content ) SELECT NEWID(), @NewSnapshotId, [c].[ChunkFlags], [c].[ChunkName], [c].[ChunkType], [c].[Version], [c].[MimeType], [c].[Content] FROM [dbo].[ChunkData] [c] WHERE [c].[SnapshotDataId] = @OldSnapshotId -- copy segmented chunks... real easy just add the mapping INSERT [dbo].[SegmentedChunk]( ChunkId, SnapshotDataId, ChunkName, ChunkType, Version, MimeType, ChunkFlags ) SELECT ChunkId, @NewSnapshotId, ChunkName, ChunkType, Version, MimeType, ChunkFlags FROM [dbo].[SegmentedChunk] WHERE [SnapshotDataId] = @OldSnapshotId END ELSE BEGIN -- copy non-segmented chunks INSERT ReportServerTempDB.dbo.[ChunkData] ( ChunkId, SnapshotDataId, ChunkFlags, ChunkName, ChunkType, Version, MimeType, Content ) SELECT NEWID(), @NewSnapshotId, [c].[ChunkFlags], [c].[ChunkName], [c].[ChunkType], [c].[Version], [c].[MimeType], [c].[Content] FROM ReportServerTempDB.dbo.[ChunkData] [c] WHERE [c].[SnapshotDataId] = @OldSnapshotId -- copy segmented chunks... real easy just add the mapping INSERT ReportServerTempDB.[dbo].[SegmentedChunk]( ChunkId, SnapshotDataId, ChunkName, ChunkType, Version, MimeType, ChunkFlags, Machine ) SELECT ChunkId, @NewSnapshotId, ChunkName, ChunkType, Version, MimeType, ChunkFlags, Machine FROM ReportServerTempDB.dbo.[SegmentedChunk] WHERE [SnapshotDataId] = @OldSnapshotId END END GO GRANT EXECUTE ON [dbo].[CopyChunks] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateNewSnapshotVersion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateNewSnapshotVersion] GO CREATE PROCEDURE [dbo].[CreateNewSnapshotVersion] @OldSnapshotId UNIQUEIDENTIFIER, @NewSnapshotId UNIQUEIDENTIFIER, @IsPermanentSnapshot BIT, @Machine NVARCHAR(512) AS BEGIN IF(@IsPermanentSnapshot = 1) BEGIN INSERT [dbo].[SnapshotData] ( SnapshotDataId, CreatedDate, ParamsHash, QueryParams, EffectiveParams, Description, DependsOnUser, PermanentRefCount, TransientRefCount, ExpirationDate, PageCount, HasDocMap, PaginationMode, ProcessingFlags ) SELECT @NewSnapshotId, [sn].CreatedDate, [sn].ParamsHash, [sn].QueryParams, [sn].EffectiveParams, [sn].Description, [sn].DependsOnUser, 0, 1, -- always create with transient refcount of 1 [sn].ExpirationDate, [sn].PageCount, [sn].HasDocMap, [sn].PaginationMode, [sn].ProcessingFlags FROM [dbo].[SnapshotData] [sn] WHERE [sn].SnapshotDataId = @OldSnapshotId END ELSE BEGIN INSERT ReportServerTempDB.dbo.[SnapshotData] ( SnapshotDataId, CreatedDate, ParamsHash, QueryParams, EffectiveParams, Description, DependsOnUser, PermanentRefCount, TransientRefCount, ExpirationDate, PageCount, HasDocMap, PaginationMode, ProcessingFlags, Machine, IsCached ) SELECT @NewSnapshotId, [sn].CreatedDate, [sn].ParamsHash, [sn].QueryParams, [sn].EffectiveParams, [sn].Description, [sn].DependsOnUser, 0, 1, -- always create with transient refcount of 1 [sn].ExpirationDate, [sn].PageCount, [sn].HasDocMap, [sn].PaginationMode, [sn].ProcessingFlags, @Machine, [sn].IsCached FROM ReportServerTempDB.dbo.[SnapshotData] [sn] WHERE [sn].SnapshotDataId = @OldSnapshotId END EXEC [dbo].[CopyChunks] @OldSnapshotId = @OldSnapshotId, @NewSnapshotId = @NewSnapshotId, @IsPermanentSnapshot = @IsPermanentSnapshot END GO GRANT EXECUTE ON [dbo].[CreateNewSnapshotVersion] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSnapshotReferences]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSnapshotReferences] GO CREATE PROCEDURE [dbo].[UpdateSnapshotReferences] @OldSnapshotId UNIQUEIDENTIFIER, @NewSnapshotId UNIQUEIDENTIFIER, @IsPermanentSnapshot BIT, @TransientRefCountModifier INT, @UpdatedReferences INT OUTPUT AS BEGIN SET @UpdatedReferences = 0 IF(@IsPermanentSnapshot = 1) BEGIN -- Update Snapshot Executions UPDATE [dbo].[Catalog] SET [SnapshotDataID] = @NewSnapshotId WHERE [SnapshotDataID] = @OldSnapshotId SELECT @UpdatedReferences = @UpdatedReferences + @@ROWCOUNT -- Update History UPDATE [dbo].[History] SET [SnapshotDataID] = @NewSnapshotId WHERE [SnapshotDataID] = @OldSnapshotId SELECT @UpdatedReferences = @UpdatedReferences + @@ROWCOUNT UPDATE [dbo].[SnapshotData] SET [PermanentRefcount] = [PermanentRefcount] - @UpdatedReferences, [TransientRefcount] = [TransientRefcount] + @TransientRefCountModifier WHERE [SnapshotDataID] = @OldSnapshotId UPDATE [dbo].[SnapshotData] SET [PermanentRefcount] = [PermanentRefcount] + @UpdatedReferences WHERE [SnapshotDataID] = @NewSnapshotId END ELSE BEGIN -- Update Execution Cache UPDATE ReportServerTempDB.dbo.[ExecutionCache] SET [SnapshotDataID] = @NewSnapshotId WHERE [SnapshotDataID] = @OldSnapshotId SELECT @UpdatedReferences = @UpdatedReferences + @@ROWCOUNT UPDATE ReportServerTempDB.dbo.[SnapshotData] SET [PermanentRefcount] = [PermanentRefcount] - @UpdatedReferences, [TransientRefcount] = [TransientRefcount] + @TransientRefCountModifier WHERE [SnapshotDataID] = @OldSnapshotId UPDATE ReportServerTempDB.dbo.[SnapshotData] SET [PermanentRefcount] = [PermanentRefcount] + @UpdatedReferences WHERE [SnapshotDataID] = @NewSnapshotId END END GO GRANT EXECUTE ON [dbo].[UpdateSnapshotReferences] TO RSExecRole GO -------------------------------------------------- ------------- Segmented Chunk Infrastructure -------------------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[OpenSegmentedChunk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[OpenSegmentedChunk] GO create proc [dbo].[OpenSegmentedChunk] @SnapshotId uniqueidentifier, @IsPermanent bit, @ChunkName nvarchar(260), @ChunkType int as begin if (@IsPermanent = 1) begin select chunk.ChunkId, chunk.ChunkFlags, seg.SegmentId, seg.LogicalByteCount as LogicalSegmentLength, seg.ActualByteCount as ActualSegmentLength from dbo.SegmentedChunk chunk left outer join ChunkSegmentMapping csm on (chunk.ChunkId = csm.ChunkId) left outer join Segment seg on (seg.SegmentId = csm.SegmentId) where chunk.SnapshotDataId = @SnapshotId and chunk.ChunkName = @ChunkName and chunk.ChunkType = @ChunkType order by csm.StartByte asc option (loop join) -- NLJ to prevent hash/merge join over scan end else begin select chunk.ChunkId, chunk.ChunkFlags, seg.SegmentId, seg.LogicalByteCount as LogicalSegmentLength, seg.ActualByteCount as ActualSegmentLength from ReportServerTempDB.dbo.SegmentedChunk chunk left outer join ReportServerTempDB.dbo.ChunkSegmentMapping csm on (chunk.ChunkId = csm.ChunkId) left outer join ReportServerTempDB.dbo.Segment seg on (seg.SegmentId = csm.SegmentId) where chunk.SnapshotDataId = @SnapshotId and chunk.ChunkName = @ChunkName and chunk.ChunkType = @ChunkType order by csm.StartByte asc option (loop join) -- NLJ to prevent hash/merge join over scan end end GO GRANT EXECUTE ON [dbo].[OpenSegmentedChunk] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateSegmentedChunk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateSegmentedChunk] GO create proc [dbo].[CreateSegmentedChunk] @SnapshotId uniqueidentifier, @IsPermanent bit, @ChunkName nvarchar(260), @ChunkFlags tinyint, @ChunkType int, @Version smallint, @MimeType nvarchar(260) = null, @Machine nvarchar(512), @ChunkId uniqueidentifier out as begin declare @output table (ChunkId uniqueidentifier) ; if (@IsPermanent = 1) begin delete SegmentedChunk where SnapshotDataId = @SnapshotId and ChunkName = @ChunkName and ChunkType = @ChunkType delete ChunkData where SnapshotDataID = @SnapshotId and ChunkName = @ChunkName and ChunkType = @ChunkType insert SegmentedChunk(SnapshotDataId, ChunkFlags, ChunkName, ChunkType, Version, MimeType) output inserted.ChunkId into @output values (@SnapshotId, @ChunkFlags, @ChunkName, @ChunkType, @Version, @MimeType) ; end else begin delete ReportServerTempDB.dbo.SegmentedChunk where SnapshotDataId = @SnapshotId and ChunkName = @ChunkName and ChunkType = @ChunkType delete ReportServerTempDB.dbo.ChunkData where SnapshotDataID = @SnapshotId and ChunkName = @ChunkName and ChunkType = @ChunkType insert ReportServerTempDB.dbo.SegmentedChunk(SnapshotDataId, ChunkFlags, ChunkName, ChunkType, Version, MimeType, Machine) output inserted.ChunkId into @output values (@SnapshotId, @ChunkFlags, @ChunkName, @ChunkType, @Version, @MimeType, @Machine) ; end select top 1 @ChunkId = ChunkId from @output end GO GRANT EXECUTE ON [dbo].[CreateSegmentedChunk] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadChunkSegment]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadChunkSegment] GO create proc [dbo].[ReadChunkSegment] @ChunkId uniqueidentifier, @SegmentId uniqueidentifier, @IsPermanent bit, @DataIndex int, @Length int as begin if(@IsPermanent = 1) begin select substring(seg.Content, @DataIndex + 1, @Length) as [Content] from Segment seg join ChunkSegmentMapping csm on (csm.SegmentId = seg.SegmentId) where csm.ChunkId = @ChunkId and csm.SegmentId = @SegmentId end else begin select substring(seg.Content, @DataIndex + 1, @Length) as [Content] from ReportServerTempDB.dbo.Segment seg join ReportServerTempDB.dbo.ChunkSegmentMapping csm on (csm.SegmentId = seg.SegmentId) where csm.ChunkId = @ChunkId and csm.SegmentId = @SegmentId end end GO GRANT EXECUTE ON [dbo].[ReadChunkSegment] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteChunkSegment]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteChunkSegment] GO create proc [dbo].[WriteChunkSegment] @ChunkId uniqueidentifier, @IsPermanent bit, @SegmentId uniqueidentifier, @DataIndex int, @Length int, @LogicalByteCount int, @Content varbinary(max) as begin if(@IsPermanent = 1) begin update Segment set LogicalByteCount = @LogicalByteCount, Content.write( substring(@Content, 1, @Length), @DataIndex, @Length ) from ChunkSegmentMapping csm where Segment.SegmentId = csm.SegmentId and csm.ChunkId = @ChunkId and csm.SegmentId = @SegmentId ; end else begin update ReportServerTempDB.dbo.Segment set LogicalByteCount = @LogicalByteCount, Content.write( substring(@Content, 1, @Length), @DataIndex, @Length ) from ReportServerTempDB.dbo.ChunkSegmentMapping csm where ReportServerTempDB.dbo.Segment.SegmentId = csm.SegmentId and csm.ChunkId = @ChunkId and csm.SegmentId = @SegmentId ; end if(@@rowcount <> 1) raiserror('unexpected # of segments update', 16, 1) end GO GRANT EXECUTE ON [dbo].[WriteChunkSegment] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateChunkSegment]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateChunkSegment] GO create proc [dbo].[CreateChunkSegment] @SnapshotId uniqueidentifier, @IsPermanent bit, @ChunkId uniqueidentifier, @Content varbinary(max) = 0x0, @StartByte bigint, @Length int = 0, @LogicalByteCount int = 0, @SegmentId uniqueidentifier out as begin declare @output table (SegmentId uniqueidentifier) if(@IsPermanent = 1) begin insert Segment(LogicalByteCount, Content) output inserted.SegmentId into @output values (@LogicalByteCount, substring(@Content, 1, @Length)) ; select top 1 @SegmentId = SegmentId from @output ; insert ChunkSegmentMapping(ChunkId, SegmentId, StartByte) values (@ChunkId, @SegmentId, @StartByte) ; end else begin insert ReportServerTempDB..Segment(LogicalByteCount, Content) output inserted.SegmentId into @output values (@LogicalByteCount, substring(@Content, 1, @Length)) ; select top 1 @SegmentId = SegmentId from @output ; insert ReportServerTempDB.dbo.ChunkSegmentMapping(ChunkId, SegmentId, StartByte) values (@ChunkId, @SegmentId, @StartByte) ; end end GO GRANT EXECUTE ON [dbo].[CreateChunkSegment] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[IsSegmentedChunk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[IsSegmentedChunk] GO create proc [dbo].[IsSegmentedChunk] @SnapshotId uniqueidentifier, @IsPermanent bit, @ChunkName nvarchar(260), @ChunkType int, @IsSegmented bit out as begin -- segmented chunks are read w/nolock -- we don't really care about locking in this scenario -- we just need to get some metadata which never changes (if it is segmented or not) if (@IsPermanent = 1) begin select top 1 @IsSegmented = IsSegmented from ( select convert(bit, 0) from [ChunkData] c where c.ChunkName = @ChunkName and c.ChunkType = @ChunkType and c.SnapshotDataId = @SnapshotId union all select convert(bit, 1) from [SegmentedChunk] c WITH(NOLOCK) where c.ChunkName = @ChunkName and c.ChunkType = @ChunkType and c.SnapshotDataId = @SnapshotId ) A(IsSegmented) end else begin select top 1 @IsSegmented = IsSegmented from ( select convert(bit, 0) from ReportServerTempDB.dbo.[ChunkData] c where c.ChunkName = @ChunkName and c.ChunkType = @ChunkType and c.SnapshotDataId = @SnapshotId union all select convert(bit, 1) from ReportServerTempDB.dbo.[SegmentedChunk] c WITH(NOLOCK) where c.ChunkName = @ChunkName and c.ChunkType = @ChunkType and c.SnapshotDataId = @SnapshotId ) A(IsSegmented) end end GO GRANT EXECUTE ON [dbo].[IsSegmentedChunk] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ShallowCopyChunk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ShallowCopyChunk] GO create proc [dbo].[ShallowCopyChunk] @SnapshotId uniqueidentifier, @ChunkId uniqueidentifier, @IsPermanent bit, @Machine nvarchar(512), @NewChunkId uniqueidentifier out as begin -- @SnapshotId & @ChunkId are the old identifiers -- build the chunksegmentmapping first to prevent race -- condition with cleaning it up select @NewChunkId = newid() ; if (@IsPermanent = 1) begin insert ChunkSegmentMapping (ChunkId, SegmentId, StartByte) select @NewChunkId, SegmentId, StartByte from ChunkSegmentMapping where ChunkId = @ChunkId ; update SegmentedChunk set ChunkId = @NewChunkId where ChunkId = @ChunkId and SnapshotDataId = @SnapshotId end else begin insert ReportServerTempDB.dbo.ChunkSegmentMapping (ChunkId, SegmentId, StartByte) select @NewChunkId, SegmentId, StartByte from ReportServerTempDB.dbo.ChunkSegmentMapping where ChunkId = @ChunkId ; -- update the machine name also, this is only really useful -- for file system chunks, in which case the snapshot should -- have been versioned on the initial update update ReportServerTempDB.dbo.SegmentedChunk set ChunkId = @NewChunkId, Machine = @Machine where ChunkId = @ChunkId and SnapshotDataId = @SnapshotId end end GO GRANT EXECUTE ON [dbo].[ShallowCopyChunk] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeepCopySegment]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeepCopySegment] GO create proc [dbo].[DeepCopySegment] @ChunkId uniqueidentifier, @IsPermanent bit, @SegmentId uniqueidentifier, @NewSegmentId uniqueidentifier out as begin select @NewSegmentId = newid() ; if (@IsPermanent = 1) begin insert Segment(SegmentId, LogicalByteCount, Content) select @NewSegmentId, seg.LogicalByteCount, seg.Content from Segment seg where seg.SegmentId = @SegmentId ; update ChunkSegmentMapping set SegmentId = @NewSegmentId where ChunkId = @ChunkId and SegmentId = @SegmentId ; end else begin insert ReportServerTempDB.dbo.Segment(SegmentId, LogicalByteCount, Content) select @NewSegmentId, seg.LogicalByteCount, seg.Content from ReportServerTempDB.dbo.Segment seg where seg.SegmentId = @SegmentId ; update ReportServerTempDB.dbo.ChunkSegmentMapping set SegmentId = @NewSegmentId where ChunkId = @ChunkId and SegmentId = @SegmentId ; end end GO GRANT EXECUTE ON [dbo].[DeepCopySegment] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSegmentMapCleanupCandidates]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSegmentMapCleanupCandidates] GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSegmentCleanupCandidates]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSegmentCleanupCandidates] GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RemoveSegmentedMapping]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RemoveSegmentedMapping] GO create proc [dbo].[RemoveSegmentedMapping] @DeleteCountPermanentMapping int, @DeleteCountTempChunk int, @DeleteCountTempMapping int, @MachineName nvarchar(260) as begin SET DEADLOCK_PRIORITY LOW declare @deleted table ( ChunkID uniqueidentifier, IsPermanent bit ); -- details on lock hints: -- we use readpast on ChunkSegmentMapping to skip past -- rows which are currently locked. they are being actively -- used so clearly we do not want to delete them. we use -- nolock on SegmentedChunk table as well, this is because -- regardless of whether or not that row is locked, we want to -- know if it is referenced by a SegmentedChunk and if -- so we do not want to delete the mapping row. ChunkIds are -- only modified when creating a shallow chunk copy(see ShallowCopyChunk), -- but in this case the ChunkSegmentMapping row is locked (via the insert) -- so we are safe. declare @toDeleteChunks table ( ChunkId uniqueidentifier ); -- clean up mappings from permanent database insert into @toDeleteChunks (ChunkId) select top (@DeleteCountPermanentMapping) ChunkId from ChunkSegmentMapping with (readpast) where not exists ( select 1 from SegmentedChunk SC with (nolock) where SC.ChunkId = ChunkSegmentMapping.ChunkId ) ; delete from ChunkSegmentMapping with (readpast) output deleted.ChunkId, convert(bit, 1) into @deleted where ChunkSegmentMapping.ChunkId in ( select td.ChunkId from @toDeleteChunks td where not exists ( select 1 from SegmentedChunk SC where SC.ChunkId = td.ChunkId )) declare @toDeleteTempChunks table ( SnapshotDataId uniqueidentifier); -- clean up SegmentedChunks from the Temp database -- for locking we play the same idea as in the previous query. -- snapshotIds never change, so again this operation is safe. insert into @toDeleteTempChunks (SnapshotDataId) select top (@DeleteCountTempChunk) SnapshotDataId from ReportServerTempDB.dbo.SegmentedChunk with (readpast) where ReportServerTempDB.dbo.SegmentedChunk.Machine = @MachineName and not exists ( select 1 from ReportServerTempDB.dbo.SnapshotData SD with (nolock) where ReportServerTempDB.dbo.SegmentedChunk.SnapshotDataId = SD.SnapshotDataID ) ; delete from ReportServerTempDB.dbo.SegmentedChunk with (readpast) where ReportServerTempDB.dbo.SegmentedChunk.SnapshotDataId in ( select td.SnapshotDataId from @toDeleteTempChunks td where not exists ( select 1 from ReportServerTempDB.dbo.SnapshotData SD where td.SnapshotDataId = SD.SnapshotDataID )) ; declare @toDeleteTempMappings table ( ChunkId uniqueidentifier ); -- clean up mappings from temp database insert into @toDeleteTempMappings (ChunkId) select top (@DeleteCountTempMapping) ChunkId from ReportServerTempDB.dbo.ChunkSegmentMapping with (readpast) where not exists ( select 1 from ReportServerTempDB.dbo.SegmentedChunk SC with (nolock) where SC.ChunkId = ReportServerTempDB.dbo.ChunkSegmentMapping.ChunkId ) ; delete from ReportServerTempDB.dbo.ChunkSegmentMapping with (readpast) output deleted.ChunkId, convert(bit, 0) into @deleted where ReportServerTempDB.dbo.ChunkSegmentMapping.ChunkId in ( select td.ChunkId from @toDeleteTempMappings td where not exists ( select 1 from ReportServerTempDB.dbo.SegmentedChunk SC where td.ChunkId = SC.ChunkId )) ; -- need to return these so we can cleanup file system chunks select distinct ChunkID, IsPermanent from @deleted ; end GO GRANT EXECUTE ON [dbo].[RemoveSegmentedMapping] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RemoveSegment]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RemoveSegment] GO create proc [dbo].[RemoveSegment] @DeleteCountPermanent int, @DeleteCountTemp int as begin SET DEADLOCK_PRIORITY LOW -- Locking: -- Similar idea as in RemovedSegmentedMapping. Readpast -- any Segments which are currently locked and run the -- inner scan with nolock. declare @numDeleted int; declare @toDeleteMapping table ( SegmentId uniqueidentifier ); insert into @toDeleteMapping (SegmentId) select top (@DeleteCountPermanent) SegmentId from Segment with (readpast) where not exists ( select 1 from ChunkSegmentMapping CSM with (nolock) where CSM.SegmentId = Segment.SegmentId ) ; delete from Segment with (readpast) where Segment.SegmentId in ( select td.SegmentId from @toDeleteMapping td where not exists ( select 1 from ChunkSegmentMapping CSM where CSM.SegmentId = td.SegmentId )); select @numDeleted = @@rowcount ; declare @toDeleteTempSegment table ( SegmentId uniqueidentifier ); insert into @toDeleteTempSegment (SegmentId) select top (@DeleteCountTemp) SegmentId from ReportServerTempDB.dbo.Segment with (readpast) where not exists ( select 1 from ReportServerTempDB.dbo.ChunkSegmentMapping CSM with (nolock) where CSM.SegmentId = ReportServerTempDB.dbo.Segment.SegmentId ) ; delete from ReportServerTempDB.dbo.Segment with (readpast) where ReportServerTempDB.dbo.Segment.SegmentId in ( select td.SegmentId from @toDeleteTempSegment td where not exists ( select 1 from ReportServerTempDB.dbo.ChunkSegmentMapping CSM where CSM.SegmentId = td.SegmentId )) ; select @numDeleted = @numDeleted + @@rowcount ; select @numDeleted; end GO GRANT EXECUTE ON [dbo].[RemoveSegment] TO RSExecRole GO -- END STORED PROCEDURESPASET ANSI_NULLS ON GO SET ANSI_PADDING ON GO SET ANSI_WARNINGS ON GO SET ARITHABORT ON GO SET CONCAT_NULL_YIELDS_NULL ON GO SET NUMERIC_ROUNDABORT OFF GO SET QUOTED_IDENTIFIER ON GO -- START STORED PROCEDURES if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetKeysForInstallation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetKeysForInstallation] GO CREATE PROCEDURE [dbo].[SetKeysForInstallation] @InstallationID uniqueidentifier, @SymmetricKey image = NULL, @PublicKey image AS update [dbo].[Keys] set [SymmetricKey] = @SymmetricKey, [PublicKey] = @PublicKey where [InstallationID] = @InstallationID and [Client] = 1 GO GRANT EXECUTE ON [dbo].[SetKeysForInstallation] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAnnouncedKey]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAnnouncedKey] GO CREATE PROCEDURE [dbo].[GetAnnouncedKey] @InstallationID uniqueidentifier AS select PublicKey, MachineName, InstanceName from Keys where InstallationID = @InstallationID and Client = 1 GO GRANT EXECUTE ON [dbo].[GetAnnouncedKey] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AnnounceOrGetKey]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AnnounceOrGetKey] GO CREATE PROCEDURE [dbo].[AnnounceOrGetKey] @MachineName nvarchar(256), @InstanceName nvarchar(32), @InstallationID uniqueidentifier, @PublicKey image, @NumAnnouncedServices int OUTPUT AS -- Acquire lock IF NOT EXISTS (SELECT * FROM [dbo].[Keys] WITH(XLOCK) WHERE [Client] < 0) BEGIN RAISERROR('Keys lock row not found', 16, 1) RETURN END -- Get the number of services that have already announced their presence SELECT @NumAnnouncedServices = count(*) FROM [dbo].[Keys] WHERE [Client] = 1 DECLARE @StoredInstallationID uniqueidentifier DECLARE @StoredInstanceName nvarchar(32) SELECT @StoredInstallationID = [InstallationID], @StoredInstanceName = [InstanceName] FROM [dbo].[Keys] WHERE [InstallationID] = @InstallationID AND [Client] = 1 IF @StoredInstallationID IS NULL -- no record present BEGIN INSERT INTO [dbo].[Keys] ([MachineName], [InstanceName], [InstallationID], [Client], [PublicKey], [SymmetricKey]) VALUES (@MachineName, @InstanceName, @InstallationID, 1, @PublicKey, null) END ELSE BEGIN IF @StoredInstanceName IS NULL BEGIN UPDATE [dbo].[Keys] SET [InstanceName] = @InstanceName WHERE [InstallationID] = @InstallationID AND [Client] = 1 END END SELECT [MachineName], [SymmetricKey], [PublicKey] FROM [Keys] WHERE [InstallationID] = @InstallationID and [Client] = 1 GO GRANT EXECUTE ON [dbo].[AnnounceOrGetKey] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetMachineName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetMachineName] GO CREATE PROCEDURE [dbo].[SetMachineName] @MachineName nvarchar(256), @InstallationID uniqueidentifier AS UPDATE [dbo].[Keys] SET MachineName = @MachineName WHERE [InstallationID] = @InstallationID and [Client] = 1 GO GRANT EXECUTE ON [dbo].[SetMachineName] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListInstallations]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListInstallations] GO CREATE PROCEDURE [dbo].[ListInstallations] AS SELECT [MachineName], [InstanceName], [InstallationID], CASE WHEN [SymmetricKey] IS null THEN 0 ELSE 1 END FROM [dbo].[Keys] WHERE [Client] = 1 GO GRANT EXECUTE ON [dbo].[ListInstallations] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListSubscriptionIDs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListSubscriptionIDs] GO CREATE PROCEDURE [dbo].[ListSubscriptionIDs] AS SELECT [SubscriptionID] FROM [dbo].[Subscriptions] WITH (XLOCK, TABLOCK) GO GRANT EXECUTE ON [dbo].ListSubscriptionIDs TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListInfoForReencryption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListInfoForReencryption] GO CREATE PROCEDURE [dbo].[ListInfoForReencryption] AS SELECT [DSID] FROM [dbo].[DataSource] WITH (XLOCK, TABLOCK) SELECT [SubscriptionID] FROM [dbo].[Subscriptions] WITH (XLOCK, TABLOCK) SELECT [InstallationID], [PublicKey] FROM [dbo].[Keys] WITH (XLOCK, TABLOCK) WHERE [Client] = 1 AND ([SymmetricKey] IS NOT NULL) GO GRANT EXECUTE ON [dbo].[ListInfoForReencryption] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDatasourceInfoForReencryption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDatasourceInfoForReencryption] GO CREATE PROCEDURE [dbo].[GetDatasourceInfoForReencryption] @DSID as uniqueidentifier AS SELECT [ConnectionString], [OriginalConnectionString], [UserName], [Password], [CredentialRetrieval], [Version] FROM [dbo].[DataSource] WHERE [DSID] = @DSID GO GRANT EXECUTE ON [dbo].[GetDatasourceInfoForReencryption] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetReencryptedDatasourceInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetReencryptedDatasourceInfo] GO CREATE PROCEDURE [dbo].[SetReencryptedDatasourceInfo] @DSID uniqueidentifier, @ConnectionString image = NULL, @OriginalConnectionString image = NULL, @UserName image = NULL, @Password image = NULL, @CredentialRetrieval int, @Version int AS UPDATE [dbo].[DataSource] SET [ConnectionString] = @ConnectionString, [OriginalConnectionString] = @OriginalConnectionString, [UserName] = @UserName, [Password] = @Password, [CredentialRetrieval] = @CredentialRetrieval, [Version] = @Version WHERE [DSID] = @DSID GO GRANT EXECUTE ON [dbo].[SetReencryptedDatasourceInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSubscriptionInfoForReencryption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSubscriptionInfoForReencryption] GO CREATE PROCEDURE [dbo].[GetSubscriptionInfoForReencryption] @SubscriptionID as uniqueidentifier AS SELECT [DeliveryExtension], [ExtensionSettings], [Version] FROM [dbo].[Subscriptions] WHERE [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetSubscriptionInfoForReencryption] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetReencryptedSubscriptionInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetReencryptedSubscriptionInfo] GO CREATE PROCEDURE [dbo].[SetReencryptedSubscriptionInfo] @SubscriptionID as uniqueidentifier, @ExtensionSettings as ntext = NULL, @Version as int AS UPDATE [dbo].[Subscriptions] SET [ExtensionSettings] = @ExtensionSettings, [Version] = @Version WHERE [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[SetReencryptedSubscriptionInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteEncryptedContent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteEncryptedContent] GO CREATE PROCEDURE [dbo].[DeleteEncryptedContent] AS -- Remove the encryption keys delete from keys where client >= 0 -- Remove the encrypted content update datasource set CredentialRetrieval = 1, -- CredentialRetrieval.Prompt ConnectionString = null, OriginalConnectionString = null, UserName = null, Password = null GO GRANT EXECUTE ON [dbo].[DeleteEncryptedContent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteKey]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteKey] GO CREATE PROCEDURE [dbo].[DeleteKey] @InstallationID uniqueidentifier AS if (@InstallationID = '00000000-0000-0000-0000-000000000000') RAISERROR('Cannot delete reserved key', 16, 1) -- Remove the encryption keys delete from keys where InstallationID = @InstallationID and Client = 1 GO GRANT EXECUTE ON [dbo].[DeleteKey] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAllConfigurationInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAllConfigurationInfo] GO CREATE PROCEDURE [dbo].[GetAllConfigurationInfo] AS SELECT [Name], [Value] FROM [ConfigurationInfo] GO GRANT EXECUTE ON [dbo].[GetAllConfigurationInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetOneConfigurationInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetOneConfigurationInfo] GO CREATE PROCEDURE [dbo].[GetOneConfigurationInfo] @Name nvarchar (260) AS SELECT [Value] FROM [ConfigurationInfo] WHERE [Name] = @Name GO GRANT EXECUTE ON [dbo].[GetOneConfigurationInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetConfigurationInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetConfigurationInfo] GO CREATE PROCEDURE [dbo].[SetConfigurationInfo] @Name nvarchar (260), @Value ntext AS DELETE FROM [ConfigurationInfo] WHERE [Name] = @Name IF @Value is not null BEGIN INSERT INTO ConfigurationInfo VALUES ( newid(), @Name, @Value ) END GO GRANT EXECUTE ON [dbo].[SetConfigurationInfo] TO RSExecRole if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddEvent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddEvent] GO CREATE PROCEDURE [dbo].[AddEvent] @EventType nvarchar (260), @EventData nvarchar (260) AS insert into [Event] ([EventID], [EventType], [EventData], [TimeEntered], [ProcessStart], [BatchID]) values (NewID(), @EventType, @EventData, GETUTCDATE(), NULL, NULL) GO GRANT EXECUTE ON [dbo].[AddEvent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteEvent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteEvent] GO CREATE PROCEDURE [dbo].[DeleteEvent] @ID uniqueidentifier AS delete from [Event] where [EventID] = @ID GO GRANT EXECUTE ON [dbo].[DeleteEvent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanEventRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanEventRecords] GO CREATE PROCEDURE [dbo].[CleanEventRecords] @MaxAgeMinutes int AS -- Reset all notifications which have been add over n minutes ago Update [Event] set [ProcessStart] = NULL, [ProcessHeartbeat] = NULL where [EventID] in ( SELECT [EventID] FROM [Event] WHERE [ProcessHeartbeat] < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) ) GO GRANT EXECUTE ON [dbo].[CleanEventRecords] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddExecutionLogEntry]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddExecutionLogEntry] GO CREATE PROCEDURE [dbo].[AddExecutionLogEntry] @InstanceName nvarchar(38), @Report nvarchar(260), @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @RequestType bit, @Format nvarchar(26), @Parameters ntext, @TimeStart DateTime, @TimeEnd DateTime, @TimeDataRetrieval int, @TimeProcessing int, @TimeRendering int, @Source tinyint, @Status nvarchar(32), @ByteCount bigint, @RowCount bigint, @ExecutionId nvarchar(64) = null, @ReportAction tinyint, @AdditionalInfo xml = null AS -- Unless is is specifically 'False', it's true if exists (select * from ConfigurationInfo where [Name] = 'EnableExecutionLogging' and [Value] like 'False') begin return end Declare @ReportID uniqueidentifier select @ReportID = ItemID from Catalog with (nolock) where Path = @Report insert into ExecutionLogStorage (InstanceName, ReportID, UserName, ExecutionId, RequestType, [Format], Parameters, ReportAction, TimeStart, TimeEnd, TimeDataRetrieval, TimeProcessing, TimeRendering, Source, Status, ByteCount, [RowCount], AdditionalInfo) Values (@InstanceName, @ReportID, @UserName, @ExecutionId, @RequestType, @Format, @Parameters, @ReportAction, @TimeStart, @TimeEnd, @TimeDataRetrieval, @TimeProcessing, @TimeRendering, @Source, @Status, @ByteCount, @RowCount, @AdditionalInfo) GO GRANT EXECUTE ON [dbo].[AddExecutionLogEntry] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ExpireExecutionLogEntries]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ExpireExecutionLogEntries] GO CREATE PROCEDURE [dbo].[ExpireExecutionLogEntries] AS SET NOCOUNT OFF -- -1 means no expiration if exists (select * from ConfigurationInfo where [Name] = 'ExecutionLogDaysKept' and CAST(CAST(Value as nvarchar) as integer) = -1) begin return end delete from ExecutionLogStorage where DateDiff(day, TimeStart, getdate()) >= (select CAST(CAST(Value as nvarchar) as integer) from ConfigurationInfo where [Name] = 'ExecutionLogDaysKept') GO GRANT EXECUTE ON [dbo].[ExpireExecutionLogEntries] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUserIDBySid]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUserIDBySid] GO -- looks up any user name by its SID, if not it creates a regular user CREATE PROCEDURE [dbo].[GetUserIDBySid] @UserSid varbinary(85), @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS SELECT @UserID = (SELECT UserID FROM Users WHERE Sid = @UserSid AND AuthType = @AuthType) IF @UserID IS NULL BEGIN SET @UserID = newid() INSERT INTO Users (UserID, Sid, UserType, AuthType, UserName) VALUES (@UserID, @UserSid, 0, @AuthType, @UserName) END GO GRANT EXECUTE ON [dbo].[GetUserIDBySid] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUserIDByName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUserIDByName] GO -- looks up any user name by its User Name, if not it creates a regular user CREATE PROCEDURE [dbo].[GetUserIDByName] @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS SELECT @UserID = (SELECT UserID FROM Users WHERE UserName = @UserName AND AuthType = @AuthType) IF @UserID IS NULL BEGIN SET @UserID = newid() INSERT INTO Users (UserID, Sid, UserType, AuthType, UserName) VALUES (@UserID, NULL, 0, @AuthType, @UserName) END GO GRANT EXECUTE ON [dbo].[GetUserIDByName] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUserID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUserID] GO -- looks up any user name, if not it creates a regular user - uses Sid CREATE PROCEDURE [dbo].[GetUserID] @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS IF @AuthType = 1 -- Windows BEGIN EXEC GetUserIDBySid @UserSid, @UserName, @AuthType, @UserID OUTPUT END ELSE BEGIN EXEC GetUserIDByName @UserName, @AuthType, @UserID OUTPUT END GO GRANT EXECUTE ON [dbo].[GetUserID] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPrincipalID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPrincipalID] GO -- looks up a principal, if not there looks up regular users and turns them into principals -- if not, it creates a principal CREATE PROCEDURE [dbo].[GetPrincipalID] @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @UserID uniqueidentifier OUTPUT AS -- windows auth IF @AuthType = 1 BEGIN -- is this a principal? SELECT @UserID = (SELECT UserID FROM Users WHERE Sid = @UserSid AND UserType = 1 AND AuthType = @AuthType) END ELSE BEGIN -- is this a principal? SELECT @UserID = (SELECT UserID FROM Users WHERE UserName = @UserName AND UserType = 1 AND AuthType = @AuthType) END IF @UserID IS NULL BEGIN IF @AuthType = 1 -- Windows BEGIN -- Is this a regular user SELECT @UserID = (SELECT UserID FROM Users WHERE Sid = @UserSid AND UserType = 0 AND AuthType = @AuthType) END ELSE BEGIN -- Is this a regular user SELECT @UserID = (SELECT UserID FROM Users WHERE UserName = @UserName AND UserType = 0 AND AuthType = @AuthType) END -- No, create a new principal IF @UserID IS NULL BEGIN SET @UserID = newid() INSERT INTO Users (UserID, Sid, UserType, AuthType, UserName) VALUES (@UserID, @UserSid, 1, @AuthType, @UserName) END ELSE BEGIN UPDATE Users SET UserType = 1 WHERE UserID = @UserID END END GO GRANT EXECUTE ON [dbo].[GetPrincipalID] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateSubscription] GO CREATE PROCEDURE [dbo].[CreateSubscription] @id uniqueidentifier, @Locale nvarchar (128), @Report_Name nvarchar (425), @OwnerSid varbinary (85) = NULL, @OwnerName nvarchar(260), @OwnerAuthType int, @DeliveryExtension nvarchar (260) = NULL, @InactiveFlags int, @ExtensionSettings ntext = NULL, @ModifiedBySid varbinary (85) = NULL, @ModifiedByName nvarchar(260), @ModifiedByAuthType int, @ModifiedDate datetime, @Description nvarchar(512) = NULL, @LastStatus nvarchar(260) = NULL, @EventType nvarchar(260), @MatchData ntext = NULL, @Parameters ntext = NULL, @DataSettings ntext = NULL, @Version int AS -- Create a subscription with the given data. The name must match a name in the -- Catalog table and it must be a report type (2) or linked report (4) DECLARE @Report_OID uniqueidentifier DECLARE @OwnerID uniqueidentifier DECLARE @ModifiedByID uniqueidentifier DECLARE @TempDeliveryID uniqueidentifier --Get the report id for this subscription select @Report_OID = (select [ItemID] from [Catalog] where [Catalog].[Path] = @Report_Name and ([Catalog].[Type] = 2 or [Catalog].[Type] = 4)) EXEC GetUserID @OwnerSid, @OwnerName, @OwnerAuthType, @OwnerID OUTPUT EXEC GetUserID @ModifiedBySid, @ModifiedByName, @ModifiedByAuthType, @ModifiedByID OUTPUT if (@Report_OID is NULL) begin RAISERROR('Report Not Found', 16, 1) return end Insert into Subscriptions ( [SubscriptionID], [OwnerID], [Report_OID], [Locale], [DeliveryExtension], [InactiveFlags], [ExtensionSettings], [ModifiedByID], [ModifiedDate], [Description], [LastStatus], [EventType], [MatchData], [LastRunTime], [Parameters], [DataSettings], [Version] ) values (@id, @OwnerID, @Report_OID, @Locale, @DeliveryExtension, @InactiveFlags, @ExtensionSettings, @ModifiedByID, @ModifiedDate, @Description, @LastStatus, @EventType, @MatchData, NULL, @Parameters, @DataSettings, @Version) GO GRANT EXECUTE ON [dbo].[CreateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeliveryRemovedInactivateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeliveryRemovedInactivateSubscription] GO CREATE PROCEDURE [dbo].[DeliveryRemovedInactivateSubscription] @DeliveryExtension nvarchar(260), @Status nvarchar(260) AS update Subscriptions set [DeliveryExtension] = '', [InactiveFlags] = [InactiveFlags] | 1, -- Delivery Provider Removed Flag == 1 [LastStatus] = @Status where [DeliveryExtension] = @DeliveryExtension GO GRANT EXECUTE ON [dbo].[DeliveryRemovedInactivateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddSubscriptionToBeingDeleted]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddSubscriptionToBeingDeleted] GO CREATE PROCEDURE [dbo].[AddSubscriptionToBeingDeleted] @SubscriptionID uniqueidentifier AS -- Delete subscription if it is already in this table -- Delete orphaned subscriptions, based on the age criteria: > 10 minutes delete from [SubscriptionsBeingDeleted] where (SubscriptionID = @SubscriptionID) or (DATEDIFF( minute, [CreationDate], GetUtcDate() ) > 10) -- Add subscription being deleted into the DeletedSubscription table insert into [SubscriptionsBeingDeleted] VALUES(@SubscriptionID, GetUtcDate()) GO GRANT EXECUTE ON [dbo].[AddSubscriptionToBeingDeleted] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RemoveSubscriptionFromBeingDeleted]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RemoveSubscriptionFromBeingDeleted] GO CREATE PROCEDURE [dbo].[RemoveSubscriptionFromBeingDeleted] @SubscriptionID uniqueidentifier AS delete from [SubscriptionsBeingDeleted] where SubscriptionID = @SubscriptionID GO GRANT EXECUTE ON [dbo].[RemoveSubscriptionFromBeingDeleted] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteSubscription] GO CREATE PROCEDURE [dbo].[DeleteSubscription] @SubscriptionID uniqueidentifier AS -- Delete the subscription delete from [Subscriptions] where [SubscriptionID] = @SubscriptionID -- Delete it from the SubscriptionsBeingDeleted EXEC RemoveSubscriptionFromBeingDeleted @SubscriptionID GO GRANT EXECUTE ON [dbo].[DeleteSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSubscription] GO CREATE PROCEDURE [dbo].[GetSubscription] @SubscriptionID uniqueidentifier AS -- Grab all of the-- subscription properties given a id select S.[SubscriptionID], S.[Report_OID], S.[Locale], S.[InactiveFlags], S.[DeliveryExtension], S.[ExtensionSettings], SUSER_SNAME(Modified.[Sid]), Modified.[UserName], S.[ModifiedDate], S.[Description], S.[LastStatus], S.[EventType], S.[MatchData], S.[Parameters], S.[DataSettings], A.[TotalNotifications], A.[TotalSuccesses], A.[TotalFailures], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], CAT.[Path], S.[LastRunTime], CAT.[Type], SD.NtSecDescPrimary, S.[Version], Owner.[AuthType] from [Subscriptions] S inner join [Catalog] CAT on S.[Report_OID] = CAT.[ItemID] inner join [Users] Owner on S.OwnerID = Owner.UserID inner join [Users] Modified on S.ModifiedByID = Modified.UserID left outer join [SecData] SD on CAT.PolicyID = SD.PolicyID AND SD.AuthType = Owner.AuthType left outer join [ActiveSubscriptions] A with (NOLOCK) on S.[SubscriptionID] = A.[SubscriptionID] where S.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListSubscriptionsUsingDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListSubscriptionsUsingDataSource] GO CREATE PROCEDURE [dbo].[ListSubscriptionsUsingDataSource] @DataSourceName nvarchar(450) AS select S.[SubscriptionID], S.[Report_OID], S.[Locale], S.[InactiveFlags], S.[DeliveryExtension], S.[ExtensionSettings], SUSER_SNAME(Modified.[Sid]), Modified.[UserName], S.[ModifiedDate], S.[Description], S.[LastStatus], S.[EventType], S.[MatchData], S.[Parameters], S.[DataSettings], A.[TotalNotifications], A.[TotalSuccesses], A.[TotalFailures], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], CAT.[Path], S.[LastRunTime], CAT.[Type], SD.NtSecDescPrimary, S.[Version], Owner.[AuthType] from [DataSource] DS inner join Catalog C on C.ItemID = DS.Link inner join Subscriptions S on S.[SubscriptionID] = DS.[SubscriptionID] inner join [Catalog] CAT on S.[Report_OID] = CAT.[ItemID] inner join [Users] Owner on S.OwnerID = Owner.UserID inner join [Users] Modified on S.ModifiedByID = Modified.UserID left join [SecData] SD on SD.[PolicyID] = CAT.[PolicyID] AND SD.AuthType = Owner.AuthType left outer join [ActiveSubscriptions] A with (NOLOCK) on S.[SubscriptionID] = A.[SubscriptionID] where C.Path = @DataSourceName GO GRANT EXECUTE ON [dbo].[ListSubscriptionsUsingDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSubscriptionStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSubscriptionStatus] GO CREATE PROCEDURE [dbo].[UpdateSubscriptionStatus] @SubscriptionID uniqueidentifier, @Status nvarchar(260) AS update Subscriptions set [LastStatus] = @Status where [SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[UpdateSubscriptionStatus] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSubscription] GO CREATE PROCEDURE [dbo].[UpdateSubscription] @id uniqueidentifier, @Locale nvarchar(260), @OwnerSid varbinary(85) = NULL, @OwnerName nvarchar(260), @OwnerAuthType int, @DeliveryExtension nvarchar(260), @InactiveFlags int, @ExtensionSettings ntext = NULL, @ModifiedBySid varbinary(85) = NULL, @ModifiedByName nvarchar(260), @ModifiedByAuthType int, @ModifiedDate datetime, @Description nvarchar(512) = NULL, @LastStatus nvarchar(260) = NULL, @EventType nvarchar(260), @MatchData ntext = NULL, @Parameters ntext = NULL, @DataSettings ntext = NULL, @Version int AS -- Update a subscription's information. DECLARE @ModifiedByID uniqueidentifier DECLARE @OwnerID uniqueidentifier EXEC GetUserID @ModifiedBySid, @ModifiedByName, @ModifiedByAuthType, @ModifiedByID OUTPUT EXEC GetUserID @OwnerSid, @OwnerName, @OwnerAuthType, @OwnerID OUTPUT -- Make sure there is a valid provider update Subscriptions set [DeliveryExtension] = @DeliveryExtension, [Locale] = @Locale, [OwnerID] = @OwnerID, [InactiveFlags] = @InactiveFlags, [ExtensionSettings] = @ExtensionSettings, [ModifiedByID] = @ModifiedByID, [ModifiedDate] = @ModifiedDate, [Description] = @Description, [LastStatus] = @LastStatus, [EventType] = @EventType, [MatchData] = @MatchData, [Parameters] = @Parameters, [DataSettings] = @DataSettings, [Version] = @Version where [SubscriptionID] = @id GO GRANT EXECUTE ON [dbo].[UpdateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[InvalidateSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[InvalidateSubscription] GO CREATE PROCEDURE [dbo].[InvalidateSubscription] @SubscriptionID uniqueidentifier, @Flags int, @LastStatus nvarchar(260) AS -- Mark all subscriptions for this report as inactive for the given flags update Subscriptions set [InactiveFlags] = S.[InactiveFlags] | @Flags, [LastStatus] = @LastStatus from Subscriptions S where SubscriptionID = @SubscriptionID GO GRANT EXECUTE ON [dbo].[InvalidateSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanNotificationRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanNotificationRecords] GO CREATE PROCEDURE [dbo].[CleanNotificationRecords] @MaxAgeMinutes int AS -- Reset all notifications which have been add over n minutes ago Update [Notifications] set [ProcessStart] = NULL, [ProcessHeartbeat] = NULL, [Attempt] = 1 where [NotificationID] in ( SELECT [NotificationID] FROM [Notifications] WHERE [ProcessHeartbeat] < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) and [Attempt] is NULL ) Update [Notifications] set [ProcessStart] = NULL, [ProcessHeartbeat] = NULL, [Attempt] = [Attempt] + 1 where [NotificationID] in ( SELECT [NotificationID] FROM [Notifications] WHERE [ProcessHeartbeat] < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) and [Attempt] is not NULL ) GO GRANT EXECUTE ON [dbo].[CleanNotificationRecords] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateSnapShotNotifications]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateSnapShotNotifications] GO CREATE PROCEDURE [dbo].[CreateSnapShotNotifications] @HistoryID uniqueidentifier, @LastRunTime datetime AS update [Subscriptions] set [LastRunTime] = @LastRunTime from History SS inner join [Subscriptions] S on S.[Report_OID] = SS.[ReportID] where SS.[HistoryID] = @HistoryID and S.EventType = 'ReportHistorySnapshotCreated' and InactiveFlags = 0 -- Find all valid subscriptions for the given report and create a new notification row for -- each subscription insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) select NewID(), S.[SubscriptionID], NULL, S.[Report_OID], NULL, S.[ExtensionSettings], S.[Locale], S.[Parameters], GETUTCDATE(), S.[LastRunTime], S.[DeliveryExtension], S.[OwnerID], 0, S.[Version] from [Subscriptions] S with (READPAST) inner join History H on S.[Report_OID] = H.[ReportID] where H.[HistoryID] = @HistoryID and S.EventType = 'ReportHistorySnapshotCreated' and InactiveFlags = 0 and S.[DataSettings] is null -- Create any data driven subscription by creating a data driven event insert into [Event] ( [EventID], [EventType], [EventData], [TimeEntered] ) select NewID(), 'DataDrivenSubscription', S.SubscriptionID, GETUTCDATE() from [Subscriptions] S with (READPAST) inner join History H on S.[Report_OID] = H.[ReportID] where H.[HistoryID] = @HistoryID and S.EventType = 'ReportHistorySnapshotCreated' and InactiveFlags = 0 and S.[DataSettings] is not null GO GRANT EXECUTE ON [dbo].[CreateSnapShotNotifications] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateDataDrivenNotification]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateDataDrivenNotification] GO CREATE PROCEDURE [dbo].[CreateDataDrivenNotification] @SubscriptionID uniqueidentifier, @ActiveationID uniqueidentifier, @ReportID uniqueidentifier, @ExtensionSettings ntext, @Locale nvarchar(128), @Parameters ntext, @LastRunTime datetime, @DeliveryExtension nvarchar(260), @OwnerSid varbinary (85) = null, @OwnerName nvarchar(260), @OwnerAuthType int, @Version int AS declare @OwnerID as uniqueidentifier EXEC GetUserID @OwnerSid,@OwnerName, @OwnerAuthType, @OwnerID OUTPUT -- Verify if subscription is being deleted if exists (select 1 from [dbo].[SubscriptionsBeingDeleted] where [SubscriptionID]=@SubscriptionID) BEGIN RAISERROR( N'The subscription is being deleted', 16, 1) return; END -- Verify if subscription was deleted or deactivated if not exists (select 1 from [dbo].[Subscriptions] where [SubscriptionID]=@SubscriptionID and [InactiveFlags] = 0) BEGIN RAISERROR( N'The subscription was deleted or deactivated', 16, 1) return; END -- Insert into the notification table insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) values ( NewID(), @SubscriptionID, @ActiveationID, @ReportID, NULL, @ExtensionSettings, @Locale, @Parameters, GETUTCDATE(), @LastRunTime, @DeliveryExtension, @OwnerID, 1, @Version ) GO GRANT EXECUTE ON [dbo].[CreateDataDrivenNotification] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateNewActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateNewActiveSubscription] GO CREATE PROCEDURE [dbo].[CreateNewActiveSubscription] @ActiveID uniqueidentifier, @SubscriptionID uniqueidentifier AS -- Insert into the activesubscription table insert into [ActiveSubscriptions] ( [ActiveID], [SubscriptionID], [TotalNotifications], [TotalSuccesses], [TotalFailures] ) values ( @ActiveID, @SubscriptionID, NULL, 0, 0 ) GO GRANT EXECUTE ON [dbo].[CreateNewActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateActiveSubscription] GO CREATE PROCEDURE [dbo].[UpdateActiveSubscription] @ActiveID uniqueidentifier, @TotalNotifications int = NULL, @TotalSuccesses int = NULL, @TotalFailures int = NULL AS if @TotalNotifications is not NULL begin update ActiveSubscriptions set TotalNotifications = @TotalNotifications where ActiveID = @ActiveID end if @TotalSuccesses is not NULL begin update ActiveSubscriptions set TotalSuccesses = TotalSuccesses + @TotalSuccesses where ActiveID = @ActiveID end if @TotalFailures is not NULL begin update ActiveSubscriptions set TotalFailures = TotalFailures + @TotalFailures where ActiveID = @ActiveID end select TotalNotifications, TotalSuccesses, TotalFailures from ActiveSubscriptions where ActiveID = @ActiveID GO GRANT EXECUTE ON [dbo].[UpdateActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteActiveSubscription]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteActiveSubscription] GO CREATE PROCEDURE [dbo].[DeleteActiveSubscription] @ActiveID uniqueidentifier AS delete from ActiveSubscriptions where ActiveID = @ActiveID GO GRANT EXECUTE ON [dbo].[DeleteActiveSubscription] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateCacheUpdateNotifications]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateCacheUpdateNotifications] GO CREATE PROCEDURE [dbo].[CreateCacheUpdateNotifications] @ReportID uniqueidentifier, @LastRunTime datetime AS update [Subscriptions] set [LastRunTime] = @LastRunTime from [Subscriptions] S where S.[Report_OID] = @ReportID and S.EventType = 'SnapshotUpdated' and InactiveFlags = 0 -- Find all valid subscriptions for the given report and create a new notification row for -- each subscription insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) select NewID(), S.[SubscriptionID], NULL, S.[Report_OID], NULL, S.[ExtensionSettings], S.[Locale], S.[Parameters], GETUTCDATE(), S.[LastRunTime], S.[DeliveryExtension], S.[OwnerID], 0, S.[Version] from [Subscriptions] S inner join Catalog C on S.[Report_OID] = C.[ItemID] where C.[ItemID] = @ReportID and S.EventType = 'SnapshotUpdated' and InactiveFlags = 0 and S.[DataSettings] is null -- Create any data driven subscription by creating a data driven event insert into [Event] ( [EventID], [EventType], [EventData], [TimeEntered] ) select NewID(), 'DataDrivenSubscription', S.SubscriptionID, GETUTCDATE() from [Subscriptions] S inner join Catalog C on S.[Report_OID] = C.[ItemID] where C.[ItemID] = @ReportID and S.EventType = 'SnapshotUpdated' and InactiveFlags = 0 and S.[DataSettings] is not null GO GRANT EXECUTE ON [dbo].[CreateCacheUpdateNotifications] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCacheSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetCacheSchedule] GO CREATE PROCEDURE [dbo].[GetCacheSchedule] @ReportID uniqueidentifier AS SELECT S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], Owner.[AuthType], RS.ReportAction FROM Schedule S with (XLOCK) inner join ReportSchedule RS on S.ScheduleID = RS.ScheduleID inner join [Users] Owner on S.[CreatedById] = Owner.[UserID] WHERE (RS.ReportAction = 1 or RS.ReportAction = 3) and -- 1 == UpdateCache, 3 == Invalidate cache RS.[ReportID] = @ReportID GO GRANT EXECUTE ON [dbo].[GetCacheSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteNotification]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteNotification] GO CREATE PROCEDURE [dbo].[DeleteNotification] @ID uniqueidentifier AS delete from [Notifications] where [NotificationID] = @ID GO GRANT EXECUTE ON [dbo].[DeleteNotification] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetNotificationAttempt]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetNotificationAttempt] GO CREATE PROCEDURE [dbo].[SetNotificationAttempt] @Attempt int, @SecondsToAdd int, @NotificationID uniqueidentifier AS update [Notifications] set [ProcessStart] = NULL, [Attempt] = @Attempt, [ProcessAfter] = DateAdd(second, @SecondsToAdd, GetUtcDate()) where [NotificationID] = @NotificationID GO GRANT EXECUTE ON [dbo].[SetNotificationAttempt] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateTimeBasedSubscriptionNotification]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateTimeBasedSubscriptionNotification] GO CREATE PROCEDURE [dbo].[CreateTimeBasedSubscriptionNotification] @SubscriptionID uniqueidentifier, @LastRunTime datetime as insert into [Notifications] ( [NotificationID], [SubscriptionID], [ActivationID], [ReportID], [SnapShotDate], [ExtensionSettings], [Locale], [Parameters], [NotificationEntered], [SubscriptionLastRunTime], [DeliveryExtension], [SubscriptionOwnerID], [IsDataDriven], [Version] ) select NewID(), S.[SubscriptionID], NULL, S.[Report_OID], NULL, S.[ExtensionSettings], S.[Locale], S.[Parameters], GETUTCDATE(), @LastRunTime, S.[DeliveryExtension], S.[OwnerID], 0, S.[Version] from [Subscriptions] S where S.[SubscriptionID] = @SubscriptionID and InactiveFlags = 0 and S.[DataSettings] is null -- Create any data driven subscription by creating a data driven event insert into [Event] ( [EventID], [EventType], [EventData], [TimeEntered] ) select NewID(), 'DataDrivenSubscription', S.SubscriptionID, GETUTCDATE() from [Subscriptions] S where S.[SubscriptionID] = @SubscriptionID and InactiveFlags = 0 and S.[DataSettings] is not null update [Subscriptions] set [LastRunTime] = @LastRunTime where [SubscriptionID] = @SubscriptionID and InactiveFlags = 0 GO GRANT EXECUTE ON [dbo].[CreateTimeBasedSubscriptionNotification] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteTimeBasedSubscriptionSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteTimeBasedSubscriptionSchedule] GO CREATE PROCEDURE [dbo].[DeleteTimeBasedSubscriptionSchedule] @SubscriptionID as uniqueidentifier as delete ReportSchedule from ReportSchedule RS inner join Subscriptions S on S.[SubscriptionID] = RS.[SubscriptionID] where S.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[DeleteTimeBasedSubscriptionSchedule] TO RSExecRole GO -------------------------------------------------- ------------- Provider Info if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListUsedDeliveryProviders]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListUsedDeliveryProviders] GO CREATE PROCEDURE [dbo].[ListUsedDeliveryProviders] AS select distinct [DeliveryExtension] from Subscriptions where [DeliveryExtension] <> '' GO GRANT EXECUTE ON [dbo].[ListUsedDeliveryProviders] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id('[dbo].[AddBatchRecord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddBatchRecord] GO CREATE PROCEDURE [dbo].[AddBatchRecord] @BatchID uniqueidentifier, @UserName nvarchar(260), @Action varchar(32), @Item nvarchar(425) = NULL, @Parent nvarchar(425) = NULL, @Param nvarchar(425) = NULL, @BoolParam bit = NULL, @Content image = NULL, @Properties ntext = NULL AS IF @Action='BatchStart' BEGIN INSERT INTO [Batch] (BatchID, AddedOn, [Action], Item, Parent, Param, BoolParam, Content, Properties) VALUES (@BatchID, GETUTCDATE(), @Action, @UserName, @Parent, @Param, @BoolParam, @Content, @Properties) END ELSE BEGIN IF EXISTS (SELECT * FROM Batch WHERE BatchID = @BatchID AND [Action] = 'BatchStart' AND Item = @UserName) BEGIN INSERT INTO [Batch] (BatchID, AddedOn, [Action], Item, Parent, Param, BoolParam, Content, Properties) VALUES (@BatchID, GETUTCDATE(), @Action, @Item, @Parent, @Param, @BoolParam, @Content, @Properties) END ELSE BEGIN RAISERROR( 'Batch does not exist', 16, 1 ) END END GO GRANT EXECUTE ON [dbo].[AddBatchRecord] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[GetBatchRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetBatchRecords] GO CREATE PROCEDURE [dbo].[GetBatchRecords] @BatchID uniqueidentifier AS SELECT [Action], Item, Parent, Param, BoolParam, Content, Properties FROM [Batch] WHERE BatchID = @BatchID ORDER BY AddedOn GO GRANT EXECUTE ON [dbo].[GetBatchRecords] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteBatchRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteBatchRecords] GO CREATE PROCEDURE [dbo].[DeleteBatchRecords] @BatchID uniqueidentifier AS SET NOCOUNT OFF DELETE FROM [Batch] WHERE BatchID = @BatchID GO GRANT EXECUTE ON [dbo].[DeleteBatchRecords] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanBatchRecords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanBatchRecords] GO CREATE PROCEDURE [dbo].[CleanBatchRecords] @MaxAgeMinutes int AS SET NOCOUNT OFF DELETE FROM [Batch] where BatchID in ( SELECT BatchID FROM [Batch] WHERE AddedOn < DATEADD(minute, -(@MaxAgeMinutes), GETUTCDATE()) ) GO GRANT EXECUTE ON [dbo].[CleanBatchRecords] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanOrphanedPolicies]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanOrphanedPolicies] GO -- Cleaning orphan policies CREATE PROCEDURE [dbo].[CleanOrphanedPolicies] AS SET NOCOUNT OFF DELETE [Policies] WHERE [Policies].[PolicyFlag] = 0 AND NOT EXISTS (SELECT ItemID FROM [Catalog] WHERE [Catalog].[PolicyID] = [Policies].[PolicyID]) DELETE [Policies] FROM [Policies] INNER JOIN [ModelItemPolicy] ON [ModelItemPolicy].[PolicyID] = [Policies].[PolicyID] WHERE NOT EXISTS (SELECT ItemID FROM [Catalog] WHERE [Catalog].[ItemID] = [ModelItemPolicy].[CatalogItemID]) GO GRANT EXECUTE ON [dbo].[CleanOrphanedPolicies] TO RSExecRole GO -------------------------------------------------- ------------- Snapshot manipulation if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[IncreaseTransientSnapshotRefcount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[IncreaseTransientSnapshotRefcount] GO CREATE PROCEDURE [dbo].[IncreaseTransientSnapshotRefcount] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @ExpirationMinutes as int AS SET NOCOUNT OFF DECLARE @soon AS datetime SET @soon = DATEADD(n, @ExpirationMinutes, GETDATE()) if @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET ExpirationDate = @soon, TransientRefcount = TransientRefcount + 1 WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET ExpirationDate = @soon, TransientRefcount = TransientRefcount + 1 WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[IncreaseTransientSnapshotRefcount] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DecreaseTransientSnapshotRefcount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DecreaseTransientSnapshotRefcount] GO CREATE PROCEDURE [dbo].[DecreaseTransientSnapshotRefcount] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS SET NOCOUNT OFF if @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET TransientRefcount = TransientRefcount - 1 WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET TransientRefcount = TransientRefcount - 1 WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[DecreaseTransientSnapshotRefcount] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[MarkSnapshotAsDependentOnUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[MarkSnapshotAsDependentOnUser] GO CREATE PROCEDURE [dbo].[MarkSnapshotAsDependentOnUser] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS SET NOCOUNT OFF if @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET DependsOnUser = 1 WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET DependsOnUser = 1 WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[MarkSnapshotAsDependentOnUser] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSnapshotProcessingFlags]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSnapshotProcessingFlags] GO CREATE PROCEDURE [dbo].[SetSnapshotProcessingFlags] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @ProcessingFlags int AS if @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET ProcessingFlags = @ProcessingFlags WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET ProcessingFlags = @ProcessingFlags WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[SetSnapshotProcessingFlags] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSnapshotChunksVersion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSnapshotChunksVersion] GO CREATE PROCEDURE [dbo].[SetSnapshotChunksVersion] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @Version as smallint AS declare @affectedRows int set @affectedRows = 0 if @IsPermanentSnapshot = 1 BEGIN if @Version > 0 BEGIN UPDATE ChunkData SET Version = @Version WHERE SnapshotDataID = @SnapshotDataID SELECT @affectedRows = @affectedRows + @@rowcount UPDATE SegmentedChunk SET Version = @Version WHERE SnapshotDataId = @SnapshotDataID SELECT @affectedRows = @affectedRows + @@rowcount END ELSE BEGIN UPDATE ChunkData SET Version = Version WHERE SnapshotDataID = @SnapshotDataID SELECT @affectedRows = @affectedRows + @@rowcount UPDATE SegmentedChunk SET Version = Version WHERE SnapshotDataId = @SnapshotDataID SELECT @affectedRows = @affectedRows + @@rowcount END END ELSE BEGIN if @Version > 0 BEGIN UPDATE ReportServerTempDB.dbo.ChunkData SET Version = @Version WHERE SnapshotDataID = @SnapshotDataID SELECT @affectedRows = @affectedRows + @@rowcount UPDATE ReportServerTempDB.dbo.SegmentedChunk SET Version = @Version WHERE SnapshotDataId = @SnapshotDataID SELECT @affectedRows = @affectedRows + @@rowcount END ELSE BEGIN UPDATE ReportServerTempDB.dbo.ChunkData SET Version = Version WHERE SnapshotDataID = @SnapshotDataID SELECT @affectedRows = @affectedRows + @@rowcount UPDATE ReportServerTempDB.dbo.SegmentedChunk SET Version = Version WHERE SnapshotDataId = @SnapshotDataID SELECT @affectedRows = @affectedRows + @@rowcount END END SELECT @affectedRows GO GRANT EXECUTE ON [dbo].[SetSnapshotChunksVersion] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[LockSnapshotForUpgrade]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[LockSnapshotForUpgrade] GO CREATE PROCEDURE [dbo].[LockSnapshotForUpgrade] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS if @IsPermanentSnapshot = 1 BEGIN SELECT ChunkName from ChunkData with (XLOCK) WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN SELECT ChunkName from ReportServerTempDB.dbo.ChunkData with (XLOCK) WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[LockSnapshotForUpgrade] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[InsertUnreferencedSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[InsertUnreferencedSnapshot] GO CREATE PROCEDURE [dbo].[InsertUnreferencedSnapshot] @ReportID as uniqueidentifier = NULL, @EffectiveParams as ntext = NULL, @QueryParams as ntext = NULL, @ParamsHash as int = NULL, @CreatedDate as datetime, @Description as nvarchar(512) = NULL, @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @ProcessingFlags as int, @SnapshotTimeoutMinutes as int, @Machine as nvarchar(512) = NULL AS DECLARE @now datetime SET @now = GETDATE() IF @IsPermanentSnapshot = 1 BEGIN INSERT INTO SnapshotData (SnapshotDataID, CreatedDate, EffectiveParams, QueryParams, ParamsHash, Description, PermanentRefcount, TransientRefcount, ExpirationDate, ProcessingFlags) VALUES (@SnapshotDataID, @CreatedDate, @EffectiveParams, @QueryParams, @ParamsHash, @Description, 0, 1, DATEADD(n, @SnapshotTimeoutMinutes, @now), @ProcessingFlags) END ELSE BEGIN INSERT INTO ReportServerTempDB.dbo.SnapshotData (SnapshotDataID, CreatedDate, EffectiveParams, QueryParams, ParamsHash, Description, PermanentRefcount, TransientRefcount, ExpirationDate, Machine, ProcessingFlags) VALUES (@SnapshotDataID, @CreatedDate, @EffectiveParams, @QueryParams, @ParamsHash, @Description, 0, 1, DATEADD(n, @SnapshotTimeoutMinutes, @now), @Machine, @ProcessingFlags) END GO GRANT EXECuTE ON [dbo].[InsertUnreferencedSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[PromoteSnapshotInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[PromoteSnapshotInfo] GO CREATE PROCEDURE [dbo].[PromoteSnapshotInfo] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @PageCount as int, @HasDocMap as bit, @PaginationMode as smallint, @ProcessingFlags as int AS -- HasDocMap: Processing engine may not -- compute this flag in all cases, which -- can lead to it being false when passed into -- this proc, however the server needs this -- flag to be true if it was ever set to be -- true in order to communicate that there is a -- document map to the viewer control. IF @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET PageCount = @PageCount, HasDocMap = COALESCE(@HasDocMap | HasDocMap, @HasDocMap), PaginationMode = @PaginationMode, ProcessingFlags = @ProcessingFlags WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET PageCount = @PageCount, HasDocMap = COALESCE(@HasDocMap | HasDocMap, @HasDocMap), PaginationMode = @PaginationMode, ProcessingFlags = @ProcessingFlags WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[PromoteSnapshotInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSnapshotPaginationInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSnapshotPaginationInfo] GO CREATE PROCEDURE [dbo].[UpdateSnapshotPaginationInfo] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit, @PageCount as int, @PaginationMode as smallint AS IF @IsPermanentSnapshot = 1 BEGIN UPDATE SnapshotData SET PageCount = @PageCount, PaginationMode = @PaginationMode WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET PageCount = @PageCount, PaginationMode = @PaginationMode WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[UpdateSnapshotPaginationInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapshotPromotedInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapshotPromotedInfo] GO CREATE PROCEDURE [dbo].[GetSnapshotPromotedInfo] @SnapshotDataID as uniqueidentifier, @IsPermanentSnapshot as bit AS -- We don't want to hold shared locks if even if we are in a repeatable -- read transaction, so explicitly use READCOMMITTED lock hint IF @IsPermanentSnapshot = 1 BEGIN SELECT PageCount, HasDocMap, PaginationMode, ProcessingFlags FROM SnapshotData WITH (READCOMMITTED) WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN SELECT PageCount, HasDocMap, PaginationMode, ProcessingFlags FROM ReportServerTempDB.dbo.SnapshotData WITH (READCOMMITTED) WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[GetSnapshotPromotedInfo] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[AddHistoryRecord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddHistoryRecord] GO -- add new record to History table CREATE PROCEDURE [dbo].[AddHistoryRecord] @HistoryID uniqueidentifier, @ReportID uniqueidentifier, @SnapshotDate datetime, @SnapshotDataID uniqueidentifier, @SnapshotTransientRefcountChange int AS INSERT INTO History (HistoryID, ReportID, SnapshotDataID, SnapshotDate) VALUES (@HistoryID, @ReportID, @SnapshotDataID, @SnapshotDate) IF @@ERROR = 0 BEGIN UPDATE SnapshotData -- Snapshots, when created, have transient refcount set to 1. Here create permanent reference -- here so we need to increase permanent refcount and decrease transient refcount. However, -- if it was already referenced by the execution snapshot, transient refcount was already -- decreased. Hence, there's a parameter @SnapshotTransientRefcountChange that is 0 or -1. SET PermanentRefcount = PermanentRefcount + 1, TransientRefcount = TransientRefcount + @SnapshotTransientRefcountChange WHERE SnapshotData.SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[AddHistoryRecord] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[SetHistoryLimit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetHistoryLimit] GO CREATE PROCEDURE [dbo].[SetHistoryLimit] @Path nvarchar (425), @SnapshotLimit int = NULL AS UPDATE Catalog SET SnapshotLimit=@SnapshotLimit WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[SetHistoryLimit] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[ListHistory]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListHistory] GO -- list all historical snapshots for a specific report CREATE PROCEDURE [dbo].[ListHistory] @ReportID uniqueidentifier AS SELECT S.SnapshotDate, ISNULL((SELECT SUM(DATALENGTH( CD.Content ) ) FROM ChunkData AS CD WHERE CD.SnapshotDataID = S.SnapshotDataID ), 0) + ISNULL( ( SELECT SUM(DATALENGTH( SEG.Content) ) FROM Segment SEG WITH(NOLOCK) JOIN ChunkSegmentMapping CSM WITH(NOLOCK) ON (CSM.SegmentId = SEG.SegmentId) JOIN SegmentedChunk C WITH(NOLOCK) ON (C.ChunkId = CSM.ChunkId AND C.SnapshotDataId = S.SnapshotDataId) ), 0) FROM History AS S -- skipping intermediate table SnapshotData WHERE S.ReportID = @ReportID GO GRANT EXECUTE ON [dbo].[ListHistory] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanHistoryForReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanHistoryForReport] GO -- delete snapshots exceeding # of snapshots. won't work if @SnapshotLimit = 0 CREATE PROCEDURE [dbo].[CleanHistoryForReport] @SnapshotLimit int, @ReportID uniqueidentifier AS SET NOCOUNT OFF DELETE FROM History WHERE ReportID = @ReportID and SnapshotDate < (SELECT MIN(SnapshotDate) FROM (SELECT TOP (@SnapshotLimit) SnapshotDate FROM History WHERE ReportID = @ReportID ORDER BY SnapshotDate DESC ) AS TopSnapshots ) GO GRANT EXECUTE ON [dbo].[CleanHistoryForReport] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[CleanAllHistories]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanAllHistories] GO -- delete snapshots exceeding # of snapshots for the whole system CREATE PROCEDURE [dbo].[CleanAllHistories] @SnapshotLimit int AS SET NOCOUNT OFF DELETE FROM History WHERE HistoryID in (SELECT HistoryID FROM History JOIN Catalog AS ReportJoinSnapshot ON ItemID = ReportID WHERE SnapshotLimit IS NULL and SnapshotDate < (SELECT MIN(SnapshotDate) FROM (SELECT TOP (@SnapshotLimit) SnapshotDate FROM History AS InnerSnapshot WHERE InnerSnapshot.ReportID = ReportJoinSnapshot.ItemID ORDER BY SnapshotDate DESC ) AS TopSnapshots ) ) GO GRANT EXECUTE ON [dbo].[CleanAllHistories] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteHistoryRecord]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteHistoryRecord] GO -- delete one historical snapshot CREATE PROCEDURE [dbo].[DeleteHistoryRecord] @ReportID uniqueidentifier, @SnapshotDate DateTime AS SET NOCOUNT OFF DELETE FROM History WHERE ReportID = @ReportID AND SnapshotDate = @SnapshotDate GO GRANT EXECUTE ON [dbo].[DeleteHistoryRecord] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteAllHistoryForReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteAllHistoryForReport] GO -- delete all snapshots for a report CREATE PROCEDURE [dbo].[DeleteAllHistoryForReport] @ReportID uniqueidentifier AS SET NOCOUNT OFF DELETE FROM History WHERE HistoryID in (SELECT HistoryID FROM History JOIN Catalog on ItemID = ReportID WHERE ReportID = @ReportID ) GO GRANT EXECUTE ON [dbo].[DeleteAllHistoryForReport] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[DeleteHistoriesWithNoPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteHistoriesWithNoPolicy] GO -- delete all snapshots for all reports that inherit system History policy CREATE PROCEDURE [dbo].[DeleteHistoriesWithNoPolicy] AS SET NOCOUNT OFF DELETE FROM History WHERE HistoryID in (SELECT HistoryID FROM History JOIN Catalog on ItemID = ReportID WHERE SnapshotLimit is null ) GO GRANT EXECUTE ON [dbo].[DeleteHistoriesWithNoPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Get_sqlagent_job_status]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[Get_sqlagent_job_status] GO CREATE PROCEDURE [dbo].[Get_sqlagent_job_status] -- Individual job parameters @job_id UNIQUEIDENTIFIER = NULL, -- If provided will only return info about this job -- Note: Only @job_id or @job_name needs to be provided @job_name sysname = NULL, -- If provided will only return info about this job @owner_login_name sysname = NULL -- If provided will only return jobs for this owner AS BEGIN DECLARE @retval INT DECLARE @job_owner_sid VARBINARY(85) DECLARE @is_sysadmin INT SET NOCOUNT ON -- Remove any leading/trailing spaces from parameters (except @owner_login_name) SELECT @job_name = LTRIM(RTRIM(@job_name)) -- Turn [nullable] empty string parameters into NULLs IF (@job_name = N'') SELECT @job_name = NULL -- Verify the job if supplied. This also checks if the caller has rights to view the job IF ((@job_id IS NOT NULL) OR (@job_name IS NOT NULL)) BEGIN EXECUTE @retval = msdb..sp_verify_job_identifiers '@job_name', '@job_id', @job_name OUTPUT, @job_id OUTPUT IF (@retval <> 0) RETURN(1) -- Failure END -- If the login name isn't given, set it to the job owner or the current caller IF(@owner_login_name IS NULL) BEGIN SET @owner_login_name = (SELECT SUSER_SNAME(sj.owner_sid) FROM msdb.dbo.sysjobs sj where sj.job_id = @job_id) SET @is_sysadmin = ISNULL(IS_SRVROLEMEMBER(N'sysadmin', @owner_login_name), 0) END ELSE BEGIN -- Check owner IF (SUSER_SID(@owner_login_name) IS NULL) BEGIN RAISERROR(14262, -1, -1, '@owner_login_name', @owner_login_name) RETURN(1) -- Failure END --only allow sysadmin types to specify the owner IF ((ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0) <> 1) AND (ISNULL(IS_MEMBER(N'SQLAgentAdminRole'), 0) = 1) AND (SUSER_SNAME() <> @owner_login_name)) BEGIN --TODO: RAISERROR(14525, -1, -1) RETURN(1) -- Failure END SET @is_sysadmin = 0 END IF (@job_id IS NOT NULL) BEGIN -- Individual job... EXECUTE @retval = master.dbo.xp_sqlagent_enum_jobs @is_sysadmin, @owner_login_name, @job_id IF (@retval <> 0) RETURN(1) -- Failure END ELSE BEGIN -- Set of jobs... EXECUTE @retval = master.dbo.xp_sqlagent_enum_jobs @is_sysadmin, @owner_login_name IF (@retval <> 0) RETURN(1) -- Failure END RETURN(0) -- Success END GO GRANT EXECUTE ON [dbo].[Get_sqlagent_job_status] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateTask] GO CREATE PROCEDURE [dbo].[CreateTask] @ScheduleID uniqueidentifier, @Name nvarchar (260), @StartDate datetime, @Flags int, @NextRunTime datetime = NULL, @LastRunTime datetime = NULL, @EndDate datetime = NULL, @RecurrenceType int = NULL, @MinutesInterval int = NULL, @DaysInterval int = NULL, @WeeksInterval int = NULL, @DaysOfWeek int = NULL, @DaysOfMonth int = NULL, @Month int = NULL, @MonthlyWeek int = NULL, @State int = NULL, @LastRunStatus nvarchar (260) = NULL, @ScheduledRunTimeout int = NULL, @UserSid varbinary (85) = null, @UserName nvarchar(260), @AuthType int, @EventType nvarchar (260), @EventData nvarchar (260), @Type int , @Path nvarchar (425) = NULL AS DECLARE @UserID uniqueidentifier EXEC GetUserID @UserSid, @UserName, @AuthType, @UserID OUTPUT -- Create a task with the given data. Insert into Schedule ( [ScheduleID], [Name], [StartDate], [Flags], [NextRunTime], [LastRunTime], [EndDate], [RecurrenceType], [MinutesInterval], [DaysInterval], [WeeksInterval], [DaysOfWeek], [DaysOfMonth], [Month], [MonthlyWeek], [State], [LastRunStatus], [ScheduledRunTimeout], [CreatedById], [EventType], [EventData], [Type], [Path] ) values (@ScheduleID, @Name, @StartDate, @Flags, @NextRunTime, @LastRunTime, @EndDate, @RecurrenceType, @MinutesInterval, @DaysInterval, @WeeksInterval, @DaysOfWeek, @DaysOfMonth, @Month, @MonthlyWeek, @State, @LastRunStatus, @ScheduledRunTimeout, @UserID, @EventType, @EventData, @Type, @Path) GO GRANT EXECUTE ON [dbo].[CreateTask] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateTask] GO CREATE PROCEDURE [dbo].[UpdateTask] @ScheduleID uniqueidentifier, @Name nvarchar (260), @StartDate datetime, @Flags int, @NextRunTime datetime = NULL, @LastRunTime datetime = NULL, @EndDate datetime = NULL, @RecurrenceType int = NULL, @MinutesInterval int = NULL, @DaysInterval int = NULL, @WeeksInterval int = NULL, @DaysOfWeek int = NULL, @DaysOfMonth int = NULL, @Month int = NULL, @MonthlyWeek int = NULL, @State int = NULL, @LastRunStatus nvarchar (260) = NULL, @ScheduledRunTimeout int = NULL AS -- Update a tasks values. ScheduleID and Report information can not be updated Update Schedule set [StartDate] = @StartDate, [Name] = @Name, [Flags] = @Flags, [NextRunTime] = @NextRunTime, [LastRunTime] = @LastRunTime, [EndDate] = @EndDate, [RecurrenceType] = @RecurrenceType, [MinutesInterval] = @MinutesInterval, [DaysInterval] = @DaysInterval, [WeeksInterval] = @WeeksInterval, [DaysOfWeek] = @DaysOfWeek, [DaysOfMonth] = @DaysOfMonth, [Month] = @Month, [MonthlyWeek] = @MonthlyWeek, [State] = @State, [LastRunStatus] = @LastRunStatus, [ScheduledRunTimeout] = @ScheduledRunTimeout where [ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[UpdateTask] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateScheduleNextRunTime]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateScheduleNextRunTime] GO CREATE PROCEDURE [dbo].[UpdateScheduleNextRunTime] @ScheduleID as uniqueidentifier, @NextRunTime as datetime as update Schedule set [NextRunTime] = @NextRunTime where [ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[UpdateScheduleNextRunTime] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListScheduledReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListScheduledReports] GO CREATE PROCEDURE [dbo].[ListScheduledReports] @ScheduleID uniqueidentifier AS -- List all reports for a schedule select RS.[ReportAction], RS.[ScheduleID], RS.[ReportID], RS.[SubscriptionID], C.[Path], C.[Name], C.[Description], C.[ModifiedDate], SUSER_SNAME(U.[Sid]), U.[UserName], DATALENGTH( C.Content ), C.ExecutionTime, S.[Type], SD.[NtSecDescPrimary] from [ReportSchedule] RS Inner join [Catalog] C on RS.[ReportID] = C.[ItemID] Inner join [Schedule] S on RS.[ScheduleID] = S.[ScheduleID] Inner join [Users] U on C.[ModifiedByID] = U.UserID left outer join [SecData] SD on SD.[PolicyID] = C.[PolicyID] AND SD.AuthType = U.AuthType where RS.[ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[ListScheduledReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListTasks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListTasks] GO CREATE PROCEDURE [dbo].[ListTasks] @Path nvarchar (425) = NULL, @Prefix nvarchar (425) = NULL AS select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], Owner.[AuthType], (select count(*) from ReportSchedule where ReportSchedule.ScheduleID = S.ScheduleID) from [Schedule] S inner join [Users] Owner on S.[CreatedById] = Owner.UserID where S.[Type] = 0 /*Type 0 is shared schedules*/ and ((@Path is null) OR (S.Path = @Path) or (S.Path like @Prefix escape '*')) GO GRANT EXECUTE ON [dbo].[ListTasks] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListTasksForMaintenance]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListTasksForMaintenance] GO CREATE PROCEDURE [dbo].[ListTasksForMaintenance] AS declare @date datetime set @date = GETUTCDATE() update [Schedule] set [ConsistancyCheck] = @date from ( SELECT TOP 20 [ScheduleID] FROM [Schedule] WITH(UPDLOCK) WHERE [ConsistancyCheck] is NULL ) AS t1 WHERE [Schedule].[ScheduleID] = t1.[ScheduleID] select top 20 S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path] from [Schedule] S where [ConsistancyCheck] = @date GO GRANT EXECUTE ON [dbo].[ListTasksForMaintenance] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ClearScheduleConsistancyFlags]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ClearScheduleConsistancyFlags] GO CREATE PROCEDURE [dbo].[ClearScheduleConsistancyFlags] AS update [Schedule] with (tablock, xlock) set [ConsistancyCheck] = NULL GO GRANT EXECUTE ON [dbo].[ClearScheduleConsistancyFlags] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAReportsReportAction]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAReportsReportAction] GO CREATE PROCEDURE [dbo].[GetAReportsReportAction] @ReportID uniqueidentifier, @ReportAction int AS select RS.[ReportAction], RS.[ScheduleID], RS.[ReportID], RS.[SubscriptionID], C.[Path] from [ReportSchedule] RS Inner join [Catalog] C on RS.[ReportID] = C.[ItemID] where C.ItemID = @ReportID and RS.[ReportAction] = @ReportAction GO GRANT EXECUTE ON [dbo].[GetAReportsReportAction] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetTimeBasedSubscriptionReportAction]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetTimeBasedSubscriptionReportAction] GO CREATE PROCEDURE [dbo].[GetTimeBasedSubscriptionReportAction] @SubscriptionID uniqueidentifier AS select RS.[ReportAction], RS.[ScheduleID], RS.[ReportID], RS.[SubscriptionID], C.[Path] from [ReportSchedule] RS Inner join [Catalog] C on RS.[ReportID] = C.[ItemID] where RS.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetTimeBasedSubscriptionReportAction] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetTaskProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetTaskProperties] GO CREATE PROCEDURE [dbo].[GetTaskProperties] @ScheduleID uniqueidentifier AS -- Grab all of a tasks properties given a task id select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], Owner.[AuthType] from [Schedule] S with (XLOCK) Inner join [Users] Owner on S.[CreatedById] = Owner.UserID where S.[ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[GetTaskProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteTask]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteTask] GO CREATE PROCEDURE [dbo].[DeleteTask] @ScheduleID uniqueidentifier AS SET NOCOUNT OFF -- Delete the task with the given task id DELETE FROM Schedule WHERE [ScheduleID] = @ScheduleID GO GRANT EXECUTE ON [dbo].[DeleteTask] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSchedulesReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSchedulesReports] GO CREATE PROCEDURE [dbo].[GetSchedulesReports] @ID uniqueidentifier AS select C.Path from ReportSchedule RS inner join Catalog C on (C.ItemID = RS.ReportID) where ScheduleID = @ID GO GRANT EXECUTE ON [dbo].[GetSchedulesReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddReportSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddReportSchedule] GO CREATE PROCEDURE [dbo].[AddReportSchedule] @ScheduleID uniqueidentifier, @ReportID uniqueidentifier, @SubscriptionID uniqueidentifier = NULL, @Action int AS -- VSTS #139366: SQL Deadlock in AddReportSchedule stored procedure -- Hold lock on [Schedule].[ScheduleID] to prevent deadlock -- with Schedule_UpdateExpiration Schedule's after update trigger select 1 from [Schedule] with (HOLDLOCK) where [Schedule].[ScheduleID] = @ScheduleID Insert into ReportSchedule ([ScheduleID], [ReportID], [SubscriptionID], [ReportAction]) values (@ScheduleID, @ReportID, @SubscriptionID, @Action) GO GRANT EXECUTE ON [dbo].[AddReportSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteReportSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteReportSchedule] GO CREATE PROCEDURE [dbo].[DeleteReportSchedule] @ScheduleID uniqueidentifier, @ReportID uniqueidentifier, @SubscriptionID uniqueidentifier = NULL, @ReportAction int AS IF @SubscriptionID is NULL BEGIN delete from ReportSchedule where ScheduleID = @ScheduleID and ReportID = @ReportID and ReportAction = @ReportAction END ELSE BEGIN delete from ReportSchedule where ScheduleID = @ScheduleID and ReportID = @ReportID and ReportAction = @ReportAction and SubscriptionID = @SubscriptionID END GO GRANT EXECUTE ON [dbo].[DeleteReportSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapShotSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapShotSchedule] GO CREATE PROCEDURE [dbo].[GetSnapShotSchedule] @ReportID uniqueidentifier AS select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], Owner.[AuthType] from Schedule S with (XLOCK) inner join ReportSchedule RS on S.ScheduleID = RS.ScheduleID inner join [Users] Owner on S.[CreatedById] = Owner.[UserID] where RS.ReportAction = 2 and -- 2 == create snapshot RS.ReportID = @ReportID GO GRANT EXECUTE ON [dbo].[GetSnapShotSchedule] TO RSExecRole GO -------------------------------------------------- ------------- Time based subscriptions if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateTimeBasedSubscriptionSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateTimeBasedSubscriptionSchedule] GO CREATE PROCEDURE [dbo].[CreateTimeBasedSubscriptionSchedule] @SubscriptionID as uniqueidentifier, @ScheduleID uniqueidentifier, @Schedule_Name nvarchar (260), @Report_Name nvarchar (425), @StartDate datetime, @Flags int, @NextRunTime datetime = NULL, @LastRunTime datetime = NULL, @EndDate datetime = NULL, @RecurrenceType int = NULL, @MinutesInterval int = NULL, @DaysInterval int = NULL, @WeeksInterval int = NULL, @DaysOfWeek int = NULL, @DaysOfMonth int = NULL, @Month int = NULL, @MonthlyWeek int = NULL, @State int = NULL, @LastRunStatus nvarchar (260) = NULL, @ScheduledRunTimeout int = NULL, @UserSid varbinary (85) = NULL, @UserName nvarchar(260), @AuthType int, @EventType nvarchar (260), @EventData nvarchar (260), @Path nvarchar (425) = NULL AS EXEC CreateTask @ScheduleID, @Schedule_Name, @StartDate, @Flags, @NextRunTime, @LastRunTime, @EndDate, @RecurrenceType, @MinutesInterval, @DaysInterval, @WeeksInterval, @DaysOfWeek, @DaysOfMonth, @Month, @MonthlyWeek, @State, @LastRunStatus, @ScheduledRunTimeout, @UserSid, @UserName, @AuthType, @EventType, @EventData, 1 /*scoped type*/, @Path if @@ERROR = 0 begin -- add a row to the reportSchedule table declare @Report_OID uniqueidentifier select @Report_OID = (select [ItemID] from [Catalog] with (HOLDLOCK) where [Catalog].[Path] = @Report_Name and ([Catalog].[Type] = 2 or [Catalog].[Type] = 4)) EXEC AddReportSchedule @ScheduleID, @Report_OID, @SubscriptionID, 4 -- TimedSubscription action end GO GRANT EXECUTE ON [dbo].[CreateTimeBasedSubscriptionSchedule] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetTimeBasedSubscriptionSchedule]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetTimeBasedSubscriptionSchedule] GO CREATE PROCEDURE [dbo].[GetTimeBasedSubscriptionSchedule] @SubscriptionID as uniqueidentifier AS select S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path], SUSER_SNAME(Owner.[Sid]), Owner.[UserName], Owner.[AuthType] from [ReportSchedule] R inner join Schedule S with (XLOCK) on R.[ScheduleID] = S.[ScheduleID] Inner join [Users] Owner on S.[CreatedById] = Owner.UserID where R.[SubscriptionID] = @SubscriptionID GO GRANT EXECUTE ON [dbo].[GetTimeBasedSubscriptionSchedule] TO RSExecRole GO -------------------------------------------------- ------------- Running Jobs if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddRunningJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddRunningJob] GO CREATE PROCEDURE [dbo].[AddRunningJob] @JobID as nvarchar(32), @StartDate as datetime, @ComputerName as nvarchar(32), @RequestName as nvarchar(425), @RequestPath as nvarchar(425), @UserSid varbinary(85) = NULL, @UserName nvarchar(260), @AuthType int, @Description as ntext = NULL, @Timeout as int, @JobAction as smallint, @JobType as smallint, @JobStatus as smallint AS SET NOCOUNT OFF DECLARE @UserID uniqueidentifier EXEC GetUserID @UserSid, @UserName, @AuthType, @UserID OUTPUT INSERT INTO RunningJobs (JobID, StartDate, ComputerName, RequestName, RequestPath, UserID, Description, Timeout, JobAction, JobType, JobStatus ) VALUES (@JobID, @StartDate, @ComputerName, @RequestName, @RequestPath, @UserID, @Description, @Timeout, @JobAction, @JobType, @JobStatus) GO GRANT EXECUTE ON [dbo].[AddRunningJob] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RemoveRunningJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RemoveRunningJob] GO CREATE PROCEDURE [dbo].[RemoveRunningJob] @JobID as nvarchar(32) AS SET NOCOUNT OFF DELETE FROM RunningJobs WHERE JobID = @JobID GO GRANT EXECUTE ON [dbo].[RemoveRunningJob] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateRunningJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateRunningJob] GO CREATE PROCEDURE [dbo].[UpdateRunningJob] @JobID as nvarchar(32), @JobStatus as smallint AS SET NOCOUNT OFF UPDATE RunningJobs SET JobStatus = @JobStatus WHERE JobID = @JobID GO GRANT EXECUTE ON [dbo].[UpdateRunningJob] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetMyRunningJobs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetMyRunningJobs] GO CREATE PROCEDURE [dbo].[GetMyRunningJobs] @ComputerName as nvarchar(32), @JobType as smallint AS SELECT JobID, StartDate, ComputerName, RequestName, RequestPath, SUSER_SNAME(Users.[Sid]), Users.[UserName], Description, Timeout, JobAction, JobType, JobStatus, Users.[AuthType] FROM RunningJobs INNER JOIN Users ON RunningJobs.UserID = Users.UserID WHERE ComputerName = @ComputerName AND JobType = @JobType GO GRANT EXECUTE ON [dbo].[GetMyRunningJobs] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListRunningJobs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ListRunningJobs] GO CREATE PROCEDURE [dbo].[ListRunningJobs] AS SELECT JobID, StartDate, ComputerName, RequestName, RequestPath, SUSER_SNAME(Users.[Sid]), Users.[UserName], Description, Timeout, JobAction, JobType, JobStatus, Users.[AuthType] FROM RunningJobs INNER JOIN Users ON RunningJobs.UserID = Users.UserID GO GRANT EXECUTE ON [dbo].[ListRunningJobs] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredJobs]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredJobs] GO CREATE PROCEDURE [dbo].[CleanExpiredJobs] AS SET NOCOUNT OFF DELETE FROM RunningJobs WHERE DATEADD(s, Timeout, StartDate) < GETDATE() GO GRANT EXECUTE ON [dbo].[CleanExpiredJobs] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateObject]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateObject] GO -- This SP should never be called with a policy ID unless it is guarenteed that -- the parent will not be deleted before the insert (such as while running this script) CREATE PROCEDURE [dbo].[CreateObject] @ItemID uniqueidentifier, @Name nvarchar (425), @Path nvarchar (425), @ParentID uniqueidentifier, @Type int, @Content image = NULL, @Intermediate uniqueidentifier = NULL, @LinkSourceID uniqueidentifier = NULL, @Property ntext = NULL, @Parameter ntext = NULL, @Description ntext = NULL, @Hidden bit = NULL, @CreatedBySid varbinary(85) = NULL, @CreatedByName nvarchar(260), @AuthType int, @CreationDate datetime, @ModificationDate datetime, @MimeType nvarchar (260) = NULL, @SnapshotLimit int = NULL, @PolicyRoot int = 0, @PolicyID uniqueidentifier = NULL, @ExecutionFlag int = 1 -- allow live execution, don't keep history AS DECLARE @CreatedByID uniqueidentifier EXEC GetUserID @CreatedBySid, @CreatedByName, @AuthType, @CreatedByID OUTPUT UPDATE Catalog SET ModifiedByID = @CreatedByID, ModifiedDate = @ModificationDate WHERE ItemID = @ParentID -- If no policyID, use the parent's IF @PolicyID is NULL BEGIN SET @PolicyID = (SELECT PolicyID FROM [dbo].[Catalog] WHERE Catalog.ItemID = @ParentID) END -- If there is no policy ID then we are guarenteed not to have a parent IF @PolicyID is NULL BEGIN RAISERROR ('Parent Not Found', 16, 1) return END INSERT INTO Catalog (ItemID, Path, Name, ParentID, Type, Content, Intermediate, LinkSourceID, Property, Description, Hidden, CreatedByID, CreationDate, ModifiedByID, ModifiedDate, MimeType, SnapshotLimit, [Parameter], PolicyID, PolicyRoot, ExecutionFlag ) VALUES (@ItemID, @Path, @Name, @ParentID, @Type, @Content, @Intermediate, @LinkSourceID, @Property, @Description, @Hidden, @CreatedByID, @CreationDate, @CreatedByID, @ModificationDate, @MimeType, @SnapshotLimit, @Parameter, @PolicyID, @PolicyRoot , @ExecutionFlag) IF @Intermediate IS NOT NULL AND @@ERROR = 0 BEGIN UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount + 1, TransientRefcount = TransientRefcount - 1 WHERE SnapshotData.SnapshotDataID = @Intermediate END GO GRANT EXECUTE ON [dbo].[CreateObject] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteObject]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteObject] GO CREATE PROCEDURE [dbo].[DeleteObject] @Path nvarchar (425), @Prefix nvarchar (850) AS SET NOCOUNT OFF -- Remove reference for intermediate formats UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 FROM Catalog AS R WITH (XLOCK) INNER JOIN [SnapshotData] AS SD ON R.Intermediate = SD.SnapshotDataID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Remove reference for execution snapshots UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 FROM Catalog AS R WITH (XLOCK) INNER JOIN [SnapshotData] AS SD ON R.SnapshotDataID = SD.SnapshotDataID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Remove history for deleted reports and linked report DELETE History FROM [Catalog] AS R INNER JOIN [History] AS S ON R.ItemID = S.ReportID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Remove model drill reports DELETE ModelDrill FROM [Catalog] AS C INNER JOIN [ModelDrill] AS M ON C.ItemID = M.ReportID WHERE (C.Path = @Path OR C.Path LIKE @Prefix ESCAPE '*') -- Adjust data sources UPDATE [DataSource] SET [Flags] = [Flags] & 0x7FFFFFFD, -- broken link [Link] = NULL FROM [Catalog] AS C INNER JOIN [DataSource] AS DS ON C.[ItemID] = DS.[Link] WHERE (C.Path = @Path OR C.Path LIKE @Prefix ESCAPE '*') -- Clean all data sources DELETE [DataSource] FROM [Catalog] AS R INNER JOIN [DataSource] AS DS ON R.[ItemID] = DS.[ItemID] WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') -- Update linked reports UPDATE LR SET LR.LinkSourceID = NULL FROM [Catalog] AS R INNER JOIN [Catalog] AS LR ON R.ItemID = LR.LinkSourceID WHERE (R.Path = @Path OR R.Path LIKE @Prefix ESCAPE '*') AND (LR.Path NOT LIKE @Prefix ESCAPE '*') -- Remove references for cache entries UPDATE SN SET PermanentRefcount = PermanentRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC on SN.SnapshotDataID = EC.SnapshotDataID INNER JOIN Catalog AS C ON EC.ReportID = C.ItemID WHERE (Path = @Path OR Path LIKE @Prefix ESCAPE '*') -- Clean cache entries for items to be deleted DELETE EC FROM ReportServerTempDB.dbo.ExecutionCache AS EC INNER JOIN Catalog AS C ON EC.ReportID = C.ItemID WHERE (Path = @Path OR Path LIKE @Prefix ESCAPE '*') -- Finally delete items DELETE FROM [Catalog] WHERE (Path = @Path OR Path LIKE @Prefix ESCAPE '*') EXEC CleanOrphanedPolicies GO GRANT EXECUTE ON [dbo].[DeleteObject] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindObjectsNonRecursive]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindObjectsNonRecursive] GO CREATE PROCEDURE [dbo].[FindObjectsNonRecursive] @Path nvarchar (425), @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.[UserName], SUSER_SNAME(MU.Sid), MU.[UserName], C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Catalog AS P ON C.ParentID = P.ItemID INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE P.Path = @Path GO GRANT EXECUTE ON [dbo].[FindObjectsNonRecursive] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindObjectsRecursive]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindObjectsRecursive] GO CREATE PROCEDURE [dbo].[FindObjectsRecursive] @Prefix nvarchar (850), @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.UserName, SUSER_SNAME(MU.Sid), MU.UserName, C.MimeType, C.ExecutionTime, C.Hidden from Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE C.Path LIKE @Prefix ESCAPE '*' GO GRANT EXECUTE ON [dbo].[FindObjectsRecursive] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindParents]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindParents] GO CREATE PROCEDURE [dbo].[FindParents] @Path nvarchar (425), @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.[UserName], SUSER_SNAME(MU.Sid), MU.[UserName], C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE @Path LIKE C.Path + '/%' ORDER BY DATALENGTH(C.Path) desc GO GRANT EXECUTE ON [dbo].[FindParents] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindObjectsByLink]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindObjectsByLink] GO CREATE PROCEDURE [dbo].[FindObjectsByLink] @Link uniqueidentifier, @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.UserName, SUSER_SNAME(MU.Sid), MU.UserName, C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE C.LinkSourceID = @Link GO GRANT EXECUTE ON [dbo].[FindObjectsByLink] TO RSExecRole GO -------------------------------------------------- ------------- Procedures used to update linked reports if exists (select * from sysobjects where id = object_id('[dbo].[GetIDPairsByLink]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetIDPairsByLink] GO CREATE PROCEDURE [dbo].[GetIDPairsByLink] @Link uniqueidentifier AS SELECT LinkSourceID, ItemID FROM Catalog WHERE LinkSourceID = @Link GO GRANT EXECUTE ON [dbo].[GetIDPairsByLink] TO RSExecRole GO if exists (select * from sysobjects where id = object_id('[dbo].[GetChildrenBeforeDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetChildrenBeforeDelete] GO CREATE PROCEDURE [dbo].[GetChildrenBeforeDelete] @Prefix nvarchar (850), @AuthType int AS SELECT C.PolicyID, C.Type, SD.NtSecDescPrimary FROM Catalog AS C LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType WHERE C.Path LIKE @Prefix ESCAPE '*' -- return children only, not item itself GO GRANT EXECUTE ON [dbo].[GetChildrenBeforeDelete] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetAllProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetAllProperties] GO CREATE PROCEDURE [dbo].[GetAllProperties] @Path nvarchar (425), @AuthType int AS select Property, Description, Type, DATALENGTH( Content ), ItemID, SUSER_SNAME(C.Sid), C.UserName, CreationDate, SUSER_SNAME(M.Sid), M.UserName, ModifiedDate, MimeType, ExecutionTime, NtSecDescPrimary, [LinkSourceID], Hidden, ExecutionFlag, SnapshotLimit, [Name] FROM Catalog INNER JOIN Users C ON Catalog.CreatedByID = C.UserID INNER JOIN Users M ON Catalog.ModifiedByID = M.UserID LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[GetAllProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetParameters] GO CREATE PROCEDURE [dbo].[GetParameters] @Path nvarchar (425), @AuthType int AS SELECT Type, [Parameter], ItemID, SecData.NtSecDescPrimary, [LinkSourceID], [ExecutionFlag] FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[GetParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetObjectContent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetObjectContent] GO CREATE PROCEDURE [dbo].[GetObjectContent] @Path nvarchar (425), @AuthType int AS SELECT Type, Content, LinkSourceID, MimeType, SecData.NtSecDescPrimary, ItemID FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[GetObjectContent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[LoadForDefinitionCheck]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[LoadForDefinitionCheck] GO -- For loading compiled definitions to check for internal republishing, this is -- done before calling GetCompiledDefinition or GetReportForExecution CREATE PROCEDURE [dbo].[LoadForDefinitionCheck] @Path nvarchar(425), @AcquireUpdateLocks bit, @AuthType int AS IF(@AcquireUpdateLocks = 0) BEGIN SELECT CompiledDefinition.SnapshotDataID, CompiledDefinition.ProcessingFlags, SecData.NtSecDescPrimary FROM Catalog MainItem LEFT OUTER JOIN SecData ON (MainItem.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType) LEFT OUTER JOIN Catalog LinkTarget WITH (INDEX = PK_CATALOG) ON (MainItem.LinkSourceID = LinkTarget.ItemID) JOIN SnapshotData CompiledDefinition ON (CompiledDefinition.SnapshotDataID = COALESCE(LinkTarget.Intermediate, MainItem.Intermediate)) WHERE MainItem.Path = @Path AND (MainItem.Type = 2 /* Report */ OR MainItem.Type = 4 /* Linked Report */) END ELSE BEGIN -- acquire upgrade locks, this means that the check is being perform in a -- different transaction context which will be committed before trying to -- perform the actual load, to prevent deadlock in the case where we have to -- republish this new transaction will acquire and hold upgrade locks SELECT CompiledDefinition.SnapshotDataID, CompiledDefinition.ProcessingFlags, SecData.NtSecDescPrimary FROM Catalog MainItem WITH(UPDLOCK ROWLOCK) LEFT OUTER JOIN SecData ON (MainItem.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType) LEFT OUTER JOIN Catalog LinkTarget WITH (UPDLOCK ROWLOCK INDEX = PK_CATALOG) ON (MainItem.LinkSourceID = LinkTarget.ItemID) JOIN SnapshotData CompiledDefinition WITH(UPDLOCK ROWLOCK) ON (CompiledDefinition.SnapshotDataID = COALESCE(LinkTarget.Intermediate, MainItem.Intermediate)) WHERE MainItem.Path = @Path AND (MainItem.Type = 2 /* Report */ OR MainItem.Type = 4 /* Linked Report */) END GO GRANT EXECUTE ON [dbo].[LoadForDefinitionCheck] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[LoadForRepublishing]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[LoadForRepublishing] GO -- Loads a report's RDL for republishing CREATE PROCEDURE [dbo].[LoadForRepublishing] @Path nvarchar(425) AS SELECT COALESCE(LinkTarget.Content, MainItem.Content) AS [Content], CompiledDefinition.SnapshotDataID, CompiledDefinition.ProcessingFlags FROM Catalog MainItem LEFT OUTER JOIN Catalog LinkTarget WITH (INDEX = PK_CATALOG) ON (MainItem.LinkSourceID = LinkTarget.ItemID) JOIN SnapshotData CompiledDefinition ON (CompiledDefinition.SnapshotDataID = COALESCE(LinkTarget.Intermediate, MainItem.Intermediate)) WHERE MainItem.Path = @Path GO GRANT EXECUTE ON [dbo].[LoadForRepublishing] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateCompiledDefinition]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateCompiledDefinition] GO CREATE PROCEDURE [dbo].[UpdateCompiledDefinition] @Path NVARCHAR(425), @OldSnapshotId UNIQUEIDENTIFIER, @NewSnapshotId UNIQUEIDENTIFIER, @ItemId UNIQUEIDENTIFIER OUTPUT AS BEGIN -- we have a clustered unique index on [Path] which the QO -- should match for the filter UPDATE [dbo].[Catalog] SET [Intermediate] = @NewSnapshotId, @ItemId = [ItemID] WHERE [Path] = @Path AND ([Intermediate] = @OldSnapshotId OR (@OldSnapshotId IS NULL AND [Intermediate] IS NULL)); DECLARE @UpdatedReferences INT ; SELECT @UpdatedReferences = @@ROWCOUNT ; IF(@UpdatedReferences <> 0) BEGIN UPDATE [dbo].[SnapshotData] SET [PermanentRefcount] = [PermanentRefcount] + @UpdatedReferences, [TransientRefcount] = [TransientRefcount] - 1 WHERE [SnapshotDataID] = @NewSnapshotId ; UPDATE [dbo].[SnapshotData] SET [PermanentRefcount] = [PermanentRefcount] - @UpdatedReferences WHERE [SnapshotDataID] = @OldSnapshotId ; END END GRANT EXECUTE ON [dbo].[UpdateCompiledDefinition] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RebindDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RebindDataSource] GO -- Republishing generates new DSID and stores those in the object model, -- in order to resolve the data sources we need to rebind the old -- data source definition to the current DSID CREATE PROCEDURE [dbo].[RebindDataSource] @ItemId uniqueidentifier, @Name nvarchar(260), @NewDSID uniqueidentifier AS UPDATE DataSource SET DSID = @NewDSID WHERE ItemID = @ItemId AND [Name] = @Name GO GRANT EXECUTE ON [dbo].[RebindDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCompiledDefinition]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetCompiledDefinition] GO -- used to create snapshots CREATE PROCEDURE [dbo].[GetCompiledDefinition] @Path nvarchar (425), @AuthType int AS SELECT MainItem.Type, MainItem.Intermediate, MainItem.LinkSourceID, MainItem.Property, MainItem.Description, SecData.NtSecDescPrimary, MainItem.ItemID, MainItem.ExecutionFlag, LinkTarget.Intermediate, LinkTarget.Property, LinkTarget.Description, MainItem.[SnapshotDataID] FROM Catalog MainItem LEFT OUTER JOIN SecData ON MainItem.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog LinkTarget with (INDEX(PK_Catalog)) on MainItem.LinkSourceID = LinkTarget.ItemID WHERE MainItem.Path = @Path GO GRANT EXECUTE ON [dbo].[GetCompiledDefinition] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetReportForExecution]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetReportForExecution] GO -- gets either the intermediate format or snapshot from cache CREATE PROCEDURE [dbo].[GetReportForExecution] @Path nvarchar (425), @ParamsHash int, @AuthType int AS DECLARE @now AS datetime SET @now = GETDATE() IF ( NOT EXISTS ( SELECT TOP 1 1 FROM Catalog AS C INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON C.ItemID = EC.ReportID INNER JOIN ReportServerTempDB.dbo.SnapshotData AS SN ON EC.SnapshotDataID = SN.SnapshotDataID WHERE C.Path = @Path AND EC.AbsoluteExpiration > @now AND SN.ParamsHash = @ParamsHash ) ) BEGIN -- no cache SELECT Cat.Type, Cat.LinkSourceID, Cat2.Path, Cat.Property, Cat.Description, SecData.NtSecDescPrimary, Cat.ItemID, CAST (0 AS BIT), -- not found, Cat.Intermediate, Cat.ExecutionFlag, SD.SnapshotDataID, SD.DependsOnUser, Cat.ExecutionTime, (SELECT Schedule.NextRunTime FROM Schedule WITH (XLOCK) INNER JOIN ReportSchedule ON Schedule.ScheduleID = ReportSchedule.ScheduleID WHERE ReportSchedule.ReportID = Cat.ItemID AND ReportSchedule.ReportAction = 1), -- update snapshot (SELECT Schedule.ScheduleID FROM Schedule INNER JOIN ReportSchedule ON Schedule.ScheduleID = ReportSchedule.ScheduleID WHERE ReportSchedule.ReportID = Cat.ItemID AND ReportSchedule.ReportAction = 1), -- update snapshot (SELECT CachePolicy.ExpirationFlags FROM CachePolicy WHERE CachePolicy.ReportID = Cat.ItemID), Cat2.Intermediate, SD.ProcessingFlags FROM Catalog AS Cat LEFT OUTER JOIN SecData ON Cat.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog AS Cat2 on Cat.LinkSourceID = Cat2.ItemID LEFT OUTER JOIN SnapshotData AS SD ON Cat.SnapshotDataID = SD.SnapshotDataID WHERE Cat.Path = @Path END ELSE BEGIN -- use cache SELECT TOP 1 Cat.Type, Cat.LinkSourceID, Cat2.Path, Cat.Property, Cat.Description, SecData.NtSecDescPrimary, Cat.ItemID, CAST (1 AS BIT), -- found, SN.SnapshotDataID, SN.DependsOnUser, SN.EffectiveParams, SN.CreatedDate, EC.AbsoluteExpiration, (SELECT CachePolicy.ExpirationFlags FROM CachePolicy WHERE CachePolicy.ReportID = Cat.ItemID), (SELECT Schedule.ScheduleID FROM Schedule WITH (XLOCK) INNER JOIN ReportSchedule ON Schedule.ScheduleID = ReportSchedule.ScheduleID WHERE ReportSchedule.ReportID = Cat.ItemID AND ReportSchedule.ReportAction = 1), -- update snapshot SN.QueryParams, SN.ProcessingFlags FROM Catalog AS Cat INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON Cat.ItemID = EC.ReportID INNER JOIN ReportServerTempDB.dbo.SnapshotData AS SN ON EC.SnapshotDataID = SN.SnapshotDataID LEFT OUTER JOIN SecData ON Cat.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog AS Cat2 on Cat.LinkSourceID = Cat2.ItemID WHERE Cat.Path = @Path AND AbsoluteExpiration > @now AND SN.ParamsHash = @ParamsHash ORDER BY SN.CreatedDate DESC END GO GRANT EXECUTE ON [dbo].[GetReportForExecution] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetReportParametersForExecution]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetReportParametersForExecution] GO -- gets either the intermediate format or snapshot from cache CREATE PROCEDURE [dbo].[GetReportParametersForExecution] @Path nvarchar (425), @HistoryID DateTime = NULL, @AuthType int AS SELECT C.[ItemID], C.[Type], C.[ExecutionFlag], [SecData].[NtSecDescPrimary], C.[Parameter], C.[Intermediate], C.[SnapshotDataID], [History].[SnapshotDataID], L.[Intermediate], C.[LinkSourceID], C.[ExecutionTime] FROM [Catalog] AS C LEFT OUTER JOIN [SecData] ON C.[PolicyID] = [SecData].[PolicyID] AND [SecData].AuthType = @AuthType LEFT OUTER JOIN [History] ON ( C.[ItemID] = [History].[ReportID] AND [History].[SnapshotDate] = @HistoryID ) LEFT OUTER JOIN [Catalog] AS L WITH (INDEX(PK_Catalog)) ON C.[LinkSourceID] = L.[ItemID] WHERE C.[Path] = @Path GO GRANT EXECUTE ON [dbo].[GetReportParametersForExecution] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[MoveObject]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[MoveObject] GO CREATE PROCEDURE [dbo].[MoveObject] @OldPath nvarchar (425), @OldPrefix nvarchar (850), @NewName nvarchar (425), @NewPath nvarchar (425), @NewParentID uniqueidentifier, @RenameOnly as bit, @MaxPathLength as int AS DECLARE @LongPath nvarchar(425) SET @LongPath = (SELECT TOP 1 Path FROM Catalog WHERE LEN(Path)-LEN(@OldPath)+LEN(@NewPath) > @MaxPathLength AND Path LIKE @OldPrefix ESCAPE '*') IF @LongPath IS NOT NULL BEGIN SELECT @LongPath RETURN END IF @RenameOnly = 0 -- if this a full-blown move, not just a rename BEGIN -- adjust policies on the top item that gets moved DECLARE @OldInheritedPolicyID as uniqueidentifier SELECT @OldInheritedPolicyID = (SELECT PolicyID FROM Catalog with (XLOCK) WHERE Path = @OldPath AND PolicyRoot = 0) IF (@OldInheritedPolicyID IS NOT NULL) BEGIN -- this was not a policy root, change it to inherit from target folder DECLARE @NewPolicyID as uniqueidentifier SELECT @NewPolicyID = (SELECT PolicyID FROM Catalog with (XLOCK) WHERE ItemID = @NewParentID) -- update item and children that shared the old policy UPDATE Catalog SET PolicyID = @NewPolicyID WHERE Path = @OldPath UPDATE Catalog SET PolicyID = @NewPolicyID WHERE Path LIKE @OldPrefix ESCAPE '*' AND Catalog.PolicyID = @OldInheritedPolicyID END END -- Update item that gets moved (Path, Name, and ParentId) update Catalog set Name = @NewName, Path = @NewPath, ParentID = @NewParentID where Path = @OldPath -- Update all its children (Path only, Names and ParentIds stay the same) update Catalog set Path = STUFF(Path, 1, LEN(@OldPath), @NewPath ) where Path like @OldPrefix escape '*' GO GRANT EXECUTE ON [dbo].[MoveObject] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ObjectExists]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ObjectExists] GO CREATE PROCEDURE [dbo].[ObjectExists] @Path nvarchar (425), @AuthType int AS SELECT Type, ItemID, SnapshotLimit, NtSecDescPrimary, ExecutionFlag, Intermediate, [LinkSourceID] FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[ObjectExists] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetAllProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetAllProperties] GO CREATE PROCEDURE [dbo].[SetAllProperties] @Path nvarchar (425), @Property ntext, @Description ntext = NULL, @Hidden bit = NULL, @ModifiedBySid varbinary (85) = NULL, @ModifiedByName nvarchar(260), @AuthType int, @ModifiedDate DateTime AS DECLARE @ModifiedByID uniqueidentifier EXEC GetUserID @ModifiedBySid, @ModifiedByName, @AuthType, @ModifiedByID OUTPUT UPDATE Catalog SET Property = @Property, Description = @Description, Hidden = @Hidden, ModifiedByID = @ModifiedByID, ModifiedDate = @ModifiedDate WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[SetAllProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FlushReportFromCache]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FlushReportFromCache] GO CREATE PROCEDURE [dbo].[FlushReportFromCache] @Path as nvarchar(425) AS SET DEADLOCK_PRIORITY LOW -- VSTS #139360: SQL Deadlock in GetReportForexecution stored procedure -- Use temporary table to keep the same order of accessing the ExecutionCache -- and SnapshotData tables as GetReportForExecution does, that is first -- delete from the ExecutionCache, then update the SnapshotData CREATE TABLE #tempSnapshot (SnapshotDataID uniqueidentifier) INSERT INTO #tempSnapshot SELECT SN.SnapshotDataID FROM ReportServerTempDB.dbo.SnapshotData AS SN WITH (UPDLOCK) INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC WITH (UPDLOCK) ON SN.SnapshotDataID = EC.SnapshotDataID INNER JOIN Catalog AS C ON EC.ReportID = C.ItemID WHERE C.Path = @Path DELETE EC FROM ReportServerTempDB.dbo.ExecutionCache AS EC INNER JOIN #tempSnapshot ON #tempSnapshot.SnapshotDataID = EC.SnapshotDataID UPDATE SN SET SN.PermanentRefcount = SN.PermanentRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN #tempSnapshot ON #tempSnapshot.SnapshotDataID = SN.SnapshotDataID GO GRANT EXECUTE ON [dbo].[FlushReportFromCache] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetParameters] GO CREATE PROCEDURE [dbo].[SetParameters] @Path nvarchar (425), @Parameter ntext AS UPDATE Catalog SET [Parameter] = @Parameter WHERE Path = @Path EXEC FlushReportFromCache @Path GO GRANT EXECUTE ON [dbo].[SetParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetObjectContent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetObjectContent] GO CREATE PROCEDURE [dbo].[SetObjectContent] @Path nvarchar (425), @Type int, @Content image = NULL, @Intermediate uniqueidentifier = NULL, @Parameter ntext = NULL, @LinkSourceID uniqueidentifier = NULL, @MimeType nvarchar (260) = NULL AS DECLARE @OldIntermediate as uniqueidentifier SET @OldIntermediate = (SELECT Intermediate FROM Catalog WITH (XLOCK) WHERE Path = @Path) UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 WHERE SnapshotData.SnapshotDataID = @OldIntermediate UPDATE Catalog SET Type=@Type, Content = @Content, Intermediate = @Intermediate, [Parameter] = @Parameter, LinkSourceID = @LinkSourceID, MimeType = @MimeType WHERE Path = @Path UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount + 1, TransientRefcount = TransientRefcount - 1 WHERE SnapshotData.SnapshotDataID = @Intermediate EXEC FlushReportFromCache @Path GO GRANT EXECUTE ON [dbo].[SetObjectContent] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetLastModified]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetLastModified] GO CREATE PROCEDURE [dbo].[SetLastModified] @Path nvarchar (425), @ModifiedBySid varbinary (85) = NULL, @ModifiedByName nvarchar(260), @AuthType int, @ModifiedDate DateTime AS DECLARE @ModifiedByID uniqueidentifier EXEC GetUserID @ModifiedBySid, @ModifiedByName, @AuthType, @ModifiedByID OUTPUT UPDATE Catalog SET ModifiedByID = @ModifiedByID, ModifiedDate = @ModifiedDate WHERE Path = @Path GO GRANT EXECUTE ON [dbo].[SetLastModified] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetNameById]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetNameById] GO CREATE PROCEDURE [dbo].[GetNameById] @ItemID uniqueidentifier AS SELECT Path FROM Catalog WHERE ItemID = @ItemID GO GRANT EXECUTE ON [dbo].[GetNameById] TO RSExecRole GO -------------------------------------------------- ------------- Data source procedures to store user names and passwords if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddDataSource] GO CREATE PROCEDURE [dbo].[AddDataSource] @DSID [uniqueidentifier], @ItemID [uniqueidentifier] = NULL, -- null for future suport dynamic delivery @SubscriptionID [uniqueidentifier] = NULL, @Name [nvarchar] (260) = NULL, -- only for scoped data sources, MUST be NULL for standalone!!! @Extension [nvarchar] (260) = NULL, @LinkID [uniqueidentifier] = NULL, -- link id is trusted, if it is provided - we use it @LinkPath [nvarchar] (425) = NULL, -- if LinkId is not provided we try to look up LinkPath @CredentialRetrieval [int], @Prompt [ntext] = NULL, @ConnectionString [image] = NULL, @OriginalConnectionString [image] = NULL, @OriginalConnectStringExpressionBased [bit] = NULL, @UserName [image] = NULL, @Password [image] = NULL, @Flags [int], @AuthType [int], @Version [int] AS DECLARE @ActualLinkID uniqueidentifier SET @ActualLinkID = NULL IF (@LinkID is NULL) AND (@LinkPath is not NULL) BEGIN SELECT Type, ItemID, NtSecDescPrimary FROM Catalog LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Path = @LinkPath SET @ActualLinkID = (SELECT ItemID FROM Catalog WHERE Path = @LinkPath) END ELSE BEGIN SET @ActualLinkID = @LinkID END INSERT INTO DataSource ([DSID], [ItemID], [SubscriptionID], [Name], [Extension], [Link], [CredentialRetrieval], [Prompt], [ConnectionString], [OriginalConnectionString], [OriginalConnectStringExpressionBased], [UserName], [Password], [Flags], [Version]) VALUES (@DSID, @ItemID, @SubscriptionID, @Name, @Extension, @ActualLinkID, @CredentialRetrieval, @Prompt, @ConnectionString, @OriginalConnectionString, @OriginalConnectStringExpressionBased, @UserName, @Password, @Flags, @Version) GO GRANT EXECUTE ON [dbo].[AddDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDataSources]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDataSources] GO CREATE PROCEDURE [dbo].[GetDataSources] @ItemID [uniqueidentifier], @AuthType int AS SELECT -- select data sources and their links (if they exist) DS.[DSID], -- 0 DS.[ItemID], -- 1 DS.[Name], -- 2 DS.[Extension], -- 3 DS.[Link], -- 4 DS.[CredentialRetrieval], -- 5 DS.[Prompt], -- 6 DS.[ConnectionString], -- 7 DS.[OriginalConnectionString], -- 8 DS.[UserName], -- 9 DS.[Password], -- 10 DS.[Flags], -- 11 DSL.[DSID], -- 12 DSL.[ItemID], -- 13 DSL.[Name], -- 14 DSL.[Extension], -- 15 DSL.[Link], -- 16 DSL.[CredentialRetrieval], -- 17 DSL.[Prompt], -- 18 DSL.[ConnectionString], -- 19 DSL.[UserName], -- 20 DSL.[Password], -- 21 DSL.[Flags], -- 22 C.Path, -- 23 SD.NtSecDescPrimary, -- 24 DS.[OriginalConnectStringExpressionBased], -- 25 DS.[Version], -- 26 DSL.[Version], -- 27 (SELECT 1 WHERE EXISTS (SELECT * from [ModelItemPolicy] AS MIP WHERE C.[ItemID] = MIP.[CatalogItemID])) -- 28 FROM [DataSource] AS DS LEFT OUTER JOIN ([DataSource] AS DSL INNER JOIN [Catalog] AS C ON DSL.[ItemID] = C.[ItemID] LEFT OUTER JOIN [SecData] AS SD ON C.[PolicyID] = SD.[PolicyID] AND SD.AuthType = @AuthType) ON DS.[Link] = DSL.[ItemID] WHERE DS.[ItemID] = @ItemID or DS.[SubscriptionID] = @ItemID GO GRANT EXECUTE ON [dbo].[GetDataSources] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteDataSources]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteDataSources] GO CREATE PROCEDURE [dbo].[DeleteDataSources] @ItemID [uniqueidentifier] AS DELETE FROM [DataSource] WHERE [ItemID] = @ItemID or [SubscriptionID] = @ItemID GO GRANT EXECUTE ON [dbo].[DeleteDataSources] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ChangeStateOfDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ChangeStateOfDataSource] GO CREATE PROCEDURE [dbo].[ChangeStateOfDataSource] @ItemID [uniqueidentifier], @Enable bit AS IF @Enable != 0 BEGIN UPDATE [DataSource] SET [Flags] = [Flags] | 1 WHERE [ItemID] = @ItemID END ELSE BEGIN UPDATE [DataSource] SET [Flags] = [Flags] & 0x7FFFFFFE WHERE [ItemID] = @ItemID END GO GRANT EXECUTE ON [dbo].[ChangeStateOfDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindItemsByDataSource]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[FindItemsByDataSource] GO CREATE PROCEDURE [dbo].[FindItemsByDataSource] @ItemID uniqueidentifier, @AuthType int AS SELECT C.Type, C.PolicyID, SD.NtSecDescPrimary, C.Name, C.Path, C.ItemID, DATALENGTH( C.Content ) AS [Size], C.Description, C.CreationDate, C.ModifiedDate, SUSER_SNAME(CU.Sid), CU.UserName, SUSER_SNAME(MU.Sid), MU.UserName, C.MimeType, C.ExecutionTime, C.Hidden FROM Catalog AS C INNER JOIN Users AS CU ON C.CreatedByID = CU.UserID INNER JOIN Users AS MU ON C.ModifiedByID = MU.UserID LEFT OUTER JOIN SecData AS SD ON C.PolicyID = SD.PolicyID AND SD.AuthType = @AuthType INNER JOIN DataSource AS DS ON C.ItemID = DS.ItemID WHERE DS.Link = @ItemID GO GRANT EXECUTE ON [dbo].[FindItemsByDataSource] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateRole] GO CREATE PROCEDURE [dbo].[CreateRole] @RoleID as uniqueidentifier, @RoleName as nvarchar(260), @Description as nvarchar(512) = null, @TaskMask as nvarchar(32), @RoleFlags as tinyint AS INSERT INTO Roles (RoleID, RoleName, Description, TaskMask, RoleFlags) VALUES (@RoleID, @RoleName, @Description, @TaskMask, @RoleFlags) GO GRANT EXECUTE ON [dbo].[CreateRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetRoles]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetRoles] GO CREATE PROCEDURE [dbo].[GetRoles] @RoleFlags as tinyint = NULL AS SELECT RoleName, Description, TaskMask FROM Roles WHERE (@RoleFlags is NULL) OR (RoleFlags = @RoleFlags) GO GRANT EXECUTE ON [dbo].[GetRoles] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteRole] GO -- Delete all policies associated with this role CREATE PROCEDURE [dbo].[DeleteRole] @RoleName nvarchar(260) AS SET NOCOUNT OFF -- if you call this, you must delete/reconstruct all policies associated with this role DELETE FROM Roles WHERE RoleName = @RoleName GO GRANT EXECUTE ON [dbo].[DeleteRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadRoleProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadRoleProperties] GO CREATE PROCEDURE [dbo].[ReadRoleProperties] @RoleName as nvarchar(260) AS SELECT Description, TaskMask, RoleFlags FROM Roles WHERE RoleName = @RoleName GO GRANT EXECUTE ON [dbo].[ReadRoleProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetRoleProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetRoleProperties] GO CREATE PROCEDURE [dbo].[SetRoleProperties] @RoleName as nvarchar(260), @Description as nvarchar(512) = NULL, @TaskMask as nvarchar(32), @RoleFlags as tinyint AS SET NOCOUNT OFF DECLARE @ExistingRoleFlags as tinyint SET @ExistingRoleFlags = (SELECT RoleFlags FROM Roles WHERE RoleName = @RoleName) IF @ExistingRoleFlags IS NULL BEGIN RETURN END IF @ExistingRoleFlags <> @RoleFlags BEGIN RAISERROR ('Bad role flags', 16, 1) END UPDATE Roles SET Description = @Description, TaskMask = @TaskMask, RoleFlags = @RoleFlags WHERE RoleName = @RoleName GO GRANT EXECUTE ON [dbo].[SetRoleProperties] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPoliciesForRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPoliciesForRole] GO CREATE PROCEDURE [dbo].[GetPoliciesForRole] @RoleName as nvarchar(260), @AuthType as int AS SELECT Policies.PolicyID, SecData.XmlDescription, Policies.PolicyFlag, Catalog.Type, Catalog.Path, ModelItemPolicy.CatalogItemID, ModelItemPolicy.ModelItemID, RelatedRoles.RoleID, RelatedRoles.RoleName, RelatedRoles.TaskMask, RelatedRoles.RoleFlags FROM Roles INNER JOIN PolicyUserRole ON Roles.RoleID = PolicyUserRole.RoleID INNER JOIN Policies ON PolicyUserRole.PolicyID = Policies.PolicyID INNER JOIN PolicyUserRole AS RelatedPolicyUserRole ON Policies.PolicyID = RelatedPolicyUserRole.PolicyID INNER JOIN Roles AS RelatedRoles ON RelatedPolicyUserRole.RoleID = RelatedRoles.RoleID LEFT OUTER JOIN SecData ON Policies.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType LEFT OUTER JOIN Catalog ON Policies.PolicyID = Catalog.PolicyID AND Catalog.PolicyRoot = 1 LEFT OUTER JOIN ModelItemPolicy ON Policies.PolicyID = ModelItemPolicy.PolicyID WHERE Roles.RoleName = @RoleName ORDER BY Policies.PolicyID GO GRANT EXECUTE ON [dbo].[GetPoliciesForRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdatePolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdatePolicy] GO CREATE PROCEDURE [dbo].[UpdatePolicy] @PolicyID as uniqueidentifier, @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @AuthType int AS UPDATE SecData SET NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND SecData.AuthType = @AuthType GO GRANT EXECUTE ON [dbo].[UpdatePolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetPolicy] GO -- this assumes the item exists in the catalog CREATE PROCEDURE [dbo].[SetPolicy] @ItemName as nvarchar(425), @ItemNameLike as nvarchar(850), @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @XmlPolicy as ntext, @AuthType int, @PolicyID uniqueidentifier OUTPUT AS SELECT @PolicyID = (SELECT PolicyID FROM Catalog WHERE Path = @ItemName AND PolicyRoot = 1) IF (@PolicyID IS NULL) BEGIN -- this is not a policy root SET @PolicyID = newid() INSERT INTO Policies (PolicyID, PolicyFlag) VALUES (@PolicyID, 0) INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) DECLARE @OldPolicyID as uniqueidentifier SELECT @OldPolicyID = (SELECT PolicyID FROM Catalog WHERE Path = @ItemName) -- update item and children that shared the old policy UPDATE Catalog SET PolicyID = @PolicyID, PolicyRoot = 1 WHERE Path = @ItemName UPDATE Catalog SET PolicyID = @PolicyID WHERE Path LIKE @ItemNameLike ESCAPE '*' AND Catalog.PolicyID = @OldPolicyID END ELSE BEGIN UPDATE Policies SET PolicyFlag = 0 WHERE Policies.PolicyID = @PolicyID DECLARE @SecDataID as uniqueidentifier SELECT @SecDataID = (SELECT SecDataID FROM SecData WHERE PolicyID = @PolicyID and AuthType = @AuthType) IF (@SecDataID IS NULL) BEGIN -- insert new sec desc's INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription ,NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN -- update existing sec desc's UPDATE SecData SET XmlDescription = @XmlPolicy, NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND AuthType = @AuthType END END DELETE FROM PolicyUserRole WHERE PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[SetPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSystemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSystemPolicy] GO -- update the system policy CREATE PROCEDURE [dbo].[SetSystemPolicy] @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @XmlPolicy as ntext, @AuthType as int, @PolicyID uniqueidentifier OUTPUT AS SELECT @PolicyID = (SELECT PolicyID FROM Policies WHERE PolicyFlag = 1) IF (@PolicyID IS NULL) BEGIN SET @PolicyID = newid() INSERT INTO Policies (PolicyID, PolicyFlag) VALUES (@PolicyID, 1) INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN DECLARE @SecDataID as uniqueidentifier SELECT @SecDataID = (SELECT SecDataID FROM SecData WHERE PolicyID = @PolicyID and AuthType = @AuthType) IF (@SecDataID IS NULL) BEGIN -- insert new sec desc's INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN -- update existing sec desc's UPDATE SecData SET XmlDescription = @XmlPolicy, NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND AuthType = @AuthType END END DELETE FROM PolicyUserRole WHERE PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[SetSystemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetModelItemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetModelItemPolicy] GO -- update the system policy CREATE PROCEDURE [dbo].[SetModelItemPolicy] @CatalogItemID as uniqueidentifier, @ModelItemID as nvarchar(425), @PrimarySecDesc as image, @SecondarySecDesc as ntext = NULL, @XmlPolicy as ntext, @AuthType as int, @PolicyID uniqueidentifier OUTPUT AS SELECT @PolicyID = (SELECT PolicyID FROM ModelItemPolicy WHERE CatalogItemID = @CatalogItemID AND ModelItemID = @ModelItemID ) IF (@PolicyID IS NULL) BEGIN SET @PolicyID = newid() INSERT INTO Policies (PolicyID, PolicyFlag) VALUES (@PolicyID, 2) INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) INSERT INTO ModelItemPolicy (ID, CatalogItemID, ModelItemID, PolicyID) VALUES (newid(), @CatalogItemID, @ModelItemID, @PolicyID) END ELSE BEGIN DECLARE @SecDataID as uniqueidentifier SELECT @SecDataID = (SELECT SecDataID FROM SecData WHERE PolicyID = @PolicyID and AuthType = @AuthType) IF (@SecDataID IS NULL) BEGIN -- insert new sec desc's INSERT INTO SecData (SecDataID, PolicyID, AuthType, XmlDescription, NTSecDescPrimary, NtSecDescSecondary) VALUES (newid(), @PolicyID, @AuthType, @XmlPolicy, @PrimarySecDesc, @SecondarySecDesc) END ELSE BEGIN -- update existing sec desc's UPDATE SecData SET XmlDescription = @XmlPolicy, NtSecDescPrimary = @PrimarySecDesc, NtSecDescSecondary = @SecondarySecDesc WHERE SecData.PolicyID = @PolicyID AND AuthType = @AuthType END END DELETE FROM PolicyUserRole WHERE PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[SetModelItemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdatePolicyPrincipal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdatePolicyPrincipal] GO CREATE PROCEDURE [dbo].[UpdatePolicyPrincipal] @PolicyID uniqueidentifier, @PrincipalSid varbinary(85) = NULL, @PrincipalName nvarchar(260), @PrincipalAuthType int, @RoleName nvarchar(260), @PrincipalID uniqueidentifier OUTPUT, @RoleID uniqueidentifier OUTPUT AS EXEC GetPrincipalID @PrincipalSid , @PrincipalName, @PrincipalAuthType, @PrincipalID OUTPUT SELECT @RoleID = (SELECT RoleID FROM Roles WHERE RoleName = @RoleName) INSERT INTO PolicyUserRole (ID, RoleID, UserID, PolicyID) VALUES (newid(), @RoleID, @PrincipalID, @PolicyID) GO GRANT EXECUTE ON [dbo].[UpdatePolicyPrincipal] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdatePolicyRole]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdatePolicyRole] GO CREATE PROCEDURE [dbo].[UpdatePolicyRole] @PolicyID uniqueidentifier, @PrincipalID uniqueidentifier, @RoleName nvarchar(260), @RoleID uniqueidentifier OUTPUT AS SELECT @RoleID = (SELECT RoleID FROM Roles WHERE RoleName = @RoleName) INSERT INTO PolicyUserRole (ID, RoleID, UserID, PolicyID) VALUES (newid(), @RoleID, @PrincipalID, @PolicyID) GO GRANT EXECUTE ON [dbo].[UpdatePolicyRole] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPolicy] GO CREATE PROCEDURE [dbo].[GetPolicy] @ItemName as nvarchar(425), @AuthType int AS SELECT SecData.XmlDescription, Catalog.PolicyRoot , SecData.NtSecDescPrimary, Catalog.Type FROM Catalog INNER JOIN Policies ON Catalog.PolicyID = Policies.PolicyID LEFT OUTER JOIN SecData ON Policies.PolicyID = SecData.PolicyID AND AuthType = @AuthType WHERE Catalog.Path = @ItemName AND PolicyFlag = 0 GO GRANT EXECUTE ON [dbo].[GetPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSystemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSystemPolicy] GO CREATE PROCEDURE [dbo].[GetSystemPolicy] @AuthType int AS SELECT SecData.NtSecDescPrimary, SecData.XmlDescription FROM Policies LEFT OUTER JOIN SecData ON Policies.PolicyID = SecData.PolicyID AND AuthType = @AuthType WHERE PolicyFlag = 1 GO GRANT EXECUTE ON [dbo].[GetSystemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeletePolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeletePolicy] GO CREATE PROCEDURE [dbo].[DeletePolicy] @ItemName as nvarchar(425) AS SET NOCOUNT OFF DECLARE @OldPolicyID uniqueidentifier SELECT @OldPolicyID = (SELECT PolicyID FROM Catalog WHERE Catalog.Path = @ItemName) UPDATE Catalog SET PolicyID = (SELECT Parent.PolicyID FROM Catalog Parent, Catalog WHERE Parent.ItemID = Catalog.ParentID AND Catalog.Path = @ItemName), PolicyRoot = 0 WHERE Catalog.PolicyID = @OldPolicyID DELETE Policies FROM Policies WHERE Policies.PolicyID = @OldPolicyID GO GRANT EXECUTE ON [dbo].[DeletePolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateSession]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateSession] GO -- Writes or updates session record CREATE PROCEDURE [dbo].[CreateSession] @SessionID as varchar(32), @CompiledDefinition as uniqueidentifier = NULL, @SnapshotDataID as uniqueidentifier = NULL, @IsPermanentSnapshot as bit = NULL, @ReportPath as nvarchar(440) = NULL, @Timeout as int, @AutoRefreshSeconds as int = NULL, @DataSourceInfo as image = NULL, @OwnerName as nvarchar (260), @OwnerSid as varbinary (85) = NULL, @AuthType as int, @EffectiveParams as ntext = NULL, @HistoryDate as datetime = NULL, @PageHeight as float = NULL, @PageWidth as float = NULL, @TopMargin as float = NULL, @BottomMargin as float = NULL, @LeftMargin as float = NULL, @RightMargin as float = NULL, @AwaitingFirstExecution as bit = NULL AS UPDATE PS SET PS.RefCount = 1 FROM ReportServerTempDB.dbo.PersistedStream as PS WHERE PS.SessionID = @SessionID UPDATE SN SET TransientRefcount = TransientRefcount + 1 FROM SnapshotData AS SN WHERE SN.SnapshotDataID = @SnapshotDataID UPDATE SN SET TransientRefcount = TransientRefcount + 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN WHERE SN.SnapshotDataID = @SnapshotDataID DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT DECLARE @now datetime SET @now = GETDATE() INSERT INTO ReportServerTempDB.dbo.SessionData ( SessionID, CompiledDefinition, SnapshotDataID, IsPermanentSnapshot, ReportPath, Timeout, AutoRefreshSeconds, Expiration, DataSourceInfo, OwnerID, EffectiveParams, CreationTime, HistoryDate, PageHeight, PageWidth, TopMargin, BottomMargin, LeftMargin, RightMargin, AwaitingFirstExecution ) VALUES ( @SessionID, @CompiledDefinition, @SnapshotDataID, @IsPermanentSnapshot, @ReportPath, @Timeout, @AutoRefreshSeconds, DATEADD(s, @Timeout, @now), @DataSourceInfo, @OwnerID, @EffectiveParams, @now, @HistoryDate, @PageHeight, @PageWidth, @TopMargin, @BottomMargin, @LeftMargin, @RightMargin, @AwaitingFirstExecution ) INSERT INTO ReportServerTempDB.dbo.SessionLock(SessionID) VALUES (@SessionID) GO GRANT EXECUTE ON [dbo].[CreateSession] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteModelItemPolicy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteModelItemPolicy] GO CREATE PROCEDURE [dbo].[DeleteModelItemPolicy] @CatalogItemID as uniqueidentifier, @ModelItemID as nvarchar(425) AS SET NOCOUNT OFF DECLARE @PolicyID uniqueidentifier SELECT @PolicyID = (SELECT PolicyID FROM ModelItemPolicy WHERE CatalogItemID = @CatalogItemID AND ModelItemID = @ModelItemID) DELETE Policies FROM Policies WHERE Policies.PolicyID = @PolicyID GO GRANT EXECUTE ON [dbo].[DeleteModelItemPolicy] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteAllModelItemPolicies]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteAllModelItemPolicies] GO CREATE PROCEDURE [dbo].[DeleteAllModelItemPolicies] @Path as nvarchar(450) AS DELETE Policies FROM Policies AS P INNER JOIN ModelItemPolicy AS MIP ON P.PolicyID = MIP.PolicyID INNER JOIN Catalog AS C ON MIP.CatalogItemID = C.ItemID WHERE C.[Path] = @Path GO GRANT EXECUTE ON [dbo].[DeleteAllModelItemPolicies] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelItemInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelItemInfo] GO CREATE PROCEDURE [dbo].[GetModelItemInfo] @Path nvarchar (425), @UseUpdateLock bit AS IF(@UseUpdateLock = 0) BEGIN SELECT C.[Intermediate] FROM [Catalog] AS C WHERE C.[Path] = @Path END ELSE BEGIN -- acquire update lock, this means that the operation is being performed in a -- different transaction context which will be committed before trying to -- perform the actual load, to prevent deadlock in the case where we have to -- republish, this new transaction will acquire and hold upgrade locks SELECT C.[Intermediate] FROM [Catalog] AS C WITH(UPDLOCK ROWLOCK) WHERE C.[Path] = @Path END SELECT MIP.[ModelItemID], SD.[NtSecDescPrimary], SD.[XmlDescription] FROM [Catalog] AS C INNER JOIN [ModelItemPolicy] AS MIP ON C.[ItemID] = MIP.[CatalogItemID] LEFT OUTER JOIN [SecData] AS SD ON MIP.[PolicyID] = SD.[PolicyID] WHERE C.[Path] = @Path GO GRANT EXECUTE ON [dbo].[GetModelItemInfo] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelDefinition]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelDefinition] GO CREATE PROCEDURE [dbo].[GetModelDefinition] @CatalogItemID as uniqueidentifier AS SELECT C.[Content] FROM [Catalog] AS C WHERE C.[ItemID] = @CatalogItemID GO GRANT EXECUTE ON [dbo].[GetModelDefinition] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddModelPerspective]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddModelPerspective] GO CREATE PROCEDURE [dbo].[AddModelPerspective] @ModelID as uniqueidentifier, @PerspectiveID as ntext, @PerspectiveName as ntext = null, @PerspectiveDescription as ntext = null AS INSERT INTO [ModelPerspective] ([ID], [ModelID], [PerspectiveID], [PerspectiveName], [PerspectiveDescription]) VALUES (newid(), @ModelID, @PerspectiveID, @PerspectiveName, @PerspectiveDescription) GO GRANT EXECUTE ON [dbo].[AddModelPerspective] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteModelPerspectives]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteModelPerspectives] GO CREATE PROCEDURE [dbo].[DeleteModelPerspectives] @ModelID as uniqueidentifier AS DELETE FROM [ModelPerspective] WHERE [ModelID] = @ModelID GO GRANT EXECUTE ON [dbo].[DeleteModelPerspectives] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelsAndPerspectives]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelsAndPerspectives] GO CREATE PROCEDURE [dbo].[GetModelsAndPerspectives] @AuthType int, @SitePathPrefix nvarchar(520) = '%' AS SELECT C.[PolicyID], SD.[NtSecDescPrimary], C.[ItemID], C.[Path], C.[Description], P.[PerspectiveID], P.[PerspectiveName], P.[PerspectiveDescription] FROM [Catalog] as C LEFT OUTER JOIN [ModelPerspective] as P ON C.[ItemID] = P.[ModelID] LEFT OUTER JOIN [SecData] AS SD ON C.[PolicyID] = SD.[PolicyID] AND SD.[AuthType] = @AuthType WHERE C.Path like @SitePathPrefix AND C.[Type] = 6 -- Model ORDER BY C.[Path] GO GRANT EXECUTE ON [dbo].[GetModelsAndPerspectives] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetModelPerspectives]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetModelPerspectives] GO CREATE PROCEDURE [dbo].[GetModelPerspectives] @Path nvarchar (425), @AuthType int AS SELECT C.[Type], SD.[NtSecDescPrimary], C.[Description] FROM [Catalog] as C LEFT OUTER JOIN [SecData] AS SD ON C.[PolicyID] = SD.[PolicyID] AND SD.[AuthType] = @AuthType WHERE [Path] = @Path SELECT P.[PerspectiveID], P.[PerspectiveName], P.[PerspectiveDescription] FROM [Catalog] as C INNER JOIN [ModelPerspective] as P ON C.[ItemID] = P.[ModelID] WHERE [Path] = @Path GO GRANT EXECUTE ON [dbo].[GetModelPerspectives] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DereferenceSessionSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DereferenceSessionSnapshot] GO CREATE PROCEDURE [dbo].[DereferenceSessionSnapshot] @SessionID as varchar(32), @OwnerID as uniqueidentifier AS UPDATE SN SET TransientRefcount = TransientRefcount - 1 FROM SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.SessionData AS SE ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID UPDATE SN SET TransientRefcount = TransientRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.SessionData AS SE ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[DereferenceSessionSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSessionData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSessionData] GO -- Writes or updates session record CREATE PROCEDURE [dbo].[SetSessionData] @SessionID as varchar(32), @ReportPath as nvarchar(440), @HistoryDate as datetime = NULL, @Timeout as int, @AutoRefreshSeconds as int = NULL, @EffectiveParams ntext = NULL, @OwnerSid as varbinary (85) = NULL, @OwnerName as nvarchar (260), @AuthType as int, @ShowHideInfo as image = NULL, @DataSourceInfo as image = NULL, @SnapshotDataID as uniqueidentifier = NULL, @IsPermanentSnapshot as bit = NULL, @SnapshotTimeoutSeconds as int = NULL, @HasInteractivity as bit, @SnapshotExpirationDate as datetime = NULL, @AwaitingFirstExecution as bit = NULL AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT DECLARE @now datetime SET @now = GETDATE() -- is there a session for the same report ? DECLARE @OldSnapshotDataID uniqueidentifier DECLARE @OldIsPermanentSnapshot bit DECLARE @OldSessionID varchar(32) SELECT @OldSessionID = SessionID, @OldSnapshotDataID = SnapshotDataID, @OldIsPermanentSnapshot = IsPermanentSnapshot FROM ReportServerTempDB.dbo.SessionData WITH (XLOCK) WHERE SessionID = @SessionID IF @OldSessionID IS NOT NULL BEGIN -- Yes, update it IF @OldSnapshotDataID != @SnapshotDataID or @SnapshotDataID is NULL BEGIN EXEC DereferenceSessionSnapshot @SessionID, @OwnerID END UPDATE ReportServerTempDB.dbo.SessionData SET SnapshotDataID = @SnapshotDataID, IsPermanentSnapshot = @IsPermanentSnapshot, Timeout = @Timeout, AutoRefreshSeconds = @AutoRefreshSeconds, SnapshotExpirationDate = @SnapshotExpirationDate, -- we want database session to expire later than in-memory session Expiration = DATEADD(s, @Timeout+10, @now), ShowHideInfo = @ShowHideInfo, DataSourceInfo = @DataSourceInfo, AwaitingFirstExecution = @AwaitingFirstExecution -- EffectiveParams = @EffectiveParams, -- no need to update user params as they are always same -- ReportPath = @ReportPath -- OwnerID = @OwnerID WHERE SessionID = @SessionID -- update expiration date on a snapshot that we reference IF @IsPermanentSnapshot != 0 BEGIN UPDATE SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutSeconds, @now) WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN UPDATE ReportServerTempDB.dbo.SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutSeconds, @now) WHERE SnapshotDataID = @SnapshotDataID END END ELSE BEGIN -- no, insert it UPDATE PS SET PS.RefCount = 1 FROM ReportServerTempDB.dbo.PersistedStream as PS WHERE PS.SessionID = @SessionID INSERT INTO ReportServerTempDB.dbo.SessionData (SessionID, SnapshotDataID, IsPermanentSnapshot, ReportPath, EffectiveParams, Timeout, AutoRefreshSeconds, Expiration, ShowHideInfo, DataSourceInfo, OwnerID, CreationTime, HasInteractivity, SnapshotExpirationDate, HistoryDate, AwaitingFirstExecution) VALUES (@SessionID, @SnapshotDataID, @IsPermanentSnapshot, @ReportPath, @EffectiveParams, @Timeout, @AutoRefreshSeconds, DATEADD(s, @Timeout, @now), @ShowHideInfo, @DataSourceInfo, @OwnerID, @now, @HasInteractivity, @SnapshotExpirationDate, @HistoryDate, @AwaitingFirstExecution) END GO GRANT EXECUTE ON [dbo].[SetSessionData] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteLockSession]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteLockSession] GO CREATE PROCEDURE [dbo].[WriteLockSession] @SessionID as varchar(32), @Persisted bit AS SET NOCOUNT OFF ; IF @Persisted = 1 BEGIN UPDATE ReportServerTempDB.dbo.SessionLock WITH (ROWLOCK) SET SessionID = SessionID WHERE SessionID = @SessionID ; END ELSE BEGIN INSERT INTO ReportServerTempDB.dbo.SessionLock WITH (ROWLOCK) (SessionID) VALUES (@SessionID) END GO GRANT EXECUTE ON [dbo].[WriteLockSession] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CheckSessionLock]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CheckSessionLock] GO CREATE PROCEDURE [dbo].[CheckSessionLock] @SessionID as varchar(32) AS DECLARE @Selected nvarchar(32) SELECT @Selected=SessionID FROM ReportServerTempDB.dbo.SessionLock WITH (ROWLOCK) WHERE SessionID = @SessionID GO GRANT EXECUTE ON [dbo].[CheckSessionLock] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSessionData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSessionData] GO -- Get record from session data, update session and snapshot CREATE PROCEDURE [dbo].[GetSessionData] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @SnapshotTimeoutMinutes as int AS DECLARE @now as datetime SET @now = GETDATE() DECLARE @DBSessionID varchar(32) DECLARE @SnapshotDataID uniqueidentifier DECLARE @IsPermanentSnapshot bit EXEC CheckSessionLock @SessionID = @SessionID DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT SELECT @DBSessionID = SE.SessionID, @SnapshotDataID = SE.SnapshotDataID, @IsPermanentSnapshot = SE.IsPermanentSnapshot FROM ReportServerTempDB.dbo.SessionData AS SE WITH (XLOCK) WHERE SE.OwnerID = @OwnerID AND SE.SessionID = @SessionID AND SE.Expiration > @now IF (@DBSessionID IS NOT NULL) BEGIN -- We return something only if session is present IF @IsPermanentSnapshot != 0 BEGIN -- If session has snapshot and it is permanent SELECT SN.SnapshotDataID, SE.ShowHideInfo, SE.DataSourceInfo, SN.Description, SE.EffectiveParams, SN.CreatedDate, SE.IsPermanentSnapshot, SE.CreationTime, SE.HasInteractivity, SE.Timeout, SE.SnapshotExpirationDate, SE.ReportPath, SE.HistoryDate, SE.CompiledDefinition, SN.PageCount, SN.HasDocMap, SE.Expiration, SN.EffectiveParams, SE.PageHeight, SE.PageWidth, SE.TopMargin, SE.BottomMargin, SE.LeftMargin, SE.RightMargin, SE.AutoRefreshSeconds, SE.AwaitingFirstExecution, SN.[DependsOnUser], SN.PaginationMode, SN.ProcessingFlags, NULL, -- No compiled definition in tempdb to get flags from CONVERT(BIT, 0) AS [FoundInCache] -- permanent snapshot is never from Cache FROM ReportServerTempDB.dbo.SessionData AS SE INNER JOIN SnapshotData AS SN ON SN.SnapshotDataID = SE.SnapshotDataID WHERE SE.SessionID = @DBSessionID UPDATE SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutMinutes, @now) WHERE SnapshotDataID = @SnapshotDataID END ELSE IF @IsPermanentSnapshot = 0 BEGIN -- If session has snapshot and it is temporary SELECT SN.SnapshotDataID, SE.ShowHideInfo, SE.DataSourceInfo, SN.Description, SE.EffectiveParams, SN.CreatedDate, SE.IsPermanentSnapshot, SE.CreationTime, SE.HasInteractivity, SE.Timeout, SE.SnapshotExpirationDate, SE.ReportPath, SE.HistoryDate, SE.CompiledDefinition, SN.PageCount, SN.HasDocMap, SE.Expiration, SN.EffectiveParams, SE.PageHeight, SE.PageWidth, SE.TopMargin, SE.BottomMargin, SE.LeftMargin, SE.RightMargin, SE.AutoRefreshSeconds, SE.AwaitingFirstExecution, SN.[DependsOnUser], SN.PaginationMode, SN.ProcessingFlags, COMP.ProcessingFlags, -- If we are AwaitingFirstExecution, then we haven't executed a -- report and therefore have not been bound to a cached snapshot -- because that binding only happens at report execution time. CASE SE.AwaitingFirstExecution WHEN 1 THEN CONVERT(BIT, 0) ELSE SN.IsCached END FROM ReportServerTempDB.dbo.SessionData AS SE INNER JOIN ReportServerTempDB.dbo.SnapshotData AS SN ON SN.SnapshotDataID = SE.SnapshotDataID LEFT OUTER JOIN ReportServerTempDB.dbo.SnapshotData AS COMP ON SE.CompiledDefinition = COMP.SnapshotDataID WHERE SE.SessionID = @DBSessionID UPDATE ReportServerTempDB.dbo.SnapshotData SET ExpirationDate = DATEADD(n, @SnapshotTimeoutMinutes, @now) WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN -- If session doesn't have snapshot SELECT null, SE.ShowHideInfo, SE.DataSourceInfo, null, SE.EffectiveParams, null, SE.IsPermanentSnapshot, SE.CreationTime, SE.HasInteractivity, SE.Timeout, SE.SnapshotExpirationDate, SE.ReportPath, SE.HistoryDate, SE.CompiledDefinition, null, null, SE.Expiration, null, SE.PageHeight, SE.PageWidth, SE.TopMargin, SE.BottomMargin, SE.LeftMargin, SE.RightMargin, SE.AutoRefreshSeconds, SE.AwaitingFirstExecution, null, null, null, COMP.ProcessingFlags, CONVERT(BIT, 0) AS [FoundInCache] -- no snapshot, so it can't be from the cache FROM ReportServerTempDB.dbo.SessionData AS SE LEFT OUTER JOIN ReportServerTempDB.dbo.SnapshotData AS COMP ON (SE.CompiledDefinition = COMP.SnapshotDataID) WHERE SE.SessionID = @DBSessionID END END -- We need this update to keep session around while we process it. UPDATE SE SET Expiration = DATEADD(s, Timeout, GetDate()) FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @DBSessionID GO GRANT EXECUTE ON [dbo].[GetSessionData] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapshotFromHistory]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapshotFromHistory] GO CREATE PROCEDURE [dbo].[GetSnapshotFromHistory] @Path nvarchar (425), @SnapshotDate datetime, @AuthType int AS SELECT Catalog.ItemID, Catalog.Type, SnapshotData.SnapshotDataID, SnapshotData.DependsOnUser, SnapshotData.Description, SecData.NtSecDescPrimary, Catalog.[Property], SnapshotData.ProcessingFlags FROM SnapshotData INNER JOIN History ON History.SnapshotDataID = SnapshotData.SnapshotDataID INNER JOIN Catalog ON History.ReportID = Catalog.ItemID LEFT OUTER JOIN SecData ON Catalog.PolicyID = SecData.PolicyID AND SecData.AuthType = @AuthType WHERE Catalog.Path = @Path AND History.SnapshotDate = @SnapshotDate GO GRANT EXECUTE ON [dbo].[GetSnapshotFromHistory] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredSessions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredSessions] GO CREATE PROCEDURE [dbo].[CleanExpiredSessions] @SessionsCleaned int OUTPUT AS SET DEADLOCK_PRIORITY LOW DECLARE @SessionToDelete table (SessionID varchar(32) COLLATE Latin1_General_CI_AS_KS_WS); DECLARE @SessionLockDeleted table (SessionID varchar(32) COLLATE Latin1_General_CI_AS_KS_WS); CREATE TABLE #tempSession (SessionID varchar(32) COLLATE Latin1_General_CI_AS_KS_WS, SnapshotDataID uniqueidentifier, CompiledDefinition uniqueidentifier) DECLARE @now as datetime SET @now = GETDATE() INSERT INTO @SessionToDelete SELECT TOP 20 SessionID FROM ReportServerTempDB.dbo.SessionData SD WITH (XLOCK) WHERE Expiration < @now SET @SessionsCleaned = @@ROWCOUNT IF @SessionsCleaned = 0 RETURN DELETE SL output deleted.SessionID into @SessionLockDeleted(SessionID) FROM ReportServerTempDB.dbo.SessionLock AS SL WITH (ROWLOCK, READPAST) INNER JOIN @SessionToDelete AS STD ON SL.SessionID = STD.SessionID SET @SessionsCleaned = @@ROWCOUNT IF @SessionsCleaned = 0 RETURN DELETE SE output deleted.SessionID, deleted.SnapshotDataID, deleted.CompiledDefinition into #tempSession (SessionID, SnapshotDataID, CompiledDefinition) FROM ReportServerTempDB.dbo.SessionData AS SE INNER JOIN @SessionLockDeleted AS SLD on SE.SessionID = SLD.SessionID -- Mark persisted streams for this session to be deleted UPDATE PS SET RefCount = 0, ExpirationDate = GETDATE() FROM ReportServerTempDB.dbo.PersistedStream AS PS INNER JOIN #tempSession on PS.SessionID = #tempsession.SessionID UPDATE SN SET TransientRefcount = TransientRefcount-1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN #tempSession AS SE ON SN.SnapshotDataID = SE.CompiledDefinition UPDATE SN SET TransientRefcount = TransientRefcount- (SELECT COUNT(*) FROM #tempSession AS SE1 WHERE SE1.SnapshotDataID = SN.SnapshotDataID) FROM SnapshotData AS SN INNER JOIN #tempSession AS SE ON SN.SnapshotDataID = SE.SnapshotDataID UPDATE SN SET TransientRefcount = TransientRefcount- (SELECT COUNT(*) FROM #tempSession AS SE1 WHERE SE1.SnapshotDataID = SN.SnapshotDataID) FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN #tempSession AS SE ON SN.SnapshotDataID = SE.SnapshotDataID GO GRANT EXECUTE ON [dbo].[CleanExpiredSessions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredCache]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredCache] GO CREATE PROCEDURE [dbo].[CleanExpiredCache] AS SET NOCOUNT OFF DECLARE @now as datetime SET @now = DATEADD(minute, -1, GETDATE()) UPDATE SN SET PermanentRefcount = PermanentRefcount - 1 FROM ReportServerTempDB.dbo.SnapshotData AS SN INNER JOIN ReportServerTempDB.dbo.ExecutionCache AS EC ON SN.SnapshotDataID = EC.SnapshotDataID WHERE EC.AbsoluteExpiration < @now DELETE EC FROM ReportServerTempDB.dbo.ExecutionCache AS EC WHERE EC.AbsoluteExpiration < @now GO GRANT EXECUTE ON [dbo].[CleanExpiredCache] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSessionCredentials]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSessionCredentials] GO CREATE PROCEDURE [dbo].[SetSessionCredentials] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @DataSourceInfo as image = NULL, @Expiration as datetime, @EffectiveParams as ntext = NULL AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT EXEC DereferenceSessionSnapshot @SessionID, @OwnerID UPDATE SE SET SE.DataSourceInfo = @DataSourceInfo, SE.SnapshotDataID = null, SE.IsPermanentSnapshot = null, SE.SnapshotExpirationDate = null, SE.ShowHideInfo = null, SE.HasInteractivity = null, SE.AutoRefreshSeconds = null, SE.Expiration = @Expiration, SE.EffectiveParams = @EffectiveParams, SE.AwaitingFirstExecution = 1 FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[SetSessionCredentials] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetSessionParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetSessionParameters] GO CREATE PROCEDURE [dbo].[SetSessionParameters] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @EffectiveParams as ntext = NULL AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT UPDATE SE SET SE.EffectiveParams = @EffectiveParams, SE.AwaitingFirstExecution = 1 FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[SetSessionParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ClearSessionSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ClearSessionSnapshot] GO CREATE PROCEDURE [dbo].[ClearSessionSnapshot] @SessionID as varchar(32), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int, @Expiration as datetime AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT EXEC DereferenceSessionSnapshot @SessionID, @OwnerID UPDATE SE SET SE.SnapshotDataID = null, SE.IsPermanentSnapshot = null, SE.SnapshotExpirationDate = null, SE.ShowHideInfo = null, SE.HasInteractivity = null, SE.AutoRefreshSeconds = null, SE.Expiration = @Expiration FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.OwnerID = @OwnerID GO GRANT EXECUTE ON [dbo].[ClearSessionSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RemoveReportFromSession]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RemoveReportFromSession] GO CREATE PROCEDURE [dbo].[RemoveReportFromSession] @SessionID as varchar(32), @ReportPath as nvarchar(440), @OwnerSid as varbinary(85) = NULL, @OwnerName as nvarchar(260), @AuthType as int AS DECLARE @OwnerID uniqueidentifier EXEC GetUserID @OwnerSid, @OwnerName, @AuthType, @OwnerID OUTPUT EXEC DereferenceSessionSnapshot @SessionID, @OwnerID DELETE SE FROM ReportServerTempDB.dbo.SessionData AS SE WHERE SE.SessionID = @SessionID AND SE.ReportPath = @ReportPath AND SE.OwnerID = @OwnerID DELETE FROM ReportServerTempDB.dbo.SessionLock WHERE SessionID=@SessionID -- Delete any persisted streams associated with this session UPDATE PS SET PS.RefCount = 0, PS.ExpirationDate = GETDATE() FROM ReportServerTempDB.dbo.PersistedStream AS PS WHERE PS.SessionID = @SessionID GO GRANT EXECUTE ON [dbo].[RemoveReportFromSession] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanBrokenSnapshots]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanBrokenSnapshots] GO CREATE PROCEDURE [dbo].[CleanBrokenSnapshots] @Machine nvarchar(512), @SnapshotsCleaned int OUTPUT, @ChunksCleaned int OUTPUT, @TempSnapshotID uniqueidentifier OUTPUT AS SET DEADLOCK_PRIORITY LOW DECLARE @now AS datetime SELECT @now = GETDATE() CREATE TABLE #tempSnapshot (SnapshotDataID uniqueidentifier) INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM SnapshotData WITH (NOLOCK) where SnapshotData.PermanentRefcount <= 0 AND ExpirationDate < @now SET @SnapshotsCleaned = @@ROWCOUNT DELETE ChunkData FROM ChunkData INNER JOIN #tempSnapshot ON ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @@ROWCOUNT DELETE SnapshotData FROM SnapshotData INNER JOIN #tempSnapshot ON SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID TRUNCATE TABLE #tempSnapshot INSERT INTO #tempSnapshot SELECT TOP 1 SnapshotDataID FROM ReportServerTempDB.dbo.SnapshotData WITH (NOLOCK) where ReportServerTempDB.dbo.SnapshotData.PermanentRefcount <= 0 AND ReportServerTempDB.dbo.SnapshotData.ExpirationDate < @now AND ReportServerTempDB.dbo.SnapshotData.Machine = @Machine SET @SnapshotsCleaned = @SnapshotsCleaned + @@ROWCOUNT SELECT @TempSnapshotID = (SELECT SnapshotDataID FROM #tempSnapshot) DELETE ReportServerTempDB.dbo.ChunkData FROM ReportServerTempDB.dbo.ChunkData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.ChunkData.SnapshotDataID = #tempSnapshot.SnapshotDataID SET @ChunksCleaned = @ChunksCleaned + @@ROWCOUNT DELETE ReportServerTempDB.dbo.SnapshotData FROM ReportServerTempDB.dbo.SnapshotData INNER JOIN #tempSnapshot ON ReportServerTempDB.dbo.SnapshotData.SnapshotDataID = #tempSnapshot.SnapshotDataID GO GRANT EXECUTE ON [dbo].[CleanBrokenSnapshots] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanOrphanedSnapshots]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanOrphanedSnapshots] GO CREATE PROCEDURE [dbo].[CleanOrphanedSnapshots] @Machine nvarchar(512), @PermanentSnapshotCount int, @TemporarySnapshotCount int, @PermanentChunkCount int, @TemporaryChunkCount int, @PermanentMappingCount int, @TemporaryMappingCount int, @PermanentSegmentCount int, @TemporarySegmentCount int, @SnapshotsCleaned int OUTPUT, @ChunksCleaned int OUTPUT, @MappingsCleaned int OUTPUT, @SegmentsCleaned int OUTPUT AS SELECT @SnapshotsCleaned = 0, @ChunksCleaned = 0, @MappingsCleaned = 0, @SegmentsCleaned = 0 ; -- use readpast rather than NOLOCK. using -- nolock could cause us to identify snapshots -- which have had the refcount decremented but -- the transaction is uncommitted which is dangerous. SET DEADLOCK_PRIORITY LOW -- cleanup of segmented chunk information happens -- top->down. meaning we delete chunk metadata, then -- mappings, then segment data. the reason for doing -- this is because it minimizes the io read cost since -- each delete step tells us the work that we need to -- do in the next step. however, there is the potential -- for failure at any step which can leave orphaned data -- structures. we have another cleanup tasks -- which will scavenge this orphaned data and clean it up -- so we don't need to be 100% robust here. this also -- means that we can play tricks like using readpast in the -- dml operations so that concurrent deletes will minimize -- blocking of each other. -- also, we optimize this cleanup for the scenario where the chunk is -- not shared. this means that if we detect that a chunk is shared -- we will not delete any of its mappings. there is potential for this -- to miss removing a chunk because it is shared and we are concurrently -- deleting the other snapshot (both see the chunk as shared...). however -- we don't deal with that case here, and will instead orphan the chunk -- mappings and segments. that is ok, we will just remove them when we -- scan for orphaned mappings/segments. declare @cleanedSnapshots table (SnapshotDataId uniqueidentifier) ; declare @cleanedChunks table (ChunkId uniqueidentifier) ; declare @cleanedSegments table (ChunkId uniqueidentifier, SegmentId uniqueidentifier) ; declare @deleteCount int ; begin transaction -- remove the actual snapshot entry -- we do this transacted with cleaning up chunk -- data because we do not lazily clean up old ChunkData table. -- we also do this before cleaning up segmented chunk data to -- get this SnapshotData record out of the table so another parallel -- cleanup task does not attempt to delete it which would just cause -- contention and reduce cleanup throughput. DELETE TOP (@PermanentSnapshotCount) SnapshotData output deleted.SnapshotDataID into @cleanedSnapshots (SnapshotDataId) FROM SnapshotData with(readpast) WHERE SnapshotData.PermanentRefCount = 0 AND SnapshotData.TransientRefCount = 0 ; SET @SnapshotsCleaned = @@ROWCOUNT ; -- clean up RS2000/RS2005 chunks DELETE ChunkData FROM ChunkData INNER JOIN @cleanedSnapshots cs ON ChunkData.SnapshotDataID = cs.SnapshotDataId SET @ChunksCleaned = @@ROWCOUNT ; commit -- clean up chunks set @deleteCount = 1 ; while (@deleteCount > 0) begin delete top (@PermanentChunkCount) SC output deleted.ChunkId into @cleanedChunks(ChunkId) from SegmentedChunk SC with (readpast) join @cleanedSnapshots cs on SC.SnapshotDataId = cs.SnapshotDataId ; set @deleteCount = @@ROWCOUNT ; set @ChunksCleaned = @ChunksCleaned + @deleteCount ; end ; -- clean up unused mappings set @deleteCount = 1 ; while (@deleteCount > 0) begin delete top(@PermanentMappingCount) CSM output deleted.ChunkId, deleted.SegmentId into @cleanedSegments (ChunkId, SegmentId) from ChunkSegmentMapping CSM with (readpast) join @cleanedChunks cc ON CSM.ChunkId = cc.ChunkId where not exists ( select 1 from SegmentedChunk SC where SC.ChunkId = cc.ChunkId ) and not exists ( select 1 from ReportServerTempDB.dbo.SegmentedChunk TSC where TSC.ChunkId = cc.ChunkId ) ; set @deleteCount = @@ROWCOUNT ; set @MappingsCleaned = @MappingsCleaned + @deleteCount ; end ; -- clean up segments set @deleteCount = 1 while (@deleteCount > 0) begin delete top (@PermanentSegmentCount) S from Segment S with (readpast) join @cleanedSegments cs on S.SegmentId = cs.SegmentId where not exists ( select 1 from ChunkSegmentMapping csm where csm.SegmentId = cs.SegmentId ) ; set @deleteCount = @@ROWCOUNT ; set @SegmentsCleaned = @SegmentsCleaned + @deleteCount ; end DELETE FROM @cleanedSnapshots ; DELETE FROM @cleanedChunks ; DELETE FROM @cleanedSegments ; begin transaction DELETE TOP (@TemporarySnapshotCount) ReportServerTempDB.dbo.SnapshotData output deleted.SnapshotDataID into @cleanedSnapshots(SnapshotDataId) FROM ReportServerTempDB.dbo.SnapshotData with(readpast) WHERE ReportServerTempDB.dbo.SnapshotData.PermanentRefCount = 0 AND ReportServerTempDB.dbo.SnapshotData.TransientRefCount = 0 AND ReportServerTempDB.dbo.SnapshotData.Machine = @Machine ; SET @SnapshotsCleaned = @SnapshotsCleaned + @@ROWCOUNT ; DELETE ReportServerTempDB.dbo.ChunkData FROM ReportServerTempDB.dbo.ChunkData INNER JOIN @cleanedSnapshots cs ON ReportServerTempDB.dbo.ChunkData.SnapshotDataID = cs.SnapshotDataId SET @ChunksCleaned = @ChunksCleaned + @@ROWCOUNT commit set @deleteCount = 1 ; while (@deleteCount > 0) begin delete SC output deleted.ChunkId into @cleanedChunks(ChunkId) from ReportServerTempDB.dbo.SegmentedChunk SC with (readpast) join @cleanedSnapshots cs on SC.SnapshotDataId = cs.SnapshotDataId ; set @deleteCount = @@ROWCOUNT ; set @ChunksCleaned = @ChunksCleaned + @deleteCount ; end ; -- clean up unused mappings set @deleteCount = 1 ; while (@deleteCount > 0) begin delete top(@TemporaryMappingCount) CSM output deleted.ChunkId, deleted.SegmentId into @cleanedSegments (ChunkId, SegmentId) from ReportServerTempDB.dbo.ChunkSegmentMapping CSM with (readpast) join @cleanedChunks cc ON CSM.ChunkId = cc.ChunkId where not exists ( select 1 from ReportServerTempDB.dbo.SegmentedChunk SC where SC.ChunkId = cc.ChunkId ) ; set @deleteCount = @@ROWCOUNT ; set @MappingsCleaned = @MappingsCleaned + @deleteCount ; end ; select distinct ChunkId from @cleanedSegments ; -- clean up segments set @deleteCount = 1 while (@deleteCount > 0) begin delete top (@TemporarySegmentCount) S from ReportServerTempDB.dbo.Segment S with (readpast) join @cleanedSegments cs on S.SegmentId = cs.SegmentId where not exists ( select 1 from ReportServerTempDB.dbo.ChunkSegmentMapping csm where csm.SegmentId = cs.SegmentId ) ; set @deleteCount = @@ROWCOUNT ; set @SegmentsCleaned = @SegmentsCleaned + @deleteCount ; end GO GRANT EXECUTE ON [dbo].[CleanOrphanedSnapshots] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetCacheOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetCacheOptions] GO CREATE PROCEDURE [dbo].[SetCacheOptions] @Path as nvarchar(425), @CacheReport as bit, @ExpirationFlags as int, @CacheExpiration as int = NULL AS DECLARE @CachePolicyID as uniqueidentifier SELECT @CachePolicyID = (SELECT CachePolicyID FROM CachePolicy with (XLOCK) INNER JOIN Catalog ON Catalog.ItemID = CachePolicy.ReportID WHERE Catalog.Path = @Path) IF @CachePolicyID IS NULL -- no policy exists BEGIN IF @CacheReport = 1 -- create a new one BEGIN INSERT INTO CachePolicy (CachePolicyID, ReportID, ExpirationFlags, CacheExpiration) (SELECT NEWID(), ItemID, @ExpirationFlags, @CacheExpiration FROM Catalog WHERE Catalog.Path = @Path) END -- ELSE if it has no policy and we want to remove its policy do nothing END ELSE -- existing policy BEGIN IF @CacheReport = 1 BEGIN UPDATE CachePolicy SET ExpirationFlags = @ExpirationFlags, CacheExpiration = @CacheExpiration WHERE CachePolicyID = @CachePolicyID EXEC FlushReportFromCache @Path END ELSE BEGIN DELETE FROM CachePolicy WHERE CachePolicyID = @CachePolicyID EXEC FlushReportFromCache @Path END END GO GRANT EXECUTE ON [dbo].[SetCacheOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCacheOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetCacheOptions] GO CREATE PROCEDURE [dbo].[GetCacheOptions] @Path as nvarchar(425) AS SELECT ExpirationFlags, CacheExpiration, S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path] FROM CachePolicy INNER JOIN Catalog ON Catalog.ItemID = CachePolicy.ReportID LEFT outer join reportschedule rs on catalog.itemid = rs.reportid and rs.reportaction = 3 LEFT OUTER JOIN [Schedule] S ON S.ScheduleID = rs.ScheduleID LEFT OUTER JOIN [Users] Owner on Owner.UserID = S.[CreatedById] WHERE Catalog.Path = @Path GO GRANT EXECUTE ON [dbo].[GetCacheOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddReportToCache]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddReportToCache] GO CREATE PROCEDURE [dbo].[AddReportToCache] @ReportID as uniqueidentifier, @ExecutionDate datetime, @SnapshotDataID uniqueidentifier, @ExpirationDate datetime OUTPUT, @ScheduleID uniqueidentifier OUTPUT AS DECLARE @ExpirationFlags as int DECLARE @Timeout as int SET @ExpirationDate = NULL SET @ScheduleID = NULL SET @ExpirationFlags = (SELECT ExpirationFlags FROM CachePolicy WHERE ReportID = @ReportID) IF @ExpirationFlags = 1 -- timeout based BEGIN SET @Timeout = (SELECT CacheExpiration FROM CachePolicy WHERE ReportID = @ReportID) SET @ExpirationDate = DATEADD(n, @Timeout, @ExecutionDate) END ELSE IF @ExpirationFlags = 2 -- schedule based BEGIN SELECT @ScheduleID=s.ScheduleID, @ExpirationDate=s.NextRunTime FROM Schedule s WITH(UPDLOCK) INNER JOIN ReportSchedule rs ON rs.ScheduleID = s.ScheduleID and rs.ReportAction = 3 WHERE rs.ReportID = @ReportID END ELSE BEGIN -- Ignore NULL case. It means that a user set the Report not to be cached after the report execution fired. IF @ExpirationFlags IS NOT NULL BEGIN RAISERROR('Invalid cache flags', 16, 1) END RETURN END -- and to the report cache INSERT INTO ReportServerTempDB.dbo.ExecutionCache (ExecutionCacheID, ReportID, ExpirationFlags, AbsoluteExpiration, RelativeExpiration, SnapshotDataID) VALUES (newid(), @ReportID, @ExpirationFlags, @ExpirationDate, @Timeout, @SnapshotDataID ) UPDATE ReportServerTempDB.dbo.SnapshotData SET PermanentRefcount = PermanentRefcount + 1, IsCached = CONVERT(BIT, 1) WHERE SnapshotDataID = @SnapshotDataID; GO GRANT EXECUTE ON [dbo].[AddReportToCache] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetExecutionOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetExecutionOptions] GO CREATE PROCEDURE [dbo].[GetExecutionOptions] @Path nvarchar(425) AS SELECT ExecutionFlag, S.[ScheduleID], S.[Name], S.[StartDate], S.[Flags], S.[NextRunTime], S.[LastRunTime], S.[EndDate], S.[RecurrenceType], S.[MinutesInterval], S.[DaysInterval], S.[WeeksInterval], S.[DaysOfWeek], S.[DaysOfMonth], S.[Month], S.[MonthlyWeek], S.[State], S.[LastRunStatus], S.[ScheduledRunTimeout], S.[EventType], S.[EventData], S.[Type], S.[Path] FROM Catalog LEFT OUTER JOIN ReportSchedule ON Catalog.ItemID = ReportSchedule.ReportID AND ReportSchedule.ReportAction = 1 LEFT OUTER JOIN [Schedule] S ON S.ScheduleID = ReportSchedule.ScheduleID LEFT OUTER JOIN [Users] Owner on Owner.UserID = S.[CreatedById] WHERE Catalog.Path = @Path GO GRANT EXECUTE ON [dbo].[GetExecutionOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetExecutionOptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetExecutionOptions] GO CREATE PROCEDURE [dbo].[SetExecutionOptions] @Path as nvarchar(425), @ExecutionFlag as int, @ExecutionChanged as bit = 0 AS IF @ExecutionChanged = 0 BEGIN UPDATE Catalog SET ExecutionFlag = @ExecutionFlag WHERE Catalog.Path = @Path END ELSE BEGIN IF (@ExecutionFlag & 3) = 2 BEGIN -- set it to snapshot, flush cache EXEC FlushReportFromCache @Path DELETE CachePolicy FROM CachePolicy INNER JOIN Catalog ON CachePolicy.ReportID = Catalog.ItemID WHERE Catalog.Path = @Path END -- now clean existing snapshot and execution time if any UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount - 1 FROM SnapshotData INNER JOIN Catalog ON SnapshotData.SnapshotDataID = Catalog.SnapshotDataID WHERE Catalog.Path = @Path UPDATE Catalog SET ExecutionFlag = @ExecutionFlag, SnapshotDataID = NULL, ExecutionTime = NULL WHERE Catalog.Path = @Path END GO GRANT EXECUTE ON [dbo].[SetExecutionOptions] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSnapshot] GO CREATE PROCEDURE [dbo].[UpdateSnapshot] @Path as nvarchar(425), @SnapshotDataID as uniqueidentifier, @executionDate as datetime AS DECLARE @OldSnapshotDataID uniqueidentifier SET @OldSnapshotDataID = (SELECT SnapshotDataID FROM Catalog WITH (XLOCK) WHERE Catalog.Path = @Path) -- update reference count in snapshot table UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount-1 WHERE SnapshotData.SnapshotDataID = @OldSnapshotDataID -- update catalog to point to the new execution snapshot UPDATE Catalog SET SnapshotDataID = @SnapshotDataID, ExecutionTime = @executionDate WHERE Catalog.Path = @Path UPDATE SnapshotData SET PermanentRefcount = PermanentRefcount+1, TransientRefcount = TransientRefcount-1 WHERE SnapshotData.SnapshotDataID = @SnapshotDataID GO GRANT EXECUTE ON [dbo].[UpdateSnapshot] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateChunkAndGetPointer]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateChunkAndGetPointer] GO CREATE PROCEDURE [dbo].[CreateChunkAndGetPointer] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int, @MimeType nvarchar(260) = NULL, @Version smallint, @Content image, @ChunkFlags tinyint = NULL, @ChunkPointer binary(16) OUTPUT AS DECLARE @ChunkID uniqueidentifier SET @ChunkID = NEWID() IF @IsPermanentSnapshot != 0 BEGIN DELETE ChunkData WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType INSERT INTO ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) VALUES (@ChunkID, @SnapshotDataID, @ChunkName, @ChunkType, @MimeType, @Version, @ChunkFlags, @Content) SELECT @ChunkPointer = TEXTPTR(Content) FROM ChunkData WHERE ChunkData.ChunkID = @ChunkID END ELSE BEGIN DELETE ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType INSERT INTO ReportServerTempDB.dbo.ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) VALUES (@ChunkID, @SnapshotDataID, @ChunkName, @ChunkType, @MimeType, @Version, @ChunkFlags, @Content) SELECT @ChunkPointer = TEXTPTR(Content) FROM ReportServerTempDB.dbo.ChunkData AS CH WHERE CH.ChunkID = @ChunkID END GO GRANT EXECUTE ON [dbo].[CreateChunkAndGetPointer] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteChunkPortion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteChunkPortion] GO CREATE PROCEDURE [dbo].[WriteChunkPortion] @ChunkPointer binary(16), @IsPermanentSnapshot bit, @DataIndex int = NULL, @DeleteLength int = NULL, @Content image AS IF @IsPermanentSnapshot != 0 BEGIN UPDATETEXT ChunkData.Content @ChunkPointer @DataIndex @DeleteLength @Content END ELSE BEGIN UPDATETEXT ReportServerTempDB.dbo.ChunkData.Content @ChunkPointer @DataIndex @DeleteLength @Content END GO GRANT EXECUTE ON [dbo].[WriteChunkPortion] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetChunkPointerAndLength]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetChunkPointerAndLength] GO CREATE PROCEDURE [dbo].[GetChunkPointerAndLength] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int AS IF @IsPermanentSnapshot != 0 BEGIN SELECT TEXTPTR(Content), DATALENGTH(Content), MimeType, ChunkFlags, Version FROM ChunkData AS CH WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END ELSE BEGIN SELECT TEXTPTR(Content), DATALENGTH(Content), MimeType, ChunkFlags, Version FROM ReportServerTempDB.dbo.ChunkData AS CH WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END GO GRANT EXECUTE ON [dbo].[GetChunkPointerAndLength] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetChunkInformation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetChunkInformation] GO CREATE PROCEDURE [dbo].[GetChunkInformation] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int AS IF @IsPermanentSnapshot != 0 BEGIN SELECT MimeType FROM ChunkData AS CH WITH (HOLDLOCK, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END ELSE BEGIN SELECT MimeType FROM ReportServerTempDB.dbo.ChunkData AS CH WITH (HOLDLOCK, ROWLOCK) WHERE SnapshotDataID = @SnapshotDataID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END GO GRANT EXECUTE ON [dbo].[GetChunkInformation] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadChunkPortion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadChunkPortion] GO CREATE PROCEDURE [dbo].[ReadChunkPortion] @ChunkPointer binary(16), @IsPermanentSnapshot bit, @DataIndex int, @Length int AS IF @IsPermanentSnapshot != 0 BEGIN READTEXT ChunkData.Content @ChunkPointer @DataIndex @Length END ELSE BEGIN READTEXT ReportServerTempDB.dbo.ChunkData.Content @ChunkPointer @DataIndex @Length END GO GRANT EXECUTE ON [dbo].[ReadChunkPortion] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CopyChunksOfType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CopyChunksOfType] GO CREATE PROCEDURE [dbo].[CopyChunksOfType] @FromSnapshotID uniqueidentifier, @FromIsPermanent bit, @ToSnapshotID uniqueidentifier, @ToIsPermanent bit, @ChunkType int, @ChunkName nvarchar(260) = NULL, @TargetChunkName nvarchar(260) = NULL AS DECLARE @Machine nvarchar(512) IF @FromIsPermanent != 0 AND @ToIsPermanent = 0 BEGIN -- copy the contiguous chunks INSERT INTO ReportServerTempDB.dbo.ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) SELECT newid(), @ToSnapshotID, COALESCE(@TargetChunkName, S.ChunkName), S.ChunkType, S.MimeType, S.Version, S.ChunkFlags, S.Content FROM ChunkData AS S WHERE S.SnapshotDataID = @FromSnapshotID AND (S.ChunkType = @ChunkType OR @ChunkType IS NULL) AND (S.ChunkName = @ChunkName OR @ChunkName IS NUll) AND NOT EXISTS( SELECT T.ChunkName FROM ReportServerTempDB.dbo.ChunkData AS T -- exclude the ones in the target WHERE T.ChunkName = COALESCE(@TargetChunkName, S.ChunkName) AND T.ChunkType = S.ChunkType AND T.SnapshotDataID = @ToSnapshotID) -- the chunks will be cleaned up by the machine in which they are being allocated to select @Machine = Machine from ReportServerTempDB.dbo.SnapshotData SD where SD.SnapshotDataID = @ToSnapshotID INSERT INTO ReportServerTempDB.dbo.SegmentedChunk (SnapshotDataId, ChunkId, ChunkFlags, ChunkName, ChunkType, Version, MimeType, Machine) SELECT @ToSnapshotID, SC.ChunkId, SC.ChunkFlags | 0x4, COALESCE(@TargetChunkName, SC.ChunkName), SC.ChunkType, SC.Version, SC.MimeType, @Machine FROM SegmentedChunk SC WITH(INDEX (UNIQ_SnapshotChunkMapping)) WHERE SC.SnapshotDataId = @FromSnapshotID AND (SC.ChunkType = @ChunkType OR @ChunkType IS NULL) AND (SC.ChunkName = @ChunkName OR @ChunkName IS NULL) AND NOT EXISTS( -- exclude chunks already in the target SELECT TSC.ChunkName FROM ReportServerTempDB.dbo.SegmentedChunk TSC -- JOIN ReportServerTempDB.dbo.SnapshotChunkMapping TSCM ON (TSC.ChunkId = TSCM.ChunkId) WHERE TSC.ChunkName = COALESCE(@TargetChunkName, SC.ChunkName) AND TSC.ChunkType = SC.ChunkType AND TSC.SnapshotDataId = @ToSnapshotID ) END ELSE IF @FromIsPermanent = 0 AND @ToIsPermanent = 0 BEGIN -- the chunks exist on the node in which they were originally allocated on, they should -- be cleaned up by that node select @Machine = Machine from ReportServerTempDB.dbo.SnapshotData SD where SD.SnapshotDataID = @FromSnapshotID INSERT INTO ReportServerTempDB.dbo.ChunkData (ChunkId, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) SELECT newid(), @ToSnapshotID, COALESCE(@TargetChunkName, S.ChunkName), S.ChunkType, S.MimeType, S.Version, S.ChunkFlags, S.Content FROM ReportServerTempDB.dbo.ChunkData AS S WHERE S.SnapshotDataID = @FromSnapshotID AND (S.ChunkType = @ChunkType OR @ChunkType IS NULL) AND (S.ChunkName = @ChunkName OR @ChunkName IS NULL) AND NOT EXISTS( SELECT T.ChunkName FROM ReportServerTempDB.dbo.ChunkData AS T -- exclude the ones in the target WHERE T.ChunkName = COALESCE(@TargetChunkName, S.ChunkName) AND T.ChunkType = S.ChunkType AND T.SnapshotDataID = @ToSnapshotID) -- copy the segmented chunks, copying the segmented -- chunks really just needs to update the mappings INSERT INTO ReportServerTempDB.dbo.SegmentedChunk (SnapshotDataId, ChunkId, ChunkName, ChunkType, Version, ChunkFlags, MimeType, Machine) SELECT @ToSnapshotID, ChunkId, COALESCE(@TargetChunkName, C.ChunkName), C.ChunkType, C.Version, C.ChunkFlags, C.MimeType, @Machine FROM ReportServerTempDB.dbo.SegmentedChunk C WITH(INDEX (UNIQ_SnapshotChunkMapping)) WHERE C.SnapshotDataId = @FromSnapshotID AND (C.ChunkType = @ChunkType OR @ChunkType IS NULL) AND (C.ChunkName = @ChunkName OR @ChunkName IS NULL) AND NOT EXISTS( -- exclude chunks that are already mapped into this snapshot SELECT T.ChunkId FROM ReportServerTempDB.dbo.SegmentedChunk T WHERE T.SnapshotDataId = @ToSnapshotID and T.ChunkName = COALESCE(@TargetChunkName, C.ChunkName) and T.ChunkType = C.ChunkType ) END ELSE IF @FromIsPermanent != 0 AND @ToIsPermanent != 0 BEGIN INSERT INTO ChunkData (ChunkID, SnapshotDataID, ChunkName, ChunkType, MimeType, Version, ChunkFlags, Content) SELECT newid(), @ToSnapshotID, COALESCE(@TargetChunkName, S.ChunkName), S.ChunkType, S.MimeType, S.Version, S.ChunkFlags, S.Content FROM ChunkData AS S WHERE S.SnapshotDataID = @FromSnapshotID AND (S.ChunkType = @ChunkType OR @ChunkType IS NULL) AND (S.ChunkName = @ChunkName OR @ChunkName IS NULL) AND NOT EXISTS( SELECT T.ChunkName FROM ChunkData AS T -- exclude the ones in the target WHERE T.ChunkName = COALESCE(@TargetChunkName, S.ChunkName) AND T.ChunkType = S.ChunkType AND T.SnapshotDataID = @ToSnapshotID) -- copy the segmented chunks, copying the segmented -- chunks really just needs to update the mappings INSERT INTO SegmentedChunk (SnapshotDataId, ChunkId, ChunkName, ChunkType, Version, ChunkFlags, C.MimeType) SELECT @ToSnapshotID, ChunkId, COALESCE(@TargetChunkName, C.ChunkName), C.ChunkType, C.Version, C.ChunkFlags, C.MimeType FROM SegmentedChunk C WITH(INDEX (UNIQ_SnapshotChunkMapping)) WHERE C.SnapshotDataId = @FromSnapshotID AND (C.ChunkType = @ChunkType OR @ChunkType IS NULL) AND (C.ChunkName = @ChunkName OR @ChunkName IS NULL) AND NOT EXISTS( -- exclude chunks that are already mapped into this snapshot SELECT T.ChunkId FROM SegmentedChunk T WHERE T.SnapshotDataId = @ToSnapshotID and T.ChunkName = COALESCE(@TargetChunkName, C.ChunkName) and T.ChunkType = C.ChunkType ) END ELSE BEGIN RAISERROR('Unsupported chunk copy', 16, 1) END GO GRANT EXECUTE ON [dbo].[CopyChunksOfType] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteSnapshotAndChunks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteSnapshotAndChunks] GO CREATE PROCEDURE [dbo].[DeleteSnapshotAndChunks] @SnapshotID uniqueidentifier, @IsPermanentSnapshot bit AS -- Delete from Snapshot, ChunkData and SegmentedChunk table. -- Shared segments are not deleted. -- TODO: currently this is being called from a bunch of places that handles exceptions. -- We should try to delete the segments in some of all of those cases as well. IF @IsPermanentSnapshot != 0 BEGIN DELETE ChunkData WHERE ChunkData.SnapshotDataID = @SnapshotID DELETE SegmentedChunk WHERE SegmentedChunk.SnapshotDataId = @SnapshotID DELETE SnapshotData WHERE SnapshotData.SnapshotDataID = @SnapshotID END ELSE BEGIN DELETE ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotID DELETE ReportServerTempDB.dbo.SegmentedChunk WHERE SnapshotDataId = @SnapshotID DELETE ReportServerTempDB.dbo.SnapshotData WHERE SnapshotDataID = @SnapshotID END GO GRANT EXECUTE ON [dbo].[DeleteSnapshotAndChunks] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteOneChunk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteOneChunk] GO CREATE PROCEDURE [dbo].[DeleteOneChunk] @SnapshotID uniqueidentifier, @IsPermanentSnapshot bit, @ChunkName nvarchar(260), @ChunkType int AS SET NOCOUNT OFF -- for segmented chunks we just need to -- remove the mapping, the cleanup thread -- will pick up the rest of the pieces IF @IsPermanentSnapshot != 0 BEGIN DELETE ChunkData WHERE SnapshotDataID = @SnapshotID AND ChunkName = @ChunkName AND ChunkType = @ChunkType DELETE SegmentedChunk WHERE SnapshotDataId = @SnapshotID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END ELSE BEGIN DELETE ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotID AND ChunkName = @ChunkName AND ChunkType = @ChunkType DELETE ReportServerTempDB.dbo.SegmentedChunk WHERE SnapshotDataId = @SnapshotID AND ChunkName = @ChunkName AND ChunkType = @ChunkType END GO GRANT EXECUTE ON [dbo].[DeleteOneChunk] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateRdlChunk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateRdlChunk] GO CREATE PROCEDURE [dbo].[CreateRdlChunk] @ItemId UNIQUEIDENTIFIER, @SnapshotId UNIQUEIDENTIFIER, @IsPermanentSnapshot BIT, @ChunkName NVARCHAR(260), @ChunkFlags TINYINT, @ChunkType INT, @Version SMALLINT, @MimeType NVARCHAR(260) = NULL AS BEGIN -- If the chunk already exists then bail out early IF EXISTS ( SELECT 1 FROM [SegmentedChunk] WHERE SnapshotDataId = @SnapshotId AND ChunkName = @ChunkName AND ChunkType = @ChunkType ) RETURN ; -- This is a 3-step process. First we need to get the RDL out of the Catalog -- table where it is stored in the Content row. Note the join to make sure -- that if ItemId is a Linked Report we go back to the main report to get the RDL. -- Once we have the RDL stored in @SegmentData, we then invoke the CreateSegmentedChunk -- stored proc which will create an empty segmented chunk for us and return the ChunkId. -- finally, once we have a ChunkId, we can invoke CreateChunkSegment to actually put the -- content into the chunk. Note that we do not every actually break the chunk into multiple -- sgements but instead we always use one. DECLARE @SegmentData VARBINARY(MAX) ; DECLARE @SegmentByteCount INT ; SELECT @SegmentData = CONVERT(VARBINARY(MAX), ISNULL(Linked.Content, Original.Content)) FROM [Catalog] Original LEFT OUTER JOIN [Catalog] Linked WITH (INDEX(PK_Catalog)) ON (Original.LinkSourceId = Linked.ItemId) WHERE [Original].[ItemId] = @ItemId ; SELECT @SegmentByteCount = DATALENGTH(@SegmentData) ; DECLARE @ChunkId UNIQUEIDENTIFIER ; EXEC [CreateSegmentedChunk] @SnapshotId = @SnapshotId, @IsPermanent = @IsPermanentSnapshot, @ChunkName = @ChunkName, @ChunkFlags = @ChunkFlags, @ChunkType = @ChunkType, @Version = @Version, @MimeType = @MimeType, @Machine = NULL, @ChunkId = @ChunkId out ; DECLARE @SegmentId UNIQUEIDENTIFIER ; EXEC [CreateChunkSegment] @SnapshotId = @SnapshotId, @IsPermanent = @IsPermanentSnapshot, @ChunkId = @ChunkId, @Content = @SegmentData, @StartByte = 0, @Length = @SegmentByteCount, @LogicalByteCount = @SegmentByteCount, @SegmentId = @SegmentId out END GO GRANT EXECUTE ON [dbo].[CreateRdlChunk] TO RSExecRole GO -------------------------------------------------- ------------- Persisted stream SPs if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeletePersistedStreams]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeletePersistedStreams] GO CREATE PROCEDURE [dbo].[DeletePersistedStreams] @SessionID varchar(32) AS SET NOCOUNT OFF delete ReportServerTempDB.dbo.PersistedStream from (select top 1 * from ReportServerTempDB.dbo.PersistedStream PS2 where PS2.SessionID = @SessionID) as e1 where e1.SessionID = ReportServerTempDB.dbo.PersistedStream.[SessionID] and e1.[Index] = ReportServerTempDB.dbo.PersistedStream.[Index] GO GRANT EXECUTE ON [dbo].[DeletePersistedStreams] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteExpiredPersistedStreams]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteExpiredPersistedStreams] GO CREATE PROCEDURE [dbo].[DeleteExpiredPersistedStreams] AS SET NOCOUNT OFF SET DEADLOCK_PRIORITY LOW DELETE ReportServerTempDB.dbo.PersistedStream FROM (SELECT TOP 1 * FROM ReportServerTempDB.dbo.PersistedStream PS2 WHERE PS2.RefCount = 0 AND GETDATE() > PS2.ExpirationDate) AS e1 WHERE e1.SessionID = ReportServerTempDB.dbo.PersistedStream.[SessionID] AND e1.[Index] = ReportServerTempDB.dbo.PersistedStream.[Index] GO GRANT EXECUTE ON [dbo].[DeleteExpiredPersistedStreams] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeletePersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeletePersistedStream] GO CREATE PROCEDURE [dbo].[DeletePersistedStream] @SessionID varchar(32), @Index int AS delete from ReportServerTempDB.dbo.PersistedStream where SessionID = @SessionID and [Index] = @Index GO GRANT EXECUTE ON [dbo].[DeletePersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[AddPersistedStream] GO CREATE PROCEDURE [dbo].[AddPersistedStream] @SessionID varchar(32), @Index int AS DECLARE @RefCount int DECLARE @id varchar(32) DECLARE @ExpirationDate datetime set @RefCount = 0 set @ExpirationDate = DATEADD(day, 2, GETDATE()) set @id = (select SessionID from ReportServerTempDB.dbo.SessionData where SessionID = @SessionID) if @id is not null begin set @RefCount = 1 end INSERT INTO ReportServerTempDB.dbo.PersistedStream (SessionID, [Index], [RefCount], [ExpirationDate]) VALUES (@SessionID, @Index, @RefCount, @ExpirationDate) GO GRANT EXECUTE ON [dbo].[AddPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[LockPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[LockPersistedStream] GO CREATE PROCEDURE [dbo].[LockPersistedStream] @SessionID varchar(32), @Index int AS SELECT [Index] FROM ReportServerTempDB.dbo.PersistedStream WITH (XLOCK) WHERE SessionID = @SessionID AND [Index] = @Index GO GRANT EXECUTE ON [dbo].[LockPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteFirstPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteFirstPortionPersistedStream] GO CREATE PROCEDURE [dbo].[WriteFirstPortionPersistedStream] @SessionID varchar(32), @Index int, @Name nvarchar(260) = NULL, @MimeType nvarchar(260) = NULL, @Extension nvarchar(260) = NULL, @Encoding nvarchar(260) = NULL, @Content image AS UPDATE ReportServerTempDB.dbo.PersistedStream set Content = @Content, [Name] = @Name, MimeType = @MimeType, Extension = @Extension WHERE SessionID = @SessionID AND [Index] = @Index SELECT TEXTPTR(Content) FROM ReportServerTempDB.dbo.PersistedStream WHERE SessionID = @SessionID AND [Index] = @Index GO GRANT EXECUTE ON [dbo].[WriteFirstPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteNextPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteNextPortionPersistedStream] GO CREATE PROCEDURE [dbo].[WriteNextPortionPersistedStream] @DataPointer binary(16), @DataIndex int, @DeleteLength int, @Content image AS UPDATETEXT ReportServerTempDB.dbo.PersistedStream.Content @DataPointer @DataIndex @DeleteLength @Content GO GRANT EXECUTE ON [dbo].[WriteNextPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetFirstPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetFirstPortionPersistedStream] GO CREATE PROCEDURE [dbo].[GetFirstPortionPersistedStream] @SessionID varchar(32) AS SELECT TOP 1 TEXTPTR(P.Content), DATALENGTH(P.Content), P.[Index], P.[Name], P.MimeType, P.Extension, P.Encoding, P.Error FROM ReportServerTempDB.dbo.PersistedStream P WITH (XLOCK) WHERE P.SessionID = @SessionID GO GRANT EXECUTE ON [dbo].[GetFirstPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetPersistedStreamError]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetPersistedStreamError] GO CREATE PROCEDURE [dbo].[SetPersistedStreamError] @SessionID varchar(32), @Index int, @AllRows bit, @Error nvarchar(512) AS if @AllRows = 0 BEGIN UPDATE ReportServerTempDB.dbo.PersistedStream SET Error = @Error WHERE SessionID = @SessionID and [Index] = @Index END ELSE BEGIN UPDATE ReportServerTempDB.dbo.PersistedStream SET Error = @Error WHERE SessionID = @SessionID END GO GRANT EXECUTE ON [dbo].[SetPersistedStreamError] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetNextPortionPersistedStream]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetNextPortionPersistedStream] GO CREATE PROCEDURE [dbo].[GetNextPortionPersistedStream] @DataPointer binary(16), @DataIndex int, @Length int AS READTEXT ReportServerTempDB.dbo.PersistedStream.Content @DataPointer @DataIndex @Length GO GRANT EXECUTE ON [dbo].[GetNextPortionPersistedStream] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSnapshotChunks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSnapshotChunks] GO CREATE PROCEDURE [dbo].[GetSnapshotChunks] @SnapshotDataID uniqueidentifier, @IsPermanentSnapshot bit AS IF @IsPermanentSnapshot != 0 BEGIN SELECT ChunkName, ChunkType, ChunkFlags, MimeType, Version, datalength(Content) FROM ChunkData WHERE SnapshotDataID = @SnapshotDataID END ELSE BEGIN SELECT ChunkName, ChunkType, ChunkFlags, MimeType, Version, datalength(Content) FROM ReportServerTempDB.dbo.ChunkData WHERE SnapshotDataID = @SnapshotDataID END GO GRANT EXECUTE ON [dbo].[GetSnapshotChunks] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetDrillthroughReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetDrillthroughReports] GO CREATE PROCEDURE [dbo].[SetDrillthroughReports] @ReportID uniqueidentifier, @ModelID uniqueidentifier, @ModelItemID nvarchar(425), @Type tinyint AS SET NOCOUNT OFF INSERT INTO ModelDrill (ModelDrillID, ModelID, ReportID, ModelItemID, [Type]) VALUES (newid(), @ModelID, @ReportID, @ModelItemID, @Type) GO GRANT EXECUTE ON [dbo].[SetDrillthroughReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeleteDrillthroughReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeleteDrillthroughReports] GO CREATE PROCEDURE [dbo].[DeleteDrillthroughReports] @ModelID uniqueidentifier, @ModelItemID nvarchar(425) AS DELETE ModelDrill WHERE ModelID = @ModelID and ModelItemID = @ModelItemID GO GRANT EXECUTE ON [dbo].[DeleteDrillthroughReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDrillthroughReports]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDrillthroughReports] GO CREATE PROCEDURE [dbo].[GetDrillthroughReports] @ModelID uniqueidentifier, @ModelItemID nvarchar(425) AS SELECT ModelDrill.Type, Catalog.Path FROM ModelDrill INNER JOIN Catalog ON ModelDrill.ReportID = Catalog.ItemID WHERE ModelID = @ModelID AND ModelItemID = @ModelItemID GO GRANT EXECUTE ON [dbo].[GetDrillthroughReports] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDrillthroughReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDrillthroughReport] GO CREATE PROCEDURE [dbo].[GetDrillthroughReport] @ModelPath nvarchar(425), @ModelItemID nvarchar(425), @Type tinyint AS SELECT CatRep.Path FROM ModelDrill INNER JOIN Catalog CatMod ON ModelDrill.ModelID = CatMod.ItemID INNER JOIN Catalog CatRep ON ModelDrill.ReportID = CatRep.ItemID WHERE CatMod.Path = @ModelPath AND ModelItemID = @ModelItemID AND ModelDrill.[Type] = @Type GO GRANT EXECUTE ON [dbo].[GetDrillthroughReport] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetUpgradeItems]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetUpgradeItems] GO CREATE PROCEDURE [dbo].[GetUpgradeItems] AS SELECT [Item], [Status] FROM [UpgradeInfo] GO GRANT EXECUTE ON [dbo].[GetUpgradeItems] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SetUpgradeItemStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SetUpgradeItemStatus] GO CREATE PROCEDURE [dbo].[SetUpgradeItemStatus] @ItemName nvarchar(260), @Status nvarchar(512) AS UPDATE [UpgradeInfo] SET [Status] = @Status WHERE [Item] = @ItemName GO GRANT EXECUTE ON [dbo].[SetUpgradeItemStatus] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPolicyRoots]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetPolicyRoots] GO CREATE PROCEDURE [dbo].[GetPolicyRoots] AS SELECT [Path], [Type] FROM [Catalog] WHERE [PolicyRoot] = 1 GO GRANT EXECUTE ON [dbo].[GetPolicyRoots] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDataSourceForUpgrade]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetDataSourceForUpgrade] GO CREATE PROCEDURE [dbo].[GetDataSourceForUpgrade] @CurrentVersion int AS SELECT [DSID] FROM [DataSource] WHERE [Version] != @CurrentVersion GO GRANT EXECUTE ON [dbo].[GetDataSourceForUpgrade] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSubscriptionsForUpgrade]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSubscriptionsForUpgrade] GO CREATE PROCEDURE [dbo].[GetSubscriptionsForUpgrade] @CurrentVersion int AS SELECT [SubscriptionID] FROM [Subscriptions] WHERE [Version] != @CurrentVersion GO GRANT EXECUTE ON [dbo].[GetSubscriptionsForUpgrade] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[StoreServerParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[StoreServerParameters] GO CREATE PROCEDURE [dbo].[StoreServerParameters] @ServerParametersID nvarchar(32), @Path nvarchar(425), @CurrentDate datetime, @Timeout int, @Expiration datetime, @ParametersValues image, @ParentParametersID nvarchar(32) = NULL AS DECLARE @ExistingServerParametersID as nvarchar(32) SET @ExistingServerParametersID = (SELECT ServerParametersID from [dbo].[ServerParametersInstance] WHERE ServerParametersID = @ServerParametersID) IF @ExistingServerParametersID IS NULL -- new row BEGIN INSERT INTO [dbo].[ServerParametersInstance] (ServerParametersID, ParentID, Path, CreateDate, ModifiedDate, Timeout, Expiration, ParametersValues) VALUES (@ServerParametersID, @ParentParametersID, @Path, @CurrentDate, @CurrentDate, @Timeout, @Expiration, @ParametersValues) END ELSE BEGIN UPDATE [dbo].[ServerParametersInstance] SET Timeout = @Timeout, Expiration = @Expiration, ParametersValues = @ParametersValues, ModifiedDate = @CurrentDate, Path = @Path, ParentID = @ParentParametersID WHERE ServerParametersID = @ServerParametersID END GO GRANT EXECUTE ON [dbo].[StoreServerParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetServerParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetServerParameters] GO CREATE PROCEDURE [dbo].[GetServerParameters] @ServerParametersID nvarchar(32) AS DECLARE @now as DATETIME SET @now = GETDATE() SELECT Child.Path, Child.ParametersValues, Parent.ParametersValues FROM [dbo].[ServerParametersInstance] Child LEFT OUTER JOIN [dbo].[ServerParametersInstance] Parent ON Child.ParentID = Parent.ServerParametersID WHERE Child.ServerParametersID = @ServerParametersID AND Child.Expiration > @now GO GRANT EXECUTE ON [dbo].[GetServerParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CleanExpiredServerParameters]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CleanExpiredServerParameters] GO CREATE PROCEDURE [dbo].[CleanExpiredServerParameters] @ParametersCleaned INT OUTPUT AS DECLARE @now as DATETIME SET @now = GETDATE() DELETE FROM [dbo].[ServerParametersInstance] WHERE ServerParametersID IN ( SELECT TOP 20 ServerParametersID FROM [dbo].[ServerParametersInstance] WHERE Expiration < @now ) SET @ParametersCleaned = @@ROWCOUNT GO GRANT EXECUTE ON [dbo].[CleanExpiredServerParameters] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CopyChunks]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CopyChunks] GO CREATE PROCEDURE [dbo].[CopyChunks] @OldSnapshotId UNIQUEIDENTIFIER, @NewSnapshotId UNIQUEIDENTIFIER, @IsPermanentSnapshot BIT AS BEGIN IF(@IsPermanentSnapshot = 1) BEGIN -- copy non-segmented chunks INSERT [dbo].[ChunkData] ( ChunkId, SnapshotDataId, ChunkFlags, ChunkName, ChunkType, Version, MimeType, Content ) SELECT NEWID(), @NewSnapshotId, [c].[ChunkFlags], [c].[ChunkName], [c].[ChunkType], [c].[Version], [c].[MimeType], [c].[Content] FROM [dbo].[ChunkData] [c] WHERE [c].[SnapshotDataId] = @OldSnapshotId -- copy segmented chunks... real easy just add the mapping INSERT [dbo].[SegmentedChunk]( ChunkId, SnapshotDataId, ChunkName, ChunkType, Version, MimeType, ChunkFlags ) SELECT ChunkId, @NewSnapshotId, ChunkName, ChunkType, Version, MimeType, ChunkFlags FROM [dbo].[SegmentedChunk] WITH (INDEX (UNIQ_SnapshotChunkMapping)) WHERE [SnapshotDataId] = @OldSnapshotId END ELSE BEGIN -- copy non-segmented chunks INSERT ReportServerTempDB.dbo.[ChunkData] ( ChunkId, SnapshotDataId, ChunkFlags, ChunkName, ChunkType, Version, MimeType, Content ) SELECT NEWID(), @NewSnapshotId, [c].[ChunkFlags], [c].[ChunkName], [c].[ChunkType], [c].[Version], [c].[MimeType], [c].[Content] FROM ReportServerTempDB.dbo.[ChunkData] [c] WHERE [c].[SnapshotDataId] = @OldSnapshotId -- copy segmented chunks... real easy just add the mapping INSERT ReportServerTempDB.[dbo].[SegmentedChunk]( ChunkId, SnapshotDataId, ChunkName, ChunkType, Version, MimeType, ChunkFlags, Machine ) SELECT ChunkId, @NewSnapshotId, ChunkName, ChunkType, Version, MimeType, ChunkFlags, Machine FROM ReportServerTempDB.dbo.[SegmentedChunk] WITH (INDEX (UNIQ_SnapshotChunkMapping)) WHERE [SnapshotDataId] = @OldSnapshotId END END GO GRANT EXECUTE ON [dbo].[CopyChunks] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateNewSnapshotVersion]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateNewSnapshotVersion] GO CREATE PROCEDURE [dbo].[CreateNewSnapshotVersion] @OldSnapshotId UNIQUEIDENTIFIER, @NewSnapshotId UNIQUEIDENTIFIER, @IsPermanentSnapshot BIT, @Machine NVARCHAR(512) AS BEGIN IF(@IsPermanentSnapshot = 1) BEGIN INSERT [dbo].[SnapshotData] ( SnapshotDataId, CreatedDate, ParamsHash, QueryParams, EffectiveParams, Description, DependsOnUser, PermanentRefCount, TransientRefCount, ExpirationDate, PageCount, HasDocMap, PaginationMode, ProcessingFlags ) SELECT @NewSnapshotId, [sn].CreatedDate, [sn].ParamsHash, [sn].QueryParams, [sn].EffectiveParams, [sn].Description, [sn].DependsOnUser, 0, 1, -- always create with transient refcount of 1 [sn].ExpirationDate, [sn].PageCount, [sn].HasDocMap, [sn].PaginationMode, [sn].ProcessingFlags FROM [dbo].[SnapshotData] [sn] WHERE [sn].SnapshotDataId = @OldSnapshotId END ELSE BEGIN INSERT ReportServerTempDB.dbo.[SnapshotData] ( SnapshotDataId, CreatedDate, ParamsHash, QueryParams, EffectiveParams, Description, DependsOnUser, PermanentRefCount, TransientRefCount, ExpirationDate, PageCount, HasDocMap, PaginationMode, ProcessingFlags, Machine, IsCached ) SELECT @NewSnapshotId, [sn].CreatedDate, [sn].ParamsHash, [sn].QueryParams, [sn].EffectiveParams, [sn].Description, [sn].DependsOnUser, 0, 1, -- always create with transient refcount of 1 [sn].ExpirationDate, [sn].PageCount, [sn].HasDocMap, [sn].PaginationMode, [sn].ProcessingFlags, @Machine, [sn].IsCached FROM ReportServerTempDB.dbo.[SnapshotData] [sn] WHERE [sn].SnapshotDataId = @OldSnapshotId END EXEC [dbo].[CopyChunks] @OldSnapshotId = @OldSnapshotId, @NewSnapshotId = @NewSnapshotId, @IsPermanentSnapshot = @IsPermanentSnapshot END GO GRANT EXECUTE ON [dbo].[CreateNewSnapshotVersion] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpdateSnapshotReferences]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[UpdateSnapshotReferences] GO CREATE PROCEDURE [dbo].[UpdateSnapshotReferences] @OldSnapshotId UNIQUEIDENTIFIER, @NewSnapshotId UNIQUEIDENTIFIER, @IsPermanentSnapshot BIT, @TransientRefCountModifier INT, @UpdatedReferences INT OUTPUT AS BEGIN SET @UpdatedReferences = 0 IF(@IsPermanentSnapshot = 1) BEGIN -- Update Snapshot Executions UPDATE [dbo].[Catalog] SET [SnapshotDataID] = @NewSnapshotId WHERE [SnapshotDataID] = @OldSnapshotId SELECT @UpdatedReferences = @UpdatedReferences + @@ROWCOUNT -- Update History UPDATE [dbo].[History] SET [SnapshotDataID] = @NewSnapshotId WHERE [SnapshotDataID] = @OldSnapshotId SELECT @UpdatedReferences = @UpdatedReferences + @@ROWCOUNT UPDATE [dbo].[SnapshotData] SET [PermanentRefcount] = [PermanentRefcount] - @UpdatedReferences, [TransientRefcount] = [TransientRefcount] + @TransientRefCountModifier WHERE [SnapshotDataID] = @OldSnapshotId UPDATE [dbo].[SnapshotData] SET [PermanentRefcount] = [PermanentRefcount] + @UpdatedReferences WHERE [SnapshotDataID] = @NewSnapshotId END ELSE BEGIN -- Update Execution Cache UPDATE ReportServerTempDB.dbo.[ExecutionCache] SET [SnapshotDataID] = @NewSnapshotId WHERE [SnapshotDataID] = @OldSnapshotId SELECT @UpdatedReferences = @UpdatedReferences + @@ROWCOUNT UPDATE ReportServerTempDB.dbo.[SnapshotData] SET [PermanentRefcount] = [PermanentRefcount] - @UpdatedReferences, [TransientRefcount] = [TransientRefcount] + @TransientRefCountModifier WHERE [SnapshotDataID] = @OldSnapshotId UPDATE ReportServerTempDB.dbo.[SnapshotData] SET [PermanentRefcount] = [PermanentRefcount] + @UpdatedReferences WHERE [SnapshotDataID] = @NewSnapshotId END END GO GRANT EXECUTE ON [dbo].[UpdateSnapshotReferences] TO RSExecRole GO -------------------------------------------------- ------------- Segmented Chunk Infrastructure -------------------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[OpenSegmentedChunk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[OpenSegmentedChunk] GO create proc [dbo].[OpenSegmentedChunk] @SnapshotId uniqueidentifier, @IsPermanent bit, @ChunkName nvarchar(260), @ChunkType int, @ChunkId uniqueidentifier out, @ChunkFlags tinyint out as begin if (@IsPermanent = 1) begin select @ChunkId = ChunkId, @ChunkFlags = ChunkFlags from dbo.SegmentedChunk chunk where chunk.SnapshotDataId = @SnapshotId and chunk.ChunkName = @ChunkName and chunk.ChunkType = @ChunkType select csm.SegmentId, csm.LogicalByteCount as LogicalSegmentLength, csm.ActualByteCount as ActualSegmentLength from ChunkSegmentMapping csm where csm.ChunkId = @ChunkId order by csm.StartByte asc end else begin select @ChunkId = ChunkId, @ChunkFlags = ChunkFlags from ReportServerTempDB.dbo.SegmentedChunk chunk where chunk.SnapshotDataId = @SnapshotId and chunk.ChunkName = @ChunkName and chunk.ChunkType = @ChunkType if @ChunkFlags & 0x4 > 0 begin -- Shallow copy: read chunk segments from catalog select csm.SegmentId, csm.LogicalByteCount as LogicalSegmentLength, csm.ActualByteCount as ActualSegmentLength from ChunkSegmentMapping csm where csm.ChunkId = @ChunkId order by csm.StartByte asc end else begin -- Regular copy: read chunk segments from temp db select csm.SegmentId, csm.LogicalByteCount as LogicalSegmentLength, csm.ActualByteCount as ActualSegmentLength from ReportServerTempDB.dbo.ChunkSegmentMapping csm where csm.ChunkId = @ChunkId order by csm.StartByte asc end end end GO GRANT EXECUTE ON [dbo].[OpenSegmentedChunk] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateSegmentedChunk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateSegmentedChunk] GO create proc [dbo].[CreateSegmentedChunk] @SnapshotId uniqueidentifier, @IsPermanent bit, @ChunkName nvarchar(260), @ChunkFlags tinyint, @ChunkType int, @Version smallint, @MimeType nvarchar(260) = null, @Machine nvarchar(512), @ChunkId uniqueidentifier out as begin declare @output table (ChunkId uniqueidentifier) ; if (@IsPermanent = 1) begin delete SegmentedChunk where SnapshotDataId = @SnapshotId and ChunkName = @ChunkName and ChunkType = @ChunkType delete ChunkData where SnapshotDataID = @SnapshotId and ChunkName = @ChunkName and ChunkType = @ChunkType insert SegmentedChunk(SnapshotDataId, ChunkFlags, ChunkName, ChunkType, Version, MimeType) output inserted.ChunkId into @output values (@SnapshotId, @ChunkFlags, @ChunkName, @ChunkType, @Version, @MimeType) ; end else begin delete ReportServerTempDB.dbo.SegmentedChunk where SnapshotDataId = @SnapshotId and ChunkName = @ChunkName and ChunkType = @ChunkType delete ReportServerTempDB.dbo.ChunkData where SnapshotDataID = @SnapshotId and ChunkName = @ChunkName and ChunkType = @ChunkType insert ReportServerTempDB.dbo.SegmentedChunk(SnapshotDataId, ChunkFlags, ChunkName, ChunkType, Version, MimeType, Machine) output inserted.ChunkId into @output values (@SnapshotId, @ChunkFlags, @ChunkName, @ChunkType, @Version, @MimeType, @Machine) ; end select top 1 @ChunkId = ChunkId from @output end GO GRANT EXECUTE ON [dbo].[CreateSegmentedChunk] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadChunkSegment]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadChunkSegment] GO create proc [dbo].[ReadChunkSegment] @ChunkId uniqueidentifier, @SegmentId uniqueidentifier, @IsPermanent bit, @DataIndex int, @Length int as begin if(@IsPermanent = 1) begin select substring(seg.Content, @DataIndex + 1, @Length) as [Content] from Segment seg join ChunkSegmentMapping csm on (csm.SegmentId = seg.SegmentId) where csm.ChunkId = @ChunkId and csm.SegmentId = @SegmentId end else begin select substring(seg.Content, @DataIndex + 1, @Length) as [Content] from ReportServerTempDB.dbo.Segment seg join ReportServerTempDB.dbo.ChunkSegmentMapping csm on (csm.SegmentId = seg.SegmentId) where csm.ChunkId = @ChunkId and csm.SegmentId = @SegmentId end end GO GRANT EXECUTE ON [dbo].[ReadChunkSegment] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteChunkSegment]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[WriteChunkSegment] GO create proc [dbo].[WriteChunkSegment] @ChunkId uniqueidentifier, @IsPermanent bit, @SegmentId uniqueidentifier, @DataIndex int, @Length int, @LogicalByteCount int, @Content varbinary(max) as begin declare @output table (actualLength int not null) ; if(@IsPermanent = 1) begin update Segment set Content.write( substring(@Content, 1, @Length), @DataIndex, @Length ) output datalength(inserted.Content) into @output(actualLength) where SegmentId = @SegmentId update ChunkSegmentMapping set LogicalByteCount = @LogicalByteCount, ActualByteCount = (select top 1 actualLength from @output) where ChunkSegmentMapping.ChunkId = @ChunkId and ChunkSegmentMapping.SegmentId = @SegmentId end else begin update ReportServerTempDB.dbo.Segment set Content.write( substring(@Content, 1, @Length), @DataIndex, @Length ) output datalength(inserted.Content) into @output(actualLength) where SegmentId = @SegmentId update ReportServerTempDB.dbo.ChunkSegmentMapping set LogicalByteCount = @LogicalByteCount, ActualByteCount = (select top 1 actualLength from @output) where ChunkId = @ChunkId and SegmentId = @SegmentId end if(@@rowcount <> 1) raiserror('unexpected # of segments update', 16, 1) end GO GRANT EXECUTE ON [dbo].[WriteChunkSegment] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateChunkSegment]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CreateChunkSegment] GO create proc [dbo].[CreateChunkSegment] @SnapshotId uniqueidentifier, @IsPermanent bit, @ChunkId uniqueidentifier, @Content varbinary(max) = 0x0, @StartByte bigint, @Length int = 0, @LogicalByteCount int = 0, @SegmentId uniqueidentifier out as begin declare @output table (SegmentId uniqueidentifier, ActualByteCount int) ; declare @ActualByteCount int ; if(@IsPermanent = 1) begin insert Segment(Content) output inserted.SegmentId, datalength(inserted.Content) into @output values (substring(@Content, 1, @Length)) ; select top 1 @SegmentId = SegmentId, @ActualByteCount = ActualByteCount from @output ; insert ChunkSegmentMapping(ChunkId, SegmentId, StartByte, LogicalByteCount, ActualByteCount) values (@ChunkId, @SegmentId, @StartByte, @LogicalByteCount, @ActualByteCount) ; end else begin insert ReportServerTempDB.dbo.Segment(Content) output inserted.SegmentId, datalength(inserted.Content) into @output values (substring(@Content, 1, @Length)) ; select top 1 @SegmentId = SegmentId, @ActualByteCount = ActualByteCount from @output ; insert ReportServerTempDB.dbo.ChunkSegmentMapping(ChunkId, SegmentId, StartByte, LogicalByteCount, ActualByteCount) values (@ChunkId, @SegmentId, @StartByte, @LogicalByteCount, @ActualByteCount) ; end end GO GRANT EXECUTE ON [dbo].[CreateChunkSegment] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[IsSegmentedChunk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[IsSegmentedChunk] GO create proc [dbo].[IsSegmentedChunk] @SnapshotId uniqueidentifier, @IsPermanent bit, @ChunkName nvarchar(260), @ChunkType int, @IsSegmented bit out as begin -- segmented chunks are read w/nolock -- we don't really care about locking in this scenario -- we just need to get some metadata which never changes (if it is segmented or not) if (@IsPermanent = 1) begin select top 1 @IsSegmented = IsSegmented from ( select convert(bit, 0) from [ChunkData] c where c.ChunkName = @ChunkName and c.ChunkType = @ChunkType and c.SnapshotDataId = @SnapshotId union all select convert(bit, 1) from [SegmentedChunk] c WITH(NOLOCK) where c.ChunkName = @ChunkName and c.ChunkType = @ChunkType and c.SnapshotDataId = @SnapshotId ) A(IsSegmented) end else begin select top 1 @IsSegmented = IsSegmented from ( select convert(bit, 0) from ReportServerTempDB.dbo.[ChunkData] c where c.ChunkName = @ChunkName and c.ChunkType = @ChunkType and c.SnapshotDataId = @SnapshotId union all select convert(bit, 1) from ReportServerTempDB.dbo.[SegmentedChunk] c WITH(NOLOCK) where c.ChunkName = @ChunkName and c.ChunkType = @ChunkType and c.SnapshotDataId = @SnapshotId ) A(IsSegmented) end end GO GRANT EXECUTE ON [dbo].[IsSegmentedChunk] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ShallowCopyChunk]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ShallowCopyChunk] GO create proc [dbo].[ShallowCopyChunk] @SnapshotId uniqueidentifier, @ChunkId uniqueidentifier, @IsPermanent bit, @Machine nvarchar(512), @NewChunkId uniqueidentifier out as begin -- @SnapshotId & @ChunkId are the old identifiers -- build the chunksegmentmapping first to prevent race -- condition with cleaning it up select @NewChunkId = newid() ; if (@IsPermanent = 1) begin insert ChunkSegmentMapping (ChunkId, SegmentId, StartByte, LogicalByteCount, ActualByteCount) select @NewChunkId, SegmentId, StartByte, LogicalByteCount, ActualByteCount from ChunkSegmentMapping where ChunkId = @ChunkId ; update SegmentedChunk set ChunkId = @NewChunkId where ChunkId = @ChunkId and SnapshotDataId = @SnapshotId end else begin insert ReportServerTempDB.dbo.ChunkSegmentMapping (ChunkId, SegmentId, StartByte, LogicalByteCount, ActualByteCount) select @NewChunkId, SegmentId, StartByte, LogicalByteCount, ActualByteCount from ReportServerTempDB.dbo.ChunkSegmentMapping where ChunkId = @ChunkId ; -- update the machine name also, this is only really useful -- for file system chunks, in which case the snapshot should -- have been versioned on the initial update update ReportServerTempDB.dbo.SegmentedChunk set ChunkId = @NewChunkId, Machine = @Machine where ChunkId = @ChunkId and SnapshotDataId = @SnapshotId end end GO GRANT EXECUTE ON [dbo].[ShallowCopyChunk] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DeepCopySegment]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[DeepCopySegment] GO create proc [dbo].[DeepCopySegment] @ChunkId uniqueidentifier, @IsPermanent bit, @SegmentId uniqueidentifier, @NewSegmentId uniqueidentifier out as begin select @NewSegmentId = newid() ; if (@IsPermanent = 1) begin insert Segment(SegmentId, Content) select @NewSegmentId, seg.Content from Segment seg where seg.SegmentId = @SegmentId ; update ChunkSegmentMapping set SegmentId = @NewSegmentId where ChunkId = @ChunkId and SegmentId = @SegmentId ; end else begin insert ReportServerTempDB.dbo.Segment(SegmentId, Content) select @NewSegmentId, seg.Content from ReportServerTempDB.dbo.Segment seg where seg.SegmentId = @SegmentId ; update ReportServerTempDB.dbo.ChunkSegmentMapping set SegmentId = @NewSegmentId where ChunkId = @ChunkId and SegmentId = @SegmentId ; end end GO GRANT EXECUTE ON [dbo].[DeepCopySegment] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSegmentMapCleanupCandidates]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSegmentMapCleanupCandidates] GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSegmentCleanupCandidates]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetSegmentCleanupCandidates] GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RemoveSegmentedMapping]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RemoveSegmentedMapping] GO create proc [dbo].[RemoveSegmentedMapping] @DeleteCountPermanentChunk int, @DeleteCountPermanentMapping int, @DeleteCountTempChunk int, @DeleteCountTempMapping int, @MachineName nvarchar(260) as begin SET DEADLOCK_PRIORITY LOW declare @deleted table ( ChunkID uniqueidentifier, IsPermanent bit ); -- details on lock hints: -- we use readpast on ChunkSegmentMapping to skip past -- rows which are currently locked. they are being actively -- used so clearly we do not want to delete them. we use -- nolock on SegmentedChunk table as well, this is because -- regardless of whether or not that row is locked, we want to -- know if it is referenced by a SegmentedChunk and if -- so we do not want to delete the mapping row. ChunkIds are -- only modified when creating a shallow chunk copy(see ShallowCopyChunk), -- but in this case the ChunkSegmentMapping row is locked (via the insert) -- so we are safe. declare @toDeletePermChunks table ( SnapshotDataId uniqueidentifier ) ; insert into @toDeletePermChunks (SnapshotDataId) select top (@DeleteCountPermanentChunk) SnapshotDataId from SegmentedChunk with (readpast) where not exists ( select 1 from SnapshotData SD with (nolock) where SegmentedChunk.SnapshotDataId = SD.SnapshotDataID ) ; delete from SegmentedChunk with (readpast) where SegmentedChunk.SnapshotDataId in ( select td.SnapshotDataId from @toDeletePermChunks td where not exists ( select 1 from SnapshotData SD where td.SnapshotDataId = SD.SnapshotDataID )) ; -- clean up segmentedchunks from permanent database declare @toDeleteChunks table ( ChunkId uniqueidentifier ); -- clean up mappings from permanent database insert into @toDeleteChunks (ChunkId) select top (@DeleteCountPermanentMapping) ChunkId from ChunkSegmentMapping with (readpast) where not exists ( select 1 from SegmentedChunk SC with (nolock) where SC.ChunkId = ChunkSegmentMapping.ChunkId ) ; delete from ChunkSegmentMapping with (readpast) output deleted.ChunkId, convert(bit, 1) into @deleted where ChunkSegmentMapping.ChunkId in ( select td.ChunkId from @toDeleteChunks td where not exists ( select 1 from SegmentedChunk SC where SC.ChunkId = td.ChunkId ) and not exists ( select 1 from ReportServerTempDB.dbo.SegmentedChunk TSC where TSC.ChunkId = td.ChunkId ) ) declare @toDeleteTempChunks table ( SnapshotDataId uniqueidentifier); -- clean up SegmentedChunks from the Temp database -- for locking we play the same idea as in the previous query. -- snapshotIds never change, so again this operation is safe. insert into @toDeleteTempChunks (SnapshotDataId) select top (@DeleteCountTempChunk) SnapshotDataId from ReportServerTempDB.dbo.SegmentedChunk with (readpast) where ReportServerTempDB.dbo.SegmentedChunk.Machine = @MachineName and not exists ( select 1 from ReportServerTempDB.dbo.SnapshotData SD with (nolock) where ReportServerTempDB.dbo.SegmentedChunk.SnapshotDataId = SD.SnapshotDataID ) ; delete from ReportServerTempDB.dbo.SegmentedChunk with (readpast) where ReportServerTempDB.dbo.SegmentedChunk.SnapshotDataId in ( select td.SnapshotDataId from @toDeleteTempChunks td where not exists ( select 1 from ReportServerTempDB.dbo.SnapshotData SD where td.SnapshotDataId = SD.SnapshotDataID )) ; declare @toDeleteTempMappings table ( ChunkId uniqueidentifier ); -- clean up mappings from temp database insert into @toDeleteTempMappings (ChunkId) select top (@DeleteCountTempMapping) ChunkId from ReportServerTempDB.dbo.ChunkSegmentMapping with (readpast) where not exists ( select 1 from ReportServerTempDB.dbo.SegmentedChunk SC with (nolock) where SC.ChunkId = ReportServerTempDB.dbo.ChunkSegmentMapping.ChunkId ) ; delete from ReportServerTempDB.dbo.ChunkSegmentMapping with (readpast) output deleted.ChunkId, convert(bit, 0) into @deleted where ReportServerTempDB.dbo.ChunkSegmentMapping.ChunkId in ( select td.ChunkId from @toDeleteTempMappings td where not exists ( select 1 from ReportServerTempDB.dbo.SegmentedChunk SC where td.ChunkId = SC.ChunkId )) ; -- need to return these so we can cleanup file system chunks select distinct ChunkID, IsPermanent from @deleted ; end GO GRANT EXECUTE ON [dbo].[RemoveSegmentedMapping] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RemoveSegment]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[RemoveSegment] GO create proc [dbo].[RemoveSegment] @DeleteCountPermanent int, @DeleteCountTemp int as begin SET DEADLOCK_PRIORITY LOW -- Locking: -- Similar idea as in RemovedSegmentedMapping. Readpast -- any Segments which are currently locked and run the -- inner scan with nolock. declare @numDeleted int; declare @toDeleteMapping table ( SegmentId uniqueidentifier ); insert into @toDeleteMapping (SegmentId) select top (@DeleteCountPermanent) SegmentId from Segment with (readpast) where not exists ( select 1 from ChunkSegmentMapping CSM with (nolock) where CSM.SegmentId = Segment.SegmentId ) ; delete from Segment with (readpast) where Segment.SegmentId in ( select td.SegmentId from @toDeleteMapping td where not exists ( select 1 from ChunkSegmentMapping CSM where CSM.SegmentId = td.SegmentId )); select @numDeleted = @@rowcount ; declare @toDeleteTempSegment table ( SegmentId uniqueidentifier ); insert into @toDeleteTempSegment (SegmentId) select top (@DeleteCountTemp) SegmentId from ReportServerTempDB.dbo.Segment with (readpast) where not exists ( select 1 from ReportServerTempDB.dbo.ChunkSegmentMapping CSM with (nolock) where CSM.SegmentId = ReportServerTempDB.dbo.Segment.SegmentId ) ; delete from ReportServerTempDB.dbo.Segment with (readpast) where ReportServerTempDB.dbo.Segment.SegmentId in ( select td.SegmentId from @toDeleteTempSegment td where not exists ( select 1 from ReportServerTempDB.dbo.ChunkSegmentMapping CSM where CSM.SegmentId = td.SegmentId )) ; select @numDeleted = @numDeleted + @@rowcount ; select @numDeleted; end GO GRANT EXECUTE ON [dbo].[RemoveSegment] TO RSExecRole GO if exists (select id from dbo.sysobjects where id = object_id(N'[dbo].[MigrateExecutionLog]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[MigrateExecutionLog] GO create proc [dbo].[MigrateExecutionLog] @updatedRow int output as begin set @updatedRow = 0 ; if exists (select id from dbo.sysobjects where id = object_id(N'[dbo].[ExecutionLog_Old]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) begin SET DEADLOCK_PRIORITY LOW ; SET NOCOUNT OFF ; insert into [dbo].[ExecutionLogStorage] ([InstanceName], [ReportID], [UserName], [ExecutionId], [RequestType], [Format], [Parameters], [ReportAction], [TimeStart], [TimeEnd], [TimeDataRetrieval], [TimeProcessing], [TimeRendering], [Source], [Status], [ByteCount], [RowCount], [AdditionalInfo]) select top (1024) with ties [InstanceName], [ReportID], [UserName], null, [RequestType], [Format], [Parameters], 1, --Render [TimeStart], [TimeEnd], [TimeDataRetrieval], [TimeProcessing], [TimeRendering], [Source], [Status], [ByteCount], [RowCount], null from [dbo].[ExecutionLog_Old] WITH (XLOCK) order by TimeStart ; delete from [dbo].[ExecutionLog_Old] where [TimeStart] in (select top (1024) with ties [TimeStart] from [dbo].[ExecutionLog_Old] order by [TimeStart]) ; set @updatedRow = @@ROWCOUNT ; IF @updatedRow = 0 begin drop table [dbo].[ExecutionLog_Old] end end end GO GRANT EXECUTE ON [dbo].[MigrateExecutionLog] TO RSExecRole GO if exists (select id from dbo.sysobjects where id = object_id(N'[dbo].[TempChunkExists]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[TempChunkExists] GO CREATE PROC [dbo].[TempChunkExists] @ChunkId uniqueidentifier AS BEGIN SELECT COUNT(1) FROM ReportServerTempDB.dbo.SegmentedChunk WHERE ChunkId = @ChunkId END GO GRANT EXECUTE ON [dbo].[TempChunkExists] TO RSExecRole GO -- END STORED PROCEDURES if not exists (select Item from [dbo].[UpgradeInfo] where [Item] = N'MigrateExecutionLog') and exists (select id from dbo.sysobjects where id = object_id(N'[dbo].[ExecutionLog_Old]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) begin INSERT INTO [dbo].[UpgradeInfo]([Item], [Status]) VALUES ('MigrateExecutionLog', 'False') end GO -------------------------------------- -- C.0.8.40 to C.0.8.41 -------------------------------------- -- No change in tables -------------------------------------- -- C.0.8.41 to C.0.8.42 -------------------------------------- -- No change in tables -------------------------------------- -- C.0.8.41 to C.0.8.43 -------------------------------------- if ( select count(*) from sysusers u join sysmembers m on u.uid = m.memberuid join sysusers r on r.uid = m.groupuid where r.name = 'db_owner' and u.name = 'RSExecRole' ) = 0 begin exec sp_addrolemember 'db_owner', 'RSExecRole' end GO PA -------------------------------------- -- T.0.8.40 to T.0.8.41 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.41 to T.0.8.42 -------------------------------------- if (select count(*) from dbo.syscolumns where id = object_id('SessionData') and name = 'ExecutionType') = 1 begin ALTER TABLE [dbo].[SessionData] DROP COLUMN [ExecutionType] end GO if (select count(*) from dbo.syscolumns where id = object_id('SessionData') and name = 'AwaitingFirstExecution') = 0 begin ALTER TABLE [dbo].[SessionData] ADD [AwaitingFirstExecution] bit NULL end GO -------------------------------------- -- T.0.8.41 to T.0.8.43 -------------------------------------- if ( select count(*) from sysusers u join sysmembers m on u.uid = m.memberuid join sysusers r on r.uid = m.groupuid where r.name = 'db_owner' and u.name = 'RSExecRole' ) = 0 begin exec sp_addrolemember 'db_owner', 'RSExecRole' end GO -------------------------------------- -- C.0.8.43 to C.0.8.44 -------------------------------------- if not exists (select * from [dbo].[ConfigurationInfo] where [Name] = N'SharePointIntegrated') begin INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'SharePointIntegrated', 'False' ) end GO -------------------------------------- -- C.0.8.44 to C.0.8.45 -------------------------------------- -- No change in tables -------------------------------------- -- C.0.8.45 to C.0.8.46 -------------------------------------- -- No change in tables -------------------------------------- -- C.0.8.46 to C.0.8.47 -------------------------------------- -- No change in tables -------------------------------------- -- C.0.8.47 to C.0.8.48 -------------------------------------- -- One change in table Schedules - new column Path: [Path] [nvarchar] (425) NULL if (select count(*) from dbo.syscolumns where id = object_id('Schedule') and name = 'Path') = 0 begin alter table [dbo].[Schedule] add Path [nvarchar] (260) NULL end GO -------------------------------------- -- C.0.8.48 to C.0.8.49 -------------------------------------- -- No change in tables -------------------------------------- -- C.0.8.49 to C.0.8.50 -------------------------------------- -- Removed unique constraint IX_Schedule. -- Added triggers Schedule_Insert and Schedule_Update. if exists (select * from dbo.sysindexes where [name]='IX_Schedule') begin alter table [dbo].[Schedule] drop constraint IX_Schedule end GO -- Triggers Schedule_Insert and Schedule_Update are to enforce -- the uniqueness of the Name+Path. We cannot use unique index as -- combined size for these columns exceeds the maximum 900 bytes. if (select count(*) from dbo.sysobjects where id = object_id(N'[dbo].[Schedule_Insert]') and OBJECTPROPERTY(id, N'IsTrigger') = 1) = 1 begin DROP TRIGGER [Schedule_Insert] end GO CREATE TRIGGER [dbo].[Schedule_Insert] ON [dbo].[Schedule] INSTEAD OF INSERT AS if exists (select * from [dbo].[Schedule] as s, inserted as ins where s.Name = ins.Name and (s.Path = ins.Path or (s.Path is null and ins.Path is null))) raiserror('Schedule already exists', 16, 1) else insert into [dbo].[Schedule] select ScheduleID, Name, StartDate, Flags, NextRunTime, LastRunTime, EndDate, RecurrenceType, MinutesInterval, DaysInterval, WeeksInterval, DaysOfWeek, DaysOfMonth, Month, MonthlyWeek, State, LastRunStatus, ScheduledRunTimeout, CreatedById, EventType, EventData, Type, ConsistancyCheck, Path from inserted GO if (select count(*) from dbo.sysobjects where id = object_id(N'[dbo].[Schedule_Update]') and OBJECTPROPERTY(id, N'IsTrigger') = 1) = 1 begin DROP TRIGGER [Schedule_Update] end GO CREATE TRIGGER [dbo].[Schedule_Update] ON [dbo].[Schedule] INSTEAD OF UPDATE AS if (update(Name) or update(Path)) and exists (select * from [dbo].[Schedule] as s with (nolock), inserted as ins where s.Name = ins.Name and (s.Path = ins.Path or (s.Path is null and ins.Path is null)) and s.ScheduleID <> ins.ScheduleID) raiserror('Schedule already exists', 16, 1) else update [dbo].[Schedule] set Name = ins.Name, StartDate = ins.StartDate, Flags = ins.Flags, NextRunTime = ins.NextRunTime, LastRunTime = ins.LastRunTime, EndDate = ins.EndDate, RecurrenceType = ins.RecurrenceType, MinutesInterval = ins.MinutesInterval, DaysInterval = ins.DaysInterval, WeeksInterval = ins.WeeksInterval, DaysOfWeek = ins.DaysOfWeek, DaysOfMonth = ins.DaysOfMonth, Month = ins.Month, MonthlyWeek = ins.MonthlyWeek, State = ins.State, LastRunStatus = ins.LastRunStatus, ScheduledRunTimeout = ins.ScheduledRunTimeout, CreatedById = ins.CreatedById, EventType = ins.EventType, EventData = ins.EventData, Type = ins.Type, ConsistancyCheck = ins.ConsistancyCheck, Path = ins.Path from inserted as ins where [Schedule].ScheduleID = ins.ScheduleID GO -------------------------------------- -- C.0.8.50 to C.0.8.51 -------------------------------------- -- add nolock to schedule_update -------------------------------------- -- C.0.8.51 to C.0.8.52 -------------------------------------- if not exists (select * from [dbo].[ConfigurationInfo] where [Name] = N'EnableLoadReportDefinition') begin INSERT INTO [dbo].[ConfigurationInfo] VALUES ( newid(), 'EnableLoadReportDefinition', 'True' ) end GO -------------------------------------- -- C.0.8.52 to C.0.8.53 -------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Schedule_Insert]') and OBJECTPROPERTY(id, N'IsTrigger') = 1) drop trigger [dbo].[Schedule_Insert] GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Schedule_Update]') and OBJECTPROPERTY(id, N'IsTrigger') = 1) drop trigger [dbo].[Schedule_Update] GO if exists (select * from dbo.sysindexes where [name]='IX_Schedule') ALTER TABLE [dbo].[Schedule] DROP CONSTRAINT [IX_Schedule] GO ALTER TABLE [dbo].[Schedule] WITH NOCHECK ADD CONSTRAINT [IX_Schedule] UNIQUE NONCLUSTERED ( [Name], [Path] ) ON [PRIMARY] GO -------------------------------------- -- C.0.8.53 to C.0.8.54 -------------------------------------- -------------------------------------- -- T.0.8.43 to T.0.8.44 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.43 to T.0.8.45 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.45 to T.0.8.49 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.49 to T.0.8.50 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.50 to T.0.8.51 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.51 to T.0.8.52 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.52 to T.0.8.53 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.8.53 to T.0.8.54 -------------------------------------- -- No change in tables -------------------------------------- -- C.0.8.54 to C.0.9.00 -------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CopyExecutionSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[CopyExecutionSnapshot] GO -------------------------------------- -- C.0.9.00 to C.0.9.01 -------------------------------------- -------------------------------------------------- ------------- Creation of tables -------------------------------------------------- -------------------------------------------------- ------------- Subscription Info if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SubscriptionsBeingDeleted]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) begin CREATE TABLE [dbo].[SubscriptionsBeingDeleted] ( [SubscriptionID] [uniqueidentifier] NOT NULL, [CreationDate] [datetime] NOT NULL ) ON [PRIMARY] GRANT SELECT, INSERT, UPDATE, DELETE, REFERENCES ON [dbo].[SubscriptionsBeingDeleted] TO RSExecRole ALTER TABLE [dbo].[SubscriptionsBeingDeleted] ADD CONSTRAINT [PK_SubscriptionsBeingDeleted] PRIMARY KEY CLUSTERED ( [SubscriptionID] ) ON [PRIMARY] end GO -------------------------------------- -- C.0.9.01 to C.0.9.02 -------------------------------------- if (select count(*) from dbo.syscolumns where id = object_id('[dbo].[SnapshotData]') and name = 'PaginationMode') = 0 begin ALTER TABLE [dbo].[SnapshotData] ADD [PaginationMode] smallint NULL end GO if (select count(*) from dbo.syscolumns where id = object_id('[dbo].[SnapshotData]') and name = 'ProcessingFlags') = 0 begin ALTER TABLE [dbo].[SnapshotData] ADD [ProcessingFlags] int NULL end GO -------------------------------------- -- C.0.9.02 to C.0.9.03 -------------------------------------- if (select count(*) from dbo.sysindexes where id = object_id('[dbo].[History]') and [name]='IX_SnapshotDataID') = 0 begin CREATE INDEX [IX_SnapshotDataID] ON [dbo].[History]([SnapshotDataID]) ON [PRIMARY] end GO if (select count(*) from dbo.sysindexes where id = object_id('[dbo].[Catalog]') and [name]='IX_SnapshotDataId') = 0 begin CREATE INDEX [IX_SnapshotDataId] ON [dbo].[Catalog]([SnapshotDataID]) ON [PRIMARY] end GO -------------------------------------- -- C.0.9.03 to C.0.9.04 -------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Segment]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) begin drop table [dbo].[Segment] declare @sql nvarchar(max) declare @objname nvarchar(max) select @objname = object_name(parent_object_id) from sys.check_constraints where name ='Positive_LogicalByteCount' if (@objname is not null) begin select @sql = N'alter table ' + QUOTENAME(@objname) + N' drop constraint Positive_LogicalByteCount' exec sp_executesql @sql end end create table [dbo].[Segment] ( SegmentId uniqueidentifier not null, LogicalByteCount int not null, Content varbinary(max), constraint [PK_Segment] primary key clustered ([SegmentId]), constraint [Positive_LogicalByteCount] check (LogicalByteCount >= 0) ) GO GRANT SELECT, UPDATE, INSERT, DELETE, REFERENCES ON [dbo].[Segment] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ChunkSegmentMapping]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) begin drop table [dbo].[ChunkSegmentMapping] end create table [dbo].[ChunkSegmentMapping] ( ChunkId uniqueidentifier not null, SegmentId uniqueidentifier not null, StartByte bigint not null, constraint [PK_ChunkSegmentMapping] primary key clustered (ChunkId, SegmentId), constraint [UNIQ_ChunkId_StartByte] unique (ChunkId, StartByte), constraint [Positive_StartByte] check (StartByte >= 0) ) GO GRANT SELECT, UPDATE, INSERT, DELETE, REFERENCES ON [dbo].[ChunkSegmentMapping] TO RSExecRole GO -------------------------------------- -- C.0.9.04 to C.0.9.05 -------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SegmentedChunk]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) begin drop table [dbo].[SegmentedChunk] end create table [dbo].[SegmentedChunk] ( [ChunkId] uniqueidentifier not null, [SnapshotDataId] uniqueidentifier not null, [ChunkFlags] tinyint NULL, [ChunkName] nvarchar(260), [ChunkType] int, [Version] smallint null, [MimeType] nvarchar(260), constraint [PK_SnapshotChunkMapping] primary key clustered (SnapshotDataId, ChunkType, ChunkName), constraint [FK_SnapshotChunkMappingSnapshotDataId] foreign key ([SnapshotDataId]) references [SnapshotData]([SnapshotDataID]) on delete cascade ) GO create unique nonclustered index [UNIQ_ChunkId_SnapshotDataId] on [dbo].[SegmentedChunk] (ChunkId, SnapshotDataId) GO GRANT SELECT, UPDATE, INSERT, DELETE, REFERENCES ON [dbo].[SegmentedChunk] TO RSExecRole GO -------------------------------------- -- C.0.9.05 to C.0.9.06 -------------------------------------- -- No change in tables -------------------------------------- -- C.0.9.06 to C.0.9.07 -------------------------------------- if (select count(*) from dbo.sysindexes where id = object_id(N'[dbo].[ChunkSegmentMapping]') and [name]='IX_ChunkSegmentMapping_SegmentId') = 0 begin create nonclustered index [IX_ChunkSegmentMapping_SegmentId] on [dbo].[ChunkSegmentMapping]([SegmentId]) end GO -------------------------------------- -- C.0.9.07 to C.0.9.08 -------------------------------------- -- Execution Log -- execution log migration is deemed as low priority task. So the implementation here is to avoid db upgrade failure over fail to migrate. if exists (select id from dbo.sysobjects where id = object_id(N'[dbo].[ExecutionLog]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) begin if not exists (select id from dbo.sysobjects where id = object_id(N'[dbo].[ExecutionLog_Old]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) begin exec sp_rename 'dbo.ExecutionLog', 'ExecutionLog_Old' -- Set that we need to upgrade the security descriptors if not exists (select * from [dbo].[UpgradeInfo] where [Item] = N'MigrateExecutionLog') begin INSERT INTO [dbo].[UpgradeInfo]([Item], [Status]) VALUES ('MigrateExecutionLog', 'False') end end else begin drop table [dbo].[ExecutionLog] end end GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ExecutionLogStorage]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) begin drop table [dbo].[ExecutionLogStorage] end GO CREATE TABLE [dbo].[ExecutionLogStorage] ( [LogEntryId] bigint primary key identity(1, 1), [InstanceName] nvarchar(38) NOT NULL, [ReportID] uniqueidentifier NULL, -- Path could be null in error conditions [UserName] nvarchar(260) NULL, [ExecutionId] nvarchar(64) NULL, [RequestType] bit NOT NULL, [Format] nvarchar(26) NULL, [Parameters] ntext NULL, [ReportAction] tinyint, [TimeStart] DateTime NOT NULL, [TimeEnd] DateTime NOT NULL, [TimeDataRetrieval] int NOT NULL, [TimeProcessing] int NOT NULL, [TimeRendering] int NOT NULL, [Source] tinyint NOT NULL, [Status] nvarchar(32) NOT NULL, [ByteCount] bigint NOT NULL, [RowCount] bigint NOT NULL, [AdditionalInfo] xml NULL ) ON [PRIMARY] GO GRANT SELECT, INSERT, UPDATE, DELETE, REFERENCES ON [dbo].[ExecutionLogStorage] TO RSExecRole GO CREATE NONCLUSTERED INDEX [IX_ExecutionLog] ON [dbo].[ExecutionLogStorage]([TimeStart], [LogEntryId]) ON [PRIMARY] GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ExecutionLog2]') and OBJECTPROPERTY(id, N'IsView') = 1) begin drop view [dbo].[ExecutionLog2] end GO CREATE VIEW [dbo].[ExecutionLog2] AS SELECT InstanceName, COALESCE(C.Path, 'Unknown') AS ReportPath, UserName, ExecutionId, CASE(RequestType) WHEN 0 THEN 'Interactive' WHEN 1 THEN 'Subscription' ELSE 'Unknown' END AS RequestType, -- SubscriptionId, Format, Parameters, CASE(ReportAction) WHEN 1 THEN 'Render' WHEN 2 THEN 'BookmarkNavigation' WHEN 3 THEN 'DocumentMapNavigation' WHEN 4 THEN 'DrillThrough' WHEN 5 THEN 'FindString' WHEN 6 THEN 'GetDocumentMap' WHEN 7 THEN 'Toggle' WHEN 8 THEN 'Sort' ELSE 'Unknown' END AS ReportAction, TimeStart, TimeEnd, TimeDataRetrieval, TimeProcessing, TimeRendering, CASE(Source) WHEN 1 THEN 'Live' WHEN 2 THEN 'Cache' WHEN 3 THEN 'Snapshot' WHEN 4 THEN 'History' WHEN 5 THEN 'AdHoc' WHEN 6 THEN 'Session' ELSE 'Unknown' END AS Source, Status, ByteCount, [RowCount], AdditionalInfo FROM ExecutionLogStorage EL WITH(NOLOCK) LEFT OUTER JOIN Catalog C WITH(NOLOCK) ON (EL.ReportID = C.ItemID) GO GRANT SELECT, REFERENCES ON [dbo].[ExecutionLog2] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ExecutionLog]') and OBJECTPROPERTY(id, N'IsView') = 1) begin drop view [dbo].[ExecutionLog] end GO CREATE VIEW [dbo].[ExecutionLog] AS SELECT [InstanceName], [ReportID], [UserName], [RequestType], [Format], [Parameters], [TimeStart], [TimeEnd], [TimeDataRetrieval], [TimeProcessing], [TimeRendering], CASE([Source]) WHEN 6 THEN 3 ELSE [Source] END AS Source, -- Session source doesn't exist in yukon, mark source as snapshot -- for in-session requests [Status], [ByteCount], [RowCount] FROM [ExecutionLogStorage] WITH (NOLOCK) WHERE [ReportAction] = 1 -- Backwards compatibility log only contains render requests GO GRANT SELECT, REFERENCES ON [dbo].[ExecutionLog] TO RSExecRole GO -------------------------------------- -- C.0.9.14 to C.0.9.15 -------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ReadLockSnapshot]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[ReadLockSnapshot] GO -------------------------------------- -- C.0.9.17 to C.0.9.18 -------------------------------------- -- No changes to tables -------------------------------------- -- C.0.9.32 to C.0.9.33 -------------------------------------- -- Having the RSExecRole in the SQLAgentUserRole is enough for Yukon: VSTS #153722 -- Move the RSExecRole from the SQLAgentOperatorRole to the SQLAgentUserRole if exists (select * from sysusers where issqlrole = 1 and name = N'SQLAgentOperatorRole') AND exists (select * from sysusers where issqlrole = 1 and name = N'SQLAgentUserRole') BEGIN EXEC msdb.dbo.sp_addrolemember N'SQLAgentUserRole', N'RSExecRole' EXEC msdb.dbo.sp_droprolemember N'SQLAgentOperatorRole', N'RSExecRole' END PA -------------------------------------- -- T.0.8.54 to T.0.9.00 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.9.00 to T.0.9.01 -------------------------------------- if (select count(*) from dbo.syscolumns where id = object_id('[dbo].[SnapshotData]') and name = 'PaginationMode') = 0 begin ALTER TABLE [dbo].[SnapshotData] ADD [PaginationMode] smallint NULL end GO if (select count(*) from dbo.syscolumns where id = object_id('[dbo].[SnapshotData]') and name = 'ProcessingFlags') = 0 begin ALTER TABLE [dbo].[SnapshotData] ADD [ProcessingFlags] int NULL end GO -------------------------------------- -- T.0.9.01 to T.0.9.02 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.9.02 to T.0.9.03 -------------------------------------- if (select count(*) from dbo.sysindexes where id = object_id('[dbo].[ExecutionCache]') and [name]='IX_SnapshotDataID') = 0 begin CREATE INDEX [IX_SnapshotDataID] ON [dbo].[ExecutionCache] ([SnapshotDataID]) end GO -------------------------------------- -- T.0.9.03 to T.0.9.04 -------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Segment]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) begin drop table [dbo].[Segment] declare @sql nvarchar(max) declare @objname nvarchar(max) select @objname = object_name(parent_object_id) from sys.check_constraints where name ='Positive_LogicalByteCount' if (@objname is not null) begin select @sql = N'alter table ' + QUOTENAME(@objname) + N' drop constraint Positive_LogicalByteCount' exec sp_executesql @sql end end create table [dbo].[Segment] ( SegmentId uniqueidentifier not null, LogicalByteCount int not null, Content varbinary(max), constraint [PK_Segment] primary key clustered ([SegmentId]), constraint [Positive_LogicalByteCount] check (LogicalByteCount >= 0) ) GO GRANT SELECT, UPDATE, INSERT, DELETE, REFERENCES ON [dbo].[Segment] TO RSExecRole GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ChunkSegmentMapping]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) begin drop table [dbo].[ChunkSegmentMapping] end create table [dbo].[ChunkSegmentMapping] ( ChunkId uniqueidentifier not null, SegmentId uniqueidentifier not null, StartByte bigint not null, constraint [PK_ChunkSegmentMapping] primary key clustered (ChunkId, SegmentId), constraint [UNIQ_ChunkId_StartByte] unique (ChunkId, StartByte), constraint [Positive_StartByte] check (StartByte >= 0) ) GO GRANT SELECT, UPDATE, INSERT, DELETE, REFERENCES ON [dbo].[ChunkSegmentMapping] TO RSExecRole GO -------------------------------------- -- T.0.9.04 to T.0.9.05 -------------------------------------- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SegmentedChunk]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) begin drop table [dbo].[SegmentedChunk] end create table [dbo].[SegmentedChunk] ( [ChunkId] uniqueidentifier not null, [SnapshotDataId] uniqueidentifier not null, [ChunkFlags] tinyint NULL, [ChunkName] nvarchar(260), [ChunkType] int, [Version] smallint null, [MimeType] nvarchar(260), [Machine] nvarchar(512) not null, constraint [PK_SnapshotChunkMapping] primary key clustered (SnapshotDataId, ChunkType, ChunkName), -- Don't use foreign key constraint here to maintain consistency... we need to manually -- clean up this table to ensure that in a farm the machine which allocates the chunk is the -- one that eventually will clean it up, and this is not necessarily the machine which -- allocated the snapshot (consider when a different machine creates a chunk in a pre-existing snapshot) -- constraint [FK_SnapshotChunkMappingSnapshotDataId] foreign key ([SnapshotDataId]) references [SnapshotData]([SnapshotDataID]) on delete cascade ) GO create unique nonclustered index [IX_ChunkId_SnapshotDataId] on [dbo].[SegmentedChunk] (ChunkId, SnapshotDataId) GO GRANT SELECT, UPDATE, INSERT, DELETE, REFERENCES ON [dbo].[SegmentedChunk] TO RSExecRole GO -------------------------------------- -- T.0.9.05 to T.0.9.06 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.9.06 to T.0.9.07 -------------------------------------- if (select count(*) from dbo.sysindexes where id = object_id(N'[dbo].[ChunkSegmentMapping]') and [name]='IX_ChunkSegmentMapping_SegmentId') = 0 begin create nonclustered index [IX_ChunkSegmentMapping_SegmentId] on [dbo].[ChunkSegmentMapping]([SegmentId]) end GO -------------------------------------- -- T.0.9.07 to T.0.9.08 -------------------------------------- -- No change in tables -------------------------------------- -- T.0.9.17 to T.0.9.18 -------------------------------------- -- Added IsCached column to SnapshotData if (select count(*) from dbo.syscolumns where id = object_id('[dbo].[SnapshotData]') and name = 'IsCached') = 0 begin ALTER TABLE [dbo].[SnapshotData] ADD [IsCached] bit default(0) end GO -- promote IsCached flag for any snapshots which are already part of the execution cache UPDATE [dbo].[SnapshotData] SET [IsCached] = CONVERT(BIT, 1) WHERE [SnapshotDataID] IN (SELECT [SnapshotDataID] FROM [dbo].[ExecutionCache]) GOPAOmȉSNg weN9Y0bhTbh0S^SN\bhTcbhS^0Rbh gRhV0Q[{tXTSN{tbh gRhV-NvQ[ SbeN9Y0bhTDn0bvbh&SNS^bhTcbh{t(u7bv bvbh eN9Y-NveN9Y0bhTDn0|~{tXTg wTO9e|~҉rRM0|~҉r[IN0|~^\'`TqQNR0|~(u7b$g w|~^\'`TqQNR v^AQO(ubhubhVbgbLbh[INvvQN[7bz0!jWyOmȉAQ(u7bg wyr[!jW-Nv!jWy0:Nbh{thVv勞[Oc[NZbvU_0_{:Nbh{thVc[ZbvU_0:Nbh gRhVv勞[Oc[N Windows gRhƋ0_{c[bh gRhV Windows gRhƋ09bh gRhV Windows gRhƋ]SuSS0O(u Reporting Services Mn]wQ͑nhƋ0:Nbh gRhVv勞[Oc[N Web gRhƋ0_{c[bh gRhV Web gRhƋ05bh gRhV Web gRhƋ]SuSS0O(u Reporting Services Mn]wQ͑nhƋ0_{:Ndkbh gRhVc[bh gRhVpenc^0:Ndkbh gRhVc[Nbh gRhVpenc^0:Nbh gRhVc[N5uP[N On0'l g:Nbh gRhVc[5uP[N On0v0Rc[ُNnKNTMb/T(u5uP[N O0 _{c[bh{thVhƋ0PA _{c[bh{thVhƋ0.bh{thVhƋ]SuSS0O(u Reporting Services Mn]wQ͑nhƋ0 bh gRhV]RYS0 bh gRhV*gRYS0bhub SNg wbh[IN0:Nbh gRhVv勞[Oc[NZbvU_0_{:Nbh gRhVc[ZbvU_0ybh gRhV[O/ec SharePoint Ɩb FO/f[S_MRN,g:g!j_ЏL0Yg`\dkbh gRhVN SharePoint NTbb/gƖb Sb_ penc^[ň u R^b bSN(W SharePoint Web ^(u z^-NO(uvbh gRhVpenc^0bh gRhVel SharePoint Mnpenc^-Nvn0_S/f*g[ň Windows SharePoint Services [a!jWbbh gRhV Web gRT Windows gR^7beCg SharePoint penc^0傁Mn gR^7bvCgP O(u SharePoint {t-N_0S_MRbh gRhV[Ock(W SharePoint Ɩb!j_ NЏL0+elNbh gRhVpenc^^zޏc0nx(WQ~ NSN SQL Server penc^0#\*go;m Reporting Services Windows gR0"]y(u Reporting Services Windows gR0(W SQL Server penc^_d NЏL,geQ0penc^g⋧NuNaYv~g0 bh gRhV]RYS0Gbh gRhVpenc^-N:\bh gRhVv[Oo`0傁mR[ bh gRhV Windows gRck(WЏL 6qTޏc0Rbh gRhV Web gR0;` NwQYgbLdkNRvcknxCgP0c[v(u7b^7b NwQY[勗{:gv{tXTyrCg0c[wQ g{tyrCgv(u7b^7b 6qT͑Ջd\O0c[vZbvU_]X[(W0c[vQN Ty0'c[vZbvU_eHe0nxOc[v Ty N*Yv^N NS+T^lW[&{0(OY: ;)O(u IIS ec[v ADSI _eHe0,{:g N*g[ň Internet Information Services (IIS)0PAASP.Net *g(W{:g NۏLlQ0c[v(u7b^7beHeb[x Ncknx0&` NwQYgbLdkNRvcknxCgP0c[wQ g{tyrCgv(u7b^7b 6qT͑Ջd\O0C` NwQY(W SQL Server penc^ NgbLdkNRvcknxCgP0c[wQ g{tyrCgv SQL Server (u7b^7b 6qT͑Ջd\O0 (u7b^7bv[x0%penc^-Nl gpenc^҉r RSExec0nxpenc^/fbh gRhVpenc^0*gnbh gRhV Windows gRv gR^7b0*gnbh gRhV Web gRv gR^7b0*g(WQz NMn[hQWYcW[B\(SSL)fN0 ~b N0Rbh gRhVMneN0zSSeHe0bh gRhVZbvU__{O(u6r~QzvzSS0(u WMI cO z^e Ov URL eHe0Qޏc~+ReHe0c[N NN WMI [OeQ0\ gN*NSpeeHe0c[@b gSpe 6qT͑Ջd\O0(c[v^(u z^`leHe0nxOc[v Ty N*Yv^N NS+T^lW[&{0(OY: /)PA+SharePoint Ɩb!j_ N/ecdkd\O0 gsQ/ecvd\Ov~Oo` SNTech04S gMn:N SharePoint Ɩb!j_vbh gRhV/ecdkd\O0el(W,g:g!j_bh gRhV NgbLdkd\O0^d\O1Y% V:N(Wbh gRhV N*g[ň Windows SharePoint Services [a!jW0[ňTMn Windows SharePoint Services 6qT͑ՋBl01d\O1Y% V:N(u Windows SharePoint Services [a!jWeleQ0'el/TRbh gRhV0N*NbY*NMneNeHe0 gsQ~Oo` hge_eN0]O(uvQN(u7b^7bOYu URL0 ~b N0R勔^(u z^0(W勡{:g N~b N0R IP 0W@W0rc[v IP 0W@WTzS~T]X[(W SSL ~[0s g~[O(u N TNS_MRBlvfN0k*N IP 0W@WTzS~TSO(uN*NfN0傁㉳Qdk O(uNs g~[v TvfN b Rds g SSL ~[v^O(uS_MRBlvfNR^e~[0 SSL fN\*glQ0:勔^(u z^eHe0S g ReportServerWebService T ReportManager /f gHe^(u z^0 URL ]OYu0MneN-NRQN URL FO*gO(u httpsys OYu[0]:Ndk^(u z^n URL0MneN-N~b N0R5uP[N OibU\cN0PA NAQO(u,g0W gR!j_0@b SSL fN NSON0 ibU\Ob~+ReHe0 ibU\ObeHheHe0*g[INN04VS_VERSION_INFOd@2 @?StringFileInfo080404B0&PlatformNT x644LegalTrademarksMicrosoft SQL Server /f Microsoft Corporation vlQFUh0 CommentsSQL&GoldenBitsTrueLCompanyNameMicrosoft Corporationh FileDescriptionReporting Services WMI providert*FileVersion2009.0100.1600.01 ((KJ_RTM).100402-1539 )JInternalNameReportingServicesWMITLegalCopyrightMicrosoft Corp. OYu@b gCg)R0ZOriginalFilenameReportingServicesWMI.DLLJProductNameMicrosoft SQL Server> ProductVersion10.50.1600.1DVarFileInfo$Translation PADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDING( $PX`hpxȣУأ(0 ( (X`P p<PX`hpxȮЮخ(ȡСء (08  ( H  xPHPpx`  (08@HPX`hpxȡСء (08@HPX`hpxȢТآ (08@HPX`hpxȣУأ (08@HPX`hpxȤФؤ (08@HPX`hpxȥХإ (08@hȦЦئ (08@HPX`hpxȧЧا (08@HPX`hpxȨШب (08@HPX`hpxȩЩة (08@HPX`hpxȪЪت (08@HPX`hpxȫЫث0X`hpxȬЬج (08@HPX`hpxȭЭح (08@HPX`hpxȮЮخ (08@HPX`hpxȯЯد (08@HPX`hpxȠРؠ (08@HPX`hpxȡСء (08@HPX`hpxȢТآ (08@HPX`hpxȣУأ (08@HPX`hpxȤФؤ (08@HPX`hpxȥХإ (08@HPX`hpxȦЦئ (08@HPX`hpȧЧا (08@HPX`hpxȨШب (08@HPX`hpxȩЩة (08@HPX`hpxȪЪت (08@HPX`hpxȫЫث (08@HPX`hpxȬЬج (08@HPX`hpxȭЭح (08@HPX`hpxȮЮخ (08@HPX`hpxȯЯد (08@HPX`hpxȠРؠ (08@HPX`hpxȡСء (08@HPX`hpxȢТآ (08@HPX`hpxȣУأ (08@HPX`hpxȤФؤ (08@HPX`hpxȥХإ (08@HPX`hpxȦЦئ (08@HPX`hpxȧЧا (08@HPX`hpxȨШب (08@HPX`hpxȩЩة (08@HPX`hpxȪЪت (08@HPX`hpxȫЫث (08@HPX`hpxȬЬج (08@HPX`hpxȭЭح (08@HPX`hpxȮЮخ (08@HPX`hpxȯЯد (08@HPX`hpxȠРؠ (08@HPX`hpxȡСء (08@HPX`hpxȢТآ (08@HPX`hpxȣУأ (08@HPX`hpxȤФؤ (08@HPX`hpxȥХإ (08@HPX`hpxȦЦئ (08@HPX`hpxȧЧا (08@HPX`hpxȨШب (08@HPX`hpxȩЩة (08@HPX`hpxȪЪت (08@HPX`hpxȫЫث (08@HPX`hpxȬЬج (08@HPX`hpxȭЭح (08@HPX`hpxȮЮخ (08@HPX`hpxȯЯد (08@HPX`hpxȠРؠ (08@HPX`hpxȡСء (08@HPX`hpxȢТآ (08@HPX`hpxȣУأ (08@HPX`hpxȤФؤ (08@HPX`hpxȥХإ (08@HPX`hpxȦЦئ (08@HPX`hpxȧЧا (08@HPX`hpxȨШب (08@HPX`hpxȩЩة (08@HPX`hpxȪЪت (08@HPX`hpxȫЫث (08@HPX`hpxȬЬج (08@HPX`hpxȭЭح (08@HPX`hpxȮЮخ (08@HPX`hpxȯЯد @ (08@HPX`hpxȠРؠ (08@HPX`hpxȡСء (08@HPX`hpxȢТآ (08@HPX`hpxȣУأ (08@HPX`hpxȤФؤ (08@HPX`hpxȥХإ (08@HPX`hpxȦЦئ (08@HPX`hpxȧЧا (08@HPX`hpx`0S *H D0@1 0 +0h +7Z0X03 +70% <<<Obsolete>>>0!0 +(*F%WQbvꠂ10`0L .P\0 +0p1+0)U "Copyright (c) 1997 Microsoft Corp.10U Microsoft Corporation1!0UMicrosoft Root Authority0 070822223102Z 120825070000Z0y1 0 UUS10U Washington10URedmond10U Microsoft Corporation1#0!UMicrosoft Code Signing PCA0"0  *H 0 y}]E941%5IwEqFԌkLRbMIl/$>e# HuEP%+ #A$bEJͳ/"J-|o;99ݽ)f;-2'Hlc\򸔣8P'N0==l9.4. }bxfs Oc,2EJ;PSfQyV>Pn5{$Rf=N+~3nGўJnS00U% 0 +0U0[pir#Q~Mˡr0p1+0)U "Copyright (c) 1997 Microsoft Corp.10U Microsoft Corporation1!0UMicrosoft Root Authority<<>c@0U00Uvp[NQD.Dc0 U0 +{~J&μNtX't*uLxMi|CʇSŸVocDDȚ  )}s9=j8m҈#i 4|.)Bk(q8 ]hͽAkf4|zB{ p֒O8|-=4 b7j#\cZ9`U3; _,˫ 0  *RA^0(ip΀Brv0z0b a>0  *H 0y1 0 UUS10U Washington10URedmond10U Microsoft Corporation1#0!UMicrosoft Code Signing PCA0 091207224029Z 110307224029Z01 0 UUS10U Washington10URedmond10U Microsoft Corporation1 0 U MOPR10UMicrosoft Corporation0"0  *H 0 0ErSkO#=Y@8s&S<B8auM\F^i[s)DdY/]nǫ9eħuꇗ&&v89&+ZT!򗍇)I,?}͖ q B5׸?ݎE }K[vrw#}5]PKGmUTN؁B1U SI0奈|^zZ7i2$00U% 0 +0U8xs2_Uƙt0U0U#0vp[NQD.Dc0DU=0;09753http://crl.microsoft.com/pki/crl/products/CSPCA.crl0H+<0:08+0,http://www.microsoft.com/pki/certs/CSPCA.crt0  *H ( oBvCB$e4uq0r7:pQ q(ps{V4ZrN {DO aun+Z 9`jT;1_,nM*v{Ƈֱ*rTn*ȞobKk=/zw9gj{cI&Bޕ" _s2r6)$ROfH&9iPNl.r!m$H@|t8JO00j O%EXzg0  *H 0p1+0)U "Copyright (c) 1997 Microsoft Corp.10U Microsoft Corporation1!0UMicrosoft Root Authority0 060916010447Z 190915070000Z0y1 0 UUS10U Washington10URedmond10U Microsoft Corporation1#0!UMicrosoft Timestamping PCA0"0  *H 0 7nBJqH>S,2ORȃ>3I1(dPKuǨծipfx'f趷 Y")/@VvmdmJT޿ǀL7VhGv\/}%V[jc|<%M9wt]\؆7,u9 |vlnz>q_*Ob`2҃N+"\hE/Pl%ׅvs6ƕz`3[AXn,HoCj&k(0$0U% 0 +0U0[pir#Q~Mˡr0p1+0)U "Copyright (c) 1997 Microsoft Corp.10U Microsoft Corporation1!0UMicrosoft Root Authority<<>c@0 +70UoN?4K;AC0 +7  SubCA0 U0U00  *H M1|PapEsT? -QS9V ތ;ɷQ!oi~k"Flm|"Fӄ6~p]Eݎ*|ɮ2Շc6!v;s!شTeJ(&`;exHϭ:ObX099!dcC/{FeJtn ̝(a|H!8Ŗ2@S=f7"̰wTQ:rD#00 a00  *H 0y1 0 UUS10U Washington10URedmond10U Microsoft Corporation1#0!UMicrosoft Timestamping PCA0 080725190115Z 130725191115Z01 0 UUS10U Washington10URedmond10U Microsoft Corporation1 0 U MOPR1'0%U nCipher DSE ESN:85D3-305C-5BCF1%0#UMicrosoft Time-Stamp Service0"0  *H 0 -g%&bK08e46$h{b,FKQ4lZ;G=.5kE<fiJ',gbT'9هN`G#{'@ 15 ӋxaŵA>6X':ڽ]L0 +0 *H  1  +70 +7 10  +70# *H  1Qp 1o~6d J!0X +7 1J0H&$SQL Server 2008 R2http://www.microsoft.com/sql0  *H J\tc쏻;XOWZvעO!^,.\ѥ?^T&;3l/7 ˬoyFWڙQo&vB͋6+Dg$.q }SVh>'94IES}8eJvGA8xR U,iկz$"AsJޞmfj\$|( Vlx@hY:{J;L0 *H  1 000y1 0 UUS10U Washington10URedmond10U Microsoft Corporation1#0!UMicrosoft Timestamping PCA a00+]0 *H  1  *H 0 *H  1 100403175237Z0# *H  1Ⱅ˷ +E6KR400  *H ;O}싏gl[i働'R,=uU[6F,sǚ/7#]DvhEbY>WP\&_ùD[:%'h+ bBԨ1XxͥhpB?:Jւt;I]Ё%%]XOkZmg,kWa{‰3]|Ŷz}`ypƜU9"2^5V"ԯoo':*cL`*