CAS

SAS Viya: How to Properly Manage the Creation and Deletion of CASLIBs

Simon 26/03/2024 10 vistas

When automating tasks in SAS© Viya, it's common to use macros to configure data sources. A classic case is looping through a list of authentication domains (for example, for Oracle) to dynamically create CASLIBs.

However, a difficulty often arises when this code needs to be executed multiple times: managing duplicates.

Illustration

The Problem: The Chicken and Egg Dilemma

Imagine a scenario where your macro loops through a list to create connections.

  1. First execution: Everything works perfectly. The CASLIBs are created.

  2. Second execution: The system returns a fatal error because the CASLIBs already exist (ERROR: Duplicate Caslib).

The natural reaction is to add an instruction to DROP the library before recreating it. But this creates a new problem: on the very first execution, or if the session is new, the library does not yet exist. The result? An error in the log (ERROR: The caslib ... does not exist).

Although this error can be ignored, it pollutes the log and can hide real problems. The goal is to have "clean" code that runs without errors, regardless of the initial state.

The Solution: Check Before Acting

The most robust method to bypass this problem is to use the CLIBEXIST function.

This function allows you to check for the existence of a CASLIB in the current session before attempting an action. If the library exists, it is deleted to be recreated cleanly. If it does not exist, we proceed directly to creation.

Code Implementation

Here's how to integrate this logic into your macro loop. The trick is to wrap the DROP statement in an %IF condition that calls CLIBEXIST.

1/* Exemple de macro boucle pour gérer les connexions Oracle */
2%macro ora_libs;
3 %local i authdomain schema;
4
5 /* Boucle sur la liste des domaines d'authentification */
6 %DO i=1 %to %sysfunc(countw(&auth_list));
7 %let authdomain = %scan(&auth_list, &i);
8 %let schema = &authdomain.;
9 
10 /* C'est ici que la magie opère : */
11 /* On vérifie si la CASLIB existe déjà dans la session active (ici 'mysession') */
12
13 %IF %sysfunc(clibexist(mysession, &schema)) %THEN %DO;
14 caslib &schema. drop;
15 %END;
16 
17 /* Création de la CASLIB propre et sans erreur */
18 caslib &schema. datasource=(
19 srctype="oracle",
20 authdomain=&authdomain.
21 path=&path.
22 schema=&schema.
23 );
24 %END;
25%mend;

Why is this important?

Using CLIBEXIST makes your code idempotent. This means you can run it once or a hundred times, the final result will be the same (the libraries are configured) and, most importantly, your execution log will remain green, without any worrying red error messages.

This is a small change that greatly improves the quality and maintainability of your SAS© Viya programs.