Sharing database instance between DatabaseLibrary and custom library

I want to implement a set of regression tests as SQL queries by using the DatabaseLibrary, with a sqlite3 in-memory DB.

*** Settings ***
Library        DatabaseLibrary

*** Test Cases ***
Test Sqlite
    Connect To Database    sqlite3    database=:memory:

The base for the database are stored in some CSV files. Those will be imported by

    Import Csv Into    table1    table1.csv

I wanted to use pandas to load the CSVs into some tables by using a custom library in python:

import pandas as pd
import sqlite3

def import_csv_into(self, table_name, csv_path):
  conn = sqlite3.connect(':memory:')
  csv_df = pd.read_csv(csv_path)
  csv_df.to_sql(table_name, conn, if_exists='replace', index=False)

Of course, the two are not using the same sqlite3 instance, therefore the data loaded by the custom library are not available to the DatabaseLibrary so that the following will fail:

${rows}=    Query    select COUNT(*) from table1

Is there a way to “share” the same sqlite3 connection instance between the two libraries?

Thanks,
Christian

I already found an option, adding it here for other’s reference:

To “share” the same sqlite3 instance between both libraries I used the following (inspired by Passing an object to another class - #12 by Mavnus04 )

import pandas as pd
from robot.libraries.BuiltIn import BuiltIn

def import_csv_into(self, table_name, csv_path):
  databaseLibrary = BuiltIn().get_library_instance(‘DatabaseLibrary’)
  conn = databaseLibrary.connection_store.get_connection(None).client

  csv_df = pd.read_csv(csv_path)
  csv_df.to_sql(table_name, conn, if_exists='replace', index=False)

It will get the default/ currently selected database connection and passes it to read_csv. BTW, this also abstracts the new keyword from sqlite3.

General question: Is this the right way to do this or is there any better way which does not require to access the internal structure of the DatabaseLibrary?

Thanks,
Christian

Using BuiltIn to fetch the instance is one option, another one if creating a custom library that subclasses DatabaseLibrary and adds the desired keywords to it. Since DatabaseLibrary is a stable release, I’d be inclined to go with that option, personally.

Good idea, this is also an option. In my case, as it was the first occurrence of this requirement, I simply added the function / keyword into the already existing custom library. But your option looks smarter as this would encapsulate the enhancement into a generic custom library.