Skip to main content
Sisense Community logo
  • Community Feedback
  • Chapters
  • Events
  • Forums
    • Help and How To
    • Product Feedback Forum
    • Strategy & Use Cases
  • Blogs
  • KB Docs
    • KB Docs
    • Add-Ons & Plug-Ins
    • APIs
    • Best Practices
    • Blox
    • CDT
    • Cloud Managed Service
    • Data Models
    • Data Sources
    • Embedding Analytics
    • How-Tos & FAQs
    • Onboarding
    • PySisense
    • Security
    • Sisense Administration
    • Sisense Intelligence & AI
    • Troubleshooting
    • Widget & Dashboard Scripts
  • Support
  • Learning
    • Sisense Academy: Free Courses and Certifications
    • Official Developer Documentation
    • Official Product Documentation
    • Official Sisense Youtube Channel
    • Sisense Compose SDK Playground
  • Use Case Gallery
All PostsDiscussionsBlogsIdeasQuestions
Leaderboards
  •                    
  •                    
  •                    
  •                    
  •                    
  •                    
  •                    
  •                    
  •                    
  •                    
  •                    
  •                    
  •                    
  •                    
  •                    
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
Discussions
  • TagsChevronRightIcon
data models
  • Idea
    • Product Feedback ForumChevronRightIcon
    Ability to rename a data model/elasticube after creation
                     
    dougnewton
    dougnewtonPosted 3 years ago • Last reply 5 days ago
             
    6
             
  • Blog banner
    • APIsChevronRightIcon

    UserReplaceTool - Automating Dashboard Ownership Transfers - Useful for Deleting User Accounts

                                                                                                     

    Automating Dashboard Ownership Transfer in Sisense with UserReplaceTool Managing and deleting user accounts in Sisense can create manual processes when users leave an organization or change roles. A frequent issue is the reassignment of dashboard ownership to prevent losing Sisense dashboards when a given user account is deleted, as deleting a Sisense user will delete all dashboards owned by that user. The UserReplaceTool addresses this task by automating the transfer of dashboard ownership of all dashboards owned by a given user, ensuring continuity and data integrity. Overview UserReplaceTool is a Python-based, API-based Tool solution designed to seamlessly transfer the ownership of dashboards and data models from one user to another in Sisense. This tool simplifies and automates this process, allowing organizations to reassign dashboard ownership without manual processes or the risk of losing dashboards and widgets. All components are accomplished by using Sisense API endpoint requests. Key Features Automated Dashboard Transfer : Reassigns ownership of all dashboards from the current user to a designated replacement user. Data Model Sharing : Ensures that all data models accessible and editable by the previous user are shared with the replacement user. Batch User Processing : Capable of handling multiple user transfers to a replacement user in a single operation, enhancing efficiency. Complete Logging:  All dashboards and datasource transferred are logged both in the console and in a separate log file. Setup Instructions 1. Setting Up the Environment To run the tool within a Python virtual environment , follow these steps: Activate the Python Virtual Environment : source /venv/bin/activate Create a Virtual Environment (if not already present): python3 -m venv .venv Install Dependencies : pip3 install -r requirements.txt For manual installation, including without using a Python virtual environment: pip3 install urllib3 jsonpath_ng pyyaml requests colorama 2. Configuration Edit the settings.yaml file to configure the tool. Key parameters include: Sisense Domain and Port : Specify the URL and port of your Sisense server, which is used for making API requests. API Bearer Token : Provide an admin-level bearer token for API authentication. See the  Sisense API Bearer Token Documentation for instructions on generating and using Bearer Tokens. Users to Replace : List the user IDs to be replaced. User IDs can be retrieved via the Users API or using the console command prism .user._id. Replacement User : Specify the user ID of the new replacement owner of all dashboards. This should typically be an admin level user. Data Model Sharing : Enable or disable the sharing of data models with the Replacement user (True or False), usually True. Dashboard Ownership Transfer : Enable or disable the transfer of dashboard ownership (True or False), usually True. Unlike Dashboards, if a user is deleted, the datasources themselves are not deleted from the server, ownership is automatically transferred to the main System Admin of the Sisense server.  3. Running the Tool Run the tool with the following command:   python3 replaceUser.py Practical Considerations Admin and Network Access : Ensure you have admin-level API access to the Sisense instance. Python Environment : Python3 and pip should be installed on the machine running the tool. All dependencies can be installed using Pip, and a Python virtual environment can be used. Once a Python Virtual Environment folder is set up it can be shared with the Tool and run directly on all systems using the same OS, but it is not cross OS compatible. By automating the transfer of dashboard ownership, UserReplaceTool provides a reliable and efficient solution for managing user transitions in Sisense. This ensures that datasources and dashboards remain accessible and under the control of the appropriate users, maintaining the continuity of Sisense resources. For further customization and configuration details, refer to the attached full Python Tool, which includes a README file and modify the "settings.yaml" file as necessary.    

    Jeremy Friedel
    Jeremy FriedelPosted 2 years ago • Last reply 1 month ago
    4
             
  • Blog banner
    • Data SourcesChevronRightIcon

    Connect Google Analytics to Sisense Using the CData JDBC Driver

                             

    Overview This article explains how to connect Google Analytics to Sisense using the CData JDBC Driver for Google Analytics. You can authenticate in one of two ways: CData embedded OAuth application — simpler setup and recommended when you do not require your own Google OAuth application. Custom Google OAuth application — requires additional configuration but gives you control over the OAuth client credentials. Both methods use the same general workflow: configure and authenticate the CData driver on a machine with browser access, then deploy the driver and OAuth settings to the Sisense server. What you'll learn By the end of this article, you will know how to: Download and install the CData JDBC Driver for Google Analytics. Configure Google Analytics authentication. Generate and persist OAuth credentials. Deploy the CData driver to a Sisense server. Create a Google Analytics connection in Sisense. Prerequisites Before you begin, you should have: Basic familiarity with the Sisense UI. Basic knowledge of Sisense data connectors. Access to the Sisense server or its file-management interface. Basic familiarity with Windows or Linux file systems. A Google account with access to the required Google Analytics property. Authentication options Option 1: CData embedded OAuth application Use this option when you want the simplest setup. CData provides OAuth credentials with the driver, so you do not need to create your own OAuth application in Google. Option 2: Custom Google OAuth application Use this option when you need your own Google OAuth client credentials. This method requires: A Google OAuth application. An OAuth Client ID. An OAuth Client Secret. An authorized redirect URI. The remaining deployment process is largely the same for both methods. Step 1: Download and install the CData driver Download the CData JDBC Driver for Google Analytics and install it on a machine where you can authenticate through a web browser. After installation, locate the driver's lib directory. macOS /Applications/CData/CData JDBC Driver for Google Analytics <version>/lib Windows C:\Program Files\CData\CData JDBC Driver for Google Analytics <version>\lib Locate and open: cdata.jdbc.googleanalytics.jar This opens the CData Connection String Builder. Step 2: Configure authentication Option 1: Use CData embedded OAuth Configure the following properties: AuthScheme=OAuth InitiateOAuth=GETANDREFRESH The initial connection string should look similar to: jdbc:googleanalytics:AuthScheme=OAuth;InitiateOAuth=GETANDREFRESH; Proceed to Step 3: Authenticate with Google . Option 2: Use a custom Google OAuth application Configure: AuthScheme=OAuth InitiateOAuth=GETANDREFRESH OAuthClientId=<client-id> OAuthClientSecret=<client-secret> The connection string should look similar to: jdbc:googleanalytics:AuthScheme=OAuth;InitiateOAuth=GETANDREFRESH;OAuthClientId=<client-id>;OAuthClientSecret=<client-secret>; Configure the redirect URI NOTE: If you don't know how to create custom Google OAuth application - check Creating a Google Application section in this article . In your Google OAuth application, add the following Authorized Redirect URI: http://localhost:33333 Note: If you are migrating from an older Sisense native Google Analytics connector, verify whether its existing OAuth credentials can still be reused before copying values from the old connector configuration. Step 3: Authenticate with Google In the CData Connection String Builder: Select Test Connection . Your default browser opens the Google authentication page. Sign in with the Google account that has access to the required Google Analytics property. Grant the requested permissions. Return to the CData Connection String Builder. After successful authentication, CData updates the connection information with the OAuth credentials. Select Copy to Clipboard to save the resulting connection string. Important: Treat the resulting connection string and OAuth settings as credentials. Do not publish real access tokens, refresh tokens, client secrets, or OAuth settings in screenshots or documentation. Step 4: Locate the OAuth settings file CData persists the OAuth authentication information in OAuthSettings.txt . Typical locations include: Windows %APPDATA%\CData\GoogleAnalytics Data Provider\OAuthSettings.txt macOS ~/Library/Application Support/ If you cannot locate the file, explicitly configure OAuthSettingsLocation in the CData Connection String Builder and repeat the authentication process. Step 5: Copy the OAuth settings to the Sisense server Copy OAuthSettings.txt to a persistent location accessible by Sisense. For example: Windows C:\OAuthSettings.txt Linux /opt/sisense/storage/data/OAuthSettings.txt Make sure the Sisense service can read and write the file. CData must be able to update the OAuth settings when refreshing authentication tokens. Step 6: Deploy the CData JDBC driver to Sisense Copy: cdata.jdbc.googleanalytics.jar to the appropriate JDBC driver directory on the Sisense server. The exact path depends on your Sisense deployment and version. Important: Verify the current Sisense documentation for the supported JDBC driver location before deploying the JAR. Deployment paths have changed between Sisense versions. Step 7: Create the connection in Sisense In Sisense, create a new Generic JDBC connection. Configure the following fields. Connection string Use the connection string generated by CData and specify the location of the OAuth settings file on the Sisense server. For example: jdbc:googleanalytics:AuthScheme=OAuth;InitiateOAuth=GETANDREFRESH;OAuthSettingsLocation="/opt/sisense/storage/data/OAuthSettings.txt"; When using your own Google OAuth application, the connection also includes: OAuthClientId=<client-id>; OAuthClientSecret=<client-secret>; JDBC JARs folder Specify the directory containing: cdata.jdbc.googleanalytics.jar Driver class Use: cdata.jdbc.googleanalytics.GoogleAnalyticsDriver Test the connection and continue to table selection once the test succeeds. Google Analytics 4 If you are connecting to Google Analytics 4, verify the current CData connection properties for GA4. Depending on the CData driver version, you may need properties such as: Schema=GoogleAnalytics4 PropertyId=<property-id> Use the current CData documentation as the source of truth for the properties supported by your installed driver version. Data model considerations The CData Google Analytics schema is not identical to the schema exposed by the former Sisense native Google Analytics connector. Tables, columns, and relationships may therefore differ. If you are migrating an existing Sisense data model, review: Table names. Column names and data types. Existing joins. Custom SQL. Calculated fields. Dashboard dependencies. You may need to modify the data model before rebuilding existing dashboards against the CData source. Troubleshooting Authentication opens successfully but Sisense cannot refresh the token Verify that: OAuthSettingsLocation points to the correct file. The OAuth settings file exists on the Sisense server. Sisense has read and write access to the file. The OAuth credentials correspond to the same Google application used during authentication. The driver works locally but not on the Sisense server Verify that: The CData JAR was copied to the correct Sisense JDBC driver directory. The configured JDBC JAR folder matches that directory. The driver class is: cdata.jdbc.googleanalytics.GoogleAnalyticsDriver Expected Google Analytics fields are missing The CData schema differs from the former native Sisense connector. Review the CData Google Analytics schema documentation and adjust the data model accordingly. Conclusion The CData JDBC Driver provides a way to connect Google Analytics to Sisense through the Generic JDBC interface. For the simplest configuration, use CData's embedded OAuth application. Use a custom Google OAuth application when you need direct control over the OAuth client credentials. Before deploying the connector in production, verify the connection properties, GA4 configuration, and JDBC deployment paths against the documentation for your current CData and Sisense versions.

    Oleksandr Burkov
    Oleksandr BurkovPosted 1 month ago
    0
             
  • Idea
    • Product Feedback ForumChevronRightIcon
    Refresh schema for all tables
             
    Tim von Ahsen
    Tim von AhsenPosted 2 years ago • Last reply 4 months ago
             
    16
             
  • Discussion
    Ihor Yokhym
    • Knowledge Base Docs
             
    Ihor YokhymAdmin
    Connecting Sisense to Amazon DocumentDB via generic JDBC [Linux]
                                             

    Introduction: Learn how to successfully connect Sisense to Amazon DocumentDB using a generic JDBC connection. This guide applies to Sisense Linux editions (both Cloud and On-Premises deployment models) and resolves common TLS-related connection reset errors. Step-by-Step Guide:   Step 1: Whitelist the Sisense Instance Before modifying any configurations in Sisense, verify that your Sisense instance IP address or network range is properly whitelisted in your AWS DocumentDB cluster's security groups. The default connection port is 27017 . Step 2: Download the driver Get the JDBC Driver for Amazon DocumentDB from the Amazon website and Github: AWS DocumentDB: Documentation AWS DocumentDB: Driver Github Step 3: Register the connector in Sisense 2.1 Go to Admin > Server & Hardware > System Management > Configuration . 2.2 Scroll to the bottom and click Manage Connectors . 2.3 In the left pane, click +JDBC Connector and fill in: Connector ID: [YOUR_NAME] Display Name: [YOUR_NAME] Class Name: software.amazon .documentdb.jdbc.DocumentDbDriver Upload JAR File: upload jar file Click Create . Step 4: Use the Generic JDBC Connection String Because of architectural differences, connecting via the native Sisense MongoDB connector can result in errors. Instead, connect using the generic AWS DocumentDB JDBC driver syntax. JDBC Connection String Template jdbc:documentdb://<hostname>:<port>/<database-name>?<options> Step 5: Configure TLS Settings and Resolve Socket Exceptions According to official AWS DocumentDB JDBC Driver documentation, the driver’s default behavior is tls=true. If your DocumentDB configuration expects plain text, a protocol mismatch occurs: the JDBC driver attempts an encrypted SSL handshake with a database node expecting unencrypted packets. DocumentDB will abruptly drop the network socket, resulting in the following error: java.net.SocketException: Connection reset To fix this, modify your connection string based on your database environment: For Non-TLS Environments: Explicitly turn off TLS encryption by adding tls=false and completely removing the tlsAllowInvalidHostnames flag. For TLS Environments: Ensure both tls=true and tlsAllowInvalidHostnames=true are active. Code Type: JDBC Connection String Example (TLS Disabled) jdbc:documentdb://<a target="_blank" rel="noopener noreferrer nofollow" href="http://my-cluster.cluster-xyz.us-east-1.docdb.amazonaws.com:27017/my_database?tls=false"><u>my-cluster.cluster-xyz.us-east-1.docdb.amazonaws.com:27017/my_database?tls=false</u></a> [Screenshot: Generic JDBC connection setup window in the Sisense Data tab] Description: The image above illustrates where to input the customized DocumentDB JDBC connection string and credential details within the Sisense Data Connector UI. Conclusion:  Successfully connecting Sisense to Amazon DocumentDB requires leveraging the generic JDBC driver framework rather than the native MongoDB connector. The most common pitfall is a TLS mismatch; explicitly declaring tls=false in your connection parameters will bypass the java.net .SocketException when working with unencrypted database nodes. References/Related Content  Sisense Documentation: Deploy Custom JDBC connector AWS DocumentDB: Documentation AWS DocumentDB: Driver Github

    4 months ago
    0
             
  • Idea
    • Product Feedback ForumChevronRightIcon
    REST API error on /elasticubes/{server}/{title}/updateCube
                     
    Tim von Ahsen
    Tim von AhsenPosted 6 months ago • Last reply 6 months ago
             
    1
             
  • Idea
    • Product Feedback ForumChevronRightIcon
    Data Source Dependency Report
                     
    dougnewton
    dougnewtonPosted 3 years ago • Last reply 6 months ago
             
    5
             
  • Discussion
    Tim von Ahsen
    • Help and How-To
             
    Tim von Ahsen
    Schedule builds in bulk
                             

    I want to schedule all my cubes to build at 2am. Or provide a list of cube names and what time each should build. Currently, I do this manually through the UI. Is there a better way?

    7 months agolast reply 7 months ago
    2
             
  • Idea
    • Product Feedback ForumChevronRightIcon
    WE NEED THE ABILITY TO DO A LEFT JOIN WITHIN THE SISENSE DATA MODEL
             
    ehannscott
    ehannscottPosted 3 years ago • Last reply 7 months ago
             
    17
             
  • Blog banner
    • APIsChevronRightIcon

    Connection Tool - Programmatically Remove Unused Datasource Connections, and List All Connections

                                                                                                                                                                     

    Connection Tool - A Tool to Programmatically Remove Unused Datasource Connections, and List All Connections     Managing connections within your Sisense server can become complex over time, if there are a large number of connections, and connections are often added, and replace earlier datasource connections. In some scenarios unused connections can accumulate, potentially cluttering the Connection Manager UI with no longer relevant connections. Although unused connections typically represent minimal direct security risk, it's considered best practice to maintain a clean, organized list of connections, and in some scenarios it can be desired to remove all unused connections. Sisense prevents the deletion of connections actively used in datasources, safeguarding your dashboards and datasources from disruptions. However, inactive or "orphaned" connections remain after datasources are deleted or a connection is replaced, potentially contributing to unnecessary UI complexity in the connection manager UI. Connections can be of any type Sisense supports, common types include various SQL connections, Excel files, and CSV files, as well as many data providers, such as Big Panda. This tool can also be used to list all connections, with no automatic deletion of unused connections. Introducing the Sisense Connection Prune Tool The Sisense Connection Prune Tool is a Python-based Sisense API based tool designed to programmatically identify and delete unused connections. It generates a CSV report listing all connections and their associated datasources, streamlining your connection management process. If desired, it can automatically remove all unused connections automatically from a Sisense server.   Using the Tool, sourcing the Virtual Environment, generating the Connection CSV   CSV Output of Used Connections and Associated Datasources   CSV opened visually to view as Table, Excel and other programs and text editors can open CSV files   Sisense Connection Prune Tool README Here's the full README included with the tool: # Sisense Connection Prune Tool A command-line tool to list used data connections and prune unused Sisense connections via CSV. It allows you to generate a CSV file of all connections and their dependencies, then delete those connections if needed, after removing the connections to keep from the CSV. ## Features - **Dry Run Mode**: Simulate deletions without making any changes. - **CSV-Based Flow**: Easily inspect and list connections to remove before deletion. - **Logging**: Extensive logs if needed. - **Error Handling**: Clear and descriptive messages for issues encountered during execution. ## Usage 1. **Activate the Virtual Environment** After downloading this project folder, activate the Python virtual environment bundled with it that includes all Python dependencies. - **Windows**: `venv\Scripts\activate` - **macOS/Linux**: `source venv/bin/activate` 2. **Configure the Tool** Open the `config.yaml` file and set your Sisense server URL, bearer token, CSV file path, and log file path. For example: ```yaml server_url: "https://your.sisense.server" bearer_token: "your_bearer_token_here" dry_run: true csv_file_path: "connections.csv" log_file_path: "connection_tool.log" ``` - **server_url**: The URL of your Sisense instance. - **bearer_token**: Your Sisense API token for authentication. - **dry_run**: If set to `true`, deletions will be simulated (no real deletions). - **csv_file_path**: Where the CSV file should be created and read from. - **log_file_path**: Where log file will be stored. 3. **Run the Tool** ```bash python3 ConnectionPruneTool.py ``` You will be prompted to choose an option: 1. **Generate connection CSV** - Fetches all Sisense connections. - Immediately removes (or simulates removing, if `dry_run` is `true`) any connection with no dependencies. - Writes all remaining connections and their dependencies to the CSV file. - **Important**: Inspect the CSV file and remove lines for any connections you want to **keep**. 2. **Delete connections from CSV list** - Reads the CSV file. - Removes or simulates removing each connection still listed. - Provides a summary report of which connections were deleted or bypassed. 4. **Review the Logs** Check the file specified in `log_file_path` for a record of all actions taken or simulated if needed. This is helpful for understanding what happened during each run and diagnosing any issues. ## Example Workflow 1. **Generate CSV** ```bash python3 ConnectionPruneTool.py # Choose option 1 when prompted ``` After generation, open the CSV file and **delete rows** corresponding to any connections you want to **keep**. 2. **Delete Connections** ```bash python3 ConnectionPruneTool.py # Choose option 2 when prompted ``` The tool will read the CSV and delete the remaining listed connections (or simulate deletion, if `dry_run` is enabled). ## Notes - Unused connections are removed automatically in step 1, without a CSV step - To keep a connection, remove its line from the CSV before proceeding with deletion. - If `dry_run` is set to `true`, no actual deletions will occur, only simulated logs and printed messages. - The log file will be cleared at the start of each run, so be sure to review or archive logs (or change log file name in config), if needed. ​ This is a command-line tool to list used data connections and prune unused Sisense connections, in general and via a CSV list. It allows a user with a data admin or higher bearer token to generate a CSV file of all connections and their dependencies, then delete those connections if needed, from the remaining connections in the CSV. Example Output: Deleted unused connection: Old_DB_Connection (ID: 123abc) CSV file generated at connections.csv. It contains 25 row(s) of active connections. Please review and remove lines for connections you want to keep before running deletion step by running tool again. Remaining lines will be deleted in deletion mode. Summary Report: Total lines in CSV (active used connections): 25 Deleted Unused Connections: - Old_DB_Connection No connections were bypassed.   API Endpoints Used Retrieve connections: GET /api/v2/connections Retrieve dependencies: GET /api/v2/connections/{connection_id}/getAllDependencies Delete connection: DELETE /api/v2/connections/{connection_id} Full Code connections.py - Uses Sisense API endpoints to: Fetch all connections (GET /api/v2/connections). Retrieve datasource dependencies for a specific connection (GET /api/v2/connections/{connection_id}/getAllDependencies). Delete a specific connection (DELETE /api/v2/connections/{connection_id}).     from helperFunctions import load_config, api_get, api_delete config = load_config() headers = {"Authorization": f"Bearer {config['bearer_token']}"} base_url = config["server_url"] # Retrieve all connections from Sisense def get_all_connections(): endpoint = f"{base_url}/api/v2/connections" return api_get(endpoint, headers) # Retrieve dependencies of a specific connection def get_connection_dependencies(connection_id): endpoint = f"{base_url}/api/v2/connections/{connection_id}/getAllDependencies" return api_get(endpoint, headers) # Delete a specific connection def delete_connection(connection_id): endpoint = f"{base_url}/api/v2/connections/{connection_id}" return api_delete(endpoint, headers) helperFunctions.py - Uses the Requests library to handle API requests (GET/DELETE). Catches and logs API errors. Uses PyYAML to read the config.yaml file for configuration.     import yaml import requests import logging # Load configuration from YAML file def load_config(): with open("config.yaml", "r") as file: return yaml.safe_load(file) # Configure logging settings def setup_logging(log_file): logging.basicConfig( filename=log_file, level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s", ) # Perform a GET request with error handling def api_get(endpoint, headers): try: response = requests.get(endpoint, headers=headers, verify=False) response.raise_for_status() return response.json() except requests.RequestException as e: logging.error(f"GET request failed: {e}") print(f"Error during GET request: {e}") return None # Perform a DELETE request with error handling def api_delete(endpoint, headers): try: response = requests.delete(endpoint, headers=headers, verify=False) response.raise_for_status() return response except requests.RequestException as e: logging.error(f"DELETE request failed: {e}") print(f"Error during DELETE request: {e}") return None ConnectionPruneTool.py - Serves as the entry point for the entire tool. Implements a CLI for user interaction. Invokes connections.py and helperFunctions.py to retrieve, analyze, and optionally delete Sisense connections. Uses Pandas to build a DataFrame of connection details and writes the results to a CSV file. Reads back the CSV file to remove selected connections after manual edits. Manages logs and prints summary reports to the terminal. import pandas as pd import logging import os from connections import ( get_all_connections, get_connection_dependencies, delete_connection, ) from helperFunctions import load_config, setup_logging # Load config yaml config = load_config() setup_logging(config["log_file_path"]) # Clear log file at start open(config["log_file_path"], "w").close() dry_run = config["dry_run"] csv_path = config["csv_file_path"] def generate_connections_csv(): """ Retrieves all connections from Sisense, deletes any that have no dependencies (unless in dry_run mode), and writes the remaining used connections and their dependent data models to a CSV file. """ # Create or clear existing CSV open(csv_path, "w").close() connections = get_all_connections() if connections is None: logging.error("Failed to retrieve connections.") print("Failed to retrieve connections.") return data = [] deleted = [] bypassed = [] # Go through each connection returned from the API for conn in connections: dependencies = get_connection_dependencies(conn["oid"]) if dependencies is None: logging.warning( f"Failed to retrieve dependencies for: {conn['name']} ({conn['oid']})" ) print( f"Failed to retrieve dependencies for: {conn['name']} ({conn['oid']})" ) bypassed.append(conn["name"]) continue # If no dependencies, optionally delete the connection (not in dry-run) if not dependencies: action_msg = "[Dry Run] Would delete" if dry_run else "Deleted" log_str = ( f"{action_msg} unused connection: {conn['name']} (ID: {conn['oid']})" ) print(log_str) logging.info(log_str) if not dry_run: try: response = delete_connection(conn["oid"]) # If response is None, treat it as a failed deletion if response is None: logging.error( f"Failed to delete unused connection: {conn['name']} ({conn['oid']})." ) print( f"Error deleting unused connection: {conn['name']} ({conn['oid']})" ) bypassed.append(conn["name"]) else: deleted.append(conn["name"]) except Exception as e: logging.error( f"Exception while deleting unused connection: {conn['name']} ({conn['oid']}) - {e}" ) print( f"Error deleting unused connection: {conn['name']} ({conn['oid']})" ) bypassed.append(conn["name"]) else: # If the connection is used, add each dependency row to CSV. # Use a fallback value if 'title' or 'oid' is missing. for dep in dependencies: dep_title = dep.get( "title", "NULL TITLE Share Datasource with associated Bearer Token user to include in CSV", ) dep_oid = dep.get("oid", "NULL OID") data.append( { "Connection Name": conn["name"], "Connection ID": conn["oid"], "Elasticube/Data Model Name": dep_title, "Elasticube/Data Model ID": dep_oid, } ) # Create a DataFrame of only the used connections (with datasource dependencies) df = pd.DataFrame(data) df.to_csv(csv_path, index=False) row_count = len(df) logging.info(f"Generated CSV at {csv_path}") print( f"CSV file generated at {csv_path}. " f"It contains {row_count} row(s) of used connections.\n" "Please review and remove lines for connections you want to keep " "before running deletion step by running tool again. Remaining lines will be deleted in deletion mode." ) # Summaries for auto-deleted (unused) connections print("\nSummary Report:") print(f"Total lines in CSV (active used connections): {row_count}") if deleted: print("\nDeleted Unused Connections:") for d in deleted: print(f" - {d}") else: print("\nNo connections were deleted in this step.") if bypassed: print("\nBypassed Connections:") for b in bypassed: print(f" - {b}") else: print("\nNo connections were bypassed in this step.") def delete_connections_from_csv(): """ Reads the CSV (remaining lines after user review, removing lines for connections to keep), then deletes each connection listed. If a delete fails or returns None, the connection is logged and added to 'bypassed'. """ if not os.path.exists(csv_path): print( "CSV file does not exist. Please generate it first or fix the config path." ) return df = pd.read_csv(csv_path) deleted = [] bypassed = [] for _, row in df.iterrows(): conn_id = row["Connection ID"] conn_name = row["Connection Name"] action_msg = "[Dry Run] Would delete" if dry_run else "Deleted" log_str = f"{action_msg} connection: {conn_name} ({conn_id})" print(log_str) logging.info(log_str) if not dry_run: try: response = delete_connection(conn_id) if response is None: logging.error( f"Failed to delete connection: {conn_name} ({conn_id})" ) print(f"Error deleting connection: {conn_name} ({conn_id})") bypassed.append(conn_name) else: deleted.append(conn_name) except Exception as e: logging.error( f"Exception while deleting connection: {conn_name} ({conn_id}) - {e}" ) print(f"Error deleting connection: {conn_name} ({conn_id})") bypassed.append(conn_name) # Print summary report print("\nSummary Report:") if deleted: print("Deleted Connections:") for d in deleted: print(f" - {d}") else: print("No connections were deleted.") if bypassed: print("\nBypassed:") for b in bypassed: print(f" - {b}") else: print("No connections were bypassed.") if __name__ == "__main__": # If there is no CSV file found, select step 1 automatically if not os.path.exists(csv_path): print( "No CSV file found; defaulting to generating connections CSV. " "Correct config if CSV file name has changed." ) generate_connections_csv() else: choice = input( "Choose an option:\n" "1 - Generate connection CSV\n" "2 - Delete connections from CSV list\n" "Enter your choice (1 or 2): " ) if choice == "1": generate_connections_csv() elif choice == "2": delete_connections_from_csv() else: print("Invalid option. Please enter '1' or '2'.") Conclusion By automating the detection of inactive connections and simplifying their removal, the Sisense Connection Prune Tool reduces clutter in the Sisense server Connection Manager UI while minimizing the risk of unintentionally impacting active datasources. Whether you opt for a dry-run mode to review potential deletions in a generated CSV file, or to simply list connections, or proceed with the full removal of unused connections, this tool offers a clear, flexible, and reliable approach to keeping your connections organized. A full copy of the tool, is attached below.        

    Jeremy Friedel
    Jeremy FriedelPosted 1 year ago • Last reply 7 months ago
    4
             
…