{"id":3221,"date":"2021-11-25T17:11:55","date_gmt":"2021-11-25T16:11:55","guid":{"rendered":"https:\/\/gdksoftware.com\/knowledgebase\/delphi-and-database-events"},"modified":"2022-01-11T15:31:19","modified_gmt":"2022-01-11T14:31:19","slug":"delphi-e-database-events","status":"publish","type":"knowledge","link":"https:\/\/gdksoftware.com\/pt-br\/base-de-conhecimento\/delphi-e-database-events","title":{"rendered":"Delphi and database events"},"content":{"rendered":"<p><strong>Delphi e eventos no Microsoft SQL Server<\/strong><\/p>\n<p>Eventos em banco de dados s\u00e3o uma maneira conveniente de notificar o aplicativo de que um certo evento ocorreu. Ao inv\u00e9s de deixar a aplica\u00e7\u00e3o estar constantemente consultando o banco de dados, voce pode ter um evento no exato momento para que o banco de dados possa notificar a aplica\u00e7\u00e3o de que uma determinada a\u00e7\u00e3o precisa ser executada. Por exemplo, vamos supor que uma aplica\u00e7\u00e3o faz uma altera\u00e7\u00e3o em um registro do cadastro de clientes, que faz com que a aplica\u00e7\u00e3o necessite realizar uma a\u00e7\u00e3o. A outra aplica\u00e7\u00e3o precisa somente esperar pelo evento, sem a necessidade de ficar constantemente acessando o banco de dados para verificar se o registro foi modificado.<\/p>\n<p><strong>FDEventAlerter<\/strong><\/p>\n<p>Em Delphi (ou ao inv\u00e9s no <a href=\"https:\/\/docwiki.embarcadero.com\/RADStudio\/Sydney\/en\/Database_Alerts_(FireDAC)\" target=\"_blank\" rel=\"noopener\">FireDAC<\/a>) voc\u00ea pode resolver isso usando um componente chamado <a href=\"https:\/\/docwiki.embarcadero.com\/Libraries\/Sydney\/en\/FireDAC.Comp.Client.TFDEventAlerter\" target=\"_blank\" rel=\"noopener\">TFDEventAlerter<\/a>. Este componente possui a capacidade de &#8216;escutar&#8217; os eventos dentro do ambiente de banco de dados. A beleza do componente TFDEventAlerter \u00e9 que ele \u00e9 desenhado para prover uma interface, independente do banco de dados que voc\u00ea usa. Com esta interface, voc\u00ea pode decidir se voc\u00ea vai esperar por um evento espec\u00edfico, ou por uma altera\u00e7\u00e3o em um registro espec\u00edfico em uma tabela.<\/p>\n<p><strong>Exemplo com Microsoft SQL Server<\/strong><\/p>\n<p>No exemplo a seguir, estamos usando Microsoft SQL Server. Para enviar os eventos com o Microsoft SQL Server, voc\u00ea pode usar <a href=\"https:\/\/docs.microsoft.com\/en-us\/sql\/relational-databases\/native-client\/features\/working-with-query-notifications?view=sql-server-ver15\" target=\"_blank\" rel=\"noopener\">Query Notifications<\/a>.<\/p>\n<p>Para estas Query Notifications, podemos usar o c\u00f3digo descrito a seguir:<\/p>\n<p><code><br \/>\n-- Cria a fila e o servi\u00e7o<br \/>\nCREATE QUEUE [NotificationsQueue];<br \/>\nCREATE SERVICE [NotificationsService] ON QUEUE [NotificationsQueue] (<br \/>\n[http:\/\/schemas.microsoft.com\/SQL\/Notifications\/PostQueryNotification]<br \/>\n);<br \/>\nGRANT SEND ON SERVICE::[NotificationsService] TO [];<\/code><br \/>\n<code><br \/>\n-- Permiss\u00f5es necess\u00e1rias para []<br \/>\nGRANT SELECT to []<br \/>\nGRANT SUBSCRIBE QUERY NOTIFICATIONS TO []<br \/>\nGRANT RECEIVE ON QueryNotificationErrorsQueue TO []<br \/>\nGRANT REFERENCES on CONTRACT::[http:\/\/schemas.microsoft.com\/SQL\/Notifications\/PostQueryNotification] to []<br \/>\nGRANT RECEIVE ON [NotificationsQueue] TO []<br \/>\nGRANT VIEW DEFINITION TO []<br \/>\n<\/code><\/p>\n<p>Uma vez que este setup est\u00e1 feito, n\u00f3s poderemos prosseguir e implementar este evento no Delphi. N\u00f3s fazemos isso colocando o componente TFDEventAlerter em um Form ou um DataModule e conectar a um banco de dados usando a propriedade Connection. Al\u00e9m disso, voc\u00ea precisa configar a fila, o servi\u00e7o e alterar os eventos usando a propriedade Names:<\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; border: solid gray; border-width: .1em .1em .1em .8em; padding: .2em .6em;\">\n<pre style=\"margin: 0; line-height: 125%;\">FDEventAlerter<span style=\"color: #333333;\">.<\/span>Connection <span style=\"color: #333333;\">:=<\/span> <span style=\"background-color: #fff0f0;\">''<\/span>\r\nFDEventAlerter<span style=\"color: #333333;\">.<\/span>Names<span style=\"color: #333333;\">.<\/span>Add(<span style=\"background-color: #fff0f0;\">'QUEUE=NotificationsQueue'<\/span>)<span style=\"color: #333333;\">;<\/span>\r\nFDEventAlerter<span style=\"color: #333333;\">.<\/span>Names<span style=\"color: #333333;\">.<\/span>Add(<span style=\"background-color: #fff0f0;\">'SERVICE=NotificationsService'<\/span>)<span style=\"color: #333333;\">;<\/span>\r\n<\/pre>\n<\/div>\n<p>Ent\u00e3o, voc\u00ea pode usar o evento OnAlert para capturar os eventos e execuar as a\u00e7\u00f5es de acordo com seu tipo, como demonstrado no evento abaixo:<\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; border: solid gray; border-width: .1em .1em .1em .8em; padding: .2em .6em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008800; font-weight: bold;\">procedure<\/span> <span style=\"color: #bb0066; font-weight: bold;\">TFrmMain<\/span><span style=\"color: #333333;\">.<\/span><span style=\"color: #0066bb; font-weight: bold;\">FDEventAlerterAlert<\/span>(ASender<span style=\"color: #333333;\">:<\/span> TFDCustomEventAlerter<span style=\"color: #333333;\">;<\/span> <span style=\"color: #008800; font-weight: bold;\">const<\/span> AEventName<span style=\"color: #333333;\">:<\/span> <span style=\"color: #008800; font-weight: bold;\">string<\/span><span style=\"color: #333333;\">;<\/span>\r\n  <span style=\"color: #008800; font-weight: bold;\">const<\/span> AArgument<span style=\"color: #333333;\">:<\/span> <span style=\"color: #333399; font-weight: bold;\">Variant<\/span>)<span style=\"color: #333333;\">;<\/span>\r\n<span style=\"color: #008800; font-weight: bold;\">begin<\/span>\r\n  mmLog<span style=\"color: #333333;\">.<\/span>Lines<span style=\"color: #333333;\">.<\/span>Add(<span style=\"background-color: #fff0f0;\">'Evento - ['<\/span> <span style=\"color: #333333;\">+<\/span> AEventName <span style=\"color: #333333;\">+<\/span> <span style=\"background-color: #fff0f0;\">'] - ['<\/span> <span style=\"color: #333333;\">+<\/span> AArgument <span style=\"color: #333333;\">+<\/span> <span style=\"background-color: #fff0f0;\">']'<\/span>)<span style=\"color: #333333;\">;<\/span>\r\n<span style=\"color: #008800; font-weight: bold;\">end<\/span><span style=\"color: #333333;\">;<\/span>\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Especificamente para o Microsoft SQL Server, voc\u00ea precisa habilitar o service-broker (ALTER DATABASE &lt;nome_do_banco_de_dados&gt; SET ENABLE_BROKER), caso contr\u00e1rio nenhum evento ser\u00e1 compartilhado com a fila e nenhum alerta ser\u00e1 capturado pelo TFDEventAlerter. Isso tamb\u00e9m est\u00e1 descrito no artigo <a href=\"https:\/\/docwiki.embarcadero.com\/RADStudio\/Sydney\/en\/Database_Alerts_(FireDAC) for Microsoft SQL Server\">https:\/\/docwiki.embarcadero.com\/RADStudio\/Sydney\/en\/Database_Alerts_(FireDAC) for Microsoft SQL Server<\/a>.<\/p>\n<p>FPara cada usu\u00e1rio de um TFDEventAlerter s\u00e3o necess\u00e1rios uma fila e um servi\u00e7o. O TFDEventAlerter criar\u00e1 essa fila e este servi\u00e7o no esquema padr\u00e3o do usu\u00e1rio logado no banco. Portanto \u00e9 necess\u00e1rio ter permiss\u00e3o para fazer o login e os criar. A fila e o servi\u00e7o ser\u00e1 associadas a um nome \u00fanico quando um nome n\u00e3o for provido. Depois, fechando e &#8220;desregistrando&#8221; o TFDEventAlerter, o componente ir\u00e1 apagar do banco seus respectivos fila e servi\u00e7o.<\/p>\n","protected":false},"featured_media":0,"parent":0,"template":"","class_list":["post-3221","knowledge","type-knowledge","status-publish","hentry","knowledge-category-arquivo-delphi"],"acf":{"author":1488,"type_hero":"compact","hero_image":3030,"hero_image_position":"","hero_title":"","hero_content":"","hero_link":null,"hero_show_h1":false},"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v26.8 (Yoast SEO v27.3) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>Delphi and database events<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/gdksoftware.com\/pt-br\/base-de-conhecimento\/delphi-e-database-events\" \/>\n<meta property=\"og:locale\" content=\"pt_BR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Delphi and database events\" \/>\n<meta property=\"og:description\" content=\"Delphi e eventos no Microsoft SQL Server Eventos em banco de dados s\u00e3o uma maneira conveniente de notificar o aplicativo de que um certo evento ocorreu. Ao inv\u00e9s de deixar a aplica\u00e7\u00e3o estar constantemente consultando o banco de dados, voce pode ter um evento no exato momento para que o banco de dados possa notificar [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/gdksoftware.com\/pt-br\/base-de-conhecimento\/delphi-e-database-events\" \/>\n<meta property=\"og:site_name\" content=\"GDK Software\" \/>\n<meta property=\"article:modified_time\" content=\"2022-01-11T14:31:19+00:00\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Est. tempo de leitura\" \/>\n\t<meta name=\"twitter:data1\" content=\"3 minutos\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/gdksoftware.com\\\/pt-br\\\/base-de-conhecimento\\\/delphi-e-database-events\",\"url\":\"https:\\\/\\\/gdksoftware.com\\\/pt-br\\\/base-de-conhecimento\\\/delphi-e-database-events\",\"name\":\"Delphi and database events\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/gdksoftware.com\\\/pt-br#website\"},\"datePublished\":\"2021-11-25T16:11:55+00:00\",\"dateModified\":\"2022-01-11T14:31:19+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/gdksoftware.com\\\/pt-br\\\/base-de-conhecimento\\\/delphi-e-database-events#breadcrumb\"},\"inLanguage\":\"pt-BR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/gdksoftware.com\\\/pt-br\\\/base-de-conhecimento\\\/delphi-e-database-events\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/gdksoftware.com\\\/pt-br\\\/base-de-conhecimento\\\/delphi-e-database-events#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/gdksoftware.com\\\/pt-br\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Knowledgebase\",\"item\":\"https:\\\/\\\/gdksoftware.com\\\/pt-br\\\/base-de-conhecimento\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Delphi\",\"item\":\"https:\\\/\\\/gdksoftware.com\\\/pt-br\\\/knowledgebase-category\\\/arquivo-delphi\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"Delphi and database events\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/gdksoftware.com\\\/pt-br#website\",\"url\":\"https:\\\/\\\/gdksoftware.com\\\/pt-br\",\"name\":\"GDK Software\",\"description\":\"Zet de stip op je horizon\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/gdksoftware.com\\\/pt-br?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"pt-BR\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Delphi and database events","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/gdksoftware.com\/pt-br\/base-de-conhecimento\/delphi-e-database-events","og_locale":"pt_BR","og_type":"article","og_title":"Delphi and database events","og_description":"Delphi e eventos no Microsoft SQL Server Eventos em banco de dados s\u00e3o uma maneira conveniente de notificar o aplicativo de que um certo evento ocorreu. Ao inv\u00e9s de deixar a aplica\u00e7\u00e3o estar constantemente consultando o banco de dados, voce pode ter um evento no exato momento para que o banco de dados possa notificar [&hellip;]","og_url":"https:\/\/gdksoftware.com\/pt-br\/base-de-conhecimento\/delphi-e-database-events","og_site_name":"GDK Software","article_modified_time":"2022-01-11T14:31:19+00:00","twitter_card":"summary_large_image","twitter_misc":{"Est. tempo de leitura":"3 minutos"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/gdksoftware.com\/pt-br\/base-de-conhecimento\/delphi-e-database-events","url":"https:\/\/gdksoftware.com\/pt-br\/base-de-conhecimento\/delphi-e-database-events","name":"Delphi and database events","isPartOf":{"@id":"https:\/\/gdksoftware.com\/pt-br#website"},"datePublished":"2021-11-25T16:11:55+00:00","dateModified":"2022-01-11T14:31:19+00:00","breadcrumb":{"@id":"https:\/\/gdksoftware.com\/pt-br\/base-de-conhecimento\/delphi-e-database-events#breadcrumb"},"inLanguage":"pt-BR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/gdksoftware.com\/pt-br\/base-de-conhecimento\/delphi-e-database-events"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/gdksoftware.com\/pt-br\/base-de-conhecimento\/delphi-e-database-events#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/gdksoftware.com\/pt-br"},{"@type":"ListItem","position":2,"name":"Knowledgebase","item":"https:\/\/gdksoftware.com\/pt-br\/base-de-conhecimento"},{"@type":"ListItem","position":3,"name":"Delphi","item":"https:\/\/gdksoftware.com\/pt-br\/knowledgebase-category\/arquivo-delphi"},{"@type":"ListItem","position":4,"name":"Delphi and database events"}]},{"@type":"WebSite","@id":"https:\/\/gdksoftware.com\/pt-br#website","url":"https:\/\/gdksoftware.com\/pt-br","name":"GDK Software","description":"Zet de stip op je horizon","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/gdksoftware.com\/pt-br?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"pt-BR"}]}},"_links":{"self":[{"href":"https:\/\/gdksoftware.com\/pt-br\/wp-json\/wp\/v2\/knowledge\/3221","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/gdksoftware.com\/pt-br\/wp-json\/wp\/v2\/knowledge"}],"about":[{"href":"https:\/\/gdksoftware.com\/pt-br\/wp-json\/wp\/v2\/types\/knowledge"}],"acf:post":[{"embeddable":true,"href":"https:\/\/gdksoftware.com\/pt-br\/wp-json\/wp\/v2\/team\/1488"}],"wp:attachment":[{"href":"https:\/\/gdksoftware.com\/pt-br\/wp-json\/wp\/v2\/media?parent=3221"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}