Package: sfconn
Snowflake connection helper functionsA Python library to simplify connecting to Snowflake databasesNotesThis is a major version upgrade and breaks compatibility with the previous versions (<0.3.0).sfconnnow relies onsnowflake-python-connectorfor accessing named connections (e.g.connections.toml). If you still need the ability use named connections from~/.snowflake/config, please continue using older version (0.2.x).sfconnmodifies the wayprivate_key_fileconnection option is evaluated in the following ways:with--keyfile-anchoroption (default$SFCONN_KEYFILE_ANCHOR): uses the supplied value to anchor any relative paths (v/s anchoring paths relative to current working directory of the running process)with--keyfile-strip-pfxoption (default$SFCONN_KEYFILE_STRIP_PFX): strips the specified prefix from the path values (so--keyfile-anchoroption can be used)InstallationUse Python's standardpiputility for installation:pipinstall--upgradesfconnUsagegetconn()Usage:defgetconn(connection_name:str|None,**overrides:dict[str,Any])->Connectiongetconnaccepts a connection name and returns a connection object with modified behavior as noted above.Example:fromsfconnimportgetconn# assuming 'dev' is a connection defined in ~/.snowflake/configwithgetconn('dev',schema='PUBLIC')ascnx:withcnx.cursor()ascsr:csr.execute('SELECT CURRENT_USER()')print("Hello "+csr.fetchone()[0])conn_opts()Usage:defconn_opts(name:str|None,**overrides:dict[str,Any])->dict[str,Any]conn_opts, returns a Pythondictobject populated with options and values. This can be useful passing as an argument tosnowflake.snowpark.Session.builder.configs()method.Example:fromsfconnimportconn_optsfromsnowflake.snowparkimportSession# assuming 'dev' is a connection defined in ~/.snowflake/configsession=Session.builder.configs(conn_opts('dev')).create()run_query*()Cursor objects add a family of few convenience methods that return anIterableof values instead of generictupleordict.<cursor>.run_query(<callable>|<class>, <sql> [,<params>]): Returns an Iterable of values.<callable>is a mapping function that shall accept all column values of a row as individual arguments, in order, and returns a value that will be used forIterable.<class>is any Python class whose attribute names, after upper-casing, are treated as column names from the result set.<class>can include only a subset of a all available column from the query result as attributes and in a different order than the query.<cursor>.run_query1(<callable>|<class>, <sql> [,<params>]): Similar torun_query, except returns a single value. Note, if at least one value is not available, raisesProgrammingErrorexception.<cursor>.run_query1_opt(<callable>|<class>, <sql> [,<params>]): Similar torun_query1, except instead of raising an exception, the method returnsNone.Examples:importdatetimeasdtfromcollectionsimportnamedtupleResult=namedtuple("Result",["user","date"])defmkResult(x:str,y:dt.date)->Result:returnResult(x,y)withgetconn()ascnx,cnx.cursor()ascsr:result=csr.run_query1(mkResult,"select current_user() as user, current_date() as date")importdatetimeasdtfromdataclassesimportdataclass@dataclassclassResult:date:dt.dateuser:strwithgetconn()ascnx,cnx.cursor()ascsr:result=csr.run_query1(Result,"select current_user() as user, current_date() as date, current_warehouse() as wh_name")Decorator functionsPython scripts that accept command-line parameters and useargparselibrary, can use decorator functions to further reduce boilerplate code needed for setting up common Snowflake connection options as command-line argumentsdefwith_connection_args(doc:str|None)->Callable[[argparse.ArgumentParser],None]:defwith_connection(logger=None)->Callable[[Connection,...],None]:defwith_connection_option(logger=None)=>Callable([dict[str,Any,...]])with_connection_args()decorator function:builds anArgumentParserobjectadds common Snowflake connection options as arguments that allow overriding values specified in~/.snowsql/configcalls the decorated function with the parser object to allow adding any script specific optionswith_connection()decorator function:consumes standard Snowflake connection options (specified withargs())creates a connection objectcalls the decorated function with a connection object as first parameter and any other script specific options that were specified on command linewith_connection_option()decorator function:Similar toentry()but passes adictof options as the first parameter. This is useful for passing options to thesnowflake.snowpark.Session.builder.configs()methodExample:fromsfconnimportargs,entry@entrydefmain(con,show_account:bool):withcon.cursor()ascsr:csr.execute('SELECT CURRENT_USER()')print("Hello "+csr.fetchone()[0])ifshow_account:csr.execute("SELECT CURRENT_ACCOUNT()")print("You are connected to account: "+csr.fetchone()[0])@args("Sample application that greets the current Snowflake user")defgetargs(parser):parser.add_argument("-a","--show-account",action='store_true',help="show snowflake account name")if__name__=='__main__':main(**vars(getargs()))get_token()Functionsfconn.get_token()returns a JWT token for connections that useprivate_key_pathoption. An optional lifetime value can be specified (default 54 minutes)Example:fromsfconnimportget_token# assuming 'dev' is a connection defined in ~/.snowflake/config and uses key-pair authenticationjwt_token=get_token('dev',120)# get a token valid for 120 minutes