<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rafael Baguena Girbes on Medium]]></title>
        <description><![CDATA[Stories by Rafael Baguena Girbes on Medium]]></description>
        <link>https://medium.com/@baggirraf?source=rss-f294e26941dd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PMQpQZRgCLAd5OGxtvEi-w.png</url>
            <title>Stories by Rafael Baguena Girbes on Medium</title>
            <link>https://medium.com/@baggirraf?source=rss-f294e26941dd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:50:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@baggirraf/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Searching for a needle in a haystack, facilitating deployments with fabric-cicd]]></title>
            <link>https://medium.com/@baggirraf/searching-for-a-needle-in-a-haystack-facilitating-deployments-with-fabric-cicd-c591fec3e478?source=rss-f294e26941dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/c591fec3e478</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[microsoft-fabric-tutorial]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[microsoft-fabric]]></category>
            <dc:creator><![CDATA[Rafael Baguena Girbes]]></dc:creator>
            <pubDate>Sun, 16 Nov 2025 20:59:47 GMT</pubDate>
            <atom:updated>2025-11-16T20:59:47.654Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Futuristic image simulating finding a needle in a haystack" src="https://cdn-images-1.medium.com/max/1024/1*hMNdhpe-jO-tRSbXZ2BL7g.png" /><figcaption>Image generated using Google Gemini</figcaption></figure><p>Nowadays, it is unthinkable to implement any solution without having at least two different environments, development and production, so that we can isolate the workloads of each one and, above all, ensure both the robustness of the changes introduced as our solutions evolve and the integrity of the most critical systems, without causing interruptions and/or temporary cessation of activity. Few things are worse than causing a problem in a production environment after deploying a new version of an application, as anyone who has suffered it knows 😅.</p><p>Within the Microsoft Fabric and Power BI ecosystem, we have deployment pipelines, a tool that allows us to promote content between environments (up to 10 different ones) in a simple and effective way, but for more robust scenarios, its potential may fall short. And that’s where our story ends, or maybe not? 😁</p><h3>Here comes a new challenger!</h3><p>Echoing the phrase from my beloved and sometimes hated classic Street Fighter II, earlier this year the <a href="https://microsoft.github.io/fabric-cicd/latest/">fabric-cicd library</a> was introduced, and with it many barriers disappeared. This open-source Python library, maintained by Microsoft itself, facilitates deployments within Fabric by acting as a task facilitator and allowing the promotion of almost all artifacts (provided they can be placed under source code control and have an API behind them) between different workspaces (in a secure manner, in case anyone had any doubts).</p><figure><img alt="Supported versions of Python, library installation, and usage example" src="https://cdn-images-1.medium.com/max/1024/1*R6B9-eKbCgq2ADG9Pb5bsg.png" /><figcaption>Image courtesy of fabric-cicd</figcaption></figure><p>It is important to note that the library alone does not perform all the magic, unless we want to run it manually for each deployment. Its true potential comes to light when combined with its use from Azure DevOps or GitHub Actions pipelines, with the aim of not only automating the task but also establishing robust control, validation, and deployment flows. In addition to this, I particularly like to add another variable to the equation, which is that, although fabric-cicd greatly facilitates this process, it is a library designed solely for deployments between different environments, so some additional actions that the overall process may require are beyond its scope.</p><p>As a way to remedy this, we can take advantage of the possibility of executing different steps in an orderly fashion in the Azure DevOps/GitHub deployment pipelines to introduce complementary post-deployment actions thanks to another powerful library called <a href="https://microsoft.github.io/fabric-cli/">fabric-cli</a> (also open source and maintained by Microsoft, but that’s a topic for another time 😋).</p><p>Following the saying “stick to what you know” and using each tool for what it does best, the combination of fabric-cicd and fabric-cli results in a combo whose potential allows you to cover virtually all the needs that may arise during deployments between environments.</p><h3>Replacement with excitement</h3><p>Returning the focus to the benefits and features of fabric-cicd, not only can it deploy content from one workspace to another, but during the journey it can also perform a crucial action: alter the deployed artifacts and modify what elements they reference, as well as modify their characteristics and configuration according to the environment to which they are traveling.</p><figure><img alt="Operator modifying content and repositioning devices according to the corresponding environment" src="https://cdn-images-1.medium.com/max/1024/1*eV0DjivW4144R8tiV6lBLw.png" /><figcaption>Image generated using Google Gemini</figcaption></figure><p>This modification process works thanks to the existence of a YAML parameter file that is incorporated into the source code of our solution. The file acts as a kind of replacement dictionary, where we indicate what value we are looking for within the solution code and how it should be replaced depending on the environment we are going to. Thanks to this file, and as if it were a telephone operator, the specified artifacts are realigned according to the specified instructions, ensuring that nothing points where it shouldn’t. While it is true that depending on how our solution is distributed, some replacements may not be necessary (<a href="https://microsoft.github.io/fabric-cicd/latest/how_to/item_types/">there are artifacts that, if they are in the same work area, already point to themselves</a>), some other aspects such as configuration values, parameters, and schedules may need to be altered.</p><figure><img alt="Example of parameter.yml file for replacements using the library" src="https://cdn-images-1.medium.com/max/1024/1*o4SGcRKd2-UGKNxd5hTGtw.png" /><figcaption>Example of replacement parameter file content</figcaption></figure><p>As can be seen in the image, searching and replacing values can be done in different ways:</p><ul><li>Globally on all elements</li><li>Through regular expressions</li><li>Using environment variables</li><li>Using dynamic artifact values</li><li>We can specify specific artifact types and/or specific artifacts</li><li>Point to the paths of the artifacts within the solution</li></ul><p>In summary, during deployment execution, the library will review each entry recorded in the parameter file and attempt to apply the corresponding replacement as specified, ensuring correct deployment execution and updated artifact configuration. As long as we don’t forget anything along the way 😈</p><h3>The devil is in the details</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kh6dfa7SBNsOh9a2jzZBRA.png" /><figcaption>Image generated using Google Gemini</figcaption></figure><p>Like everything else in life, nothing is immune to failure. No matter how hard we try to do things right, it is possible that one day, unintentionally, errors will be introduced into the system, and unfortunately, this has consequences.</p><p>If we register invalid references in the parameter file, the library’s prior validation during deployment will detect these errors and the promotion process between environments will either not take place or will take place without applying some of the replacements, resulting in an incomplete solution that may not function correctly when executed.</p><p>These errors can arise for several reasons, such as:</p><ul><li>Mistakes when referencing artifacts and/or paths</li><li>Project modifications where elements are removed but the file is not updated</li><li>Renaming of existing artifacts</li></ul><p>Of all of these, the last two are the most relevant, especially if we are working on a solution where we collaborate with several people and some changes may go unnoticed.</p><p>Let’s take a closer look:</p><ul><li>Imagine that we have a notebook that we initially mistakenly name <em>yaml_entries generator</em>, after which we protect the code of our solution.</li><li>Later, we realize the naming error and fix it with a new commit, renaming the notebook as <em>yaml_entries_generator</em>.</li><li>In the Power BI/Fabric service, we will see the notebook with the new name:</li></ul><figure><img alt="View of the Power BI/Fabric service showing the renamed notebook" src="https://cdn-images-1.medium.com/max/937/1*z7Oq7xoQIDR7M0sMpnrhZA.png" /><figcaption>Name of the notebook in the Power BI/Fabric service</figcaption></figure><ul><li>While our solution (at the source code level) will keep the original name (without the underscore between entries and generator):</li></ul><figure><img alt="View of the solution showing the notebook with the original name" src="https://cdn-images-1.medium.com/max/319/1*-7HFKdUId-4boEg4JUEu_A.png" /><figcaption>Name of the notebook in our source code controlled solution</figcaption></figure><ul><li>This is very important depending on <a href="https://microsoft.github.io/fabric-cicd/latest/how_to/parameterization/">how we reference the replacement values</a>:<br>– If we use the artifact path (<em>file_path</em> attribute), we must use the exact name of the artifact in our solution, otherwise the deployment will fail because the path cannot be found within the project. It is also important that the specified path matches, not just the name of the artifact, especially if we use relative paths that may omit it.<br>– On the other hand, if we use the reference by name (<em>item_name</em> attribute), we can refer to the artifact both by the name it has at the service level and by the name at the solution level, thanks to the fact that this is recorded in the <em>.platform</em> file that accompanies each artifact:</li></ul><figure><img alt="Contents of the artifact’s .platform file where the reference to the renamed artifact is stored, valid for use with item_name" src="https://cdn-images-1.medium.com/max/1024/1*pbnad-j253-XseCrLCfZCQ.png" /><figcaption>Contents of the .platform file in the example notebook</figcaption></figure><h3>Finding the needle in the haystack</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yCgynbbzG1R-Jv5tEYkr9A.png" /><figcaption>Image generated using Google Gemini</figcaption></figure><p>So, now that we have outlined the potential problem and you have read this far, the least I can do is tell you the solution. And not just one, but two 😁</p><h4>Validations with fabric-cicd</h4><p>Within the fabric-cicd repository itself, we have <a href="https://github.com/microsoft/fabric-cicd/blob/main/devtools/debug_parameterization.py">a tool</a> that can be used to validate the replacement parameters file. Its content (at the time of writing this article) is as follows:</p><pre># Copyright (c) Microsoft Corporation.<br># Licensed under the MIT License.<br><br># The following is intended for developers of fabric-cicd to debug parameter.yml file locally against the github repo<br><br>import sys<br>from pathlib import Path<br><br>from azure.identity import ClientSecretCredential<br><br>import fabric_cicd.constants as constants<br>from fabric_cicd import change_log_level<br>from fabric_cicd._parameter._utils import validate_parameter_file<br><br>root_directory = Path(__file__).resolve().parent.parent<br>sys.path.insert(0, str(root_directory / &quot;src&quot;))<br><br># Uncomment to enable debug<br># change_log_level()<br><br># In this example, the parameter.yml file sits within the root/sample/workspace directory<br>repository_directory = str(root_directory / &quot;sample&quot; / &quot;workspace&quot;)<br><br># Explicitly define valid item types<br>item_type_in_scope = [&quot;DataPipeline&quot;, &quot;Notebook&quot;, &quot;Environment&quot;, &quot;SemanticModel&quot;, &quot;Report&quot;]<br><br># Set target environment<br>environment = &quot;PPE&quot;<br><br># Uncomment to use a parameter file in a different location (default location is within repository directory)<br># Use absolute path<br># parameter_file_path = str(root_directory / &quot;sample&quot; / &quot;config&quot; / &quot;parameter.yml&quot;)<br># or use relative path<br># parameter_file_path = &quot;../config/parameter.yml&quot;<br><br>validate_parameter_file(<br>    repository_directory=repository_directory,<br>    item_type_in_scope=item_type_in_scope,<br>    # Comment to exclude target environment in validation<br>    environment=environment,<br>    # Uncomment to use a different parameter file name within the repository directory (default name: parameter.yml)<br>    # Assign to the constant in constants.py or pass in a string directly<br>    # parameter_file_name=constants.PARAMETER_FILE_NAME,<br>    # Uncomment to use a parameter file from outside the repository (takes precedence over parameter_file_name)<br>    # parameter_file_path=parameter_file_path,<br>    # Uncomment to use SPN auth<br>    # token_credential=token_credential,<br>)</pre><p>If we download the file and include it in our solution, once we adapt the path, environment, and types of artifacts we want to validate, we can run it to obtain the warnings and/or errors found in the validation of our file:</p><figure><img alt="Output via terminal of the validation result performed with the debug_parameterization.py file." src="https://cdn-images-1.medium.com/max/1024/1*y2f8LJAAIMjBmMQU4TEGpw.png" /><figcaption>Output via terminal of the validation result performed with the debug_parameterization.py file.</figcaption></figure><p>We can increase the level of detail further by following the instructions in the code and uncommenting the line with the call to <em>change_log_level()</em> to get even more messages, which help to better determine the causes of the warnings:</p><figure><img alt="Extended message output by the terminal, including names of undetected elements" src="https://cdn-images-1.medium.com/max/1024/1*iN89Xg4e78cpBc5M87PxfA.png" /><figcaption>Output of validation result via terminal with additional log messages</figcaption></figure><p>As can be seen in the screenshot, the extended messages tell us, in this case, which element is missing from the directory, allowing us to easily correct the error, or maybe not? 😋(That’s two!)</p><h4>Who said sequels were never any good?</h4><p>Although using relative paths with wildcards can simplify the process if we use replacements via <em>file_path</em>, our project structure may not always allow for their use in all cases, where it may be more advisable to use the <em>item_name</em> attribute instead. And this is where, unless I am mistaken, I found a crack in the armor.<br>If we look at the previous screenshot, we can see that the library’s debugging method tells us that the <em>nb_etl_magic_table99</em> artifact does not exist within the repository directory. However, this is not the only artifact within the corresponding section defined in our replacement parameters YAML that does not exist in the repository; there are several more:</p><figure><img alt="Fictitious entries within the parameter.yaml file" src="https://cdn-images-1.medium.com/max/614/1*XGSbTB02l9XS9GM9gVGVhA.png" /><figcaption>Example of non-existent artifacts within the parameter.yaml file</figcaption></figure><p>I placed a couple of fictitious entries in different numbers and positions in order to verify that, regardless of how many erroneous values we have within a section, the debugging tool only shows us the last value detected in these cases, which means it would take multiple executions to determine which entries are incorrect.</p><p>On the other hand, although we can validate that the file is well formed and that its content is correct, we have no way of determining which elements of the solution are not included within the YAML.</p><p>While it is true that, depending on the replacement strategy implemented (mainly relative paths using <em>file_path</em>) and the structure of our project, we may be somewhat more protected against this, but again, we are exposed to possible mistakes and/or oversights on our part, which leave out elements of the solution that need to be acted upon during deployment and which, although they do not cause an immediate error in the deployment, may cause one later when we try to execute them, so better safe than sorry, right? 😉</p><h4>New kid in town</h4><p>So, it was time to get down to work and do something to alleviate these shortcomings and resolve them, either by complementing the existing validator or using it independently to streamline checks and ensure the smooth operation of our solutions as they evolve.</p><p>And that is how the script affectionately named <strong><em>YAMLFICATOR!</em></strong> was born, which evolved into a tool that:</p><ul><li>Analyzes all incorrect entries specified in the YAML replacement file, regardless of whether they use the <em>item_name </em>or <em>file_path</em> attributes, as well as the different replacement modes (<em>key_value_replace </em>or <em>find_replace</em>), so that none are left out and multiple executions are not required.</li><li>Detects those artifacts within the solution that are not registered in the YAML, making it possible to narrow the search to specific artifact types and/or exclude paths from the analysis. This means that as our solution grows and evolves, we have an additional protection mechanism that ensures that no element that needs it is left out of the replacements.</li><li>Although it does not require the original library, it emulates its operating mechanism in many ways, so that they retain a certain similarity and are easy to use:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_-vzeldS4CTKKR8IVcPTHA.png" /><figcaption>Output issued by console reporting what has been detected at different levels</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SsCdm9rBZsZjiYu2kORGEA.png" /><figcaption>Log file with results obtained for the execution</figcaption></figure><p>Although it has ultimately become more than just a simple script, the idea is that using it should be as easy as:</p><ul><li>Including it in our project</li><li>Importing the module</li><li>Launching its execution with the desired configuration</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2hIuHAa0DHjVQL2O4wwHog.png" /><figcaption>Example of using yamlficator</figcaption></figure><p>So, if you’ve made it this far and want to take a closer look at the tool and/or use it in your projects, it’s available in <a href="https://github.com/l2aFa/rafabric/tree/main/yamlficator_tool">my GitHub repository</a>, where you’ll find more information about it, additional resources, and other items that may be of interest to you.</p><p>I hope you find it useful 😃! And, above all, I hope it saves you a few headaches when it’s not clear which artifact you still need to configure 😋</p><p>Happy deployments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c591fec3e478" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Buscando la aguja en el pajar, facilitando despliegues con fabric-cicd]]></title>
            <link>https://medium.com/@baggirraf/buscando-la-aguja-en-el-pajar-facilitando-despliegues-con-fabric-cicd-fa967f1d0fce?source=rss-f294e26941dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa967f1d0fce</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[microsoft-fabric]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[microsoft-fabric-tutorial]]></category>
            <dc:creator><![CDATA[Rafael Baguena Girbes]]></dc:creator>
            <pubDate>Sun, 16 Nov 2025 20:59:12 GMT</pubDate>
            <atom:updated>2025-11-16T20:59:12.642Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Imagen futurista simulando el encontrar la aguja en el pajar" src="https://cdn-images-1.medium.com/max/1024/1*hMNdhpe-jO-tRSbXZ2BL7g.png" /><figcaption>Imagen generada gracias a Google Gemini</figcaption></figure><p>Hoy en día resulta impensable implementar cualquier solución donde no contemos con diferentes entornos, como mínimo dos, desarrollo y producción, de forma que podamos aislar las cargas de trabajo de cada uno de ellos y, especialmente, asegurar tanto la robustez de los cambios introducidos al evolucionar nuestras soluciones como la integridad de los sistemas más críticos, sin ocasionar interrupciones y/o el cese temporal de su actividad. Pocas cosas hay peores que ocasionar un problema en un entorno productivo tras desplegar una nueva versión de un aplicativo, quién lo probó lo sabe 😅.</p><p>Dentro del ecosistema de Microsoft Fabric y Power BI, contamos con las canalizaciones de implementación, una herramienta que permite llevar a cabo la promoción de contenido entre entornos (hasta 10 diferentes) de forma simple y eficaz, pero para escenarios más robustos es posible que su potencial se quede corto. Y aquí acaba nuestra historia, ¿o quizás no? 😁</p><h3><strong>¡Aquí viene un nuevo peleador!</strong></h3><p>Emulando la frase de mi clásico querido y a veces odiado Street Fighter II, a principios de este año se introdujo la librería <a href="https://microsoft.github.io/fabric-cicd/latest/">fabric-cicd</a> y con él desaparecieron muchas de las barreras. Esta librería de Python de carácter open source y mantenida por el propio Microsoft, facilita la acción de llevar a cabo los despliegues dentro de Fabric actuando como un facilitador de la tarea y permitiendo la promoción de casi todos los artefactos (siempre que puedan ponerse bajo control de código fuente y cuenten con un API por detrás) entre diferentes áreas de trabajo (de forma securizada por si alguien tenía dudas).</p><figure><img alt="Versiones soportadas de Python, instalación de la librería y ejemplo de uso" src="https://cdn-images-1.medium.com/max/1024/1*R6B9-eKbCgq2ADG9Pb5bsg.png" /><figcaption>Imagen cortesía de fabric-cicd</figcaption></figure><p>Es importante destacar que la librería por sí sola no lleva a cabo toda la magia, salvo que queramos ejecutarla manualmente para cada despliegue. Su verdadero potencial sale a relucir cuando se combina con su uso desde canalizaciones de despliegue de Azure DevOps o GitHub Actions, con el objetivo no solo de automatizar la tarea si no de establecer flujos robustos de control, validación y despliegue. Además de esto, a mí particularmente me gusta añadir otra variable a la ecuación y es que, aunque fabric-cicd facilita enormemente este proceso, es una librería pensada únicamente para realizar despliegues entre diferentes entornos, por lo que algunas acciones adicionales que pueda requerir el proceso global le quedan fuera de alcance.</p><p>Como forma de remediarlo, podemos aprovechar la posibilidad de ejecutar diferentes pasos de forma ordenada en las canalizaciones de despliegue para introducir acciones complementarias post despliegue gracias a otra gran potente librería como es <a href="https://microsoft.github.io/fabric-cli/">fabric-cli</a> (también open source y mantenida por Microsoft, pero está ya mejor para otra ocasión 😋).</p><p>Siguiendo el dicho de zapatero a tus zapatos y utilizando cada uno para lo que mejor hace, la dupla de fabric-cicd y fabric-cli resulta en un combo cuyo potencial permite cubrir prácticamente todas las necesidades que pueden presentarse durante los despliegues entre entornos.</p><h3>Reemplazando, que es gerundio</h3><p>Devolviendo el foco de nuevo a las bondades y características de fabric-cicd, no solo únicamente puede llevar a cabo el despliegue el contenido de un área de trabajo a otra si no que durante el transcurso del viaje también puede llevar a cabo una acción crucial, re apuntar los artefactos afectados y modificar a qué elementos referencian, así como modificar sus características y configuración según al entorno al que viajan.</p><figure><img alt="Operadora modificando los contenidos y reapuntando los artefactos según el entorno al que corresponda" src="https://cdn-images-1.medium.com/max/1024/1*eV0DjivW4144R8tiV6lBLw.png" /><figcaption>Imagen generada gracias a Google Gemini</figcaption></figure><p>Este proceso de modificación funciona gracias a la existencia de un fichero YAML de parámetros que se incorpora al código fuente de nuestra solución. El fichero actúa como una especie de diccionario de reemplazos, donde indicamos que valor buscamos dentro del código de la solución y cómo debería reemplazarlo dependiendo del entorno al que vayamos. Gracias a él y como si de una operadora de telefonía se tratase, los artefactos especificados se realinean según las instrucciones especificadas y aseguramos que no haya nada que no apunte a donde no deba. Si bien es cierto que dependiendo de cómo esté distribuida nuestra solución es posible que no sean necesarios algunos reemplazos (<a href="https://microsoft.github.io/fabric-cicd/latest/how_to/item_types/">hay artefactos que si se encuentran en la misma área de trabajo ya se reapuntan solos</a>), algunos otros aspectos como valores de configuración, parámetros y programaciones es posible que sí sea necesario alterarlos.</p><figure><img alt="Ejemplo de fichero parameter.yml para reemplazos mediante la librería" src="https://cdn-images-1.medium.com/max/1024/1*cTdFDrX5draWMMTMhJhUhw.png" /><figcaption>Ejemplo de contenido del fichero de parámetros de reemplazo</figcaption></figure><p>Tal como puede verse en la imagen, la búsqueda y reemplazo de valores puede llevarse a cabo de diferentes formas:</p><ul><li>Global sobre todos los elementos</li><li>A través de expresiones regulares</li><li>Empleando variables de entorno</li><li>Utilizando valores dinámicos de artefactos</li><li>Podemos indicar tipos de artefacto concreto y/o artefactos específicos</li><li>Apuntar a las rutas de los artefactos dentro de la solución</li></ul><p>De forma resumida, durante la ejecución del despliegue, la librería revisará cada entrada registrada en el fichero de parámetros y tratará de aplicar el reemplazo correspondiente según lo especificado, lo que asegurará una correcta ejecución del despliegue y la configuración actualizada de los artefactos. Siempre y cuando no nos olvidemos nada por el camino 😈</p><h3>El diablo está en los detalles</h3><figure><img alt="Ejemplo de que todo proceso no está exento de fallos" src="https://cdn-images-1.medium.com/max/1024/1*kh6dfa7SBNsOh9a2jzZBRA.png" /><figcaption>Imagen generada gracias a Google Gemini</figcaption></figure><p>Como todo en esta vida, nada está exento de fallos. Por muy bien que tratemos de hacer las cosas, es posible que algún día sin pretenderlo se introduzcan errores en el sistema y eso desafortunadamente tiene sus consecuencias.</p><p>Si registramos referencias inválidas dentro del fichero de parámetros, la validación previa que hace la librería dentro del despliegue detectará dichos fallos y el proceso de promoción entre entornos no se llevará a cabo o bien se realizará, pero sin aplicar algunos de los reemplazos lo que dará lugar a una solución incompleta y con riesgo de no funcionar correctamente al ejecutarse.</p><p>Estos fallos pueden surgir por varios motivos, como:</p><ul><li>Equivocaciones al referenciar los artefactos y/o rutas</li><li>Evoluciones de la solución donde se eliminan elementos, pero no se actualiza el fichero</li><li>Renombrados de artefactos existentes</li></ul><p>De todos ellos, los dos últimos son los que resultan más relevantes, especialmente si trabajamos en una solución donde colaboramos con varias personas y algunos cambios pueden pasarnos desapercibidos.</p><p>Vamos a verlo más de cerca:</p><ul><li>Imaginemos que tenemos un cuaderno que bautizamos en primer lugar erróneamente como <em>yaml_entries generator</em>, tras lo que protegemos el código de nuestra solución.</li><li>Posteriormente, nos damos cuenta del error de nomenclatura y lo solucionamos con un nuevo commit, renombrando el cuaderno como <em>yaml_entries_generator</em>.</li><li>En el servicio de Power BI/Fabric veremos el cuaderno con el nuevo nombre:</li></ul><figure><img alt="Vista del servicio de Power BI/Fabric donde se ve el cuaderno renombrado" src="https://cdn-images-1.medium.com/max/987/1*dgsdtGYgzK5Fr3J3moxRaA.png" /><figcaption>Nombre del cuaderno en el servicio de Power BI/Fabric</figcaption></figure><ul><li>Mientras que nuestra solución (a nivel de código fuente) mantendrá el nombre original (sin el guión bajo entre entries y generator):</li></ul><figure><img alt="Vista de la solución donde se ve el cuaderno con el nombre original" src="https://cdn-images-1.medium.com/max/319/1*-7HFKdUId-4boEg4JUEu_A.png" /><figcaption>Nombre del cuaderno en nuestra solución bajo control de código fuente</figcaption></figure><ul><li>Esto resulta muy relevante según <a href="https://microsoft.github.io/fabric-cicd/latest/how_to/parameterization/">como hagamos la referencia para el reemplazo de valores</a>:<br>– Si utilizamos la ruta del artefacto (atributo <em>file_path</em>), tenemos que usar el nombre exacto que tenga el artefacto a nivel de nuestra solución, de lo contrario provocaremos el fallo del despliegue al no encontrarse la ruta dentro del proyecto. También es importante que la ruta especificada coincida, no solo el nombre del artefacto, sobre todo si usamos rutas relativas que puedan omitir este.<br>– En cambio, si utilizamos la referencia por nombre (atributo <em>item_name</em>), podremos referirnos al artefacto tanto por el nombre con el que cuente a nivel del servicio como por el nombre a nivel de la solución, gracias a que esto queda registrado en el fichero <em>.platform</em> que acompaña a cada artefacto:</li></ul><figure><img alt="Contenido del fichero .platform del artefacto donde se guarda la referencia al artefacto renombrado, válido para su uso con item_name" src="https://cdn-images-1.medium.com/max/1024/1*pbnad-j253-XseCrLCfZCQ.png" /><figcaption>Contenido del fichero .platform del cuaderno de ejemplo</figcaption></figure><h3>Encontrando la aguja en el pajar</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yCgynbbzG1R-Jv5tEYkr9A.png" /><figcaption>Imagen generada gracias a Google Gemini</figcaption></figure><p>Así pues, ahora que hemos expuesto la posible problemática y has llegado hasta aquí, qué menos que contarte la solución. Y no una, sino dos 😁</p><h4>Validaciones con fabric-cicd</h4><p>Dentro del propio repositorio de fabric-cicd, contamos con <a href="https://github.com/microsoft/fabric-cicd/blob/main/devtools/debug_parameterization.py">una herramienta</a> con la que es posible llevar a cabo validaciones del fichero de parámetros de reemplazo, su contenido (a fecha de redacción de este artículo) viene a ser el siguiente:</p><pre># Copyright (c) Microsoft Corporation.<br># Licensed under the MIT License.<br><br># The following is intended for developers of fabric-cicd to debug parameter.yml file locally against the github repo<br><br>import sys<br>from pathlib import Path<br><br>from azure.identity import ClientSecretCredential<br><br>import fabric_cicd.constants as constants<br>from fabric_cicd import change_log_level<br>from fabric_cicd._parameter._utils import validate_parameter_file<br><br>root_directory = Path(__file__).resolve().parent.parent<br>sys.path.insert(0, str(root_directory / &quot;src&quot;))<br><br># Uncomment to enable debug<br># change_log_level()<br><br># In this example, the parameter.yml file sits within the root/sample/workspace directory<br>repository_directory = str(root_directory / &quot;sample&quot; / &quot;workspace&quot;)<br><br># Explicitly define valid item types<br>item_type_in_scope = [&quot;DataPipeline&quot;, &quot;Notebook&quot;, &quot;Environment&quot;, &quot;SemanticModel&quot;, &quot;Report&quot;]<br><br># Set target environment<br>environment = &quot;PPE&quot;<br><br># Uncomment to use a parameter file in a different location (default location is within repository directory)<br># Use absolute path<br># parameter_file_path = str(root_directory / &quot;sample&quot; / &quot;config&quot; / &quot;parameter.yml&quot;)<br># or use relative path<br># parameter_file_path = &quot;../config/parameter.yml&quot;<br><br>validate_parameter_file(<br>    repository_directory=repository_directory,<br>    item_type_in_scope=item_type_in_scope,<br>    # Comment to exclude target environment in validation<br>    environment=environment,<br>    # Uncomment to use a different parameter file name within the repository directory (default name: parameter.yml)<br>    # Assign to the constant in constants.py or pass in a string directly<br>    # parameter_file_name=constants.PARAMETER_FILE_NAME,<br>    # Uncomment to use a parameter file from outside the repository (takes precedence over parameter_file_name)<br>    # parameter_file_path=parameter_file_path,<br>    # Uncomment to use SPN auth<br>    # token_credential=token_credential,<br>)</pre><p>Si descargamos el fichero y lo incluimos dentro de nuestra solución, una vez adaptemos la ruta, el entorno y los tipos de artefactos que queremos validar, podremos ejecutarlo para obtener los warnings y/o errores encontrados en la validación de nuestro fichero:</p><figure><img alt="Salida por terminal del resultado de la validación efectuada con el fichero debug_parameterization.py" src="https://cdn-images-1.medium.com/max/1024/1*y2f8LJAAIMjBmMQU4TEGpw.png" /><figcaption>Salida por terminal del resultado de la validación efectuada con el fichero debug_parameterization.py</figcaption></figure><p>Podemos aumentar más el nivel de detalle siguiendo las instrucciones del código y descomentando la línea con la llamada a <em>change_log_level()</em> para obtener aún más mensajes, que ayudan a determinar mejor las causas de los warnings:</p><figure><img alt="Salida extendida de mensajes por la terminal, incluyendo nombres de elementos no detectados" src="https://cdn-images-1.medium.com/max/1024/1*iN89Xg4e78cpBc5M87PxfA.png" /><figcaption>Salida por terminal del resultado de la validación con mensajes de log adicionales</figcaption></figure><p>Tal como puede verse en la captura, los mensajes extendidos nos indican, en este caso, qué elemento es el que no se encuentra del directorio, permitiendo subsanar el error fácilmente, ¿o quizás no? 😋(¡van dos!)</p><h4>¿Quién dijo que segundas partes nunca fueron buenas?</h4><p>Aunque usar rutas relativas con comodines puede simplificarnos el proceso si utilizamos reemplazos a través de <em>file_path</em>, puede que no siempre la estructura de nuestro proyecto posibilite su uso para todos los casos , donde alternativamente sea más recomendable emplear el atributo de <em>item_name. </em>Y es aquí donde, salvo error por mi parte, encontré una grieta en la armadura.</p><p>Si miramos la captura anterior, veremos que el método de depuración de la librería nos indica que el artefacto <em>nb_etl_magic_table99 </em>no existe dentro del directorio del repositorio<em>. </em>Sin embargo, este no es el único artefacto dentro de la sección correspondiente definida en nuestro YAML de parámetros de reemplazo que no existe en el repositorio, hay varios más:</p><figure><img alt="Entradas ficticias dentro del fichero parameter.yaml" src="https://cdn-images-1.medium.com/max/614/1*XGSbTB02l9XS9GM9gVGVhA.png" /><figcaption>Ejemplo de artefactos no existentes dentro del fichero parameter.yaml</figcaption></figure><p>Coloqué un par de entradas ficticias en diferente número y posición con el objetivo de corroborar que, independientemente de cuántos valores erróneos tengamos dentro de un apartado, la herramienta de depuración únicamente nos enseña el último valor detectado en estos casos, por lo que nos llevaría múltiples ejecuciones determinar qué entradas son las incorrectas.</p><p>Por otro lado, si bien podemos validar que el fichero esté bien conformado y que su contenido sea correcto, no tenemos forma de determinar qué elementos de la solución no están incluidos dentro del YAML.</p><p>Si bien es cierto que, en función de la estrategia de reemplazo implementada (principalmente rutas relativas mediante <em>file_path</em>) y la estructura de nuestro proyecto, podemos estar algo más protegidos frente a esto, nuevamente aquí estamos expuestos a posibles equivocaciones y/o descuidos por nuestra parte, que dejen fuera elementos de la solución sobre los que sea necesario actuar durante el despliegue y que si bien no provocan un error inmediato en este, pueden producirlo más tarde cuando tratemos de ejecutarlos, por lo que mejor prevenir que curar, ¿verdad? 😉</p><h4>El chico nuevo en la ciudad</h4><p>Así pues, tocaba ponerse manos a la obra y hacer algo que posibilitase paliar estas carencias y poder resolverlas, bien complementando el validador ya existente o bien usado de forma independiente para poder agilizar las comprobaciones y asegurar el buen funcionamiento de los despliegues de nuestras soluciones conforme evolucionan.</p><p>Y es así cómo nació el script cariñosamente bautizado como <strong><em>¡YAMLFICATOR!</em></strong>, el cual fue evolucionando hasta convertirse en una herramienta que:</p><ul><li>Analiza todas las entradas incorrectas especificadas dentro del fichero YAML de reemplazos, independientemente de si utilizan los atributos de <em>item_name </em>o <em>file_path, </em>así como los diferentes modos de reemplazo (<em>key_value_replace</em> o <em>find_replace)</em>, de forma que no se deja ninguna en el tintero ni requiere múltiples ejecuciones.</li><li>Detecta aquellos artefactos existentes dentro de la solución que no están registrados dentro del YAML, posibilitando acotar la búsqueda sobre tipos de artefactos concretos y/o la exclusión de rutas del análisis. Con lo que conforme nuestra solución crezca y evolucione, contamos con un mecanismo de protección adicional que garantiza que ningún elemento que lo necesite quede fuera de los reemplazos.</li><li>Si bien no precisa de la librería original, emula su mecanismo de funcionamiento en muchos aspectos, de forma que guarden cierta similitud y faciliten su utilización:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_-vzeldS4CTKKR8IVcPTHA.png" /><figcaption>Salida emitida por consola informando de lo detectado en diferentes niveles</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SsCdm9rBZsZjiYu2kORGEA.png" /><figcaption>Fichero de log con resultados obtenidos para la ejecución</figcaption></figure><p>Aunque finalmente ha quedado en algo más que un simple script, la idea es que utilizarlo sea tan sencillo como:</p><ul><li>Incluirlo dentro de nuestro proyecto</li><li>Importar el módulo</li><li>Lanzar su ejecución con la configuración deseada</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2hIuHAa0DHjVQL2O4wwHog.png" /><figcaption>Ejemplo de uso de yamlficator</figcaption></figure><p>Así pues, si has llegado hasta aquí y quieres echarle un vistazo más de cerca a la herramienta y/o poder utilizarla dentro de tus desarrollos, la tienes disponible dentro de <a href="https://github.com/l2aFa/rafabric/tree/main/yamlficator_tool">mi repositorio en GitHub</a>, donde encontrarás más información al respecto, recursos adicionales y otros elementos que quizá sean de tu interés.</p><p>Espero que os sea de utilidad 😃! Y, sobre todo, que también os ahorre algún que otro quebradero de cabeza cuando no se identifica claramente qué artefacto es el que nos falta por configurar 😋</p><p>¡Felices despliegues!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa967f1d0fce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[⏱️ One to schedule them all! Scheduling and executing processes in Microsoft Fabric]]></title>
            <link>https://medium.com/@baggirraf/%EF%B8%8F-one-to-schedule-them-all-scheduling-and-executing-processes-in-microsoft-fabric-ef50da361bc0?source=rss-f294e26941dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef50da361bc0</guid>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[scheduling]]></category>
            <category><![CDATA[microsoft-fabric]]></category>
            <category><![CDATA[data-orchestration]]></category>
            <dc:creator><![CDATA[Rafael Baguena Girbes]]></dc:creator>
            <pubDate>Thu, 24 Jul 2025 18:06:55 GMT</pubDate>
            <atom:updated>2025-07-24T18:06:55.233Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LaVK6X50mItvwB5JmC50TQ.png" /><figcaption>Image generated by Copilot</figcaption></figure><p>First of all, to avoid any misunderstandings, I must confess that, although I love being able to combine some of my passions and hobbies (sorry, I couldn’t resist 😝), we cannot schedule all our processes within Fabric through a single element.</p><p>However, we can use certain strategies and actions to achieve a similar effect that allows us to both facilitate and simplify these processes, reducing the number of components needed(to some extent) and expanding Fabric’s capabilities even further.</p><h3>Every journey begins with a first step</h3><p>Firstly, we need to establish the topic we are going to discuss: the scheduling and process execution capabilities within Microsoft Fabric.</p><p>Once we have our solution, as a general rule, it needs to be executed with a certain frequency so that it carries out its characteristic actions and refreshes the related data within a specific time frame. To do this, Fabric allows us to schedule the execution of certain artifacts such as pipelines, notebooks, data flows and/or semantic models through its interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*4Usvdhw-3eLzKltuM23BUQ.png" /><figcaption>Scheduling executions in Microsoft Fabric</figcaption></figure><p>The available options are virtually identical for all artifacts, with the exception of semantic models, which retain the functionality already established in Power BI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-So_dFolx8XLs199feNZAQ.png" /><figcaption>Refresh schedule for semantic models</figcaption></figure><p>Although they are quite thorough and useful for most scenarios, all these options alone do not allow for issues such as the following to be addressed:</p><ul><li><strong>Having more than one schedule per artifact</strong> — It is not currently possible to define a monthly and weekly (or other type of) frequency for the same item (planned for Q3 2025 <a href="https://roadmap.fabric.microsoft.com/?product=datafactory">Microsoft Fabric Roadmap</a>, although only for pipelines)</li><li><strong>Possibility of dynamising executions </strong>— Unlike its ‘siblings’ <a href="https://learn.microsoft.com/en-us/azure/data-factory/how-to-create-schedule-trigger?tabs=data-factory">Azure Data Factory and Azure Synapse</a>, it is not possible to pass parameter values to a Fabric Data Factory schedule (or any of the other experiences), and although we also have triggers, they are limited in terms of the scenarios allowed.</li><li><strong>Reuse and repurpose existing elements</strong> — Since we cannot configure parameters and/or more than one schedule per element, in the worst case scenario we may find ourselves having to duplicate artifacts in order to output certain scenarios, thereby increasing the maintenance cost of our solutions.</li></ul><p>Are these difficulties completely unavoidable? Let’s put it to the test 😁</p><h3>⚔️ Time to take up arms!</h3><p>So, although I emphasise once again that it is not possible to have a single element to program them all and bind them in darkness… I mean govern them, it is possible to reach a middle ground where we can both implement different schedules for the same element and pass parameters (if it has them) to dynamise its execution without having to duplicate our artifacts, but rather reuse them multiple times.</p><p>There are surely different ways to achieve this (especially when the planned options arrive), but the method described below seems to me to be the simplest, most powerful, and most robust way to solve this scenario, at least for now. It offers a reusable pattern that facilitates scheduling and programming executions in Fabric.</p><p>While it is true that not all that glitters is gold, given that we will need at least one artifact for each schedule we need to set, at least until the planned future developments arrive and assuming that they cover everything mentioned above in its entirety (🤞🏻🤞🏻🤞🏻).</p><p>So, how do we make it possible? Thanks to the combination of three main elements:</p><ul><li>⚙️ <a href="https://learn.microsoft.com/en-us/rest/api/fabric/articles/">Fabric REST API</a>, which allows us to go beyond the options offered by Fabric through its interface. It is thanks to the <a href="https://learn.microsoft.com/en-us/rest/api/fabric/core/job-scheduler/run-on-demand-item-job?tabs=HTTP">Job Scheduler — Run On Demand Item Job</a> method that we achieve the ‘magic’ 🪄.</li><li>🔗 <a href="https://learn.microsoft.com/en-us/python/api/semantic-link-sempy/sempy.fabric?view=semantic-link-python">Semantic link</a>, a living marvel that facilitates tasks and actions at all levels (development, administration, governance, integration, etc.). In this specific case, we will use its <a href="https://learn.microsoft.com/es-es/python/api/semantic-link-sempy/sempy.fabric.fabricrestclient?view=semantic-link-python">FabricRestClient</a> and <a href="https://learn.microsoft.com/es-es/python/api/semantic-link-sempy/sempy.fabric.powerbirestclient?view=semantic-link-python">PowerBIRestClient</a> classes to facilitate the task of interacting with the API.</li><li>🐍 <a href="https://learn.microsoft.com/en-us/fabric/data-engineering/using-python-experience-on-notebook">Python notebooks</a>, with a quick start and very economical CU consumption for the action they will perform, as well as being able to use the semantic link/sempy library without any problems. We will refer to them as <strong><em>‘schedulers’</em></strong> from now on to make things easier. It can also be implemented with a Spark notebook without any problems.</li></ul><p>Additionally, we will have/can count on some extra elements such as:</p><ul><li>📦A ‘trigger’ artifact that will be indispensable (without it, there is no execution). This could be, for example, a Spark pipeline or notebook (although we can also invoke Gen2 data flows or semantic models, even copy jobs) that encompasses all parts of our solution and also supports parameters (which, although not mandatory, facilitates dynamisation and reuse).<br>Let’s imagine a Fabric Data Factory pipeline where we have the sequenced and ordered execution of all the elements of our solution through different tasks.<br>In the case of a medallion architecture implementation, we would have everything from extraction from the sources to subsequent layered processing and processing of the final analytical model. If we execute this element, our entire solution is processed.</li><li>🗂️An optional metadata system that controls and streamlines the execution of the previous element. Thanks to this system, and in combination with the parameters defined in the artifacts, information is retrieved from the elements or values that need to be processed, making it possible, for example, to control and filter which entities and/or models will be processed in each execution.<br>You can explore ideas on how to implement it in <a href="https://medium.com/@baggirraf/microsoft-fabric-sql-databases-more-than-meets-the-ai-ye-30c81bf393c0">another of my articles</a>.</li></ul><p>In simplified form, we can see this in the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*KRaQD9rwaLsv9TX96Gv3zg.png" /><figcaption>Flow of the proposed solution, one notebook for each necessary schedule</figcaption></figure><p>As we can see in the image, we would have several <strong><em>“schedulers”</em></strong> that would follow the same pattern… What pattern, you may ask? Let’s take a look!</p><h3>🤺 All for one and one for all</h3><p>Previously, we discussed three elements needed to make this possible: a notebook, the semantic link library, and Fabric’s REST API. In addition, to make the task easier, we will use the <em>fabric_rest_api_caller</em> and <em>get_artifact_guid_by_name</em> functions that I have published in my <a href="https://github.com/l2aFa/rafabric/blob/main/pyspark/sempy_functions.ipynb">GitHub repository</a>, where you can find more information about their definition and characteristics.</p><p>The second of these is particularly useful when working with multiple environments (development, testing, production, etc.) because, although the artifact identifier will change between different environments, its name should (as a general rule) remain the same. This ensures that we are pointing to the correct element before dynamically triggering its execution:</p><pre>def get_artifact_guid_by_name(<br>    artifact_name: str, workspace: str = None, artifact_type: str = None<br>) -&gt; str | None:<br>    try:<br>        artifact_guid: str = &quot;&quot;<br>        if workspace:<br>            items_pandas_df = fabric.list_items(workspace=workspace)<br>        else:<br>            items_pandas_df = fabric.list_items()<br><br>        artifact_info = items_pandas_df[items_pandas_df[&quot;Display Name&quot;] == artifact_name]<br>        if not artifact_info.empty:<br>            if artifact_type:<br>                filtered_artifact_info = artifact_info[artifact_info[&quot;Type&quot;] == artifact_type]<br>                if not filtered_artifact_info.empty:<br>                    artifact_guid = filtered_artifact_info[&quot;Id&quot;].iloc[0]<br>                else:<br>                    print(<br>                        f&quot;*INFO*: ⚠️ Artifact &#39;{artifact_name}&#39; of type {artifact_type} was not found in &#39;{workspace if workspace else &#39;current workspace&#39;}&#39;.&quot;<br>                    )<br>                    return None<br>            else:<br>                artifact_guid = artifact_info[&quot;Id&quot;].iloc[0]<br>            return artifact_guid<br>        else:<br>            print(<br>                f&quot;*INFO*: ⚠️ Artifact &#39;{artifact_name}&#39; was not found in &#39;{workspace if workspace else &#39;current workspace&#39;}&#39;.&quot;<br>            )<br>            return None<br><br>    except Exception as err:<br>        print(f&quot;*ERROR*: ❌ Error obtaining {artifact_name} identifier, the error ocurred is: {err=}&quot;)<br>        return None</pre><p>Once all the ingredients are in place, let’s imagine that we have a pipeline named<strong><em> “scheduled_pl_01”</em></strong>, which has two parameters defined as <strong><em>“scheduler_sample_param_01”</em></strong> and “<strong><em>scheduler_sample_param_02” </em></strong>within the pipeline itself.</p><p>If we need to schedule the execution of this pipeline with certain values in the parameters at a certain frequency, we would implement something similar to the example shown below, where, for simplicity’s sake, only the calls to the aforementioned functions are shown, with a <a href="https://github.com/l2aFa/rafabric/blob/main/pyspark/job_scheduler_pattern.ipynb">more comprehensive example available in the repository</a>.</p><pre>workspace_id = fabric.get_workspace_id()<br><br>artifact_name = &quot;scheduled_pl_01&quot;<br>artifact_type = &quot;DataPipeline&quot;<br>artifact_id = get_artifact_guid_by_name(artifact_name= artifact_name, workspace= workspace_id, artifact_type=artifact_type)<br>if not artifact_id:<br>    raise Exception(f&quot;*ERROR*: ❌ Artifact &#39;{artifact_name}&#39; not found in workspace &#39;{workspace_id}&#39;&quot;)<br><br>scheduler_sample_param_01 = &quot;I was passed first&quot;<br>scheduler_sample_param_02 = &quot;I was second&quot;<br><br>job_type = &quot;Pipeline&quot;<br>rest_api_uri = f&quot;v1/workspaces/{workspace_id}/items/{artifact_id}/jobs/instances?jobType={job_type}&quot;<br> The arguments for the call can also be skipped if the artifact has no parameters as well<br>payload = {<br>    &quot;executionData&quot;: {<br>        &quot;parameters&quot;: {<br>            &quot;scheduler_sample_param_01&quot;: scheduler_sample_param_01,<br>            &quot;scheduler_sample_param_02&quot;: scheduler_sample_param_02<br>        }<br>    }<br>}<br><br>response = fabric_rest_api_caller(source_uri=rest_api_uri, method=&quot;post&quot;, audience=&quot;fabric&quot;, source_payload=payload)</pre><p>The process is simple: we specify the values we need in advance, such as the workspace where the artifact we want to invoke is located, its name and type (although some of these values are optional depending on our case). We then set the values for the artifact’s parameters (if it has any) and configure the API call that we will invoke once everything is ready. This will result in the execution of the referenced artifact, as well as all those that it invokes in turn, using the parameters we have specified:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OKQMeu2M1RPbd8kwLRdMNA.png" /><figcaption>Example of execution through the scheduler, which calls the pipeline that in turn executes two different notebooks</figcaption></figure><p>Once all this has been done (it is always advisable to test first 😁), we would schedule the execution of the notebook and, if we need another schedule, we would simply duplicate this notebook, change the values of the parameters we pass in the invocation (if necessary) and schedule this new notebook with a different frequency.</p><p>This way, we can have different schedules under the same repeatable and highly configurable pattern.</p><h3>🪧The road goes on and on, even in the dark</h3><p>In addition to all of the above, and as specified in the complete example, it is important to highlight the following points to consider:</p><ul><li>The configuration of the arguments/payload that we carry out in the API call in order to pass parameters has a different structure depending on the artifact we want to invoke (pipeline, notebook, Gen2 data flow, etc.).</li><li>For Gen2 dataflows, there is an additional aspect to consider: the use of parameters is a feature in preview at the time of writing this article, and <a href="https://learn.microsoft.com/en-us/fabric/data-factory/dataflow-parameters">this feature must be enabled in the artifact beforehand</a>, or the invocation will fail. Be aware of the limitations that apply after enabling it.</li><li>The call made by the <strong><em>“scheduler” </em></strong>type notebook is asynchronous; its execution ends once the referenced artifact is invoked, without waiting for this process to finish. Its progress could be monitored, if necessary, based on the response returned in the invocation and <a href="https://learn.microsoft.com/en-us/rest/api/fabric/core/job-scheduler/get-item-job-instance?tabs=HTTP">other API methods</a> (this might be better for another article later on 😋).</li><li>The classification of job types is not documented, or at least I haven’t been able to find it 😅. It should be noted that the type of artifact and the type of job are not the same and do not use the same literals. Here is a small dictionary of correspondences that may be useful for this and other things:</li></ul><pre>artifact_type_to_job_type = {<br>    &quot;DataPipeline&quot;: &quot;Pipeline&quot;, # Data Factory pipeline<br>    &quot;Dataflow&quot;: &quot;Refresh&quot;, # Dataflow Gen2<br>    &quot;Notebook&quot;: &quot;RunNotebook&quot; # Spark/Python notebook<br>    }</pre><p>So, we have seen how we can achieve multiple dynamic schedules within Microsoft Fabric so that we can use this feature if we need it until the planned functionality arrives, and even with it already implemented, if it falls short and/or is not as flexible as we need it to be.</p><p>I hope you find this useful.</p><p>Next stop: how to retrieve and view the schedules configured on our Fabric artifacts. Stay tuned 😉.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef50da361bc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[⏱️ ¡Uno para programarlos a todos! Agendado y ejecución de procesos en Microsoft Fabric]]></title>
            <link>https://medium.com/@baggirraf/%EF%B8%8F-uno-para-programarlos-a-todos-agendado-y-ejecuci%C3%B3n-de-procesos-en-microsoft-fabric-775cfc36f720?source=rss-f294e26941dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/775cfc36f720</guid>
            <category><![CDATA[scheduling]]></category>
            <category><![CDATA[data-orchestration]]></category>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[microsoft-fabric]]></category>
            <dc:creator><![CDATA[Rafael Baguena Girbes]]></dc:creator>
            <pubDate>Thu, 24 Jul 2025 18:06:42 GMT</pubDate>
            <atom:updated>2025-07-24T18:06:42.618Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LaVK6X50mItvwB5JmC50TQ.png" /><figcaption>Imagen generada por Copilot</figcaption></figure><p>Lo primero de todo y por evitar posibles equívocos, debo confesar que, aunque me encanta poder combinar parte de mis pasiones y aficiones (disculpad que no haya podido resistirme 😝), no podemos programar todos nuestros procesos dentro de Fabric a través de un único elemento.</p><p>No obstante, sí que podemos utilizar ciertas estrategias y acciones para conseguir un efecto similar que nos permita tanto facilitar dichos procesos como simplificarlos, reduciendo el número de componentes necesarios (hasta cierto punto) y pudiendo extender las capacidades de Fabric más allá.</p><h3>Todo viaje comienza con un primer paso</h3><p>En primer lugar, ahora sí, es necesario establecer el tema del que vamos a tratar, las capacidades de agendado y ejecución de procesos dentro de Microsoft Fabric.</p><p>Una vez tenemos nuestra solución, por norma general, es necesario que esta se ejecute con cierta frecuencia de manera que lleve a cabo las acciones que le caracterizan y refresque los datos relacionados dentro de una periodicidad específica. Para ello, Fabric nos permite programar la ejecución de algunos artefactos como canalizaciones, cuadernos, flujos de datos y/o modelos semánticos a través de su interfaz:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HX3RaOCnH_cXwkAc5vl-Sw.png" /><figcaption>Programación de ejecuciones en Microsoft Fabric</figcaption></figure><p>Las opciones disponibles son idénticas prácticamente para todos los artefactos, a excepción de los modelos semánticos que conservan el funcionamiento ya establecido en Power BI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*upUqfiPu8eC8PfyVwhYdyg.png" /><figcaption>Agendado de refrescos para modelos semánticos</figcaption></figure><p>Aunque resultan bastante completas y útiles para la mayoría de escenarios, todas estas opciones por si solas no permiten poder dar salida a cuestiones tales como:</p><ul><li><strong>Tener más de una programación por artefacto </strong>— No es posible definir una periodicidad mensual y semanal (o de otro tipo) para el mismo elemento en estos instantes (está previsto para el Q3 del 2025 <a href="https://roadmap.fabric.microsoft.com/?product=datafactory">Microsoft Fabric Roadmap</a> aunque solo para las canalizaciones)</li><li><strong>Posibilidad de dinamizar las ejecuciones</strong> — A diferencia de sus “hermanos” <a href="https://learn.microsoft.com/es-es/azure/data-factory/how-to-create-schedule-trigger?tabs=data-factory">Azure Data Factory y Azure Synapse</a>, no es posible pasarle valores de parámetros a una programación de Fabric Data Factory (o de cualquiera de las otras experiencias) y aunque disponemos también de desencadenadores, están limitados en cuanto a los escenarios permitidos.</li><li><strong>Reutilizar y reaprovechar elementos ya existentes </strong>— Como no podemos configurar parámetros y/o más de una programación por elemento, en el peor de los casos podemos vernos en la necesidad de duplicar artefactos para poder dar salida a determinados escenarios, incrementando con ello el coste de mantenimiento de nuestras soluciones.</li></ul><p>¿Son estas dificultades totalmente insalvables? Pongámoslo a prueba 😁</p><h3>⚔️ ¡Hora de pasar a las armas!</h3><p>Así pues, aunque de nuevo recalco que no es posible tener un único elemento para programarlos a todos y atarlos en las tinieblas…digo gobernarlos, sí que es posible llegar a un punto intermedio donde podamos tanto implementar diferentes programaciones para un mismo elemento como podamos pasarle parámetros (si los tiene) para dinamizar su ejecución y sin necesidad de tener que duplicar nuestros artefactos, si no que podamos reaprovecharlos.</p><p>Seguramente hay diferentes maneras de poder lograr esto (más aún cuando lleguen las opciones planificadas), pero la forma expuesta a continuación me ha parecido la más sencilla, potente y robusta de cara a poder solventar este escenario, al menos por ahora. Ofreciendo un patrón reutilizable que facilita el agendado y programación de ejecuciones en Fabric.</p><p>Si bien es cierto que no es oro todo lo que reluce, dado que precisaremos como mínimo un artefacto por cada programación que necesitemos agendar, al menos hasta que lleguen las futuras novedades previstas y contando con que cubran todo lo expuesto anteriormente en su totalidad (🤞🏻🤞🏻🤞🏻).</p><p>Entonces, ¿cómo lo hacemos posible? Gracias a la combinación de tres elementos principales:</p><ul><li>⚙️ <a href="https://learn.microsoft.com/es-es/rest/api/fabric/articles/">API REST de Fabric</a>, que nos permiten ir más allá de las opciones que posibilita Fabric a través de su interfaz. Será gracias al método <a href="https://learn.microsoft.com/es-es/rest/api/fabric/core/job-scheduler/run-on-demand-item-job?tabs=HTTP">Job Scheduler — Run On Demand Item Job</a> que logremos la “magia” 🪄.</li><li>🔗 <a href="https://learn.microsoft.com/en-us/python/api/semantic-link-sempy/sempy.fabric?view=semantic-link-python">Semantic link</a>, maravilla viviente que facilita tareas y acciones a todos los niveles (desarrollo, administración, gobierno, integración, etc.). Para este caso en concreto, utilizaremos sus clases <a href="https://learn.microsoft.com/es-es/python/api/semantic-link-sempy/sempy.fabric.fabricrestclient?view=semantic-link-python">FabricRestClient</a> y <a href="https://learn.microsoft.com/es-es/python/api/semantic-link-sempy/sempy.fabric.powerbirestclient?view=semantic-link-python">PowerBIRestClient</a> para facilitarnos la tarea de interactuar con la API.</li><li>🐍 <a href="https://learn.microsoft.com/es-es/fabric/data-engineering/using-python-experience-on-notebook">Cuadernos de Python</a>, con un arranque rápido y un consumo de CU muy económico para la acción que realizarán, así como pueden usar la librería semantic link/sempy sin problemas. Nos referiremos a ellos como <strong><em>“schedulers”</em></strong> de ahora en adelante para facilitar las cosas. Puede también implementarse con un cuaderno de Spark sin problemas.</li></ul><p>Adicionalmente, contaremos/podemos contar con algunos elementos extra como:</p><ul><li>📦Un artefacto “disparador” que resultará indispensable (sin él no hay ejecución). Se trataría, por ejemplo, de una canalización o cuaderno de Spark (aunque también podemos invocar flujos de datos Gen2 o modelos semánticos, incluso trabajos de copia) que englobe todas las partes de nuestra solución y que además admita parámetros (que, aunque no es obligatorio facilita la dinamización y reutilización).<br>Imaginemos una canalización de Fabric Data Factory donde tenemos la ejecución secuenciada y ordenada de todos los elementos de nuestra solución a través de diferentes tareas. <br>En el caso de una implementación de arquitectura medallón tendríamos desde la extracción desde los orígenes, al posterior procesamiento por capas y el procesado del modelo analítico final. Si ejecutamos este elemento, se procesa toda nuestra solución por completo.</li><li>🗂️Un sistema de metadatos, de carácter opcional, que controle y dinamice las ejecuciones del elemento anterior. Gracias a él y de forma combinada junto a los parámetros definidos en los artefactos, se recupera la información de los elementos o valores que deben procesarse, logrando, por ejemplo, controlar y filtrar qué entidades y/o modelos se tratarán en cada ejecución. <br>Puedes explorar ideas sobre cómo implementarlo en <a href="https://medium.com/@baggirraf/bases-de-datos-sql-en-microsoft-fabric-m%C3%A1s-all%C3%A1-de-la-alegr-ia-ca6c9acb05ce">otro de mis artículos</a>.</li></ul><p>De forma simplificada, podemos verlo en el siguiente diagrama:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*NFHkrBwpJs5PPhw58srTzg.png" /><figcaption>Flujo de la solución propuesta, un cuaderno por cada programación necesaria</figcaption></figure><p>Tal como vemos en la imagen, contaríamos con varios “<strong><em>schedulers</em></strong><em>”</em> que seguirían un mismo patrón…¿qué patrón os estaréis preguntando? ¡Veámoslo también!</p><h3>🤺 Uno para todos y todos para uno</h3><p>Anteriormente hablábamos de tres elementos para poder hacer esto posible: un cuaderno , la librería semantic link y el API REST de Fabric. Además, para facilitar la tarea haremos uso de las funciones <em>fabric_rest_api_caller</em> y <em>get_artifact_guid_by_name</em> que tengo publicadas dentro de mi <a href="https://github.com/l2aFa/rafabric/blob/main/pyspark/sempy_functions.ipynb">repositorio de GitHub</a>, donde puede encontrarse más información sobre su definición y características. <br>La segunda de ellas resulta especialmente útil cuando trabajemos con varios entornos (desarrollo, test, producción, etc.) puesto que, aunque el identificador del artefacto cambiará entre los diferentes entornos su nombre debería (por norma general) ser el mismo. De esta forma, nos aseguramos de apuntar al elemento correcto antes de disparar su ejecución de forma dinámica:</p><pre>def get_artifact_guid_by_name(<br>    artifact_name: str, workspace: str = None, artifact_type: str = None<br>) -&gt; str | None:<br>    try:<br>        artifact_guid: str = &quot;&quot;<br>        if workspace:<br>            items_pandas_df = fabric.list_items(workspace=workspace)<br>        else:<br>            items_pandas_df = fabric.list_items()<br><br>        artifact_info = items_pandas_df[items_pandas_df[&quot;Display Name&quot;] == artifact_name]<br>        if not artifact_info.empty:<br>            if artifact_type:<br>                filtered_artifact_info = artifact_info[artifact_info[&quot;Type&quot;] == artifact_type]<br>                if not filtered_artifact_info.empty:<br>                    artifact_guid = filtered_artifact_info[&quot;Id&quot;].iloc[0]<br>                else:<br>                    print(<br>                        f&quot;*INFO*: ⚠️ Artifact &#39;{artifact_name}&#39; of type {artifact_type} was not found in &#39;{workspace if workspace else &#39;current workspace&#39;}&#39;.&quot;<br>                    )<br>                    return None<br>            else:<br>                artifact_guid = artifact_info[&quot;Id&quot;].iloc[0]<br>            return artifact_guid<br>        else:<br>            print(<br>                f&quot;*INFO*: ⚠️ Artifact &#39;{artifact_name}&#39; was not found in &#39;{workspace if workspace else &#39;current workspace&#39;}&#39;.&quot;<br>            )<br>            return None<br><br>    except Exception as err:<br>        print(f&quot;*ERROR*: ❌ Error obtaining {artifact_name} identifier, the error ocurred is: {err=}&quot;)<br>        return None</pre><p>Reunidos todos los ingredientes, imaginemos que tenemos una canalización con nombre <strong>“<em>scheduled_pl_01”</em></strong>, la cual cuenta con dos parámetros definidos como <strong>“<em>scheduler_sample_param_01”</em></strong><em> </em>y <strong>“<em>scheduler_sample_param_02”</em></strong><em> </em>dentro de la propia canalización<em>. <br></em>Si necesitamos programar la ejecución de esta canalización con unos valores determinados en los parámetros con una periodicidad determinada<em>, </em>implementaríamos algo semejante al ejemplo mostrado a continuación, donde, por cuestiones de simplicidad, se reflejan solo las invocaciones a las funciones anteriormente citadas quedando disponible un <a href="https://github.com/l2aFa/rafabric/blob/main/pyspark/job_scheduler_pattern.ipynb">ejemplo más amplio dentro del repositorio</a>.</p><pre>workspace_id = fabric.get_workspace_id()<br><br>artifact_name = &quot;scheduled_pl_01&quot;<br>artifact_type = &quot;DataPipeline&quot;<br>artifact_id = get_artifact_guid_by_name(artifact_name= artifact_name, workspace= workspace_id, artifact_type=artifact_type)<br>if not artifact_id:<br>    raise Exception(f&quot;*ERROR*: ❌ Artifact &#39;{artifact_name}&#39; not found in workspace &#39;{workspace_id}&#39;&quot;)<br><br>scheduler_sample_param_01 = &quot;I was passed first&quot;<br>scheduler_sample_param_02 = &quot;I was second&quot;<br><br>job_type = &quot;Pipeline&quot;<br>rest_api_uri = f&quot;v1/workspaces/{workspace_id}/items/{artifact_id}/jobs/instances?jobType={job_type}&quot;<br> The arguments for the call can also be skipped if the artifact has no parameters as well<br>payload = {<br>    &quot;executionData&quot;: {<br>        &quot;parameters&quot;: {<br>            &quot;scheduler_sample_param_01&quot;: scheduler_sample_param_01,<br>            &quot;scheduler_sample_param_02&quot;: scheduler_sample_param_02<br>        }<br>    }<br>}<br><br>response = fabric_rest_api_caller(source_uri=rest_api_uri, method=&quot;post&quot;, audience=&quot;fabric&quot;, source_payload=payload)</pre><p>El proceso es simple, especificamos los valores que necesitemos previamente como el área de trabajo donde se encuentre el artefacto que queremos invocar, su nombre y tipo (aunque algunos de estos valores son opcionales dependiendo de nuestro caso). Posteriormente establecemos los valores de los parámetros del artefacto (si los tiene) y conformamos la llamada a la API que invocaremos una vez listo todo. Lo que nos dará como resultado la ejecución del artefacto referenciado, así como todos los que el mismo invoque a su vez, utilizando los parámetros que hayamos especificado:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*13ZGIo1z8DvPnHZkdANT2g.png" /><figcaption>Ejemplo de ejecución a través del scheduler, el cual llama a la canalización que a su vez ejecuta dos cuadernos distintos</figcaption></figure><p>Una vez hecho todo esto (recomendable probar primero siempre 😁) agendaríamos la ejecución del cuaderno y si necesitamos otra programación bastaría con duplicar este cuaderno, cambiar los valores de los parámetros que le pasemos en la invocación (si es necesario) y agendar este nuevo cuaderno con una periodicidad distinta. <br>De esta forma podremos contar con distintas programaciones bajo un mismo patrón repetible y altamente configurable.</p><h3><strong>🪧El camino sigue y sigue, incluso en la oscuridad</strong></h3><p>Además de todo lo anterior y tal como especifico en el ejemplo completo, es importante destacar los siguientes puntos a tener en cuenta:</p><ul><li>La configuración de los argumentos/payload que llevemos a cabo en la llamada de la API para poder pasar parámetros, cuenta con diferente estructura dependiendo del artefacto que queramos invocar (canalización, cuaderno, flujo de datos Gen2, etc.).</li><li>Para los flujos de datos Gen2 hay además que tener en cuenta un aspecto adicional, el uso de parámetros es una característica en versión preliminar a fecha de es este artículo y es <a href="https://learn.microsoft.com/es-es/fabric/data-factory/dataflow-parameters">necesario activar esta característica previamente en el artefacto</a> o la invocación fallará. Ojo con las limitaciones presentes tras activarlo.</li><li>La llamada que realiza el cuaderno de tipo <strong><em>“scheduler”</em></strong> es asíncrona, su ejecución finaliza una vez invocado el artefacto que se referencia, sin esperar a que este proceso acabe. Podría controlarse su evolución, en caso de ser necesario, en función de la respuesta devuelta en la invocación y <a href="https://learn.microsoft.com/en-us/rest/api/fabric/core/job-scheduler/get-item-job-instance?tabs=HTTP">otros métodos de la API</a> (esto quizá mejor para otro artículo más adelante 😋)</li><li>La clasificación de los tipos de jobs no se encuentra documentada o al menos yo no la he encontrado 😅. Hay que tener en cuenta que el tipo de artefacto y el tipo de job no son lo mismo ni utilizan los mismos literales, dejo un pequeño diccionario de correspondencias que puede resultar útil tanto para esto como para otras cosas:</li></ul><pre>artifact_type_to_job_type = {<br>    &quot;DataPipeline&quot;: &quot;Pipeline&quot;, # Canalización de Data Factory<br>    &quot;Dataflow&quot;: &quot;Refresh&quot;, # Flujo de datos Gen2<br>    &quot;Notebook&quot;: &quot;RunNotebook&quot; # Cuaderno de Spark/Python<br>    }</pre><p>Así pues, hemos visto cómo podemos lograr obtener múltiples programaciones dinámicas dentro de Microsoft Fabric de forma que podemos lograr dar salida a esta característica si la necesitamos hasta que llegue la funcionalidad prevista e incluso aún con ella ya implementa, si es que se nos queda corta y/o no es todo lo flexible que podamos necesitar.</p><p>Espero que os pueda ser de utilidad.</p><p>Próxima parada como poder recuperar y visualizar las programaciones configuradas sobre nuestros artefactos de Fabric, permanezcan atent@s 😉.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=775cfc36f720" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microsoft Fabric SQL Databases, more than meets the AI-ye!]]></title>
            <link>https://medium.com/@baggirraf/microsoft-fabric-sql-databases-more-than-meets-the-ai-ye-30c81bf393c0?source=rss-f294e26941dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/30c81bf393c0</guid>
            <category><![CDATA[metadata]]></category>
            <category><![CDATA[microsoft-fabric]]></category>
            <category><![CDATA[sql-database]]></category>
            <category><![CDATA[orchestration]]></category>
            <category><![CDATA[audit]]></category>
            <dc:creator><![CDATA[Rafael Baguena Girbes]]></dc:creator>
            <pubDate>Sun, 22 Jun 2025 10:47:50 GMT</pubDate>
            <atom:updated>2025-06-22T10:47:50.605Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ClFv5fqSTkVgkoyLa6M7A.jpeg" /><figcaption>AI-generated image</figcaption></figure><p>One of the most recent services that has been incorporated into the “Swiss Army Knife” as I usually describe Microsoft Fabric are <a href="https://learn.microsoft.com/en-us/fabric/database/sql/overview"><em>SQL databases</em></a>, a friendly experience, based on Azure SQL databases, which allows us to provision operational databases in a matter of seconds ⏱️.</p><p>This new resource focuses on three fundamental pillars:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*8Ft3Lj1gGw3UZ1x75tb32A.png" /><figcaption>Image credit Microsoft</figcaption></figure><p>This is why, thanks both to Fabric’s own unification and integration and to the support of some specific functionalities (<a href="https://devblogs.microsoft.com/azure-sql/langchain-with-sqlvectorstore-example/"><em>native vector search capabilities</em></a>), it is possible to create artificial intelligence applications faster and with fewer impediments, reducing the implementation and development times needed to start getting the most out of our solutions as soon as possible.</p><p>If one thing is clear it is that AI is here to stay, but does this mean that we can only take advantage of SQL databases for this option? It doesn’t have to, perhaps there’s more than meets the AI-ye! 👀</p><h3>1️⃣If there was not enough to choose from</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*akKMaB0EbKWgADDwzy9jbA.png" /><figcaption>AI-generated image with a few tweaks</figcaption></figure><p>Within Microsoft Fabric, we have different options for storing data in our processes and solutions.</p><p>Before discussing possible use cases and applications, it is important to be clear about the characteristics of each of the available artifacts and their best scope of application. In this way, we will be able to better decide which ones (which need not be exclusive) to use depending on the nature of our solution. Fortunately, there are several resources available to help us in this task (and <a href="https://powerbi.microsoft.com/es-es/blog/unify-datamart-with-fabric-data-warehouse/"><em>some of them will soon be retired</em></a>).</p><p>Specifically, Microsoft has different guides that we can use to facilitate the decision:</p><ul><li><a href="https://learn.microsoft.com/en-us/fabric/fundamentals/decision-guide-data-store">Fabric decision guide — choose a data store — Microsoft Fabric | Microsoft Learn</a></li><li><a href="https://techcommunity.microsoft.com/blog/analyticsonazure/decision-guide-for-selecting-an-analytical-data-store-in-microsoft-fabric/4362079">Decision Guide for Selecting an Analytical Data Store in Microsoft Fabric | Microsoft Community Hub</a></li></ul><p>If we take a look at them, we will find some features that can be useful for our solutions, especially if we have or want to implement a system governed through metadata, i.e. having one or more artifacts where the information that we can use to configure, dynamize and control the execution of our processes will reside, thus facilitating different aspects such as reusability, operational, automation and/or auditing of operations.</p><p>More specifically, the particularity that we can take advantage of SQL databases is their speed in access and writing for operations with low volume of data, performed concurrently and that can also benefit from advanced functionalities such as the use of indexes and/or <a href="https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property?view=sql-server-ver17"><em>fields with the IDENTITY property</em></a>.</p><p>Although in the past we could compensate for the lack of this artifact by using instead, for example, a warehouse, a lakehouse or even configuration files, none of these solutions is perhaps as well suited as the SQL database (although each scenario is different!), either because they were not designed for this purpose but to operate with large volumes in the case of the former or because of operational issues and ease of editing in the case of the latter.</p><h3>2️⃣Time to take action</h3><p>Let’s see in which scenarios the addition of a SQL database within our solution can be particularly useful.</p><p>To do so, let’s imagine an ETL process developed under Microsoft Fabric such as the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nDXOVQ8sDxSeSBjhZFga8A.png" /><figcaption>Fabric Data Factory pipeline example for data processing and ordered execution of operations</figcaption></figure><p>In this case, thanks to the benefits of Fabric’s SQL databases, we can implement a process where we can apply different use cases thanks to the integration between the several elements and experiences available, so that we can achieve dynamic, standardized and especially reliable solutions.</p><p>Let’s take a look at some of them.</p><h4>♻️ Metadata-driven processes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EYjL-XevNNhHOzcoexAvhQ.png" /><figcaption>Metadata system — AI-generated image</figcaption></figure><p>Although there are different methods for its implementation and each scenario will be different, with Fabric SQL databases we have a powerful artifact that can act as the heart of our solution.</p><p>Through them, we can incorporate a metadata system where we can centralize, among other things, aspects such as the particular configuration of each entity to be processed (associated load pattern, order of precedence, dependencies, etc.) or specific values to be taken into account for the layer to be executed (if we have, for example, a medallion architecture 🥉🥈🥇), thus achieving a greater degree of dynamism and automation within our processes, facilitating their orchestration, reutilization, maintenance and evolution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*V8gsAbTBE7-VCRfLJAzVoA.png" /><figcaption>Retrieval of configurations and runtime values through metadata system</figcaption></figure><p>If we go back to the previous example, the pipeline retrieves the necessary information from our metadata database to perform the extraction and processing of different entities within a given layer, where we will use for each of them both the recovered configuration values and the results of the previous execution. In this way, we manage to dynamize the execution of the process so that we can both reuse artifacts and reduce implementation times (one pipeline to process them all! 💍) and increase its robustness and ease of re-execution after possible previous failures, adjusting their values and allowing to resume the failed execution where it left off.</p><p>In addition, for example, we can include specific field mapping specifications for those that require it, so that we can control the schemas of the processed entities and avoid possible problems due to discrepancies, unsupported characters and/or evolutions that may occur on a daily basis, thus ensuring greater reliability and control within our processes, since it is important to control what data we dump into our system from the very first moment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*mYysyusvDQld9RAgoDrCAg.png" /><figcaption>Field mapping control and schema used within the CopyData activity</figcaption></figure><h4>📝Operations auditing and logging</h4><p>Thanks to the possibility of encapsulating the logic used within SQL database stored procedures, we can implement different elements that, depending on the parameters received, can act in one way or another and/or be used by different processes, thus standardizing the actions performed and centralizing their logic.</p><p>A crucial aspect within our operations is the auditing and recording of operations, keeping track of what has been executed, how long it has taken, what state it has been left in, how many records have been processed, etc. These are very relevant aspects that help to keep our system supervised and facilitate debugging and control of incidents when they happen (which they will 😁).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j7ELv1YrbE7vM4ojx0GNYw.png" /><figcaption>Example of an audit table within our system</figcaption></figure><p>Although we already have native mechanisms within Fabric, such as the <strong><em>Monitor</em></strong> section, thanks to SQL databases, we can customize the logs and traces of our solutions, opening the door to more elaborate scenarios where multiple concurrent writes and/or recurring accesses to retrieve specific values simultaneously is not a problem, but quite the opposite.</p><p>To top it off, all of this is replicated through the SQL Endpoint linked to the artifact, making the information available to other Fabric resources such as Spark notebooks and/or lakehouse.</p><h4>🚦Control flow and disaster recovery</h4><p>Extending even more the previously exposed use cases, although with Fabric it is no longer necessary to worry (at first glance😜) about what time to schedule the processes as it happened before thanks to Fabric’s own features such as <a href="https://learn.microsoft.com/en-us/fabric/enterprise/throttling#bursting"><em>bursting</em></a> and <a href="https://learn.microsoft.com/en-us/fabric/enterprise/throttling#smoothing"><em>smoothing</em></a>, it is possible that sometimes we have some processes where we need to control that they do not run until some other finishes and/or if some other are running. Even if we want to achieve idempotent solutions, we can check the information recorded by the previous execution to be able to resume, for example, a failed execution from the point where it left off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hs4ccu6GuZlAue8OT7ik-w.png" /><figcaption>Checking of running processes and details of previous executions recorded in the metadata system</figcaption></figure><p>By recording all executions in a table in our database, we can check what is being executed before launching each process and establish either a previous wait or not execute it directly.</p><p>At the same time, if we have a table where we record the traces of each execution, we could, for example, implement a process that can automatically relaunch those loads that have been delayed and/or those that present errors, avoiding possible concerns and that the freshness of data within the system could be harmed.</p><h3>3️⃣Conclusions</h3><p>So, we have seen how the inherent properties and features of Fabric’s SQL databases can extend the capabilities of our processes and solutions in ways that were previously not possible or less straightforward to implement.</p><p>In addition to all their goodness for artificial intelligence processes, they are a worthy companion to consider as we journey through any of the experiences within the Fabric ecosystem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30c81bf393c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bases de datos SQL en Microsoft Fabric, más allá de la alegr-IA]]></title>
            <link>https://medium.com/@baggirraf/bases-de-datos-sql-en-microsoft-fabric-m%C3%A1s-all%C3%A1-de-la-alegr-ia-ca6c9acb05ce?source=rss-f294e26941dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca6c9acb05ce</guid>
            <category><![CDATA[orchestration]]></category>
            <category><![CDATA[metadata]]></category>
            <category><![CDATA[audit]]></category>
            <category><![CDATA[microsoft-fabric]]></category>
            <category><![CDATA[sql-database]]></category>
            <dc:creator><![CDATA[Rafael Baguena Girbes]]></dc:creator>
            <pubDate>Sun, 22 Jun 2025 10:47:13 GMT</pubDate>
            <atom:updated>2025-06-22T10:47:13.855Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ClFv5fqSTkVgkoyLa6M7A.jpeg" /><figcaption>Imagen generada por IA</figcaption></figure><p>Uno de los servicios más recientes que se ha incorporado dentro de la “navaja suiza” como acostumbro a describir Microsoft Fabric son las <a href="https://learn.microsoft.com/es-es/fabric/database/sql/overview"><em>bases de datos SQL</em></a>, una experiencia amigable, basada en las bases de datos de Azure SQL, que nos permite aprovisionar bases de datos operativas en cuestión de segundos ⏱️.</p><p>Este nuevo recurso, se centra en tres pilares fundamentales:</p><figure><img alt="Pilares de bases de datos SQL en Fabric — Imagen generada por IA" src="https://cdn-images-1.medium.com/max/1024/1*ZjVXTX1mfsmwBJPbeuHbmQ.png" /><figcaption>Pilares de bases de datos SQL en Fabric — Imagen generada por IA</figcaption></figure><p>Es por ello que, gracias tanto a la unificación e integración propias de Fabric como al soporte de algunas funcionalidades concretas (<a href="https://devblogs.microsoft.com/azure-sql/langchain-with-sqlvectorstore-example/"><em>capacidad nativa para búsqueda vectorial</em></a>), es posible crear aplicaciones de inteligencia artificial más rápido y con menos impedimentos, reduciendo los tiempos de implementación y desarrollo necesarios para empezar a sacar el máximo partido a nuestras soluciones cuanto antes.</p><p>Si algo está claro es que la IA ha llegado para quedarse, pero ¿significa esto que sólo podemos aprovechar las bases de datos SQL para esta opción? No tiene por qué, ¡quizás hay algo más allá de la alegr-IA! 👀</p><h3>1️⃣Por si no había suficientes para elegir</h3><figure><img alt="Tomando una decisión — Imagen generada por IA" src="https://cdn-images-1.medium.com/max/1024/1*akKMaB0EbKWgADDwzy9jbA.png" /><figcaption>Tomando una decisión — Imagen generada por IA</figcaption></figure><p>Dentro de Microsoft Fabric, contamos con diferentes opciones para poder almacenar datos en nuestros procesos y soluciones.</p><p>Antes de hablar de posibles casos de uso y aplicaciones, es importante tener claras las características de cada uno de los artefactos disponibles y su mejor ámbito de aplicación. De este modo, podremos decidir mejor cuáles (que no tienen por qué ser excluyentes) utilizar en función de la naturaleza de nuestra solución. Afortunadamente, disponemos de diferentes recursos para ayudarnos en esta tarea (además de que <a href="https://powerbi.microsoft.com/es-es/blog/unify-datamart-with-fabric-data-warehouse/"><em>alguno va a ser jubilado en breves</em></a>).</p><p>En concreto, Microsoft dispone de diferentes guías que podemos utilizar para facilitar la decisión:</p><ul><li><a href="https://learn.microsoft.com/es-es/fabric/fundamentals/decision-guide-data-store">Guía de decisiones de Fabric: selección de un almacén de datos — Microsoft Fabric | Microsoft Learn</a></li><li><a href="https://techcommunity.microsoft.com/blog/analyticsonazure/decision-guide-for-selecting-an-analytical-data-store-in-microsoft-fabric/4362079">Decision Guide for Selecting an Analytical Data Store in Microsoft Fabric | Microsoft Community Hub</a></li></ul><p>Si les echamos un vistazo, encontraremos algunas características que pueden ser útiles para nuestras soluciones, especialmente si tenemos o queremos implementar un sistema gobernado a través de metadatos, es decir, contar con uno o varios artefactos donde residirá la información que podemos utilizar para configurar, dinamizar y controlar la ejecución de nuestros procesos, facilitando así diferentes aspectos como la reusabilidad, operativa, automatización y/o auditoría de las operaciones.</p><p>Más concretamente, la particularidad que podemos aprovechar de las bases de datos SQL es su rapidez en el acceso y escritura para operaciones con bajo volumen de datos, realizadas de forma concurrente y que además pueden beneficiarse de funcionalidades avanzadas como el uso de índices y/o <a href="https://learn.microsoft.com/es-es/sql/t-sql/statements/create-table-transact-sql-identity-property?view=sql-server-ver17"><em>campos con la propiedad de IDENTITY</em></a>.</p><p>Aunque anteriormente podíamos compensar la carencia de este artefacto utilizando en su lugar, por ejemplo, un almacén, un lakehouse o incluso ficheros de configuración, ninguna de estas soluciones se adapta quizá tan bien como puede hacerlo la base de datos SQL (¡aunque cada escenario es un mundo!), bien porque no fueron diseñadas para este fin sino para operar con grandes volúmenes en el caso de las primeras o por cuestiones operativas y de facilidad para la edición en el caso de las segundas.</p><h3>2️⃣Hora de pasar a la acción</h3><p>Veamos en qué escenarios puede ser especialmente útil la adición de una base de datos SQL dentro de nuestra solución.</p><p>Para ello, imaginemos un proceso ETL desarrollado bajo Microsoft Fabric tal como el siguiente:</p><figure><img alt="Ejemplo de canalización de Fabric Data Factory para procesamiento de datos y ejecución ordenada de operaciones" src="https://cdn-images-1.medium.com/max/1024/1*Q7dPqkUW_zLTjBaWHwjS6Q.png" /><figcaption>Ejemplo de canalización de Fabric Data Factory para procesamiento de datos y ejecución ordenada de operaciones</figcaption></figure><p>En este caso, gracias a las bondades de las bases de datos SQL de Fabric, podemos implementar un proceso donde aplicar diferentes casos de uso gracias a la integración entre los diferentes elementos y experiencias disponibles, de forma que logremos soluciones dinámicas, estandarizadas y especialmente confiables.</p><p>Veamos algunos de ellos.</p><h4>♻️Procesos dirigidos por metadatos</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EYjL-XevNNhHOzcoexAvhQ.png" /><figcaption>Sistema de metadatos — Imagen generada por IA</figcaption></figure><p>Aunque existen diferentes métodos para su implementación y cada escenario será distinto, con las bases de datos SQL de Fabric disponemos de un potente artefacto que puede actuar como corazón de nuestra solución.</p><p>A través de ellas, podemos incorporar un sistema de metadatos donde podemos centralizar, entre otras cosas, aspectos tales como la configuración particular de cada entidad que debamos procesar (patrón de carga asociado, orden de precedencia, dependencias, etc.) o valores específicos a tener en cuenta para la capa que vamos a ejecutar (si contamos por ejemplo con una arquitectura medallón 🥉🥈🥇), consiguiendo así un mayor grado de dinamismo y automatización dentro de nuestros procesos, de forma que se facilita su orquestación, reutilización, mantenimiento y evolución.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*Ff_EIUcpYmlifSQ9eXYgKg.png" /><figcaption>Recuperación de configuraciones y valores de ejecución a través de sistema de metadatos</figcaption></figure><p>Si volvemos al ejemplo anterior, la canalización consulta la información necesaria de nuestra base de datos de metadatos para llevar a cabo la extracción y procesamiento de diferentes entidades dentro de una determinada capa, donde utilizaremos para cada una de ellas tanto los valores de configuración recuperados como los resultados de la ejecución previa. De esta forma, conseguimos dinamizar la ejecución del proceso de manera que podamos tanto reutilizar artefactos y reducir tiempos de implementación (¡una canalización para procesarlas a todas!💍) como incrementar su robustez y facilidad de reejecución tras posibles fallos previos, ajustando sus valores y permitiendo retomar la ejecución fallida donde se quedó.</p><p>Además, por ejemplo, podemos incluir especificaciones concretas de mapeo de campos para las que lo precisen, de forma que nos permitan controlar los esquemas de las entidades procesadas y lograr evitar posibles problemas por discrepancias, caracteres no soportados y/o evoluciones que puedan producirse en el día a día, garantizando así una mayor fiabilidad y control dentro de nuestros procesos, puesto que es importante controlar que datos volcamos en nuestro sistema desde el primer momento.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*nivLXk4dO8WoTKJ_3zHV3A.png" /><figcaption>Control de mapeo de campos y esquema utilizado dentro de la actividad de copia</figcaption></figure><h4>📝Auditoría y logado de operaciones</h4><p>Gracias a la posibilidad de encapsular la lógica empleada dentro de procedimientos almacenados de la base de datos SQL, podemos implementar diferentes elementos que, en función de los parámetros recibidos, pueden actuar de una forma u otra y/o ser utilizados por parte de diferentes procesos, estandarizando así las acciones realizadas y centralizando su lógica.</p><p>Un aspecto crucial dentro de nuestras operaciones es la auditoría y registro de las operaciones, llevar un control de lo que se ha ejecutado, cuánto tiempo ha tardado, en qué estado ha quedado, cuántos registros se han procesado, etc. Son aspectos muy relevantes que ayudan a mantener supervisado nuestro sistema y facilitan la depuración y control de incidencias cuando estas ocurran (que lo harán 😁).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j7ELv1YrbE7vM4ojx0GNYw.png" /><figcaption>Ejemplo de tabla de auditoría dentro de nuestro sistema</figcaption></figure><p>Aunque ya disponemos de mecanismos nativos dentro de Fabric, como la sección de <strong><em>Supervisión</em></strong>, gracias a las bases de datos SQL, podemos personalizar los logs y trazas de nuestras soluciones, abriendo la puerta a escenarios más elaborados donde múltiples escrituras concurrentes y/o accesos recurrentes para recuperar valores específicos simultáneamente no es un problema, sino todo lo contrario.</p><p>Por si fuera poco, todo esto se replica a través del SQL Endpoint vinculado al artefacto, lo que hace que la información esté disponible para otros recursos de Fabric como cuadernos de Spark y/o lakehouse.</p><h4>🚦Control de ejecución y recuperación frente a desastres</h4><p>Ampliando aún más los casos de uso anteriormente expuestos, aunque con Fabric ya no es necesario preocuparnos (a priori 😜) de a qué hora programar los procesos como ocurría antes gracias a características propias de Fabric como el <a href="https://learn.microsoft.com/es-es/fabric/enterprise/throttling#bursting"><em>bursting</em></a> y el <a href="https://learn.microsoft.com/es-es/fabric/enterprise/throttling#smoothing"><em>smoothing</em></a>, es posible que en ocasiones tengamos algunos procesos donde necesitemos controlar que no se ejecuten hasta que algún otro proceso termine y/o si algún otro se encuentra en ejecución. Incluso si queremos lograr soluciones idempotentes, podamos comprobar la información registrada por la ejecución previa para poder retomar, por ejemplo, una ejecución fallida desde el punto que se quedó.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pLzylcXzU5FL41z5lUs_uQ.png" /><figcaption>Comprobación de procesos en ejecución y detalles de ejecuciones previas registradas en el sistema de metadatos</figcaption></figure><p>Al registrar todas las ejecuciones en una tabla de nuestra base de datos, podemos comprobar qué se está ejecutando antes de lanzar cada proceso y establecer bien una espera previa o no ejecutarlo directamente.</p><p>Al mismo tiempo, si disponemos de una tabla donde registremos las trazas de cada ejecución, podríamos, por ejemplo, implementar un proceso que pueda relanzar automáticamente aquellas cargas que se hayan retrasado y/o las que presenten errores, evitando posibles preocupaciones y que la frescura de datos dentro del sistema se vea perjudicada.</p><h3>3️⃣Conclusiones</h3><p>Así pues, hemos visto cómo las propiedades y características inherentes de las bases de datos SQL de Fabric pueden ampliar las capacidades de nuestros procesos y soluciones de formas que antes no eran posibles o resultaban menos sencillas de implementar.</p><p>Además de todas sus bondades para procesos de inteligencia artificial, son un digno compañero a considerar en nuestro viaje por cualquiera de las experiencias dentro del ecosistema de Fabric.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca6c9acb05ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cada cosa a su tiempo: sincronización y refresco de modelos semánticos con Microsoft Fabric]]></title>
            <link>https://medium.com/@baggirraf/cada-cosa-a-su-tiempo-sincronizaci%C3%B3n-y-refresco-de-modelos-sem%C3%A1nticos-con-microsoft-fabric-b6efec06185e?source=rss-f294e26941dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6efec06185e</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[fabric]]></category>
            <dc:creator><![CDATA[Rafael Baguena Girbes]]></dc:creator>
            <pubDate>Wed, 19 Feb 2025 19:19:20 GMT</pubDate>
            <atom:updated>2025-02-19T19:21:08.149Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yhlJvUU-e4f3QgzWiC5D1Q.jpeg" /><figcaption>Imagen generada por IA</figcaption></figure><p>Hace unos días y tras estar experimentando un tiempo con Fabric, se me planteaba un escenario complejo dentro del desarrollo de una solución: ¿cómo asegurar que nuestros datos estaban actualizados previamente a refrescar el modelo semántico que se nutre de ellos?</p><p>Si bien es cierto que se han publicado mejoras al respecto de las cuestiones que veníamos experimentado en el uso del SQL Endpoint de Fabric en la pasada <a href="https://blog.fabric.microsoft.com/es/blog/microsoft-fabric-january-2025-update?ft=All#post-18117-_Toc188889251"><strong><em>actualización de enero</em></strong></a>, resulta más efectivo poder controlar este aspecto y no dejarlo en manos del azar, ya que Murphy siempre hace de las suyas.</p><p>Para poder explicarlo mejor, vamos a dar un poco de contexto al escenario de forma que ayude a entender tanto el caso de uso como su resolución. Imaginemos que tenemos una solución en Fabric implementada siguiendo este esquema basado en la arquitectura medallón:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dqCjhMmk1AQo4WmRtYctLQ.png" /><figcaption>Ejemplo sencillo de arquitectura medallón en Fabric</figcaption></figure><p>Tal como puede apreciarse en la imagen, para nuestro caso de uso (y de forma simplificada), el proceso de ingesta recopila datos de diversas fuentes que pasan a historificarse dentro del área de trabajo correspondiente a la capa <em>bronze </em>en formato Parquet. A partir de ahí, tras varios procesos de filtrado, deduplicación y limpieza con los que confeccionamos nuestras tablas delta en el área de <em>silver</em>, aplicaremos diversas transformaciones sobre estas con el objetivo de materializar nuestras entidades dimensionales en la capa final, <em>gold</em>.</p><p>Ahora que ya tenemos las piezas sobre la mesa, nos falta el paso final, refrescar los datos de nuestro modelo semántico. Para ello, utilizaremos el <a href="https://learn.microsoft.com/es-es/fabric/data-engineering/lakehouse-sql-analytics-endpoint"><strong><em>endpoint SQL</em></strong></a> asociado a nuestro <em>lakehouse </em>de la capa <em>gold</em>, el cual contendrá una réplica de solo lectura de nuestras tablas delta, y he aquí la cuestión, ¿por qué usar el <em>endpoint </em>y no procesar directamente desde el <em>lakehouse</em>?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yb1IGnhOHG51EqSpjcKx-w.jpeg" /><figcaption>Imagen generada por IA</figcaption></figure><p>Como buena práctica desde los tiempos de SQL Server Analysis Services, es más que recomendable establecer una capa de abstracción (siempre que sea posible) entre nuestros orígenes de datos y el modelo semántico. Esto es algo que no podemos hacer en todos los escenarios, pero sí algo que deberíamos poner en práctica cuando contemos con un <em>data warehouse</em> o un data <em>lakehouse </em>dentro de nuestro ecosistema. El motivo es simple, dentro de ellos, podemos definir vistas sobre las tablas que contengan nuestros datos y gracias a ellas podemos llevar a cabo acciones tales como seleccionar qué columnas necesitamos, darles un alias concreto, implementar lógicas sobre determinados campos y/o incluso establecer filtros en la información que se consulta.</p><p>De esta forma, obtenemos varias ventajas:</p><ul><li>Podemos tener diferentes disposiciones para la misma tabla, lo que resulta especialmente útil cuando una tabla está presente en varios modelos pero con diferente esquema y/o si contamos con <em>roleplaying dimensions </em>en nuestro modelo</li><li>Aislamos lógicas y transformaciones a nivel de vista, evitando así que estén definidas en Power BI y si estas sufren modificaciones, no necesitamos alterar nuestro modelo, bastará con cambiar el código de la vista y refrescar</li><li>Estandarizamos y centralizamos la lógica de nuestras entidades, facilitando su reusabilidad y haciendo más sencillas las actualizaciones</li><li>Simplificamos las labores de Power Query durante la importación del dato, dado que solo tendrá que leer sin riesgo a desactivar el plegado de consultas, que tan importante resulta</li></ul><p>Así pues, si tan maravillosas son las vistas, ¿dónde está el problema en este escenario? La respuesta en la actualización de los datos replicados dentro del <em>endpoint</em>, el cual si no tiene actividad procede a entrar en una especie de letargo que le hace apagarse y no responder hasta que es consultado, lo que puede provocar que el modelo se refresque con información desactualizada y que el <em>endpoint </em>no muestre los últimos datos volcados por el proceso, incluso que lo pillemos “durmiendo” y que el refresco falle.</p><p>Aunque podemos paliar el fallo de pillarlo “calentando” mediante opciones como la configuración de reintentos de conexión, esto no nos asegura que la sincronización de datos se haya completado. Si bien se me ocurría alguna idea sencilla con la que poder intentar solventarlo, no fue hasta que vi por casualidad un artículo de <a href="https://www.linkedin.com/in/dennestorres/">Dennes Torres</a> que se me iluminó del todo la bombilla.</p><p><a href="https://www.red-gate.com/simple-talk/blogs/sql-endpoint-secrets-you-need-to-know/?utm_source=sqlservercentral&amp;utm_medium=email&amp;utm_campaign=newsletter-1820&amp;utm_term=advocates&amp;utm_content=advocates">SQL Endpoint Secrets you need to know — Simple Talk</a></p><p>En él, Dennes detalla aspectos como la frecuencia de refresco de la caché del <em>endpoint </em>y especialmente la posibilidad de invocarlo a través de una API (no documentada eso sí), he aquí la solución 😁</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lR0bA3xmTY200AlZ4BVSFQ.jpeg" /><figcaption>“Let there be light” — Imagen generada por IA</figcaption></figure><p>Si disponemos de una API, podemos llamarla y pese a que sea asíncrona, también contamos con un método para poder consultar el estado de nuestra petición (¡gracias de nuevo Dennes!). Con esto y gracias a la fantástica librería de <a href="https://github.com/m-kovalsky/Fabric?tab=readme-ov-file"><strong><em>sempy en Fabric</em></strong></a><strong><em> </em></strong>(bendito sea Michael Kovalsky), ya tenemos suficiente para poder resolver el problema.</p><p>Gracias a que <em>sempy </em>cuenta con diferentes métodos para el uso de APIs (facilitando la autenticación) y procesamiento de modelos, podemos establecer un flujo sencillo que:</p><ul><li>En primer lugar, lance la petición de refresco del <em>endpoint SQL</em> y compruebe periódicamente su estado (recordemos que es asíncrono) para controlar su correcta ejecución y disponibilidad</li><li>Posteriormente, lanzar la petición de refresco del modelo y de la misma forma, compruebe su estado para tener presente cuando finaliza (dado que también es una llamada asíncrona)</li><li>Para los chequeos, dejamos una ventana de 30 segundos entre cada llamada para evitar saturar a la API</li></ul><p>Para ello, haremos uso de tres funciones distintas. En primer lugar, por simplificar las llamadas a través del cliente REST de <em>sempy</em>, una función que nos sirva de <em>wrapper </em>para llevarlas a cabo:</p><pre>import sempy.fabric as fabric<br>import time, json<br><br>def fabric_rest_api_caller(<br>    source_uri: str, method: str, source_payload: str = None<br>) -&gt; dict:<br>    try:<br>        fabric_client = fabric.FabricRestClient()<br>        match (method):<br>            case &quot;post&quot;:<br>                if source_payload:<br>                    response = fabric_client.post(source_uri, json=source_payload)<br>                else:<br>                    response = fabric_client.post(source_uri)<br>            case &quot;get&quot;:<br>                response = fabric_client.get(source_uri)<br>            case _:<br>                raise NotImplementedError<br>        return response<br>    except NotImplementedError:<br>        print(&quot;*ERROR*: ❌ Specified method is not implemented.&quot;)<br>    except Exception as err:<br>        print(f&quot;*ERROR*: ❌ Something went wrong, the error ocurred is: {err=}&quot;)</pre><p>En segundo lugar, una función para refrescar el <em>endpoint SQL </em>a través de una llamada a la anterior, para posteriormente<em> </em>comprobar el estado de nuestra petición cada 30 segundos y así asegurar que se completa correctamente.</p><pre>def sql_endpoint_refresh(sql_endpoint_id: str) -&gt; None:<br>    call_uri: str = f&quot;/v1.0/myorg/lhdatamarts/{sql_endpoint_id}&quot;<br>    payload: dict = {&quot;commands&quot;: [{&quot;$type&quot;: &quot;MetadataRefreshCommand&quot;}]}<br><br>    try:<br>        print(f&quot;*INFO*: ▶️ Starting refresh for &#39;{sql_endpoint_id}&#39; SQL Endpoint.&quot;)<br>        refresh_response = fabric_rest_api_caller(call_uri, &quot;post&quot;, payload)<br>        batch_id_value: str = refresh_response.json()[&quot;batchId&quot;]<br>        progress_status: str = refresh_response.json()[&quot;progressState&quot;]<br><br>        status_uri: str = (<br>            f&quot;/v1.0/myorg/lhdatamarts/{sql_endpoint_id}/batches/{batch_id_value}&quot;<br>        )<br>        while progress_status == &quot;inProgress&quot;:<br>            print(f&quot;*INFO*: 🔎 Checking status for &#39;{batch_id_value}&#39; batch.&quot;)<br>            status_response = fabric_rest_api_caller(status_uri, &quot;get&quot;)<br>            progress_status: str = status_response.json()[&quot;progressState&quot;]<br>            print(f&quot;*INFO*: ⚠️ Current status is &#39;{progress_status}&#39;.&quot;)<br>            match(progress_status):<br>                case &quot;success&quot;:<br>                    break<br>                case &quot;failed&quot;:<br>                    raise Exception(&quot;The refresh has failed.&quot;)<br>                case _:<br>                    print(&quot;*INFO*: ⌛ Checking again in 30 seconds.&quot;)<br>                    time.sleep(30)<br><br>        print(f&quot;*INFO*: ✅ SQL Endpoint &#39;{sql_endpoint_id}&#39; successfully refreshed.&quot;)<br>    except Exception as err:<br>        print(f&quot;*ERROR*: ❌ Something went wrong, the error ocurred is: {err=}&quot;)</pre><p>Finalmente, una función parecida a la anterior, donde gracias a los métodos existentes en <em>sempy</em>, realizaremos una petición de refresco sobre un modelo semántico y comprobaremos su estado cada 30 segundos para asegurar que finaliza.</p><pre>def semantic_model_refresh(workspace_id: str, dataset_id: str) -&gt; None:<br>    try:<br>        print(f&quot;*INFO*: ▶️ Starting refresh for &#39;{dataset_id}&#39; semantic model.&quot;)<br><br>        refresh_request_id = fabric.refresh_dataset(<br>            dataset=dataset_id, workspace=workspace_id<br>        )<br><br>        refresh_status: str = &quot;Not started&quot;<br>        while refresh_status not in {&quot;Completed&quot;, &quot;Failed&quot;}:<br>            refresh_details = fabric.get_refresh_execution_details(<br>                dataset=dataset_id,<br>                refresh_request_id=refresh_request_id,<br>                workspace=workspace_id,<br>            )<br>            refresh_status = refresh_details.status<br>            print(f&quot;*INFO*: ⚠️ Current status is &#39;{refresh_status}&#39;.&quot;)<br><br>            match (refresh_status):<br>                case &quot;Completed&quot;:<br>                    break<br>                case &quot;Failed&quot;:<br>                    raise Exception(&quot;The refresh has failed.&quot;)<br>                case _:<br>                    print(&quot;*INFO*: ⌛ Checking again in 30 seconds.&quot;)<br>                    time.sleep(30)<br><br>        print(f&quot;*INFO*: ✅ Semantic model &#39;{dataset_id}&#39; successfully refreshed.&quot;)<br>    except Exception as err:<br>        print(f&quot;*ERROR*: ❌ Something went wrong, the error ocurred is: {err=}&quot;)</pre><p>De este modo, una vez actualizada nuestra capa <em>gold</em>, podemos montar una secuencia de operaciones que refresque el <em>endpoint SQL</em> y espere hasta que esté listo para procesar nuestro modelo semántico de forma síncrona. Algo tal que así:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*59WcaY5GTBy-i88Zk7fxMA.png" /><figcaption>Ejemplo de ejecución de las funciones</figcaption></figure><p>Esto es solo un comienzo, puesto que si lo combinamos con un sistema de metadatos podemos crear un flujo que procese varios modelos y se preocupe de refrescar cada endpoint que los alimente de forma paralela, pero eso ya mejor otro día :)</p><p>Si te ha gustado el artículo, puedes encontrar el código junto a más funciones y ejemplos dentro de mi repositorio de GitHub</p><p><a href="https://github.com/l2aFa">l2aFa (Rafael Báguena Girbés) · GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6efec06185e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>