index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
714,007 |
pyjdbc.connect
|
add
|
Add an argument to the parser
:param name: the name of the argument, any kwarg with this name will be accepted
:param position: (optional) if you want to support this variable as a positional argument
:param argtype: (optional) the data type of the argument. `isinstance` will be used to test for this type
:param mandatory: (optional) indicates is this is a required argument
:param requires: (optional) a sequence of other fields by `name` that are required if this field is set
:param excludes: (optional) a sequence of other fields by `name` that cannot be set if this field is defined
:param default: (optional) defines a default value
:param description: (optional) the description of the field
:return:
|
def add(self,
name,
position=None,
argtype=None,
mandatory=None,
requires=None,
excludes=None,
default=None,
description=None):
"""
Add an argument to the parser
:param name: the name of the argument, any kwarg with this name will be accepted
:param position: (optional) if you want to support this variable as a positional argument
:param argtype: (optional) the data type of the argument. `isinstance` will be used to test for this type
:param mandatory: (optional) indicates is this is a required argument
:param requires: (optional) a sequence of other fields by `name` that are required if this field is set
:param excludes: (optional) a sequence of other fields by `name` that cannot be set if this field is defined
:param default: (optional) defines a default value
:param description: (optional) the description of the field
:return:
"""
if not isinstance(name, str):
raise TypeError('name must be string, got: {}'.format(type(name)))
if name in self._named_args:
raise NameError('argument is already defined: {}'.format(name))
self._named_args[name] = ArgumentOpts(name=name,
position=position,
argtype=argtype,
mandatory=mandatory,
requires=requires,
excludes=excludes,
default=default,
description=description)
|
(self, name, position=None, argtype=None, mandatory=None, requires=None, excludes=None, default=None, description=None)
|
714,008 |
pyjdbc.connect
|
parse
|
:return: connection arguments keyed by argument value
:rtype: ConnectArguments
|
def parse(self):
"""
:return: connection arguments keyed by argument value
:rtype: ConnectArguments
"""
self._register_args()
if not self._named_args:
raise ValueError('the current parser: "{}" has no configured arguments\n'
'Any arguments passed to this parser will be ignored.'
'You may have forgot to configure a custom parser'.format(
self.__class__.__name__
))
args_dict = self._parse_args(*self._args, **self._kwargs)
return ConnectArguments(args_dict)
|
(self)
|
714,009 |
pyjdbc.connect
|
ConnectArguments
|
Stores connection arguments
|
class ConnectArguments:
"""
Stores connection arguments
"""
def __init__(self, parsed_args: dict):
if not isinstance(parsed_args, dict):
raise ValueError('properties must be instanceof `parsed_args`')
self.__dict__['_parsed'] = parsed_args
def __getattr__(self, item: str):
if item not in self.__dict__['_parsed']:
valid = '\n'.join(self.__dict__['_parsed'].keys())
raise NameError('invalid argument name: {}, valid arguments: {}'.format(item, valid))
return self.__dict__['_parsed'][item]
def __setattr__(self, key, value):
self.__dict__['_parsed'][key] = value
def __getitem__(self, key):
return self.__dict__['_parsed'][key]
def __setitem__(self, key, value):
self.__dict__['_parsed'][key] = value
def get(self, key, default=None):
return self.__dict__['_parsed'].get(key, default)
def __iter__(self):
return iter(self.__dict__['_parsed'])
def items(self):
return self.__dict__['_parsed'].items()
|
(parsed_args: dict)
|
714,010 |
pyjdbc.connect
|
__getattr__
| null |
def __getattr__(self, item: str):
if item not in self.__dict__['_parsed']:
valid = '\n'.join(self.__dict__['_parsed'].keys())
raise NameError('invalid argument name: {}, valid arguments: {}'.format(item, valid))
return self.__dict__['_parsed'][item]
|
(self, item: str)
|
714,011 |
pyjdbc.connect
|
__getitem__
| null |
def __getitem__(self, key):
return self.__dict__['_parsed'][key]
|
(self, key)
|
714,012 |
pyjdbc.connect
|
__init__
| null |
def __init__(self, parsed_args: dict):
if not isinstance(parsed_args, dict):
raise ValueError('properties must be instanceof `parsed_args`')
self.__dict__['_parsed'] = parsed_args
|
(self, parsed_args: dict)
|
714,013 |
pyjdbc.connect
|
__iter__
| null |
def __iter__(self):
return iter(self.__dict__['_parsed'])
|
(self)
|
714,014 |
pyjdbc.connect
|
__setattr__
| null |
def __setattr__(self, key, value):
self.__dict__['_parsed'][key] = value
|
(self, key, value)
|
714,015 |
pyjdbc.connect
|
__setitem__
| null |
def __setitem__(self, key, value):
self.__dict__['_parsed'][key] = value
|
(self, key, value)
|
714,016 |
pyjdbc.connect
|
get
| null |
def get(self, key, default=None):
return self.__dict__['_parsed'].get(key, default)
|
(self, key, default=None)
|
714,017 |
pyjdbc.connect
|
items
| null |
def items(self):
return self.__dict__['_parsed'].items()
|
(self)
|
714,018 |
pyjdbc.connect
|
ConnectFunction
|
Contains the logic to correctly implement a `connect` function for your db-api-2.0
compliant jdbc wrapper.
Generally implementations only need override __init__ arguments and `get_connection()`
|
class ConnectFunction:
"""
Contains the logic to correctly implement a `connect` function for your db-api-2.0
compliant jdbc wrapper.
Generally implementations only need override __init__ arguments and `get_connection()`
"""
_driver_path = None
_driver_class = None
_connection_class = None
_cursor_class = None
_parser = None
_type_conversion = None
_runtime_invocation_ok = None
def __init__(self,
driver_path,
driver_class,
connection_class=JdbcConnection,
cursor_class=JdbcCursor,
parser=ArgumentParser,
type_conversion=JdbcTypeConversion,
runtime_invocation_ok=True):
self.driver_path = driver_path
self.driver_class = driver_class
self.connection_class = connection_class
self.cursor_class = cursor_class
self.parser = parser
self.type_conversion = type_conversion
self.runtime_invocation_ok = runtime_invocation_ok
@property
def driver_path(self):
return self._driver_path
@driver_path.setter
def driver_path(self, path: str):
self._driver_path = path
@property
def driver_class(self):
return self._driver_class
@driver_class.setter
def driver_class(self, cls: str):
"""
The driver class to instantiate JDBC connections with.
:param cls: a string giving the fully qualified Java class name
:return:
"""
self._driver_class = cls
@property
def connection_class(self):
return self._connection_class
@connection_class.setter
def connection_class(self, cls):
if not issubclass(cls, JdbcConnection):
raise ValueError('"connection_class" must be class of {}'.format(str(JdbcConnection)))
self._connection_class = cls
@property
def cursor_class(self):
return self._cursor_class
@cursor_class.setter
def cursor_class(self, cls):
if not issubclass(cls, JdbcCursor):
raise ValueError('"connection_class" must be class of {}'.format(str(JdbcCursor)))
self._cursor_class = cls
@property
def runtime_invocation_ok(self):
return self._cursor_class
@runtime_invocation_ok.setter
def runtime_invocation_ok(self, is_ok):
"""
Indicates if it is acceptable it invoke the JDBC Driver directly from the Jar file AFTER
JVM startup.
:param is_ok: True/False
:type is_ok: bool
:return:
"""
if not isinstance(is_ok, bool):
raise ValueError('"isok" must be bool, got: {}'.format(type(is_ok)))
self._runtime_invocation_ok = is_ok
@property
def parser(self):
"""
class object used to parse *args, and **kwargs passed into connect
:return: parser class object
:rtype: ArgumentParser
"""
return self._parser
@parser.setter
def parser(self, parser: ArgumentParser):
self._parser = parser
@property
def type_conversion(self):
return self._type_conversion
@type_conversion.setter
def type_conversion(self, cls):
if not issubclass(cls, JdbcTypeConversion):
raise ValueError('"type_conversion" must be class of {}'.format(str(JdbcTypeConversion)))
self._type_conversion = cls
def get_connection(self, driver_class: JClass, arguments: ConnectArguments):
"""
Creates and returns the python JdbcConnection object wrapper instance
:return: JdbcConnection instance
:rtype: JdbcConnection
"""
raise NotImplementedError('this method must be defined by the implementation')
def handle_args(self, arguments: ConnectArguments):
"""
Optional method that can be implemented by subclasses
Called immediately after arguments are successfully parsed, before
any additional operations are performed.
Useful for setting driver options from argument inputs.
For example if you need to set the `driver_path` or `driver_class` at
runtime perhaps based upon user configuration.
:param arguments:
:return:
"""
pass
def parse_args(self, *args, **kwargs):
"""
:param args:
:param kwargs:
:rtype: ConnectArguments
:return: returns an instance of ConnectArguments containing
"""
ParserClass = self.parser
parser = ParserClass(*args, **kwargs)
args = parser.parse()
self.handle_args(args)
return args
def load_driver(self):
"""
Loads the driver defined via `driver_path` and `driver_class`
if self.
Classpath.load_jar_class('sqlite-jdbc-3.21.0.jar', 'org.sqlite.SQLiteConnection')
:return: Java driver class object via JPype
:rtype: JConnection
"""
if self.driver_path and not (isfile(self.driver_path) or isdir(self.driver_path)):
raise ValueError('"driver_path" is not a valid jar file or directory {}\n'
'"driver_path" can be set to `None` if the classpath is configured by'
'the user'.format(self.driver_path))
if self.driver_class is None or not str(self.driver_class).strip():
raise ValueError('"driver_class" must be set on {}'.format(self.__class__))
if Jvm.is_running():
# if the jvm is already running, it's possible the class we need has already been loaded before
# or is already on the classpath
try:
driver = JClass(self.driver_class)
except JClass('java.lang.ClassNotFoundException'):
pass
else:
return driver
# if the jvm has NOT been started, add the driver jar to the classpath explicitly
# and try to load the class
# this is designed this way to ensure the only time we use the users provided classpath
# is when driver_path has NOT been given.
if not Jvm.is_running() and not self.driver_path:
Jvm.start()
# try to load the driver normally, this assumes the classpath has been set for us by the user
try:
driver = JClass(self.driver_class)
except JClass('java.lang.ClassNotFoundException'):
raise DriverNotFoundError('The driver class "{}" could not be found on '
'the classpath\n'
'Note: no jar-path was passed to pyjdbc via '
'"driver_path"\n'
'Classpath:\n'
'{}'.format(self.driver_class, Classpath.get()))
else:
return driver
if not Jvm.is_running():
# according to jpype a jar file can be added to the classpath directly:
# https://jpype.readthedocs.io/en/latest/quickguide.html#starting-jpype
Classpath.add(self.driver_path)
Jvm.start()
try:
driver = JClass(self.driver_class)
except (TypeError, JClass('java.lang.ClassNotFoundException')):
raise DriverNotFoundError('The driver class "{}" could not be found on the classpath.\n'
'"driver_path" = {}\n'
'Classpath:\n'
'{}'.format(self.driver_class, self.driver_path, Classpath.get())) from None
else:
return driver
else:
if not self.runtime_invocation_ok:
raise RuntimeError('Error in driver {} - runtime invocation of the pyjdbc based driver: "{}" '
'is not allowed.\n'
'you may need to set the classpath via the java.Classpath method before invoking'
'the driver!'.format(self.driver_class, self.__class__.__name__)) from None
try:
driver = Classpath.load_jar_class(self.driver_path, self.driver_class)
except (TypeError, JClass('java.lang.ClassNotFoundException')) as e:
raise DriverNotFoundError('unable to load jdbc driver class: "{}" from {}'.format(
self.driver_class, self.driver_path
)) from e
return driver
def connect(self, *args, **kwargs):
"""
Loads driver class and retrieves connection
Lower level interface than ``get_connection()``
Driver implementations may override this method if they wish to override driver loading semantics
:param args: driver specific positional arguments
:param kwargs: driver specific keyword arguments
:return: JdbcConnection instance or subclass of
:rtype: JdbcConnection
"""
arguments = self.parse_args(*args, **kwargs)
driver_class = self.load_driver()
return self.get_connection(driver_class, arguments)
def __call__(self, *args, **kwargs):
"""
:param args:
:param kwargs:
:return: Python JdbcConnection instance
"""
return self.connect(*args, **kwargs)
|
(driver_path, driver_class, connection_class=<class 'pyjdbc.dbapi.JdbcConnection'>, cursor_class=<class 'pyjdbc.dbapi.JdbcCursor'>, parser=<class 'pyjdbc.connect.ArgumentParser'>, type_conversion=<class 'pyjdbc.types.JdbcTypeConversion'>, runtime_invocation_ok=True)
|
714,019 |
pyjdbc.connect
|
__call__
|
:param args:
:param kwargs:
:return: Python JdbcConnection instance
|
def __call__(self, *args, **kwargs):
"""
:param args:
:param kwargs:
:return: Python JdbcConnection instance
"""
return self.connect(*args, **kwargs)
|
(self, *args, **kwargs)
|
714,020 |
pyjdbc.connect
|
__init__
| null |
def __init__(self,
driver_path,
driver_class,
connection_class=JdbcConnection,
cursor_class=JdbcCursor,
parser=ArgumentParser,
type_conversion=JdbcTypeConversion,
runtime_invocation_ok=True):
self.driver_path = driver_path
self.driver_class = driver_class
self.connection_class = connection_class
self.cursor_class = cursor_class
self.parser = parser
self.type_conversion = type_conversion
self.runtime_invocation_ok = runtime_invocation_ok
|
(self, driver_path, driver_class, connection_class=<class 'pyjdbc.dbapi.JdbcConnection'>, cursor_class=<class 'pyjdbc.dbapi.JdbcCursor'>, parser=<class 'pyjdbc.connect.ArgumentParser'>, type_conversion=<class 'pyjdbc.types.JdbcTypeConversion'>, runtime_invocation_ok=True)
|
714,021 |
pyjdbc.connect
|
connect
|
Loads driver class and retrieves connection
Lower level interface than ``get_connection()``
Driver implementations may override this method if they wish to override driver loading semantics
:param args: driver specific positional arguments
:param kwargs: driver specific keyword arguments
:return: JdbcConnection instance or subclass of
:rtype: JdbcConnection
|
def connect(self, *args, **kwargs):
"""
Loads driver class and retrieves connection
Lower level interface than ``get_connection()``
Driver implementations may override this method if they wish to override driver loading semantics
:param args: driver specific positional arguments
:param kwargs: driver specific keyword arguments
:return: JdbcConnection instance or subclass of
:rtype: JdbcConnection
"""
arguments = self.parse_args(*args, **kwargs)
driver_class = self.load_driver()
return self.get_connection(driver_class, arguments)
|
(self, *args, **kwargs)
|
714,022 |
pyjdbc.connect
|
get_connection
|
Creates and returns the python JdbcConnection object wrapper instance
:return: JdbcConnection instance
:rtype: JdbcConnection
|
def get_connection(self, driver_class: JClass, arguments: ConnectArguments):
"""
Creates and returns the python JdbcConnection object wrapper instance
:return: JdbcConnection instance
:rtype: JdbcConnection
"""
raise NotImplementedError('this method must be defined by the implementation')
|
(self, driver_class: jpype._jclass.JClass, arguments: pyjdbc.connect.ConnectArguments)
|
714,023 |
pyjdbc.connect
|
handle_args
|
Optional method that can be implemented by subclasses
Called immediately after arguments are successfully parsed, before
any additional operations are performed.
Useful for setting driver options from argument inputs.
For example if you need to set the `driver_path` or `driver_class` at
runtime perhaps based upon user configuration.
:param arguments:
:return:
|
def handle_args(self, arguments: ConnectArguments):
"""
Optional method that can be implemented by subclasses
Called immediately after arguments are successfully parsed, before
any additional operations are performed.
Useful for setting driver options from argument inputs.
For example if you need to set the `driver_path` or `driver_class` at
runtime perhaps based upon user configuration.
:param arguments:
:return:
"""
pass
|
(self, arguments: pyjdbc.connect.ConnectArguments)
|
714,024 |
pyjdbc.connect
|
load_driver
|
Loads the driver defined via `driver_path` and `driver_class`
if self.
Classpath.load_jar_class('sqlite-jdbc-3.21.0.jar', 'org.sqlite.SQLiteConnection')
:return: Java driver class object via JPype
:rtype: JConnection
|
def load_driver(self):
"""
Loads the driver defined via `driver_path` and `driver_class`
if self.
Classpath.load_jar_class('sqlite-jdbc-3.21.0.jar', 'org.sqlite.SQLiteConnection')
:return: Java driver class object via JPype
:rtype: JConnection
"""
if self.driver_path and not (isfile(self.driver_path) or isdir(self.driver_path)):
raise ValueError('"driver_path" is not a valid jar file or directory {}\n'
'"driver_path" can be set to `None` if the classpath is configured by'
'the user'.format(self.driver_path))
if self.driver_class is None or not str(self.driver_class).strip():
raise ValueError('"driver_class" must be set on {}'.format(self.__class__))
if Jvm.is_running():
# if the jvm is already running, it's possible the class we need has already been loaded before
# or is already on the classpath
try:
driver = JClass(self.driver_class)
except JClass('java.lang.ClassNotFoundException'):
pass
else:
return driver
# if the jvm has NOT been started, add the driver jar to the classpath explicitly
# and try to load the class
# this is designed this way to ensure the only time we use the users provided classpath
# is when driver_path has NOT been given.
if not Jvm.is_running() and not self.driver_path:
Jvm.start()
# try to load the driver normally, this assumes the classpath has been set for us by the user
try:
driver = JClass(self.driver_class)
except JClass('java.lang.ClassNotFoundException'):
raise DriverNotFoundError('The driver class "{}" could not be found on '
'the classpath\n'
'Note: no jar-path was passed to pyjdbc via '
'"driver_path"\n'
'Classpath:\n'
'{}'.format(self.driver_class, Classpath.get()))
else:
return driver
if not Jvm.is_running():
# according to jpype a jar file can be added to the classpath directly:
# https://jpype.readthedocs.io/en/latest/quickguide.html#starting-jpype
Classpath.add(self.driver_path)
Jvm.start()
try:
driver = JClass(self.driver_class)
except (TypeError, JClass('java.lang.ClassNotFoundException')):
raise DriverNotFoundError('The driver class "{}" could not be found on the classpath.\n'
'"driver_path" = {}\n'
'Classpath:\n'
'{}'.format(self.driver_class, self.driver_path, Classpath.get())) from None
else:
return driver
else:
if not self.runtime_invocation_ok:
raise RuntimeError('Error in driver {} - runtime invocation of the pyjdbc based driver: "{}" '
'is not allowed.\n'
'you may need to set the classpath via the java.Classpath method before invoking'
'the driver!'.format(self.driver_class, self.__class__.__name__)) from None
try:
driver = Classpath.load_jar_class(self.driver_path, self.driver_class)
except (TypeError, JClass('java.lang.ClassNotFoundException')) as e:
raise DriverNotFoundError('unable to load jdbc driver class: "{}" from {}'.format(
self.driver_class, self.driver_path
)) from e
return driver
|
(self)
|
714,025 |
pyjdbc.connect
|
parse_args
|
:param args:
:param kwargs:
:rtype: ConnectArguments
:return: returns an instance of ConnectArguments containing
|
def parse_args(self, *args, **kwargs):
"""
:param args:
:param kwargs:
:rtype: ConnectArguments
:return: returns an instance of ConnectArguments containing
"""
ParserClass = self.parser
parser = ParserClass(*args, **kwargs)
args = parser.parse()
self.handle_args(args)
return args
|
(self, *args, **kwargs)
|
714,026 |
pyjdbc.connect
|
Decorator
|
Contains decorator functions (static methods) for decorating functions to configure
function arguments
|
class Decorator:
"""
Contains decorator functions (static methods) for decorating functions to configure
function arguments
"""
@staticmethod
def argument(name=None,
position=None,
argtype=None,
mandatory=False,
requires=(),
excludes=(),
default=None,
description=None,
choices=None,
secret=None):
"""
Decorate a function to create an argument automatically
:param name: The name of the argument, (kwarg name) if not provided will be the name of the function being
decorated.
:param position: Position (if positional / required argument), positions start at 0.
positional arguments are automatically mandatory
:param argtype: The python type of the argument, if the given argument is not an instance of this type
an exception will be raised.
:param mandatory: Bool that indicates if the argument is required.
:param requires: A sequence of other argument names - if this argument is set, this ensures the other arguments
mentioned by `requires` are also set.
:param excludes: A sequence of other argument names - if this argument is set, the named arguments must NOT
be set.
:param default: A default value for the argument, excludes "mandatory".
:param description: Help text for the argument
:param choices: Sequence defining the allowable set of options the argument value may be.
:param secret: Indicates if the argument is sensitive / secret - the argument will be excluded from logging or
errors.
:return: The decorated function (with a ``_argument`` attribute initialized as ``ArgumentOpts``
"""
def decorator(func):
if name is None:
name2 = func.__name__
else:
name2 = name
fn_args = inspect.getfullargspec(func).args
if len(fn_args) < 2:
raise ValueError('decorated function [{}] must accept at least 1 argument <value>'.format(str(func)))
description2 = doc_str(func) if description is None else description
if not description2:
description2 = str(func)
arg = ArgumentOpts(name=name2,
position=position,
argtype=argtype,
mandatory=mandatory,
requires=requires,
excludes=excludes,
default=default,
description=description2,
choices=choices,
secret=secret,
fn=func)
# store the argument inside the function object.
setattr(func, DECORATOR_ATTRIBUTE, arg)
return func
return decorator
|
()
|
714,027 |
pyjdbc.connect
|
argument
|
Decorate a function to create an argument automatically
:param name: The name of the argument, (kwarg name) if not provided will be the name of the function being
decorated.
:param position: Position (if positional / required argument), positions start at 0.
positional arguments are automatically mandatory
:param argtype: The python type of the argument, if the given argument is not an instance of this type
an exception will be raised.
:param mandatory: Bool that indicates if the argument is required.
:param requires: A sequence of other argument names - if this argument is set, this ensures the other arguments
mentioned by `requires` are also set.
:param excludes: A sequence of other argument names - if this argument is set, the named arguments must NOT
be set.
:param default: A default value for the argument, excludes "mandatory".
:param description: Help text for the argument
:param choices: Sequence defining the allowable set of options the argument value may be.
:param secret: Indicates if the argument is sensitive / secret - the argument will be excluded from logging or
errors.
:return: The decorated function (with a ``_argument`` attribute initialized as ``ArgumentOpts``
|
@staticmethod
def argument(name=None,
position=None,
argtype=None,
mandatory=False,
requires=(),
excludes=(),
default=None,
description=None,
choices=None,
secret=None):
"""
Decorate a function to create an argument automatically
:param name: The name of the argument, (kwarg name) if not provided will be the name of the function being
decorated.
:param position: Position (if positional / required argument), positions start at 0.
positional arguments are automatically mandatory
:param argtype: The python type of the argument, if the given argument is not an instance of this type
an exception will be raised.
:param mandatory: Bool that indicates if the argument is required.
:param requires: A sequence of other argument names - if this argument is set, this ensures the other arguments
mentioned by `requires` are also set.
:param excludes: A sequence of other argument names - if this argument is set, the named arguments must NOT
be set.
:param default: A default value for the argument, excludes "mandatory".
:param description: Help text for the argument
:param choices: Sequence defining the allowable set of options the argument value may be.
:param secret: Indicates if the argument is sensitive / secret - the argument will be excluded from logging or
errors.
:return: The decorated function (with a ``_argument`` attribute initialized as ``ArgumentOpts``
"""
def decorator(func):
if name is None:
name2 = func.__name__
else:
name2 = name
fn_args = inspect.getfullargspec(func).args
if len(fn_args) < 2:
raise ValueError('decorated function [{}] must accept at least 1 argument <value>'.format(str(func)))
description2 = doc_str(func) if description is None else description
if not description2:
description2 = str(func)
arg = ArgumentOpts(name=name2,
position=position,
argtype=argtype,
mandatory=mandatory,
requires=requires,
excludes=excludes,
default=default,
description=description2,
choices=choices,
secret=secret,
fn=func)
# store the argument inside the function object.
setattr(func, DECORATOR_ATTRIBUTE, arg)
return func
return decorator
|
(name=None, position=None, argtype=None, mandatory=False, requires=(), excludes=(), default=None, description=None, choices=None, secret=None)
|
714,028 |
hivejdbc
|
DictCursor
| null |
class DictCursor(JdbcDictCursor):
pass
|
(connection: pyjdbc.dbapi.JdbcConnection, type_conversion, rowcounts=True)
|
714,031 |
pyjdbc.dbapi
|
__init__
| null |
def __init__(self, connection: JdbcConnection, type_conversion, rowcounts=True):
self._connection = connection
self._type_conversion = type_conversion
self._description = None
self._metadata = None
self._statement = None
self._resultset = None
self._rowcount = -1
self._get_rowcounts = rowcounts
if not isinstance(connection, JdbcConnection):
raise ValueError('"connection" arg must be instance of {}'.format(str(JdbcConnection)))
|
(self, connection: pyjdbc.dbapi.JdbcConnection, type_conversion, rowcounts=True)
|
714,032 |
pyjdbc.dbapi
|
__iter__
| null |
def __iter__(self):
while True:
row = self.fetchone()
if row is None:
break
else:
yield row
|
(self)
|
714,033 |
pyjdbc.dbapi
|
_check_params
| null |
def _check_params(self, params):
if isinstance(params, dict):
return
if not isinstance(params, Sequence) or isinstance(params, (str, bytes)):
raise ValueError('parameters must be a sequence or a dictionary, got: {}'.format(type(params)))
|
(self, params)
|
714,034 |
pyjdbc.dbapi
|
_clear_connection
| null |
def _clear_connection(self):
self._connection = None
|
(self)
|
714,035 |
pyjdbc.dbapi
|
_clear_metadata
| null |
def _clear_metadata(self):
self._metadata = None
self._description = None
|
(self)
|
714,036 |
pyjdbc.dbapi
|
_close_resultset
| null |
def _close_resultset(self):
if self._resultset_valid():
self._resultset.close()
self._resultset = None
|
(self)
|
714,037 |
pyjdbc.dbapi
|
_close_statement
| null |
def _close_statement(self):
if self._statement:
self._statement.close()
self._statement = None
|
(self)
|
714,038 |
pyjdbc.dbapi
|
_connection_valid
| null |
def _connection_valid(self):
return not self._connection.is_closed()
|
(self)
|
714,039 |
pyjdbc.dbapi
|
_parse_params
|
Parse %s style or ":name" style parameters.
If use :name style parameters, ``params`` must be a dictionary.
:param sql: sql statement
:param params: parameters (sequence or dictionary)
:return:
|
def _parse_params(self, sql, params):
"""
Parse %s style or ":name" style parameters.
If use :name style parameters, ``params`` must be a dictionary.
:param sql: sql statement
:param params: parameters (sequence or dictionary)
:return:
"""
if not params:
raise ValueError('params must be `None` or a non empty sequence or dictionary, got: {}'.format(params))
orig_params = copy(params)
self._check_params(params)
if isinstance(params, dict):
try:
# convert ":param" to ? parameters
query = sqlparams.SQLParams('named', 'qmark')
operation, params = query.format(sql, params)
except KeyError as e:
key = e.args[0]
raise ValueError('":{}" is missing from parameters template in statement: "{}"'
'\nParameters: {}'.format(key, sql, dict(orig_params)))
# sqlparams will not check for un-consumed keyword parameters
# this is an error because the user is passing in arguments that are not being used by the query
if len(params) < len(orig_params):
missing = ['":{}"'.format(key) for key in orig_params if ':{}'.format(key) not in sql]
raise ValueError('sql statement is missing named template paramaters:\n ({})\n'
'given paramaters:\n {}\n'
'in query:\n{}'.format(
', '.join(map(str, missing)),
str(dict(orig_params)),
textwrap.indent(sql.strip(), ' '*4)))
else:
try:
# convert %s to ? parameters
query = sqlparams.SQLParams('format', 'qmark')
operation, params = query.format(sql, params)
except IndexError as e:
fmt_count = sql.count('%s')
raise ValueError('`params` contains incorrect number of arguments for "%s"'
'templates in query.\n'
'expected: [{}] arguments, got: [{}]'.format(fmt_count, len(params)))
# sqlparams will not check for un-consumed or un-needed positional parameters
extra_args = len(orig_params) - len(params)
if extra_args:
raise ValueError('`params` contains {} more elements than were consumed by query templates:\n{}\n'
'arguments given: [{}]\nunused: [{}]'.format(
extra_args,
textwrap.indent(sql.strip(), ' '*4),
', '.join(map(str, orig_params)),
', '.join(map(str, orig_params[len(params):]))))
return operation, params
|
(self, sql, params)
|
714,040 |
pyjdbc.dbapi
|
_reset
| null |
def _reset(self):
# close any previously used resources
self._clear_metadata()
self._close_statement()
self._close_resultset()
|
(self)
|
714,041 |
pyjdbc.dbapi
|
_resultset_valid
| null |
def _resultset_valid(self):
return bool(self._resultset)
|
(self)
|
714,042 |
pyjdbc.dbapi
|
_warnings
| null |
def _warnings(self):
if not self._resultset_valid():
return ''
warning = self._resultset.getWarnings()
if not warning:
return ''
try:
return 'cursor warning: {}'.format(str(warning.getMessage()))
except Exception:
return ''
|
(self)
|
714,043 |
pyjdbc.dbapi
|
close
|
close the cursor, the cursor cannot be used again.
:return:
|
def close(self):
"""
close the cursor, the cursor cannot be used again.
:return:
"""
# close all open resources.
self._clear_connection()
self._clear_metadata()
try:
self._close_statement()
except Exception:
pass
try:
self._close_resultset()
except Exception:
pass
|
(self)
|
714,044 |
pyjdbc.dbapi
|
execute
|
Execute a sql statement with an optional set of parameters
:param operation: Sql text
:param params: a sequence or dictionary of parameters
Parameters can be positional templates ``%s`` or named templates ``:name``
:param operation:
:param params:
:return:
|
def execute(self, operation, params=None):
"""
Execute a sql statement with an optional set of parameters
:param operation: Sql text
:param params: a sequence or dictionary of parameters
Parameters can be positional templates ``%s`` or named templates ``:name``
:param operation:
:param params:
:return:
"""
if not self._connection_valid():
raise Error('the connection has been closed')
self._reset()
conn = self._connection.jdbc_connection()
# handle parameters
if params is not None:
operation, params = self._parse_params(operation, params)
# prepare the statement
self._statement = stmt = conn.prepareStatement(operation)
stmt.clearParameters()
for column, value in enumerate(params or [], start=1):
# note that in JDBC the first column index is 1
if isinstance(value, str):
jvalue = JString(value)
stmt.setString(column, jvalue)
elif isinstance(value, float):
jvalue = JDouble(value)
stmt.setDouble(column, jvalue)
elif isinstance(value, int):
try:
jvalue = JInt(value)
stmt.setInt(column, jvalue)
except Exception:
jvalue = JLong(value)
stmt.setLong(column, jvalue)
elif isinstance(value, bool):
jvalue = JBoolean(value)
stmt.setBoolean(column, jvalue)
elif isinstance(value, bytes):
ByteArray = JArray(JByte)
jvalue = ByteArray(value.decode('utf-8'))
stmt.setBytes(column, jvalue)
else:
stmt.setObject(column, value)
try:
has_resultset = stmt.execute()
except JClass('org.apache.hive.service.cli.HiveSQLException') as e:
raise ProgrammingError('Error executing statement:\n{}\n{}'.format(operation, e)) from None
self._rowcount = -1
if has_resultset:
self._resultset = resultset = stmt.getResultSet()
self._metadata = resultset.getMetaData()
# get rowcount
if self._get_rowcounts:
try:
if self._resultset.last(): # if the cursor can be moved to the last row.
self._rowcount = resultset.getRow()
resultset.beforeFirst()
except JClass('java.sql.SQLException'):
# ResultSet.last() is not supported
pass
else:
try:
self._rowcount = stmt.getUpdateCount()
except JClass('java.sql.SQLException'):
# not supported
pass
|
(self, operation, params=None)
|
714,045 |
pyjdbc.dbapi
|
executemany
|
Execute many statements each with a different set of parameters
:param operation: Sql text
:param seq_of_parameters: a sequence of sequences containing parameters to pass into `operation`
Parameters can be positional templates ``%s`` or named templates ``:name``
:return:
|
def executemany(self, operation, seq_of_parameters):
"""
Execute many statements each with a different set of parameters
:param operation: Sql text
:param seq_of_parameters: a sequence of sequences containing parameters to pass into `operation`
Parameters can be positional templates ``%s`` or named templates ``:name``
:return:
"""
try:
orig_sql = operation
self._reset()
conn = self._connection.jdbc_connection()
self._statement = stmt = conn.prepareStatement(operation)
for params in seq_of_parameters:
if params is not None:
operation, params = self._parse_params(operation, params)
for column, value in enumerate(params or [], start=1):
stmt.setObject(column, value)
stmt.addBatch()
batch_rowcounts = stmt.executeBatch()
self._rowcount = sum(batch_rowcounts)
self._reset()
except JClass('java.sql.SQLException') as e:
# addBatch/executeBatch not supported
rowcount = 0
for params in seq_of_parameters:
self.execute(orig_sql, params)
if self._rowcount > 0:
rowcount += self._rowcount
self._rowcount = rowcount if self._get_rowcounts else -1
|
(self, operation, seq_of_parameters)
|
714,047 |
pyjdbc.dbapi
|
fetchmany
| null |
def fetchmany(self, size=None):
# TODO implement this in a java class
if not self._resultset_valid():
raise DatabaseError('result set is no longer valid ' + self._warnings())
if size is None:
size = self.batch_size
# TODO: handle SQLException if not supported by db
self._resultset.setFetchSize(size)
rows = []
row = None
for i in range(size):
row = self.fetchone()
if row is None:
break
else:
rows.append(row)
# reset fetch size
if row:
# TODO: handle SQLException if not supported by db
self._resultset.setFetchSize(0)
return rows
|
(self, size=None)
|
714,048 |
pyjdbc.dbapi
|
fetchone
| null |
def fetchone(self):
row = super().fetchone()
if row:
names = self.column_names
return dict(zip(names, row))
|
(self)
|
714,050 |
hivejdbc
|
HiveArgParser
| null |
class HiveArgParser(ArgumentParser):
host = ArgumentOpts(position=0, argtype=str, description='Hive Host, ie: `example.org`, can also be a comma'
'separated list of hosts to attempt')
database = ArgumentOpts(position=1, argtype=str, description='Database name to connect to, `default`')
port = ArgumentOpts(argtype=int, default=10000, description='Hive port, deafults to `10000`')
driver = ArgumentOpts(argtype=str, description='Location to hive uber-jar (not required if Hive, Hadoop jars '
'are on the classpath already)')
cursor = ArgumentOpts(argtype=JdbcCursor, description='cursor class for queries')
ssl = ArgumentOpts(argtype=bool, description='enable ssl connection mode, if the server is running with '
'ssl certificates enabled this is required')
trust_password = ArgumentOpts(argtype=str, secret=True, requires=['trust_store', 'ssl'])
user = ArgumentOpts(argtype=str, description='Hive username if using username/password auth')
password = ArgumentOpts(argtype=str, secret=True, requires=['user'], description='Hive basic auth password')
user_principal = ArgumentOpts(argtype=str, description='Kerberos user principal', requires=['user_keytab'])
realm = ArgumentOpts(argtype=str, description='Kerberos realm (domain), if set, "realm" must also be set,'
'normally this value can be obtained automatically '
'from "default_realm" within krb5.conf',
requires=['principal', 'user_keytab', 'kdc'])
properties = ArgumentOpts(argtype=dict, default={},
description='properties passed to org.apache.hive.jdbc.HiveDriver "connect" method')
transport = ArgumentOpts(argtype=str, default='binary', choices=('binary', 'http'))
http_path = ArgumentOpts(argtype=str, description='HTTP endpoint for when HiveServer2 is running in HTTP mode.\n'
'this is a rarely used option. Only set this if `transport` '
'is set to `binary`')
init_file = ArgumentOpts(argtype=str, description='This script file is written with SQL statements which will be '
'executed automatically after connection')
service_discovery_mode = ArgumentOpts(argtype=str, choices=['zooKeeper'], requires=['zookeeper_namespace'],
description='If using zookeeper service discovery you must set this')
zookeeper_namespace = ArgumentOpts(argtype=str,
requires=['service_discovery_mode'],
description='Zookeeper namespace string for service discovery')
@Decorator.argument(argtype=str, requires=['trust_password', 'ssl'])
def trust_store(self, path):
"""Path to the java ssl trust-store, generally required if ssl=True"""
if not isinstance(path, str):
raise ValueError('expected `str`, got: {}'.format(type(path)))
if not isfile(path):
raise ValueError('not a valid file')
return path
@Decorator.argument(argtype=str, excludes=['username', 'password'])
def principal(self, user):
"""Hive SERVICE principal, usually "hive" - should be fully qualified: `hive@EXAMPLE.COM`"""
if not isinstance(user, str):
raise ValueError('expected `str`, got: {}'.format(type(user)))
if not Jvm.is_running():
Jvm.add_argument('javax.security.auth.useSubjectCredsOnly',
'-Djavax.security.auth.useSubjectCredsOnly=false')
else:
System.set_property('javax.security.auth.useSubjectCredsOnly', 'false')
return user
@Decorator.argument(argtype=str, requires=['principal', 'user_principal'])
def user_keytab(self, path):
"""Kerberos keytab - if provided the module will attempt kerberos login without the need for ``kinit``"""
if not isinstance(path, str):
raise ValueError('expected `str`, got: {}'.format(type(path)))
if not isfile(path):
raise ValueError('not a valid file')
return path
@Decorator.argument(argtype=str, requires=['principal'])
def krb5_conf(self, path):
"""Kerberos krb5.conf - default locations for the file are platform dependent
or set via environment variable: "KRB5_CONFIG" - if your configuration is in a default location you
typically do not need to explicitly provide this configuration."""
if not isinstance(path, str):
raise ValueError('expected `str`, got: {}'.format(type(path)))
if not Jvm.is_running():
Jvm.add_argument('java.security.krb5.conf', '-Djava.security.krb5.conf={}'.format(path))
else:
System.set_property('java.security.krb5.conf', path)
if not isfile(path):
raise ValueError('not a valid file')
return path
@Decorator.argument(argtype=str, requires=['principal', 'user_principal', 'user_keytab'])
def kdc(self, kdc_host):
"""Kerberos kdc hostname:port combination"""
if not isinstance(kdc_host, str):
raise ValueError('expecting `str`, got: {}'.format(type(kdc_host)))
if ':' not in kdc_host or len(kdc_host.split(':')) != 2 or not str(kdc_host.split(':')[-1]).isdigit():
raise ValueError('kdc must contain a host and numerical port separated by ":", '
'kdc invalid: {}'. format(kdc_host))
if not Jvm.is_running():
Jvm.add_argument('java.security.krb5.kdc', '-Djava.security.krb5.kdc={}'.format(kdc_host))
else:
System.set_property('java.security.krb5.kdc', kdc_host)
return kdc_host
@Decorator.argument(argtype=dict)
def hive_conf_list(self, conf_map):
"""
dictionary of key/value pairs of hive configuration variables for the session.
the driver will automatically url encode the variables as needed
"""
raise NotImplementedError('hive_conf_list is not yet supported')
@Decorator.argument(argtype=dict)
def hive_var_list(self, var_map):
"""
dictionary of key/value pairs of Hive variables for this session.
the driver will automatically url encode the variables as needed
"""
raise NotImplementedError('hive_var_list is not yet supported')
|
(*args, **kwargs)
|
714,057 |
hivejdbc
|
hive_conf_list
|
dictionary of key/value pairs of hive configuration variables for the session.
the driver will automatically url encode the variables as needed
|
@Decorator.argument(argtype=dict)
def hive_conf_list(self, conf_map):
"""
dictionary of key/value pairs of hive configuration variables for the session.
the driver will automatically url encode the variables as needed
"""
raise NotImplementedError('hive_conf_list is not yet supported')
|
(self, conf_map)
|
714,058 |
hivejdbc
|
hive_var_list
|
dictionary of key/value pairs of Hive variables for this session.
the driver will automatically url encode the variables as needed
|
@Decorator.argument(argtype=dict)
def hive_var_list(self, var_map):
"""
dictionary of key/value pairs of Hive variables for this session.
the driver will automatically url encode the variables as needed
"""
raise NotImplementedError('hive_var_list is not yet supported')
|
(self, var_map)
|
714,059 |
hivejdbc
|
kdc
|
Kerberos kdc hostname:port combination
|
@Decorator.argument(argtype=str, requires=['principal', 'user_principal', 'user_keytab'])
def kdc(self, kdc_host):
"""Kerberos kdc hostname:port combination"""
if not isinstance(kdc_host, str):
raise ValueError('expecting `str`, got: {}'.format(type(kdc_host)))
if ':' not in kdc_host or len(kdc_host.split(':')) != 2 or not str(kdc_host.split(':')[-1]).isdigit():
raise ValueError('kdc must contain a host and numerical port separated by ":", '
'kdc invalid: {}'. format(kdc_host))
if not Jvm.is_running():
Jvm.add_argument('java.security.krb5.kdc', '-Djava.security.krb5.kdc={}'.format(kdc_host))
else:
System.set_property('java.security.krb5.kdc', kdc_host)
return kdc_host
|
(self, kdc_host)
|
714,060 |
hivejdbc
|
krb5_conf
|
Kerberos krb5.conf - default locations for the file are platform dependent
or set via environment variable: "KRB5_CONFIG" - if your configuration is in a default location you
typically do not need to explicitly provide this configuration.
|
@Decorator.argument(argtype=str, requires=['principal'])
def krb5_conf(self, path):
"""Kerberos krb5.conf - default locations for the file are platform dependent
or set via environment variable: "KRB5_CONFIG" - if your configuration is in a default location you
typically do not need to explicitly provide this configuration."""
if not isinstance(path, str):
raise ValueError('expected `str`, got: {}'.format(type(path)))
if not Jvm.is_running():
Jvm.add_argument('java.security.krb5.conf', '-Djava.security.krb5.conf={}'.format(path))
else:
System.set_property('java.security.krb5.conf', path)
if not isfile(path):
raise ValueError('not a valid file')
return path
|
(self, path)
|
714,062 |
hivejdbc
|
principal
|
Hive SERVICE principal, usually "hive" - should be fully qualified: `hive@EXAMPLE.COM`
|
@Decorator.argument(argtype=str, excludes=['username', 'password'])
def principal(self, user):
"""Hive SERVICE principal, usually "hive" - should be fully qualified: `hive@EXAMPLE.COM`"""
if not isinstance(user, str):
raise ValueError('expected `str`, got: {}'.format(type(user)))
if not Jvm.is_running():
Jvm.add_argument('javax.security.auth.useSubjectCredsOnly',
'-Djavax.security.auth.useSubjectCredsOnly=false')
else:
System.set_property('javax.security.auth.useSubjectCredsOnly', 'false')
return user
|
(self, user)
|
714,063 |
hivejdbc
|
trust_store
|
Path to the java ssl trust-store, generally required if ssl=True
|
@Decorator.argument(argtype=str, requires=['trust_password', 'ssl'])
def trust_store(self, path):
"""Path to the java ssl trust-store, generally required if ssl=True"""
if not isinstance(path, str):
raise ValueError('expected `str`, got: {}'.format(type(path)))
if not isfile(path):
raise ValueError('not a valid file')
return path
|
(self, path)
|
714,064 |
hivejdbc
|
user_keytab
|
Kerberos keytab - if provided the module will attempt kerberos login without the need for ``kinit``
|
@Decorator.argument(argtype=str, requires=['principal', 'user_principal'])
def user_keytab(self, path):
"""Kerberos keytab - if provided the module will attempt kerberos login without the need for ``kinit``"""
if not isinstance(path, str):
raise ValueError('expected `str`, got: {}'.format(type(path)))
if not isfile(path):
raise ValueError('not a valid file')
return path
|
(self, path)
|
714,065 |
hivejdbc
|
HiveConnect
| null |
class HiveConnect(ConnectFunction):
def handle_args(self, args: ConnectArguments):
"""
Handle args is called before the JVM is started
:param args:
:return:
"""
# set driver path from connect function argument `driver`
driver_path = args.get('driver')
self.driver_path = abspath(driver_path) if driver_path else None
# override the cursor class if requested.
if args.get('cursor'):
self.cursor_class = args.get('cursor')
# handle various ways kerberos can be configured:
if args.get('principal'): # kerberos is method of auth
if args.get('user_keytab'):
# if user_keytab is set, this means we are expected to perform the kerberos authentication.
# we'll use jaas to accomplish this.
kerberos.configure_jaas(use_password=False, no_prompt=True, use_ticket_cache=False,
principal=args.user_principal, keytab=args.user_keytab)
elif args.get('principal'):
# If principal is set, but user_keytab is not set, this means we're just looking for an existing
# kinit session to authenticate
# this jaas configuration DOES NOT PROMPT for username/password
# but looks for an existing kerberos ticket created by the operating system or `kinit`
kerberos.configure_jaas(use_password=False, no_prompt=True, use_ticket_cache=True)
else:
pass
if not Jvm.is_running():
# we don't want to see warnings about log4j not being configured, so we'll disable the log4j logger
# this will not prevent other log messages from appearing in stdout
Jvm.add_argument('org.apache.logging.log4j.simplelog.StatusLogger.level',
'-Dorg.apache.logging.log4j.simplelog.StatusLogger.level=OFF')
else:
System.set_property('org.apache.logging.log4j.simplelog.StatusLogger.level', 'OFF')
# if the realm is not set try to set it from the principal
if args.get('kdc') and not args.get('realm'):
args.realm = (kerberos.realm_from_principal(args.principal) or
kerberos.realm_from_principal(args.get('user_principal', '')))
if not args.realm:
raise ValueError('Argument "realm" must be set if "kdc" is set, either explicitly or in '
'the principal name')
if args.get('kdc') and args.get('realm'):
# set the realm
if not Jvm.is_running():
Jvm.add_argument('java.security.krb5.realm', '-Djava.security.krb5.realm={}'.format(args.realm))
else:
System.set_property('java.security.krb5.realm', args.realm)
def get_connection(self, driver_class: JClass, args: ConnectArguments):
"""
Hive specific implementation of JdbcConnection setup
When this method is called the jvm has been started, and the driver_class has been found
see: https://cwiki.apache.org/confluence/display/Hive/HiveServer2+Clients
:param driver_class: HiveDriver `JClass` reference
:type driver_class: org.apache.hive.jdbc.HiveDriver
:param args: Connection arguments containing options derived from ``hivejdbc.HiveArgParser``
:type args: pyjdbc.connect.ConnectArguments
:return: db-api-2 connection instance
:rtype: pyjdbc.dbapi.JdbcConnection
"""
log = logging.getLogger(self.__class__.__name__)
if ',' not in args.host:
check_server(args.host, args.port)
HiveDriver = driver_class
java_props = Properties.from_dict(args.properties or {})
options = []
# Create the Connection String based on Arguments
host_part = 'jdbc:hive2://{host}:{port}/{database}'.format(host=args.host,
port=args.port,
database=args.database)
options.append(host_part)
# -- all options after the database are called "session-variables" ------------------------
# Configure initFile - must be the first option in session-vars
if args.get('init_file'):
options.append('initFile={}'.format(args.init_file))
# username/password support - note that user can be given without password for unsecured hive servers
if args.get('user'):
options.append('user={}'.format(args.user))
if args.get('password'):
options.append('password={}'.format(args.password))
# Configure transport mode
if args.get('transport'):
options.append('transportMode={}'.format(args.transport))
# Configure SSL options
if args.get('ssl'):
options.append('ssl=true')
if args.get('trust_store'):
options.append('sslTrustStore={}'.format(args.trust_store))
if args.get('trust_password'):
options.append('trustStorePassword={}'.format(args.trust_password))
# Configure Kerberos if given
if args.get('principal'):
options.append('principal={}'.format(args.principal))
if args.get('transport') == 'http' and args.get('http_path'):
options.append('httpPath={}'.format(args.http_path))
if args.get('service_discovery_mode'):
options.append('serviceDiscoveryMode={}'.format(args.service_discovery_mode))
options.append('zooKeeperNamespace={}'.format(args.zookeeper_namespace))
conn_str = ';'.join(options)
#if args.get('user_keytab'):
# self.kerberos_login(args)
log.debug('hive connection string: %s', conn_str) # TODO make secure
hive_driver = HiveDriver()
try:
# connect(String url, Properties info)
java_conn = hive_driver.connect(conn_str, java_props)
except JClass('java.sql.SQLException') as e:
# TODO self.handle_exception(e)
raise
return JdbcConnection(connection=java_conn,
cursor_class=self.cursor_class,
type_conversion=self.type_conversion())
def handle_exception(self, exc):
"""
Looks for known exceptions and raises more useful errors.
:param exc:
:return:
"""
# TODO handle known exceptions
# resolve the exception hierarchy so we can search through all exception messages.
hierarchy = []
cause = exc
while True:
cause = getattr(cause, '__cause__', None)
if not cause:
break
else:
hierarchy.append(cause)
def handle_missing_kerberos_ticket(self, exc):
pass
|
(driver_path, driver_class, connection_class=<class 'pyjdbc.dbapi.JdbcConnection'>, cursor_class=<class 'pyjdbc.dbapi.JdbcCursor'>, parser=<class 'pyjdbc.connect.ArgumentParser'>, type_conversion=<class 'pyjdbc.types.JdbcTypeConversion'>, runtime_invocation_ok=True)
|
714,069 |
hivejdbc
|
get_connection
|
Hive specific implementation of JdbcConnection setup
When this method is called the jvm has been started, and the driver_class has been found
see: https://cwiki.apache.org/confluence/display/Hive/HiveServer2+Clients
:param driver_class: HiveDriver `JClass` reference
:type driver_class: org.apache.hive.jdbc.HiveDriver
:param args: Connection arguments containing options derived from ``hivejdbc.HiveArgParser``
:type args: pyjdbc.connect.ConnectArguments
:return: db-api-2 connection instance
:rtype: pyjdbc.dbapi.JdbcConnection
|
def get_connection(self, driver_class: JClass, args: ConnectArguments):
"""
Hive specific implementation of JdbcConnection setup
When this method is called the jvm has been started, and the driver_class has been found
see: https://cwiki.apache.org/confluence/display/Hive/HiveServer2+Clients
:param driver_class: HiveDriver `JClass` reference
:type driver_class: org.apache.hive.jdbc.HiveDriver
:param args: Connection arguments containing options derived from ``hivejdbc.HiveArgParser``
:type args: pyjdbc.connect.ConnectArguments
:return: db-api-2 connection instance
:rtype: pyjdbc.dbapi.JdbcConnection
"""
log = logging.getLogger(self.__class__.__name__)
if ',' not in args.host:
check_server(args.host, args.port)
HiveDriver = driver_class
java_props = Properties.from_dict(args.properties or {})
options = []
# Create the Connection String based on Arguments
host_part = 'jdbc:hive2://{host}:{port}/{database}'.format(host=args.host,
port=args.port,
database=args.database)
options.append(host_part)
# -- all options after the database are called "session-variables" ------------------------
# Configure initFile - must be the first option in session-vars
if args.get('init_file'):
options.append('initFile={}'.format(args.init_file))
# username/password support - note that user can be given without password for unsecured hive servers
if args.get('user'):
options.append('user={}'.format(args.user))
if args.get('password'):
options.append('password={}'.format(args.password))
# Configure transport mode
if args.get('transport'):
options.append('transportMode={}'.format(args.transport))
# Configure SSL options
if args.get('ssl'):
options.append('ssl=true')
if args.get('trust_store'):
options.append('sslTrustStore={}'.format(args.trust_store))
if args.get('trust_password'):
options.append('trustStorePassword={}'.format(args.trust_password))
# Configure Kerberos if given
if args.get('principal'):
options.append('principal={}'.format(args.principal))
if args.get('transport') == 'http' and args.get('http_path'):
options.append('httpPath={}'.format(args.http_path))
if args.get('service_discovery_mode'):
options.append('serviceDiscoveryMode={}'.format(args.service_discovery_mode))
options.append('zooKeeperNamespace={}'.format(args.zookeeper_namespace))
conn_str = ';'.join(options)
#if args.get('user_keytab'):
# self.kerberos_login(args)
log.debug('hive connection string: %s', conn_str) # TODO make secure
hive_driver = HiveDriver()
try:
# connect(String url, Properties info)
java_conn = hive_driver.connect(conn_str, java_props)
except JClass('java.sql.SQLException') as e:
# TODO self.handle_exception(e)
raise
return JdbcConnection(connection=java_conn,
cursor_class=self.cursor_class,
type_conversion=self.type_conversion())
|
(self, driver_class: jpype._jclass.JClass, args: pyjdbc.connect.ConnectArguments)
|
714,070 |
hivejdbc
|
handle_args
|
Handle args is called before the JVM is started
:param args:
:return:
|
def handle_args(self, args: ConnectArguments):
"""
Handle args is called before the JVM is started
:param args:
:return:
"""
# set driver path from connect function argument `driver`
driver_path = args.get('driver')
self.driver_path = abspath(driver_path) if driver_path else None
# override the cursor class if requested.
if args.get('cursor'):
self.cursor_class = args.get('cursor')
# handle various ways kerberos can be configured:
if args.get('principal'): # kerberos is method of auth
if args.get('user_keytab'):
# if user_keytab is set, this means we are expected to perform the kerberos authentication.
# we'll use jaas to accomplish this.
kerberos.configure_jaas(use_password=False, no_prompt=True, use_ticket_cache=False,
principal=args.user_principal, keytab=args.user_keytab)
elif args.get('principal'):
# If principal is set, but user_keytab is not set, this means we're just looking for an existing
# kinit session to authenticate
# this jaas configuration DOES NOT PROMPT for username/password
# but looks for an existing kerberos ticket created by the operating system or `kinit`
kerberos.configure_jaas(use_password=False, no_prompt=True, use_ticket_cache=True)
else:
pass
if not Jvm.is_running():
# we don't want to see warnings about log4j not being configured, so we'll disable the log4j logger
# this will not prevent other log messages from appearing in stdout
Jvm.add_argument('org.apache.logging.log4j.simplelog.StatusLogger.level',
'-Dorg.apache.logging.log4j.simplelog.StatusLogger.level=OFF')
else:
System.set_property('org.apache.logging.log4j.simplelog.StatusLogger.level', 'OFF')
# if the realm is not set try to set it from the principal
if args.get('kdc') and not args.get('realm'):
args.realm = (kerberos.realm_from_principal(args.principal) or
kerberos.realm_from_principal(args.get('user_principal', '')))
if not args.realm:
raise ValueError('Argument "realm" must be set if "kdc" is set, either explicitly or in '
'the principal name')
if args.get('kdc') and args.get('realm'):
# set the realm
if not Jvm.is_running():
Jvm.add_argument('java.security.krb5.realm', '-Djava.security.krb5.realm={}'.format(args.realm))
else:
System.set_property('java.security.krb5.realm', args.realm)
|
(self, args: pyjdbc.connect.ConnectArguments)
|
714,071 |
hivejdbc
|
handle_exception
|
Looks for known exceptions and raises more useful errors.
:param exc:
:return:
|
def handle_exception(self, exc):
"""
Looks for known exceptions and raises more useful errors.
:param exc:
:return:
"""
# TODO handle known exceptions
# resolve the exception hierarchy so we can search through all exception messages.
hierarchy = []
cause = exc
while True:
cause = getattr(cause, '__cause__', None)
if not cause:
break
else:
hierarchy.append(cause)
|
(self, exc)
|
714,072 |
hivejdbc
|
handle_missing_kerberos_ticket
| null |
def handle_missing_kerberos_ticket(self, exc):
pass
|
(self, exc)
|
714,075 |
hivejdbc.types
|
HiveTypeConversion
| null |
class HiveTypeConversion(JdbcTypeConversion):
@jdbctype(getter='getString', setter='setString', pytype=list)
def ARRAY(self, value):
return self.json_str(value)
@jdbctype(getter='getString', setter='setString', pytype=dict)
def STRUCT(self, value):
return self.json_str(value)
@jdbctype(getter='getString', setter='setString', pytype=dict)
def MAP(self, value):
return self.json_str(value)
def json_str(self, value):
"""
Hive does not support ResultSet.getArray() - instead you must decode arrays manually.
the string returned is valid json
see: https://github.com/apache/hive/blob/master/jdbc/src/java/org/apache/hive/jdbc/HiveBaseResultSet.java#L556
"""
value = str(value)
if not value.strip():
return None
try:
return json.loads(value)
except json.JSONDecodeError as e:
raise ValueError('unable to decode Hive json string: {}\nColumn Value:\n{}'.format(e, value))
|
()
|
714,076 |
hivejdbc.types
|
ARRAY
| null |
@jdbctype(getter='getString', setter='setString', pytype=list)
def ARRAY(self, value):
return self.json_str(value)
|
(self, value)
|
714,077 |
pyjdbc.types
|
DATE
| null |
@jdbctype(getter='getDate', setter='setDate', pytype=datetime.datetime)
def DATE(self, value):
# The following code requires Python 3.3+ on dates before year 1900.
dt = datetime.datetime.strptime(str(value)[:10], "%Y-%m-%d")
return dt.strftime("%Y-%m-%d")
|
(self, value)
|
714,078 |
pyjdbc.types
|
DECIMAL
| null |
@jdbctype(getter='getObject', setter='setDecimal')
def DECIMAL(self, value):
return self.decimal_and_numeric(value)
|
(self, value)
|
714,079 |
hivejdbc.types
|
MAP
| null |
@jdbctype(getter='getString', setter='setString', pytype=dict)
def MAP(self, value):
return self.json_str(value)
|
(self, value)
|
714,080 |
pyjdbc.types
|
NUMERIC
| null |
@jdbctype(getter='getObject', setter='setNumeric')
def NUMERIC(self, value):
return self.decimal_and_numeric(value)
|
(self, value)
|
714,081 |
hivejdbc.types
|
STRUCT
| null |
@jdbctype(getter='getString', setter='setString', pytype=dict)
def STRUCT(self, value):
return self.json_str(value)
|
(self, value)
|
714,082 |
pyjdbc.types
|
TIME
| null |
@jdbctype(getter='getTime', setter='setTime', pytype=datetime.time)
def TIME(self, value):
# Jdbc Time format is in: hh:mm:ss
time_str = value.toString()
return datetime.time.strptime(time_str, "%H:%M:%S")
|
(self, value)
|
714,083 |
pyjdbc.types
|
TIMESTAMP
| null |
@jdbctype(getter='getTimestamp', setter='setTimestamp', pytype=datetime.datetime)
def TIMESTAMP(self, value):
dt = datetime.datetime.strptime(str(value)[:19], "%Y-%m-%d %H:%M:%S")
dt = dt.replace(microsecond=int(str(value.getNanos())[:6]))
return dt
|
(self, value)
|
714,084 |
pyjdbc.types
|
__init__
| null |
def __init__(self):
self._jdbc_types = {}
self._configure_jdbc()
|
(self)
|
714,085 |
pyjdbc.types
|
_configure_jdbc
| null |
def _configure_jdbc(self):
for cls in reversed(type(self).mro()):
for obj_name, obj in cls.__dict__.items():
jdbc = getattr(obj, '_jdbctype', None)
if isinstance(obj, JdbcType):
jdbc = obj
elif not jdbc or not isinstance(jdbc, JdbcType):
continue
# if the argument has no name, the property that defines it is the name
if not jdbc.name:
jdbc.name = obj_name
self._jdbc_types[jdbc.name] = jdbc
|
(self)
|
714,086 |
pyjdbc.types
|
decimal_and_numeric
| null |
def decimal_and_numeric(self, value):
if hasattr(value, 'scale'):
scale = value.scale()
if scale == 0:
return int(value.longValue())
else:
return Decimal(value.doubleValue())
else:
return Decimal(value)
|
(self, value)
|
714,087 |
pyjdbc.types
|
jdbc_name
|
Given a jdbc type code return the type name
:param jdbc_code:
:return:
|
def jdbc_name(self, jdbc_code):
"""
Given a jdbc type code return the type name
:param jdbc_code:
:return:
"""
try:
type_name = str(JClass('java.sql.JDBCType').valueOf(jdbc_code)).upper()
except Exception as e:
raise ValueError('unable to resolve jdbc type code: {}'.format(jdbc_code)) from e
return type_name
|
(self, jdbc_code)
|
714,088 |
pyjdbc.types
|
jdbc_type
|
:param jdbc_name: the jdbc type name (capitalized)
:param default: default value to return if jdbc type isn't matched
:return: JdbcType object that contains type mapping logic
:rtype: JdbcType
|
def jdbc_type(self, jdbc_name, default=None):
"""
:param jdbc_name: the jdbc type name (capitalized)
:param default: default value to return if jdbc type isn't matched
:return: JdbcType object that contains type mapping logic
:rtype: JdbcType
"""
return self._jdbc_types.get(jdbc_name, default)
|
(self, jdbc_name, default=None)
|
714,089 |
pyjdbc.types
|
jdbc_value
|
Convert a python value to a JDBC value
:param pyvalue:
:param resultset:
:param jdbc_code:
:param jdbc_name:
:return:
|
def jdbc_value(self, pyvalue, resultset, jdbc_code, jdbc_name):
"""
Convert a python value to a JDBC value
:param pyvalue:
:param resultset:
:param jdbc_code:
:param jdbc_name:
:return:
"""
return
|
(self, pyvalue, resultset, jdbc_code, jdbc_name)
|
714,090 |
hivejdbc.types
|
json_str
|
Hive does not support ResultSet.getArray() - instead you must decode arrays manually.
the string returned is valid json
see: https://github.com/apache/hive/blob/master/jdbc/src/java/org/apache/hive/jdbc/HiveBaseResultSet.java#L556
|
def json_str(self, value):
"""
Hive does not support ResultSet.getArray() - instead you must decode arrays manually.
the string returned is valid json
see: https://github.com/apache/hive/blob/master/jdbc/src/java/org/apache/hive/jdbc/HiveBaseResultSet.java#L556
"""
value = str(value)
if not value.strip():
return None
try:
return json.loads(value)
except json.JSONDecodeError as e:
raise ValueError('unable to decode Hive json string: {}\nColumn Value:\n{}'.format(e, value))
|
(self, value)
|
714,091 |
pyjdbc.types
|
py_type
|
Get the python type associated with the given jdbc_type
:param jdbc_code:
:param jdbc_name:
:return:
|
def py_type(self, jdbc_code=None, jdbc_name=None):
"""
Get the python type associated with the given jdbc_type
:param jdbc_code:
:param jdbc_name:
:return:
"""
if jdbc_code is not None:
type_name = self.jdbc_name(jdbc_code)
elif jdbc_name is not None:
type_name = jdbc_name.upper()
else:
raise ValueError('one of `jdbc_code` or `jdbc_name` must be provided')
mapper = self.jdbc_type(type_name, self.JDBC_DEFAULT)
return mapper.pytype
|
(self, jdbc_code=None, jdbc_name=None)
|
714,092 |
pyjdbc.types
|
py_value
|
Retrieve the python value for the given type
:param resultset: Java ResultSet object
:param column: Column index to retrieve value from
:param jdbc_code: JDBCType code
:param jdbc_name: JDBCType name (optional)
:return:
|
def py_value(self, resultset, column_idx, jdbc_code=None, jdbc_name=None):
"""
Retrieve the python value for the given type
:param resultset: Java ResultSet object
:param column: Column index to retrieve value from
:param jdbc_code: JDBCType code
:param jdbc_name: JDBCType name (optional)
:return:
"""
# if the value is null return None
if resultset.wasNull():
return
if not isinstance(column_idx, int):
raise ValueError('"column" invalid type, expected `int` got: {}'.format(type(column_idx)))
if column_idx < 1:
raise ValueError('"column" invalid value: {} - jdbc columns must be 1 or greater'.format(column_idx))
if jdbc_code is not None:
type_name = self.jdbc_name(jdbc_code)
elif jdbc_name is not None:
type_name = jdbc_name.upper()
else:
raise ValueError('one of `jdbc_code` or `jdbc_name` must be provided')
# get "converter" the JdbcType object that will inform us how to map this value to python
converter = self.jdbc_type(type_name, self.JDBC_DEFAULT)
if converter.resultset:
# if resultset is true, this means the function signature should pass (resultset, column-index)
if not callable(converter.fn):
raise ValueError('JdbcType "{}" has no function associated, but resultset=True'.format(converter.name))
try:
if converter.decorator:
return converter.fn(self, resultset, column_idx)
else:
return converter.fn(resultset, column_idx)
except Exception as e:
raise ValueError('error converting "{}" to "{}" - via resultset function: "{}", Error: {}'.format(
type_name, converter.pytype, converter.name, e
)) from e
else:
# it's our responsibility to use the "getter" to retrieve the value automatically
try:
get_value = getattr(resultset, converter.getter)
except Exception as e:
raise AttributeError('JdbcType: {} - unable to find method named {}'.format(
type_name, converter.getter
)) from e
try:
jdbc_value = get_value(column_idx)
except Exception as e:
raise AttributeError('JdbcType: {} - unable to get value via {} - {}'.format(
type_name, converter.getter, str(e)
)) from e
# if the value is null return None
if resultset.wasNull() or jdbc_value is None:
return
# call the conversion function if its been set.
if converter.fn is not None:
if converter.decorator:
jdbc_value = converter.fn(self, jdbc_value)
else:
jdbc_value = converter.fn(jdbc_value)
# don't try to apply a type if the type is set to "object" or if its None
# object means "any type"
elif converter.pytype is not None and converter.pytype is not object:
try:
if callable(converter.pytype):
jdbc_value = converter.pytype(jdbc_value)
if not isinstance(jdbc_value, converter.pytype):
raise ValueError('unexpected type {}, expected: {}'.format(type(jdbc_value)), converter.pytype)
except Exception as e:
raise ValueError('error converting "{}" to "{}" - {}'.format(
type_name, converter.pytype, e
)) from e
return jdbc_value
|
(self, resultset, column_idx, jdbc_code=None, jdbc_name=None)
|
714,093 |
jpype._jclass
|
JClass
|
Meta class for all Java class instances.
When called as an object, JClass will contruct a new Java class wrapper.
All Python wrappers for Java classes derive from this type.
To test if a Python class is a Java wrapper use
``isinstance(obj, jpype.JClass)``.
Args:
className (str): name of a Java type.
Keyword Args:
loader (java.lang.ClassLoader): specifies a class loader to use
when creating a class.
initialize (bool): If true the class will be loaded and initialized.
Otherwise, static members will be uninitialized.
Returns:
JavaClass: a new wrapper for a Java class
Raises:
TypeError: if the component class is invalid or could not be found.
|
class JClass(_jpype._JClass, metaclass=JClassMeta):
"""Meta class for all Java class instances.
When called as an object, JClass will contruct a new Java class wrapper.
All Python wrappers for Java classes derive from this type.
To test if a Python class is a Java wrapper use
``isinstance(obj, jpype.JClass)``.
Args:
className (str): name of a Java type.
Keyword Args:
loader (java.lang.ClassLoader): specifies a class loader to use
when creating a class.
initialize (bool): If true the class will be loaded and initialized.
Otherwise, static members will be uninitialized.
Returns:
JavaClass: a new wrapper for a Java class
Raises:
TypeError: if the component class is invalid or could not be found.
"""
def __new__(cls, jc, loader=None, initialize=True):
if loader and isinstance(jc, str):
jc = _jpype._java_lang_Class.forName(jc, initialize, loader)
# Handle generics
if isinstance(jc, str) and jc.endswith(">"):
i = jc.find("<")
params = jc[i + 1:-1]
ret = _jpype._getClass(jc[:i])
acceptParams = len(ret.class_.getTypeParameters())
if acceptParams == 0:
raise TypeError(
"Java class '%s' does not take parameters" % (ret.__name__))
if len(params) > 0:
params = params.split(',')
if len(params) > 0 and len(params) != len(ret.class_.getTypeParameters()):
raise TypeError(
"Java generic class '%s' length mismatch" % (ret.__name__))
return ret
# Pass to class factory to create the type
return _jpype._getClass(jc)
|
(jc, loader=None, initialize=True)
|
714,094 |
jpype._jclass
|
__new__
| null |
def __new__(cls, jc, loader=None, initialize=True):
if loader and isinstance(jc, str):
jc = _jpype._java_lang_Class.forName(jc, initialize, loader)
# Handle generics
if isinstance(jc, str) and jc.endswith(">"):
i = jc.find("<")
params = jc[i + 1:-1]
ret = _jpype._getClass(jc[:i])
acceptParams = len(ret.class_.getTypeParameters())
if acceptParams == 0:
raise TypeError(
"Java class '%s' does not take parameters" % (ret.__name__))
if len(params) > 0:
params = params.split(',')
if len(params) > 0 and len(params) != len(ret.class_.getTypeParameters()):
raise TypeError(
"Java generic class '%s' length mismatch" % (ret.__name__))
return ret
# Pass to class factory to create the type
return _jpype._getClass(jc)
|
(cls, jc, loader=None, initialize=True)
|
714,095 |
pyjdbc.dbapi
|
JdbcConnection
| null |
class JdbcConnection:
def __init__(self, connection, cursor_class, type_conversion=None):
"""
:param connection: java.sql.Connection
:param cursor_class: pyjdbc.dbapi.JdbcCursor or subclass
:param type_conversion:
"""
self._connection = connection
self._cursor_class = cursor_class
self._type_conversion = type_conversion
if not issubclass(cursor_class, JdbcCursor):
raise ValueError('"cursor_class" must be instance of {}, got: {}, {}'.format(
JdbcCursor.__name__,
type(cursor_class),
getattr(cursor_class, '__name__')
))
if not isinstance(type_conversion, JdbcTypeConversion):
raise ValueError('"type_conversion" must be instance of {}, got: {}'.format(
JdbcTypeConversion.__name__,
type(type_conversion)
))
def is_closed(self):
return self._connection.isClosed()
def jdbc_connection(self):
return self._connection
def close(self):
if self._connection.isClosed():
raise Error('Connection already closed')
self._connection.close()
def commit(self):
# TODO exception handling
self._connection.commit()
def rollback(self):
# TODO exception handling
self._connection.rollback()
def cursor(self):
"""
Create a new cursor
:return:
:rtype: JdbcCursor
"""
return self._cursor_class(self, self._type_conversion)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
|
(connection, cursor_class, type_conversion=None)
|
714,098 |
pyjdbc.dbapi
|
__init__
|
:param connection: java.sql.Connection
:param cursor_class: pyjdbc.dbapi.JdbcCursor or subclass
:param type_conversion:
|
def __init__(self, connection, cursor_class, type_conversion=None):
"""
:param connection: java.sql.Connection
:param cursor_class: pyjdbc.dbapi.JdbcCursor or subclass
:param type_conversion:
"""
self._connection = connection
self._cursor_class = cursor_class
self._type_conversion = type_conversion
if not issubclass(cursor_class, JdbcCursor):
raise ValueError('"cursor_class" must be instance of {}, got: {}, {}'.format(
JdbcCursor.__name__,
type(cursor_class),
getattr(cursor_class, '__name__')
))
if not isinstance(type_conversion, JdbcTypeConversion):
raise ValueError('"type_conversion" must be instance of {}, got: {}'.format(
JdbcTypeConversion.__name__,
type(type_conversion)
))
|
(self, connection, cursor_class, type_conversion=None)
|
714,099 |
pyjdbc.dbapi
|
close
| null |
def close(self):
if self._connection.isClosed():
raise Error('Connection already closed')
self._connection.close()
|
(self)
|
714,100 |
pyjdbc.dbapi
|
commit
| null |
def commit(self):
# TODO exception handling
self._connection.commit()
|
(self)
|
714,101 |
pyjdbc.dbapi
|
cursor
|
Create a new cursor
:return:
:rtype: JdbcCursor
|
def cursor(self):
"""
Create a new cursor
:return:
:rtype: JdbcCursor
"""
return self._cursor_class(self, self._type_conversion)
|
(self)
|
714,102 |
pyjdbc.dbapi
|
is_closed
| null |
def is_closed(self):
return self._connection.isClosed()
|
(self)
|
714,103 |
pyjdbc.dbapi
|
jdbc_connection
| null |
def jdbc_connection(self):
return self._connection
|
(self)
|
714,104 |
pyjdbc.dbapi
|
rollback
| null |
def rollback(self):
# TODO exception handling
self._connection.rollback()
|
(self)
|
714,105 |
pyjdbc.dbapi
|
JdbcCursor
| null |
class JdbcCursor:
batch_size = 1
def __init__(self, connection: JdbcConnection, type_conversion, rowcounts=True):
self._connection = connection
self._type_conversion = type_conversion
self._description = None
self._metadata = None
self._statement = None
self._resultset = None
self._rowcount = -1
self._get_rowcounts = rowcounts
if not isinstance(connection, JdbcConnection):
raise ValueError('"connection" arg must be instance of {}'.format(str(JdbcConnection)))
@property
def rowcount(self):
"""
cursor rowcount
returns -1 for unknown rowcount
:return: rowcount
:rtype: int
"""
return self._rowcount
@property
def column_names(self):
"""
By default jdbc drivers return prefixed column names
Returns non-prefixed column names, preserves prefix only when ambiguity exists
:return:
"""
if not self._metadata:
return None
meta = self._metadata
columns = range(1, meta.getColumnCount() + 1)
names = [str(meta.getColumnName(col)) for col in columns]
if not names:
return
# detect common prefix - if all columns are prefixed with the same table-name, remove that
# prefix. There can be no ambiguity so the prefix is not needed.
if '.' in names[0]:
prefix = names[0].split('.', 1)[-1] + '.'
if all([n.startswith(prefix) for n in names]):
names = [names.replace(prefix, '', 1)]
else:
# it's also possible all the column names are unique without a prefix
no_prefix = [n.split('.', 1)[1] for n in names]
if len(set(no_prefix)) == len(names):
names = no_prefix
return names
@property
def description(self):
if self._description:
return self._description
if not self._metadata:
return
meta = self._metadata
count = meta.getColumnCount()
self._description = []
for col in range(1, count + 1):
size = meta.getColumnDisplaySize(col)
jdbc_type = meta.getColumnType(col)
if jdbc_type == 0: # NULL
type_desc = 'NULL'
else:
dbapi_type = self._type_conversion.py_type(jdbc_type)
dbapi_type_str = getattr(dbapi_type, '__name__', None) or str(dbapi_type)
jdbc_type_name = (self._type_conversion.jdbc_name(jdbc_type) or str(meta.getColumnTypeName(col)).upper())
type_desc = '{} - JDBC:{}'.format(dbapi_type_str, jdbc_type_name)
# some drivers return Integer.MAX_VALUE when the metadata is not present
max_int = JClass('java.lang.Integer').MAX_VALUE
size = size if size != max_int else None
precision = meta.getPrecision(col)
precision = precision if precision != max_int else None
scale = meta.getScale(col)
scale = scale if scale != max_int else None
col_desc = (meta.getColumnName(col), # name
type_desc, # type_code
size, # display_size
size, # internal_size
precision, # precision
scale, # scale
meta.isNullable(col)) # null_ok
self._description.append(col_desc)
return self._description
def _clear_metadata(self):
self._metadata = None
self._description = None
def _clear_connection(self):
self._connection = None
def _close_statement(self):
if self._statement:
self._statement.close()
self._statement = None
def _close_resultset(self):
if self._resultset_valid():
self._resultset.close()
self._resultset = None
def _connection_valid(self):
return not self._connection.is_closed()
def _resultset_valid(self):
return bool(self._resultset)
def close(self):
"""
close the cursor, the cursor cannot be used again.
:return:
"""
# close all open resources.
self._clear_connection()
self._clear_metadata()
try:
self._close_statement()
except Exception:
pass
try:
self._close_resultset()
except Exception:
pass
def _reset(self):
# close any previously used resources
self._clear_metadata()
self._close_statement()
self._close_resultset()
def _warnings(self):
if not self._resultset_valid():
return ''
warning = self._resultset.getWarnings()
if not warning:
return ''
try:
return 'cursor warning: {}'.format(str(warning.getMessage()))
except Exception:
return ''
def _check_params(self, params):
if isinstance(params, dict):
return
if not isinstance(params, Sequence) or isinstance(params, (str, bytes)):
raise ValueError('parameters must be a sequence or a dictionary, got: {}'.format(type(params)))
def _parse_params(self, sql, params):
"""
Parse %s style or ":name" style parameters.
If use :name style parameters, ``params`` must be a dictionary.
:param sql: sql statement
:param params: parameters (sequence or dictionary)
:return:
"""
if not params:
raise ValueError('params must be `None` or a non empty sequence or dictionary, got: {}'.format(params))
orig_params = copy(params)
self._check_params(params)
if isinstance(params, dict):
try:
# convert ":param" to ? parameters
query = sqlparams.SQLParams('named', 'qmark')
operation, params = query.format(sql, params)
except KeyError as e:
key = e.args[0]
raise ValueError('":{}" is missing from parameters template in statement: "{}"'
'\nParameters: {}'.format(key, sql, dict(orig_params)))
# sqlparams will not check for un-consumed keyword parameters
# this is an error because the user is passing in arguments that are not being used by the query
if len(params) < len(orig_params):
missing = ['":{}"'.format(key) for key in orig_params if ':{}'.format(key) not in sql]
raise ValueError('sql statement is missing named template paramaters:\n ({})\n'
'given paramaters:\n {}\n'
'in query:\n{}'.format(
', '.join(map(str, missing)),
str(dict(orig_params)),
textwrap.indent(sql.strip(), ' '*4)))
else:
try:
# convert %s to ? parameters
query = sqlparams.SQLParams('format', 'qmark')
operation, params = query.format(sql, params)
except IndexError as e:
fmt_count = sql.count('%s')
raise ValueError('`params` contains incorrect number of arguments for "%s"'
'templates in query.\n'
'expected: [{}] arguments, got: [{}]'.format(fmt_count, len(params)))
# sqlparams will not check for un-consumed or un-needed positional parameters
extra_args = len(orig_params) - len(params)
if extra_args:
raise ValueError('`params` contains {} more elements than were consumed by query templates:\n{}\n'
'arguments given: [{}]\nunused: [{}]'.format(
extra_args,
textwrap.indent(sql.strip(), ' '*4),
', '.join(map(str, orig_params)),
', '.join(map(str, orig_params[len(params):]))))
return operation, params
def execute(self, operation, params=None):
"""
Execute a sql statement with an optional set of parameters
:param operation: Sql text
:param params: a sequence or dictionary of parameters
Parameters can be positional templates ``%s`` or named templates ``:name``
:param operation:
:param params:
:return:
"""
if not self._connection_valid():
raise Error('the connection has been closed')
self._reset()
conn = self._connection.jdbc_connection()
# handle parameters
if params is not None:
operation, params = self._parse_params(operation, params)
# prepare the statement
self._statement = stmt = conn.prepareStatement(operation)
stmt.clearParameters()
for column, value in enumerate(params or [], start=1):
# note that in JDBC the first column index is 1
if isinstance(value, str):
jvalue = JString(value)
stmt.setString(column, jvalue)
elif isinstance(value, float):
jvalue = JDouble(value)
stmt.setDouble(column, jvalue)
elif isinstance(value, int):
try:
jvalue = JInt(value)
stmt.setInt(column, jvalue)
except Exception:
jvalue = JLong(value)
stmt.setLong(column, jvalue)
elif isinstance(value, bool):
jvalue = JBoolean(value)
stmt.setBoolean(column, jvalue)
elif isinstance(value, bytes):
ByteArray = JArray(JByte)
jvalue = ByteArray(value.decode('utf-8'))
stmt.setBytes(column, jvalue)
else:
stmt.setObject(column, value)
try:
has_resultset = stmt.execute()
except JClass('org.apache.hive.service.cli.HiveSQLException') as e:
raise ProgrammingError('Error executing statement:\n{}\n{}'.format(operation, e)) from None
self._rowcount = -1
if has_resultset:
self._resultset = resultset = stmt.getResultSet()
self._metadata = resultset.getMetaData()
# get rowcount
if self._get_rowcounts:
try:
if self._resultset.last(): # if the cursor can be moved to the last row.
self._rowcount = resultset.getRow()
resultset.beforeFirst()
except JClass('java.sql.SQLException'):
# ResultSet.last() is not supported
pass
else:
try:
self._rowcount = stmt.getUpdateCount()
except JClass('java.sql.SQLException'):
# not supported
pass
def executemany(self, operation, seq_of_parameters):
"""
Execute many statements each with a different set of parameters
:param operation: Sql text
:param seq_of_parameters: a sequence of sequences containing parameters to pass into `operation`
Parameters can be positional templates ``%s`` or named templates ``:name``
:return:
"""
try:
orig_sql = operation
self._reset()
conn = self._connection.jdbc_connection()
self._statement = stmt = conn.prepareStatement(operation)
for params in seq_of_parameters:
if params is not None:
operation, params = self._parse_params(operation, params)
for column, value in enumerate(params or [], start=1):
stmt.setObject(column, value)
stmt.addBatch()
batch_rowcounts = stmt.executeBatch()
self._rowcount = sum(batch_rowcounts)
self._reset()
except JClass('java.sql.SQLException') as e:
# addBatch/executeBatch not supported
rowcount = 0
for params in seq_of_parameters:
self.execute(orig_sql, params)
if self._rowcount > 0:
rowcount += self._rowcount
self._rowcount = rowcount if self._get_rowcounts else -1
def fetchone(self):
if not self._resultset_valid():
raise DatabaseError('result set is no longer valid ' + self._warnings())
if not self._resultset.next():
return None # end of result set
row = []
num_cols = self._metadata.getColumnCount()
for column_number in range(1, num_cols + 1):
jdbc_type = self._metadata.getColumnType(column_number)
pyvalue = self._type_conversion.py_value(self._resultset, column_idx=column_number, jdbc_code=jdbc_type)
row.append(pyvalue)
return tuple(row)
def fetchmany(self, size=None):
# TODO implement this in a java class
if not self._resultset_valid():
raise DatabaseError('result set is no longer valid ' + self._warnings())
if size is None:
size = self.batch_size
# TODO: handle SQLException if not supported by db
self._resultset.setFetchSize(size)
rows = []
row = None
for i in range(size):
row = self.fetchone()
if row is None:
break
else:
rows.append(row)
# reset fetch size
if row:
# TODO: handle SQLException if not supported by db
self._resultset.setFetchSize(0)
return rows
def fetchall(self):
rows = []
while True:
row = self.fetchone()
if row is None:
break
else:
rows.append(row)
return rows
def __iter__(self):
while True:
row = self.fetchone()
if row is None:
break
else:
yield row
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
|
(connection: pyjdbc.dbapi.JdbcConnection, type_conversion, rowcounts=True)
|
714,125 |
pyjdbc.dbapi
|
fetchone
| null |
def fetchone(self):
if not self._resultset_valid():
raise DatabaseError('result set is no longer valid ' + self._warnings())
if not self._resultset.next():
return None # end of result set
row = []
num_cols = self._metadata.getColumnCount()
for column_number in range(1, num_cols + 1):
jdbc_type = self._metadata.getColumnType(column_number)
pyvalue = self._type_conversion.py_value(self._resultset, column_idx=column_number, jdbc_code=jdbc_type)
row.append(pyvalue)
return tuple(row)
|
(self)
|
714,126 |
pyjdbc.dbapi
|
JdbcDictCursor
| null |
class JdbcDictCursor(JdbcCursor):
def fetchone(self):
row = super().fetchone()
if row:
names = self.column_names
return dict(zip(names, row))
|
(connection: pyjdbc.dbapi.JdbcConnection, type_conversion, rowcounts=True)
|
714,147 |
pyjdbc.java
|
Jvm
| null |
class Jvm:
ARGS = {}
@classmethod
def add_argument(cls, identifier, option):
"""
Add an argument to the jvm, (this must be used BEFORE the jvm is started)
If the jvm is already running RuntimeError will be raised
Set a jvm argument, examples include:
-Xmx1099m
-Djava.class.path=PATH_TO_JAR
:param identifier: a string identifier so Jvm options aren't duplicated: ie: ``javax.net.ssl.trustStore``
:type identifier: str
:param option: the full jvm option argument, ie: ``-Djavax.net.ssl.trustStore=trust.jks``
:type option: str
:raises: RuntimeError
:return:
"""
if cls.is_running():
raise RuntimeError('The JVM has been started, any options set after the JVM is started will have no '
'effect.\n'
'Set jvm options before acquiring any connections with `pyjdbc`')
if not any((option.startswith('-D'), option.startswith('-X'))):
raise ValueError('invalid argument "option": {}, jvm arguments must start with "-D" or "-X" \n'
'Examples:\n'
' -Xmx1099m\n',
' -Djavax.net.ssl.trustStore=trust.jks'.format(option))
cls.ARGS[identifier] = option
@classmethod
def start(cls):
# start the jvm
jpype.startJVM(*cls.ARGS.values(), interrupt=True)
@staticmethod
def stop():
jpype.shutdownJVM()
@staticmethod
def is_running():
return jpype.isJVMStarted()
@classmethod
def check_running(cls):
if cls.is_running():
raise RuntimeError('The jvm is already running')
@staticmethod
def path():
return jpype.getDefaultJVMPath()
@staticmethod
def version():
return jpype.getJVMVersion()
|
()
|
714,148 |
pyjdbc.java
|
is_running
| null |
@staticmethod
def is_running():
return jpype.isJVMStarted()
|
()
|
714,149 |
pyjdbc.java
|
path
| null |
@staticmethod
def path():
return jpype.getDefaultJVMPath()
|
()
|
714,150 |
pyjdbc.java
|
stop
| null |
@staticmethod
def stop():
jpype.shutdownJVM()
|
()
|
714,151 |
pyjdbc.java
|
version
| null |
@staticmethod
def version():
return jpype.getJVMVersion()
|
()
|
714,152 |
pyjdbc.java
|
Properties
| null |
class Properties:
PROPERTIES_CLASS = 'java.util.Properties'
@classmethod
def from_dict(cls, dictionary):
JProperties = JClass(cls.PROPERTIES_CLASS)
jprops = JProperties()
for k, v in dictionary.items():
if not isinstance(k, str):
raise ValueError('[{}] keys must be strings, got: {}'.format(cls.PROPERTIES_CLASS, type(k)))
jprops.setProperty(k, v)
return jprops
@classmethod
def from_tuple(cls, sequence):
as_dict = dict(sequence)
return cls.from_dict(as_dict)
@staticmethod
def to_dict(properties):
keys = properties.stringPropertyNames()
dictionary = {key: properties.getProperty(key) for key in keys}
return dictionary
@staticmethod
def to_tuple(properties):
keys = properties.stringPropertyNames()
sequence = [(key, properties.getProperty(key)) for key in keys]
return sequence
|
()
|
714,153 |
pyjdbc.java
|
to_dict
| null |
@staticmethod
def to_dict(properties):
keys = properties.stringPropertyNames()
dictionary = {key: properties.getProperty(key) for key in keys}
return dictionary
|
(properties)
|
714,154 |
pyjdbc.java
|
to_tuple
| null |
@staticmethod
def to_tuple(properties):
keys = properties.stringPropertyNames()
sequence = [(key, properties.getProperty(key)) for key in keys]
return sequence
|
(properties)
|
714,155 |
pyjdbc.java
|
System
|
Wrapper around java.lang.System
|
class System:
"""
Wrapper around java.lang.System
"""
@staticmethod
def _system():
return JClass('java.lang.System')
@classmethod
def get_property(cls, name):
return cls._system().getProperty(name)
@classmethod
def set_property(cls, name, value):
cls._system().setProperty(name, value)
@classmethod
def clear_property(cls, name):
return cls._system().clearProperty(name)
@classmethod
def get_env(cls, name):
return cls._system().getenv(name)
|
()
|
714,156 |
pyjdbc.java
|
_system
| null |
@staticmethod
def _system():
return JClass('java.lang.System')
|
()
|
714,158 |
hivejdbc
|
check_server
| null |
def check_server(hostname, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
ipaddress.ip_address(hostname)
except ValueError:
try:
address = socket.gethostbyname(hostname.strip())
except socket.gaierror as e:
raise Error('Hive server at "{}:{}" is not reachable - {}'.format(hostname, port, e))
else:
address = hostname
try:
s.connect((address, int(port)))
s.shutdown(2)
except Exception as e:
raise Error('No Hive server is listening at "{}:{}" - {}'.format(hostname, port, e))
|
(hostname, port)
|
714,170 |
apispec_oneofschema.plugin
|
MarshmallowPlugin
| null |
class MarshmallowPlugin(marshmallow.MarshmallowPlugin):
Converter = OneofOpenAPIConverter
|
(schema_name_resolver: 'typing.Callable[[type[Schema]], str] | None' = None) -> 'None'
|
714,171 |
apispec.ext.marshmallow
|
__init__
| null |
def __init__(
self,
schema_name_resolver: typing.Callable[[type[Schema]], str] | None = None,
) -> None:
super().__init__()
self.schema_name_resolver = schema_name_resolver or resolver
self.spec: APISpec | None = None
self.openapi_version: Version | None = None
self.converter: OpenAPIConverter | None = None
self.resolver: SchemaResolver | None = None
|
(self, schema_name_resolver: Optional[Callable[[type[marshmallow.schema.Schema]], str]] = None) -> NoneType
|
714,172 |
apispec.ext.marshmallow
|
header_helper
|
Header component helper that allows using a marshmallow
:class:`Schema <marshmallow.Schema>` in header definition.
:param dict header: header fields. May contain a marshmallow
Schema class or instance.
|
def header_helper(self, header: dict, **kwargs: typing.Any):
"""Header component helper that allows using a marshmallow
:class:`Schema <marshmallow.Schema>` in header definition.
:param dict header: header fields. May contain a marshmallow
Schema class or instance.
"""
assert self.resolver # needed for mypy
self.resolver.resolve_schema(header)
return header
|
(self, header: dict, **kwargs: Any)
|
714,173 |
apispec.ext.marshmallow
|
init_spec
| null |
def init_spec(self, spec: APISpec) -> None:
super().init_spec(spec)
self.spec = spec
self.openapi_version = spec.openapi_version
self.converter = self.Converter(
openapi_version=spec.openapi_version,
schema_name_resolver=self.schema_name_resolver,
spec=spec,
)
self.resolver = self.Resolver(
openapi_version=spec.openapi_version, converter=self.converter
)
|
(self, spec: apispec.core.APISpec) -> NoneType
|
714,174 |
apispec.ext.marshmallow
|
map_to_openapi_type
|
Set mapping for custom field class.
:param type field_cls: Field class to set mapping for.
``*args`` can be:
- a pair of the form ``(type, format)``
- a core marshmallow field type (in which case we reuse that type's mapping)
Examples: ::
# Override Integer mapping
class Int32(Integer):
# ...
ma_plugin.map_to_openapi_type(Int32, 'string', 'int32')
# Map to ('integer', None) like Integer
class IntegerLike(Integer):
# ...
ma_plugin.map_to_openapi_type(IntegerLike, Integer)
|
def map_to_openapi_type(self, field_cls, *args):
"""Set mapping for custom field class.
:param type field_cls: Field class to set mapping for.
``*args`` can be:
- a pair of the form ``(type, format)``
- a core marshmallow field type (in which case we reuse that type's mapping)
Examples: ::
# Override Integer mapping
class Int32(Integer):
# ...
ma_plugin.map_to_openapi_type(Int32, 'string', 'int32')
# Map to ('integer', None) like Integer
class IntegerLike(Integer):
# ...
ma_plugin.map_to_openapi_type(IntegerLike, Integer)
"""
assert self.converter is not None, "init_spec has not yet been called"
return self.converter.map_to_openapi_type(field_cls, *args)
|
(self, field_cls, *args)
|
714,175 |
apispec.ext.marshmallow
|
operation_helper
| null |
def operation_helper(
self,
path: str | None = None,
operations: dict | None = None,
**kwargs: typing.Any,
) -> None:
assert self.resolver # needed for mypy
self.resolver.resolve_operations(operations)
|
(self, path: Optional[str] = None, operations: Optional[dict] = None, **kwargs: Any) -> NoneType
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.