repository_name
stringlengths 7
55
| func_path_in_repository
stringlengths 4
223
| func_name
stringlengths 1
134
| whole_func_string
stringlengths 75
104k
| language
stringclasses 1
value | func_code_string
stringlengths 75
104k
| func_code_tokens
sequencelengths 19
28.4k
| func_documentation_string
stringlengths 1
46.9k
| func_documentation_tokens
sequencelengths 1
1.97k
| split_name
stringclasses 1
value | func_code_url
stringlengths 87
315
|
---|---|---|---|---|---|---|---|---|---|---|
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | docx_docx_gen_text | def docx_docx_gen_text(doc: DOCX_DOCUMENT_TYPE,
config: TextProcessingConfig) -> Iterator[str]:
# only called if docx loaded
"""
Iterate through a DOCX file and yield text.
Args:
doc: DOCX document to process
config: :class:`TextProcessingConfig` control object
Yields:
pieces of text (paragraphs)
"""
if in_order:
for thing in docx_docx_iter_block_items(doc):
if isinstance(thing, docx.text.paragraph.Paragraph):
yield docx_process_simple_text(thing.text, config.width)
elif isinstance(thing, docx.table.Table):
yield docx_process_table(thing, config)
else:
for paragraph in doc.paragraphs:
yield docx_process_simple_text(paragraph.text, config.width)
for table in doc.tables:
yield docx_process_table(table, config) | python | def docx_docx_gen_text(doc: DOCX_DOCUMENT_TYPE,
config: TextProcessingConfig) -> Iterator[str]:
# only called if docx loaded
"""
Iterate through a DOCX file and yield text.
Args:
doc: DOCX document to process
config: :class:`TextProcessingConfig` control object
Yields:
pieces of text (paragraphs)
"""
if in_order:
for thing in docx_docx_iter_block_items(doc):
if isinstance(thing, docx.text.paragraph.Paragraph):
yield docx_process_simple_text(thing.text, config.width)
elif isinstance(thing, docx.table.Table):
yield docx_process_table(thing, config)
else:
for paragraph in doc.paragraphs:
yield docx_process_simple_text(paragraph.text, config.width)
for table in doc.tables:
yield docx_process_table(table, config) | [
"def",
"docx_docx_gen_text",
"(",
"doc",
":",
"DOCX_DOCUMENT_TYPE",
",",
"config",
":",
"TextProcessingConfig",
")",
"->",
"Iterator",
"[",
"str",
"]",
":",
"# only called if docx loaded",
"if",
"in_order",
":",
"for",
"thing",
"in",
"docx_docx_iter_block_items",
"(",
"doc",
")",
":",
"if",
"isinstance",
"(",
"thing",
",",
"docx",
".",
"text",
".",
"paragraph",
".",
"Paragraph",
")",
":",
"yield",
"docx_process_simple_text",
"(",
"thing",
".",
"text",
",",
"config",
".",
"width",
")",
"elif",
"isinstance",
"(",
"thing",
",",
"docx",
".",
"table",
".",
"Table",
")",
":",
"yield",
"docx_process_table",
"(",
"thing",
",",
"config",
")",
"else",
":",
"for",
"paragraph",
"in",
"doc",
".",
"paragraphs",
":",
"yield",
"docx_process_simple_text",
"(",
"paragraph",
".",
"text",
",",
"config",
".",
"width",
")",
"for",
"table",
"in",
"doc",
".",
"tables",
":",
"yield",
"docx_process_table",
"(",
"table",
",",
"config",
")"
] | Iterate through a DOCX file and yield text.
Args:
doc: DOCX document to process
config: :class:`TextProcessingConfig` control object
Yields:
pieces of text (paragraphs) | [
"Iterate",
"through",
"a",
"DOCX",
"file",
"and",
"yield",
"text",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L840-L864 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | convert_docx_to_text | def convert_docx_to_text(
filename: str = None, blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts a DOCX file to text.
Pass either a filename or a binary object.
Args:
filename: filename to process
blob: binary ``bytes`` object to process
config: :class:`TextProcessingConfig` control object
Returns:
text contents
Notes:
- Old ``docx`` (https://pypi.python.org/pypi/python-docx) has been
superseded (see https://github.com/mikemaccana/python-docx).
- ``docx.opendocx(file)`` uses :class:`zipfile.ZipFile`, which can take
either a filename or a file-like object
(https://docs.python.org/2/library/zipfile.html).
- Method was:
.. code-block:: python
with get_filelikeobject(filename, blob) as fp:
document = docx.opendocx(fp)
paratextlist = docx.getdocumenttext(document)
return '\n\n'.join(paratextlist)
- Newer ``docx`` is python-docx
- https://pypi.python.org/pypi/python-docx
- https://python-docx.readthedocs.org/en/latest/
- http://stackoverflow.com/questions/25228106
However, it uses ``lxml``, which has C dependencies, so it doesn't always
install properly on e.g. bare Windows machines.
PERFORMANCE of my method:
- nice table formatting
- but tables grouped at end, not in sensible places
- can iterate via ``doc.paragraphs`` and ``doc.tables`` but not in
true document order, it seems
- others have noted this too:
- https://github.com/python-openxml/python-docx/issues/40
- https://github.com/deanmalmgren/textract/pull/92
- ``docx2txt`` is at https://pypi.python.org/pypi/docx2txt/0.6; this is
pure Python. Its command-line function appears to be for Python 2 only
(2016-04-21: crashes under Python 3; is due to an encoding bug). However,
it seems fine as a library. It doesn't handle in-memory blobs properly,
though, so we need to extend it.
PERFORMANCE OF ITS ``process()`` function:
- all text comes out
- table text is in a sensible place
- table formatting is lost.
- Other manual methods (not yet implemented):
http://etienned.github.io/posts/extract-text-from-word-docx-simply/.
Looks like it won't deal with header stuff (etc.) that ``docx2txt``
handles.
- Upshot: we need a DIY version.
- See also this "compile lots of techniques" libraries, which has C
dependencies: http://textract.readthedocs.org/en/latest/
"""
if True:
text = ''
with get_filelikeobject(filename, blob) as fp:
for xml in gen_xml_files_from_docx(fp):
text += docx_text_from_xml(xml, config)
return text | python | def convert_docx_to_text(
filename: str = None, blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts a DOCX file to text.
Pass either a filename or a binary object.
Args:
filename: filename to process
blob: binary ``bytes`` object to process
config: :class:`TextProcessingConfig` control object
Returns:
text contents
Notes:
- Old ``docx`` (https://pypi.python.org/pypi/python-docx) has been
superseded (see https://github.com/mikemaccana/python-docx).
- ``docx.opendocx(file)`` uses :class:`zipfile.ZipFile`, which can take
either a filename or a file-like object
(https://docs.python.org/2/library/zipfile.html).
- Method was:
.. code-block:: python
with get_filelikeobject(filename, blob) as fp:
document = docx.opendocx(fp)
paratextlist = docx.getdocumenttext(document)
return '\n\n'.join(paratextlist)
- Newer ``docx`` is python-docx
- https://pypi.python.org/pypi/python-docx
- https://python-docx.readthedocs.org/en/latest/
- http://stackoverflow.com/questions/25228106
However, it uses ``lxml``, which has C dependencies, so it doesn't always
install properly on e.g. bare Windows machines.
PERFORMANCE of my method:
- nice table formatting
- but tables grouped at end, not in sensible places
- can iterate via ``doc.paragraphs`` and ``doc.tables`` but not in
true document order, it seems
- others have noted this too:
- https://github.com/python-openxml/python-docx/issues/40
- https://github.com/deanmalmgren/textract/pull/92
- ``docx2txt`` is at https://pypi.python.org/pypi/docx2txt/0.6; this is
pure Python. Its command-line function appears to be for Python 2 only
(2016-04-21: crashes under Python 3; is due to an encoding bug). However,
it seems fine as a library. It doesn't handle in-memory blobs properly,
though, so we need to extend it.
PERFORMANCE OF ITS ``process()`` function:
- all text comes out
- table text is in a sensible place
- table formatting is lost.
- Other manual methods (not yet implemented):
http://etienned.github.io/posts/extract-text-from-word-docx-simply/.
Looks like it won't deal with header stuff (etc.) that ``docx2txt``
handles.
- Upshot: we need a DIY version.
- See also this "compile lots of techniques" libraries, which has C
dependencies: http://textract.readthedocs.org/en/latest/
"""
if True:
text = ''
with get_filelikeobject(filename, blob) as fp:
for xml in gen_xml_files_from_docx(fp):
text += docx_text_from_xml(xml, config)
return text | [
"def",
"convert_docx_to_text",
"(",
"filename",
":",
"str",
"=",
"None",
",",
"blob",
":",
"bytes",
"=",
"None",
",",
"config",
":",
"TextProcessingConfig",
"=",
"_DEFAULT_CONFIG",
")",
"->",
"str",
":",
"if",
"True",
":",
"text",
"=",
"''",
"with",
"get_filelikeobject",
"(",
"filename",
",",
"blob",
")",
"as",
"fp",
":",
"for",
"xml",
"in",
"gen_xml_files_from_docx",
"(",
"fp",
")",
":",
"text",
"+=",
"docx_text_from_xml",
"(",
"xml",
",",
"config",
")",
"return",
"text"
] | Converts a DOCX file to text.
Pass either a filename or a binary object.
Args:
filename: filename to process
blob: binary ``bytes`` object to process
config: :class:`TextProcessingConfig` control object
Returns:
text contents
Notes:
- Old ``docx`` (https://pypi.python.org/pypi/python-docx) has been
superseded (see https://github.com/mikemaccana/python-docx).
- ``docx.opendocx(file)`` uses :class:`zipfile.ZipFile`, which can take
either a filename or a file-like object
(https://docs.python.org/2/library/zipfile.html).
- Method was:
.. code-block:: python
with get_filelikeobject(filename, blob) as fp:
document = docx.opendocx(fp)
paratextlist = docx.getdocumenttext(document)
return '\n\n'.join(paratextlist)
- Newer ``docx`` is python-docx
- https://pypi.python.org/pypi/python-docx
- https://python-docx.readthedocs.org/en/latest/
- http://stackoverflow.com/questions/25228106
However, it uses ``lxml``, which has C dependencies, so it doesn't always
install properly on e.g. bare Windows machines.
PERFORMANCE of my method:
- nice table formatting
- but tables grouped at end, not in sensible places
- can iterate via ``doc.paragraphs`` and ``doc.tables`` but not in
true document order, it seems
- others have noted this too:
- https://github.com/python-openxml/python-docx/issues/40
- https://github.com/deanmalmgren/textract/pull/92
- ``docx2txt`` is at https://pypi.python.org/pypi/docx2txt/0.6; this is
pure Python. Its command-line function appears to be for Python 2 only
(2016-04-21: crashes under Python 3; is due to an encoding bug). However,
it seems fine as a library. It doesn't handle in-memory blobs properly,
though, so we need to extend it.
PERFORMANCE OF ITS ``process()`` function:
- all text comes out
- table text is in a sensible place
- table formatting is lost.
- Other manual methods (not yet implemented):
http://etienned.github.io/posts/extract-text-from-word-docx-simply/.
Looks like it won't deal with header stuff (etc.) that ``docx2txt``
handles.
- Upshot: we need a DIY version.
- See also this "compile lots of techniques" libraries, which has C
dependencies: http://textract.readthedocs.org/en/latest/ | [
"Converts",
"a",
"DOCX",
"file",
"to",
"text",
".",
"Pass",
"either",
"a",
"filename",
"or",
"a",
"binary",
"object",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L868-L951 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | convert_odt_to_text | def convert_odt_to_text(filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts an OpenOffice ODT file to text.
Pass either a filename or a binary object.
"""
# We can't use exactly the same method as for DOCX files, using docx:
# sometimes that works, but sometimes it falls over with:
# KeyError: "There is no item named 'word/document.xml' in the archive"
with get_filelikeobject(filename, blob) as fp:
z = zipfile.ZipFile(fp)
tree = ElementTree.fromstring(z.read('content.xml'))
# ... may raise zipfile.BadZipfile
textlist = [] # type: List[str]
for element in tree.iter():
if element.text:
textlist.append(element.text.strip())
return '\n\n'.join(textlist) | python | def convert_odt_to_text(filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts an OpenOffice ODT file to text.
Pass either a filename or a binary object.
"""
# We can't use exactly the same method as for DOCX files, using docx:
# sometimes that works, but sometimes it falls over with:
# KeyError: "There is no item named 'word/document.xml' in the archive"
with get_filelikeobject(filename, blob) as fp:
z = zipfile.ZipFile(fp)
tree = ElementTree.fromstring(z.read('content.xml'))
# ... may raise zipfile.BadZipfile
textlist = [] # type: List[str]
for element in tree.iter():
if element.text:
textlist.append(element.text.strip())
return '\n\n'.join(textlist) | [
"def",
"convert_odt_to_text",
"(",
"filename",
":",
"str",
"=",
"None",
",",
"blob",
":",
"bytes",
"=",
"None",
",",
"config",
":",
"TextProcessingConfig",
"=",
"_DEFAULT_CONFIG",
")",
"->",
"str",
":",
"# We can't use exactly the same method as for DOCX files, using docx:",
"# sometimes that works, but sometimes it falls over with:",
"# KeyError: \"There is no item named 'word/document.xml' in the archive\"",
"with",
"get_filelikeobject",
"(",
"filename",
",",
"blob",
")",
"as",
"fp",
":",
"z",
"=",
"zipfile",
".",
"ZipFile",
"(",
"fp",
")",
"tree",
"=",
"ElementTree",
".",
"fromstring",
"(",
"z",
".",
"read",
"(",
"'content.xml'",
")",
")",
"# ... may raise zipfile.BadZipfile",
"textlist",
"=",
"[",
"]",
"# type: List[str]",
"for",
"element",
"in",
"tree",
".",
"iter",
"(",
")",
":",
"if",
"element",
".",
"text",
":",
"textlist",
".",
"append",
"(",
"element",
".",
"text",
".",
"strip",
"(",
")",
")",
"return",
"'\\n\\n'",
".",
"join",
"(",
"textlist",
")"
] | Converts an OpenOffice ODT file to text.
Pass either a filename or a binary object. | [
"Converts",
"an",
"OpenOffice",
"ODT",
"file",
"to",
"text",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L972-L991 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | convert_html_to_text | def convert_html_to_text(
filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts HTML to text.
"""
with get_filelikeobject(filename, blob) as fp:
soup = bs4.BeautifulSoup(fp)
return soup.get_text() | python | def convert_html_to_text(
filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts HTML to text.
"""
with get_filelikeobject(filename, blob) as fp:
soup = bs4.BeautifulSoup(fp)
return soup.get_text() | [
"def",
"convert_html_to_text",
"(",
"filename",
":",
"str",
"=",
"None",
",",
"blob",
":",
"bytes",
"=",
"None",
",",
"config",
":",
"TextProcessingConfig",
"=",
"_DEFAULT_CONFIG",
")",
"->",
"str",
":",
"with",
"get_filelikeobject",
"(",
"filename",
",",
"blob",
")",
"as",
"fp",
":",
"soup",
"=",
"bs4",
".",
"BeautifulSoup",
"(",
"fp",
")",
"return",
"soup",
".",
"get_text",
"(",
")"
] | Converts HTML to text. | [
"Converts",
"HTML",
"to",
"text",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L999-L1008 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | convert_xml_to_text | def convert_xml_to_text(filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts XML to text.
"""
with get_filelikeobject(filename, blob) as fp:
soup = bs4.BeautifulStoneSoup(fp)
return soup.get_text() | python | def convert_xml_to_text(filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts XML to text.
"""
with get_filelikeobject(filename, blob) as fp:
soup = bs4.BeautifulStoneSoup(fp)
return soup.get_text() | [
"def",
"convert_xml_to_text",
"(",
"filename",
":",
"str",
"=",
"None",
",",
"blob",
":",
"bytes",
"=",
"None",
",",
"config",
":",
"TextProcessingConfig",
"=",
"_DEFAULT_CONFIG",
")",
"->",
"str",
":",
"with",
"get_filelikeobject",
"(",
"filename",
",",
"blob",
")",
"as",
"fp",
":",
"soup",
"=",
"bs4",
".",
"BeautifulStoneSoup",
"(",
"fp",
")",
"return",
"soup",
".",
"get_text",
"(",
")"
] | Converts XML to text. | [
"Converts",
"XML",
"to",
"text",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L1016-L1024 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | convert_rtf_to_text | def convert_rtf_to_text(filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts RTF to text.
"""
unrtf = tools['unrtf']
if unrtf: # Best
args = [unrtf, '--text', '--nopict']
if UNRTF_SUPPORTS_QUIET:
args.append('--quiet')
if filename:
args.append(filename)
return get_cmd_output(*args)
else:
return get_cmd_output_from_stdin(blob, *args)
elif pyth: # Very memory-consuming:
# https://github.com/brendonh/pyth/blob/master/pyth/plugins/rtf15/reader.py # noqa
with get_filelikeobject(filename, blob) as fp:
doc = pyth.plugins.rtf15.reader.Rtf15Reader.read(fp)
return (
pyth.plugins.plaintext.writer.PlaintextWriter.write(doc).getvalue()
)
else:
raise AssertionError("No RTF-reading tool available") | python | def convert_rtf_to_text(filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts RTF to text.
"""
unrtf = tools['unrtf']
if unrtf: # Best
args = [unrtf, '--text', '--nopict']
if UNRTF_SUPPORTS_QUIET:
args.append('--quiet')
if filename:
args.append(filename)
return get_cmd_output(*args)
else:
return get_cmd_output_from_stdin(blob, *args)
elif pyth: # Very memory-consuming:
# https://github.com/brendonh/pyth/blob/master/pyth/plugins/rtf15/reader.py # noqa
with get_filelikeobject(filename, blob) as fp:
doc = pyth.plugins.rtf15.reader.Rtf15Reader.read(fp)
return (
pyth.plugins.plaintext.writer.PlaintextWriter.write(doc).getvalue()
)
else:
raise AssertionError("No RTF-reading tool available") | [
"def",
"convert_rtf_to_text",
"(",
"filename",
":",
"str",
"=",
"None",
",",
"blob",
":",
"bytes",
"=",
"None",
",",
"config",
":",
"TextProcessingConfig",
"=",
"_DEFAULT_CONFIG",
")",
"->",
"str",
":",
"unrtf",
"=",
"tools",
"[",
"'unrtf'",
"]",
"if",
"unrtf",
":",
"# Best",
"args",
"=",
"[",
"unrtf",
",",
"'--text'",
",",
"'--nopict'",
"]",
"if",
"UNRTF_SUPPORTS_QUIET",
":",
"args",
".",
"append",
"(",
"'--quiet'",
")",
"if",
"filename",
":",
"args",
".",
"append",
"(",
"filename",
")",
"return",
"get_cmd_output",
"(",
"*",
"args",
")",
"else",
":",
"return",
"get_cmd_output_from_stdin",
"(",
"blob",
",",
"*",
"args",
")",
"elif",
"pyth",
":",
"# Very memory-consuming:",
"# https://github.com/brendonh/pyth/blob/master/pyth/plugins/rtf15/reader.py # noqa",
"with",
"get_filelikeobject",
"(",
"filename",
",",
"blob",
")",
"as",
"fp",
":",
"doc",
"=",
"pyth",
".",
"plugins",
".",
"rtf15",
".",
"reader",
".",
"Rtf15Reader",
".",
"read",
"(",
"fp",
")",
"return",
"(",
"pyth",
".",
"plugins",
".",
"plaintext",
".",
"writer",
".",
"PlaintextWriter",
".",
"write",
"(",
"doc",
")",
".",
"getvalue",
"(",
")",
")",
"else",
":",
"raise",
"AssertionError",
"(",
"\"No RTF-reading tool available\"",
")"
] | Converts RTF to text. | [
"Converts",
"RTF",
"to",
"text",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L1032-L1056 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | availability_rtf | def availability_rtf() -> bool:
"""
Is an RTF processor available?
"""
unrtf = tools['unrtf']
if unrtf:
return True
elif pyth:
log.warning("RTF conversion: unrtf missing; "
"using pyth (less efficient)")
return True
else:
return False | python | def availability_rtf() -> bool:
"""
Is an RTF processor available?
"""
unrtf = tools['unrtf']
if unrtf:
return True
elif pyth:
log.warning("RTF conversion: unrtf missing; "
"using pyth (less efficient)")
return True
else:
return False | [
"def",
"availability_rtf",
"(",
")",
"->",
"bool",
":",
"unrtf",
"=",
"tools",
"[",
"'unrtf'",
"]",
"if",
"unrtf",
":",
"return",
"True",
"elif",
"pyth",
":",
"log",
".",
"warning",
"(",
"\"RTF conversion: unrtf missing; \"",
"\"using pyth (less efficient)\"",
")",
"return",
"True",
"else",
":",
"return",
"False"
] | Is an RTF processor available? | [
"Is",
"an",
"RTF",
"processor",
"available?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L1059-L1071 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | convert_doc_to_text | def convert_doc_to_text(filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts Microsoft Word DOC files to text.
"""
antiword = tools['antiword']
if antiword:
if filename:
return get_cmd_output(antiword, '-w', str(config.width), filename)
else:
return get_cmd_output_from_stdin(blob, antiword, '-w',
str(config.width), '-')
else:
raise AssertionError("No DOC-reading tool available") | python | def convert_doc_to_text(filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts Microsoft Word DOC files to text.
"""
antiword = tools['antiword']
if antiword:
if filename:
return get_cmd_output(antiword, '-w', str(config.width), filename)
else:
return get_cmd_output_from_stdin(blob, antiword, '-w',
str(config.width), '-')
else:
raise AssertionError("No DOC-reading tool available") | [
"def",
"convert_doc_to_text",
"(",
"filename",
":",
"str",
"=",
"None",
",",
"blob",
":",
"bytes",
"=",
"None",
",",
"config",
":",
"TextProcessingConfig",
"=",
"_DEFAULT_CONFIG",
")",
"->",
"str",
":",
"antiword",
"=",
"tools",
"[",
"'antiword'",
"]",
"if",
"antiword",
":",
"if",
"filename",
":",
"return",
"get_cmd_output",
"(",
"antiword",
",",
"'-w'",
",",
"str",
"(",
"config",
".",
"width",
")",
",",
"filename",
")",
"else",
":",
"return",
"get_cmd_output_from_stdin",
"(",
"blob",
",",
"antiword",
",",
"'-w'",
",",
"str",
"(",
"config",
".",
"width",
")",
",",
"'-'",
")",
"else",
":",
"raise",
"AssertionError",
"(",
"\"No DOC-reading tool available\"",
")"
] | Converts Microsoft Word DOC files to text. | [
"Converts",
"Microsoft",
"Word",
"DOC",
"files",
"to",
"text",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L1079-L1093 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | convert_anything_to_text | def convert_anything_to_text(
filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Convert arbitrary files to text, using ``strings`` or ``strings2``.
(``strings`` is a standard Unix command to get text from any old rubbish.)
"""
strings = tools['strings'] or tools['strings2']
if strings:
if filename:
return get_cmd_output(strings, filename)
else:
return get_cmd_output_from_stdin(blob, strings)
else:
raise AssertionError("No fallback string-reading tool available") | python | def convert_anything_to_text(
filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Convert arbitrary files to text, using ``strings`` or ``strings2``.
(``strings`` is a standard Unix command to get text from any old rubbish.)
"""
strings = tools['strings'] or tools['strings2']
if strings:
if filename:
return get_cmd_output(strings, filename)
else:
return get_cmd_output_from_stdin(blob, strings)
else:
raise AssertionError("No fallback string-reading tool available") | [
"def",
"convert_anything_to_text",
"(",
"filename",
":",
"str",
"=",
"None",
",",
"blob",
":",
"bytes",
"=",
"None",
",",
"config",
":",
"TextProcessingConfig",
"=",
"_DEFAULT_CONFIG",
")",
"->",
"str",
":",
"strings",
"=",
"tools",
"[",
"'strings'",
"]",
"or",
"tools",
"[",
"'strings2'",
"]",
"if",
"strings",
":",
"if",
"filename",
":",
"return",
"get_cmd_output",
"(",
"strings",
",",
"filename",
")",
"else",
":",
"return",
"get_cmd_output_from_stdin",
"(",
"blob",
",",
"strings",
")",
"else",
":",
"raise",
"AssertionError",
"(",
"\"No fallback string-reading tool available\"",
")"
] | Convert arbitrary files to text, using ``strings`` or ``strings2``.
(``strings`` is a standard Unix command to get text from any old rubbish.) | [
"Convert",
"arbitrary",
"files",
"to",
"text",
"using",
"strings",
"or",
"strings2",
".",
"(",
"strings",
"is",
"a",
"standard",
"Unix",
"command",
"to",
"get",
"text",
"from",
"any",
"old",
"rubbish",
".",
")"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L1109-L1124 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | document_to_text | def document_to_text(filename: str = None,
blob: bytes = None,
extension: str = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts a document to text.
This function selects a processor based on the file extension (either from
the filename, or, in the case of a BLOB, the extension specified manually
via the ``extension`` parameter).
Pass either a filename or a binary object.
- Raises an exception for malformed arguments, missing files, bad
filetypes, etc.
- Returns a string if the file was processed (potentially an empty string).
"""
if not filename and not blob:
raise ValueError("document_to_text: no filename and no blob")
if filename and blob:
raise ValueError("document_to_text: specify either filename or blob")
if blob and not extension:
raise ValueError("document_to_text: need extension hint for blob")
if filename:
stub, extension = os.path.splitext(filename)
else:
if extension[0] != ".":
extension = "." + extension
extension = extension.lower()
# Ensure blob is an appropriate type
log.debug(
"filename: {}, blob type: {}, blob length: {}, extension: {}".format(
filename,
type(blob),
len(blob) if blob is not None else None,
extension))
# If we were given a filename and the file doesn't exist, don't bother.
if filename and not os.path.isfile(filename):
raise ValueError("document_to_text: no such file: {!r}".format(
filename))
# Choose method
info = ext_map.get(extension)
if info is None:
log.warning("Unknown filetype: {}; using generic tool", extension)
info = ext_map[None]
func = info[CONVERTER]
return func(filename, blob, config) | python | def document_to_text(filename: str = None,
blob: bytes = None,
extension: str = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts a document to text.
This function selects a processor based on the file extension (either from
the filename, or, in the case of a BLOB, the extension specified manually
via the ``extension`` parameter).
Pass either a filename or a binary object.
- Raises an exception for malformed arguments, missing files, bad
filetypes, etc.
- Returns a string if the file was processed (potentially an empty string).
"""
if not filename and not blob:
raise ValueError("document_to_text: no filename and no blob")
if filename and blob:
raise ValueError("document_to_text: specify either filename or blob")
if blob and not extension:
raise ValueError("document_to_text: need extension hint for blob")
if filename:
stub, extension = os.path.splitext(filename)
else:
if extension[0] != ".":
extension = "." + extension
extension = extension.lower()
# Ensure blob is an appropriate type
log.debug(
"filename: {}, blob type: {}, blob length: {}, extension: {}".format(
filename,
type(blob),
len(blob) if blob is not None else None,
extension))
# If we were given a filename and the file doesn't exist, don't bother.
if filename and not os.path.isfile(filename):
raise ValueError("document_to_text: no such file: {!r}".format(
filename))
# Choose method
info = ext_map.get(extension)
if info is None:
log.warning("Unknown filetype: {}; using generic tool", extension)
info = ext_map[None]
func = info[CONVERTER]
return func(filename, blob, config) | [
"def",
"document_to_text",
"(",
"filename",
":",
"str",
"=",
"None",
",",
"blob",
":",
"bytes",
"=",
"None",
",",
"extension",
":",
"str",
"=",
"None",
",",
"config",
":",
"TextProcessingConfig",
"=",
"_DEFAULT_CONFIG",
")",
"->",
"str",
":",
"if",
"not",
"filename",
"and",
"not",
"blob",
":",
"raise",
"ValueError",
"(",
"\"document_to_text: no filename and no blob\"",
")",
"if",
"filename",
"and",
"blob",
":",
"raise",
"ValueError",
"(",
"\"document_to_text: specify either filename or blob\"",
")",
"if",
"blob",
"and",
"not",
"extension",
":",
"raise",
"ValueError",
"(",
"\"document_to_text: need extension hint for blob\"",
")",
"if",
"filename",
":",
"stub",
",",
"extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"else",
":",
"if",
"extension",
"[",
"0",
"]",
"!=",
"\".\"",
":",
"extension",
"=",
"\".\"",
"+",
"extension",
"extension",
"=",
"extension",
".",
"lower",
"(",
")",
"# Ensure blob is an appropriate type",
"log",
".",
"debug",
"(",
"\"filename: {}, blob type: {}, blob length: {}, extension: {}\"",
".",
"format",
"(",
"filename",
",",
"type",
"(",
"blob",
")",
",",
"len",
"(",
"blob",
")",
"if",
"blob",
"is",
"not",
"None",
"else",
"None",
",",
"extension",
")",
")",
"# If we were given a filename and the file doesn't exist, don't bother.",
"if",
"filename",
"and",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"raise",
"ValueError",
"(",
"\"document_to_text: no such file: {!r}\"",
".",
"format",
"(",
"filename",
")",
")",
"# Choose method",
"info",
"=",
"ext_map",
".",
"get",
"(",
"extension",
")",
"if",
"info",
"is",
"None",
":",
"log",
".",
"warning",
"(",
"\"Unknown filetype: {}; using generic tool\"",
",",
"extension",
")",
"info",
"=",
"ext_map",
"[",
"None",
"]",
"func",
"=",
"info",
"[",
"CONVERTER",
"]",
"return",
"func",
"(",
"filename",
",",
"blob",
",",
"config",
")"
] | Converts a document to text.
This function selects a processor based on the file extension (either from
the filename, or, in the case of a BLOB, the extension specified manually
via the ``extension`` parameter).
Pass either a filename or a binary object.
- Raises an exception for malformed arguments, missing files, bad
filetypes, etc.
- Returns a string if the file was processed (potentially an empty string). | [
"Converts",
"a",
"document",
"to",
"text",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L1211-L1261 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | is_text_extractor_available | def is_text_extractor_available(extension: str) -> bool:
"""
Is a text extractor available for the specified extension?
"""
if extension is not None:
extension = extension.lower()
info = ext_map.get(extension)
if info is None:
return False
availability = info[AVAILABILITY]
if type(availability) == bool:
return availability
elif callable(availability):
return availability()
else:
raise ValueError(
"Bad information object for extension: {}".format(extension)) | python | def is_text_extractor_available(extension: str) -> bool:
"""
Is a text extractor available for the specified extension?
"""
if extension is not None:
extension = extension.lower()
info = ext_map.get(extension)
if info is None:
return False
availability = info[AVAILABILITY]
if type(availability) == bool:
return availability
elif callable(availability):
return availability()
else:
raise ValueError(
"Bad information object for extension: {}".format(extension)) | [
"def",
"is_text_extractor_available",
"(",
"extension",
":",
"str",
")",
"->",
"bool",
":",
"if",
"extension",
"is",
"not",
"None",
":",
"extension",
"=",
"extension",
".",
"lower",
"(",
")",
"info",
"=",
"ext_map",
".",
"get",
"(",
"extension",
")",
"if",
"info",
"is",
"None",
":",
"return",
"False",
"availability",
"=",
"info",
"[",
"AVAILABILITY",
"]",
"if",
"type",
"(",
"availability",
")",
"==",
"bool",
":",
"return",
"availability",
"elif",
"callable",
"(",
"availability",
")",
":",
"return",
"availability",
"(",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Bad information object for extension: {}\"",
".",
"format",
"(",
"extension",
")",
")"
] | Is a text extractor available for the specified extension? | [
"Is",
"a",
"text",
"extractor",
"available",
"for",
"the",
"specified",
"extension?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L1264-L1280 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | main | def main() -> None:
"""
Command-line processor. See ``--help`` for details.
"""
logging.basicConfig(level=logging.DEBUG)
parser = argparse.ArgumentParser()
parser.add_argument("inputfile", nargs="?", help="Input file name")
parser.add_argument(
"--availability", nargs='*',
help="File extensions to check availability for (use a '.' prefix, "
"and use the special extension 'None' to check the fallback "
"processor")
parser.add_argument(
"--plain", action="store_true",
help="Keep it plain: minimize layout (e.g. of tables) and maximize "
"the likelihood of source sentence flowing properly in the "
"output (e.g. for natural language processing).")
parser.add_argument(
"--width", type=int, default=DEFAULT_WIDTH,
help="Word wrapping width (default {})".format(DEFAULT_WIDTH))
parser.add_argument(
"--min-col-width", type=int, default=DEFAULT_MIN_COL_WIDTH,
help="Minimum column width for tables (default {})".format(
DEFAULT_MIN_COL_WIDTH))
args = parser.parse_args()
if args.availability:
for ext in args.availability:
if ext.lower() == 'none':
ext = None
available = is_text_extractor_available(ext)
print("Extractor for extension {} present: {}".format(ext,
available))
return
if not args.inputfile:
parser.print_help(sys.stderr)
return
config = TextProcessingConfig(
width=args.width,
min_col_width=args.min_col_width,
plain=args.plain,
)
result = document_to_text(filename=args.inputfile, config=config)
if result is None:
return
else:
print(result) | python | def main() -> None:
"""
Command-line processor. See ``--help`` for details.
"""
logging.basicConfig(level=logging.DEBUG)
parser = argparse.ArgumentParser()
parser.add_argument("inputfile", nargs="?", help="Input file name")
parser.add_argument(
"--availability", nargs='*',
help="File extensions to check availability for (use a '.' prefix, "
"and use the special extension 'None' to check the fallback "
"processor")
parser.add_argument(
"--plain", action="store_true",
help="Keep it plain: minimize layout (e.g. of tables) and maximize "
"the likelihood of source sentence flowing properly in the "
"output (e.g. for natural language processing).")
parser.add_argument(
"--width", type=int, default=DEFAULT_WIDTH,
help="Word wrapping width (default {})".format(DEFAULT_WIDTH))
parser.add_argument(
"--min-col-width", type=int, default=DEFAULT_MIN_COL_WIDTH,
help="Minimum column width for tables (default {})".format(
DEFAULT_MIN_COL_WIDTH))
args = parser.parse_args()
if args.availability:
for ext in args.availability:
if ext.lower() == 'none':
ext = None
available = is_text_extractor_available(ext)
print("Extractor for extension {} present: {}".format(ext,
available))
return
if not args.inputfile:
parser.print_help(sys.stderr)
return
config = TextProcessingConfig(
width=args.width,
min_col_width=args.min_col_width,
plain=args.plain,
)
result = document_to_text(filename=args.inputfile, config=config)
if result is None:
return
else:
print(result) | [
"def",
"main",
"(",
")",
"->",
"None",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"inputfile\"",
",",
"nargs",
"=",
"\"?\"",
",",
"help",
"=",
"\"Input file name\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--availability\"",
",",
"nargs",
"=",
"'*'",
",",
"help",
"=",
"\"File extensions to check availability for (use a '.' prefix, \"",
"\"and use the special extension 'None' to check the fallback \"",
"\"processor\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--plain\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Keep it plain: minimize layout (e.g. of tables) and maximize \"",
"\"the likelihood of source sentence flowing properly in the \"",
"\"output (e.g. for natural language processing).\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--width\"",
",",
"type",
"=",
"int",
",",
"default",
"=",
"DEFAULT_WIDTH",
",",
"help",
"=",
"\"Word wrapping width (default {})\"",
".",
"format",
"(",
"DEFAULT_WIDTH",
")",
")",
"parser",
".",
"add_argument",
"(",
"\"--min-col-width\"",
",",
"type",
"=",
"int",
",",
"default",
"=",
"DEFAULT_MIN_COL_WIDTH",
",",
"help",
"=",
"\"Minimum column width for tables (default {})\"",
".",
"format",
"(",
"DEFAULT_MIN_COL_WIDTH",
")",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"if",
"args",
".",
"availability",
":",
"for",
"ext",
"in",
"args",
".",
"availability",
":",
"if",
"ext",
".",
"lower",
"(",
")",
"==",
"'none'",
":",
"ext",
"=",
"None",
"available",
"=",
"is_text_extractor_available",
"(",
"ext",
")",
"print",
"(",
"\"Extractor for extension {} present: {}\"",
".",
"format",
"(",
"ext",
",",
"available",
")",
")",
"return",
"if",
"not",
"args",
".",
"inputfile",
":",
"parser",
".",
"print_help",
"(",
"sys",
".",
"stderr",
")",
"return",
"config",
"=",
"TextProcessingConfig",
"(",
"width",
"=",
"args",
".",
"width",
",",
"min_col_width",
"=",
"args",
".",
"min_col_width",
",",
"plain",
"=",
"args",
".",
"plain",
",",
")",
"result",
"=",
"document_to_text",
"(",
"filename",
"=",
"args",
".",
"inputfile",
",",
"config",
"=",
"config",
")",
"if",
"result",
"is",
"None",
":",
"return",
"else",
":",
"print",
"(",
"result",
")"
] | Command-line processor. See ``--help`` for details. | [
"Command",
"-",
"line",
"processor",
".",
"See",
"--",
"help",
"for",
"details",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L1297-L1342 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | set_verbose_logging | def set_verbose_logging(verbose: bool) -> None:
"""Chooses basic or verbose logging."""
if verbose:
set_loglevel(logging.DEBUG)
else:
set_loglevel(logging.INFO) | python | def set_verbose_logging(verbose: bool) -> None:
"""Chooses basic or verbose logging."""
if verbose:
set_loglevel(logging.DEBUG)
else:
set_loglevel(logging.INFO) | [
"def",
"set_verbose_logging",
"(",
"verbose",
":",
"bool",
")",
"->",
"None",
":",
"if",
"verbose",
":",
"set_loglevel",
"(",
"logging",
".",
"DEBUG",
")",
"else",
":",
"set_loglevel",
"(",
"logging",
".",
"INFO",
")"
] | Chooses basic or verbose logging. | [
"Chooses",
"basic",
"or",
"verbose",
"logging",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L863-L868 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | debug_sql | def debug_sql(sql: str, *args: Any) -> None:
"""Writes SQL and arguments to the log."""
log.debug("SQL: %s" % sql)
if args:
log.debug("Args: %r" % args) | python | def debug_sql(sql: str, *args: Any) -> None:
"""Writes SQL and arguments to the log."""
log.debug("SQL: %s" % sql)
if args:
log.debug("Args: %r" % args) | [
"def",
"debug_sql",
"(",
"sql",
":",
"str",
",",
"*",
"args",
":",
"Any",
")",
"->",
"None",
":",
"log",
".",
"debug",
"(",
"\"SQL: %s\"",
"%",
"sql",
")",
"if",
"args",
":",
"log",
".",
"debug",
"(",
"\"Args: %r\"",
"%",
"args",
")"
] | Writes SQL and arguments to the log. | [
"Writes",
"SQL",
"and",
"arguments",
"to",
"the",
"log",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L875-L879 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | delimit | def delimit(x: str, delims: Tuple[str, str]) -> str:
"""Delimits x, using delims[0] (left) and delims[1] (right)."""
return delims[0] + x + delims[1] | python | def delimit(x: str, delims: Tuple[str, str]) -> str:
"""Delimits x, using delims[0] (left) and delims[1] (right)."""
return delims[0] + x + delims[1] | [
"def",
"delimit",
"(",
"x",
":",
"str",
",",
"delims",
":",
"Tuple",
"[",
"str",
",",
"str",
"]",
")",
"->",
"str",
":",
"return",
"delims",
"[",
"0",
"]",
"+",
"x",
"+",
"delims",
"[",
"1",
"]"
] | Delimits x, using delims[0] (left) and delims[1] (right). | [
"Delimits",
"x",
"using",
"delims",
"[",
"0",
"]",
"(",
"left",
")",
"and",
"delims",
"[",
"1",
"]",
"(",
"right",
")",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L882-L884 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | get_sql_select_all_fields_by_key | def get_sql_select_all_fields_by_key(
table: str,
fieldlist: Sequence[str],
keyname: str,
delims: Tuple[str, str] = ("", "")) -> str:
"""Returns SQL:
SELECT [all fields in the fieldlist] WHERE [keyname] = ?
"""
return (
"SELECT " +
",".join([delimit(x, delims) for x in fieldlist]) +
" FROM " + delimit(table, delims) +
" WHERE " + delimit(keyname, delims) + "=?"
) | python | def get_sql_select_all_fields_by_key(
table: str,
fieldlist: Sequence[str],
keyname: str,
delims: Tuple[str, str] = ("", "")) -> str:
"""Returns SQL:
SELECT [all fields in the fieldlist] WHERE [keyname] = ?
"""
return (
"SELECT " +
",".join([delimit(x, delims) for x in fieldlist]) +
" FROM " + delimit(table, delims) +
" WHERE " + delimit(keyname, delims) + "=?"
) | [
"def",
"get_sql_select_all_fields_by_key",
"(",
"table",
":",
"str",
",",
"fieldlist",
":",
"Sequence",
"[",
"str",
"]",
",",
"keyname",
":",
"str",
",",
"delims",
":",
"Tuple",
"[",
"str",
",",
"str",
"]",
"=",
"(",
"\"\"",
",",
"\"\"",
")",
")",
"->",
"str",
":",
"return",
"(",
"\"SELECT \"",
"+",
"\",\"",
".",
"join",
"(",
"[",
"delimit",
"(",
"x",
",",
"delims",
")",
"for",
"x",
"in",
"fieldlist",
"]",
")",
"+",
"\" FROM \"",
"+",
"delimit",
"(",
"table",
",",
"delims",
")",
"+",
"\" WHERE \"",
"+",
"delimit",
"(",
"keyname",
",",
"delims",
")",
"+",
"\"=?\"",
")"
] | Returns SQL:
SELECT [all fields in the fieldlist] WHERE [keyname] = ? | [
"Returns",
"SQL",
":",
"SELECT",
"[",
"all",
"fields",
"in",
"the",
"fieldlist",
"]",
"WHERE",
"[",
"keyname",
"]",
"=",
"?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L907-L920 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | get_sql_insert | def get_sql_insert(table: str,
fieldlist: Sequence[str],
delims: Tuple[str, str] = ("", "")) -> str:
"""Returns ?-marked SQL for an INSERT statement."""
return (
"INSERT INTO " + delimit(table, delims) +
" (" +
",".join([delimit(x, delims) for x in fieldlist]) +
") VALUES (" +
",".join(["?"] * len(fieldlist)) +
")"
) | python | def get_sql_insert(table: str,
fieldlist: Sequence[str],
delims: Tuple[str, str] = ("", "")) -> str:
"""Returns ?-marked SQL for an INSERT statement."""
return (
"INSERT INTO " + delimit(table, delims) +
" (" +
",".join([delimit(x, delims) for x in fieldlist]) +
") VALUES (" +
",".join(["?"] * len(fieldlist)) +
")"
) | [
"def",
"get_sql_insert",
"(",
"table",
":",
"str",
",",
"fieldlist",
":",
"Sequence",
"[",
"str",
"]",
",",
"delims",
":",
"Tuple",
"[",
"str",
",",
"str",
"]",
"=",
"(",
"\"\"",
",",
"\"\"",
")",
")",
"->",
"str",
":",
"return",
"(",
"\"INSERT INTO \"",
"+",
"delimit",
"(",
"table",
",",
"delims",
")",
"+",
"\" (\"",
"+",
"\",\"",
".",
"join",
"(",
"[",
"delimit",
"(",
"x",
",",
"delims",
")",
"for",
"x",
"in",
"fieldlist",
"]",
")",
"+",
"\") VALUES (\"",
"+",
"\",\"",
".",
"join",
"(",
"[",
"\"?\"",
"]",
"*",
"len",
"(",
"fieldlist",
")",
")",
"+",
"\")\"",
")"
] | Returns ?-marked SQL for an INSERT statement. | [
"Returns",
"?",
"-",
"marked",
"SQL",
"for",
"an",
"INSERT",
"statement",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L923-L934 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | get_sql_insert_or_update | def get_sql_insert_or_update(table: str,
fieldlist: Sequence[str],
delims: Tuple[str, str] = ("", "")) -> str:
"""Returns ?-marked SQL for an INSERT-or-if-duplicate-key-UPDATE statement.
"""
# http://stackoverflow.com/questions/4205181
return """
INSERT INTO {table} ({fields})
VALUES ({placeholders})
ON DUPLICATE KEY UPDATE {updatelist}
""".format(
table=delimit(table, delims),
fields=",".join([delimit(x, delims) for x in fieldlist]),
placeholders=",".join(["?"] * len(fieldlist)),
updatelist=",".join(
["{field}=VALUES({field})".format(field=delimit(x, delims))
for x in fieldlist]
),
) | python | def get_sql_insert_or_update(table: str,
fieldlist: Sequence[str],
delims: Tuple[str, str] = ("", "")) -> str:
"""Returns ?-marked SQL for an INSERT-or-if-duplicate-key-UPDATE statement.
"""
# http://stackoverflow.com/questions/4205181
return """
INSERT INTO {table} ({fields})
VALUES ({placeholders})
ON DUPLICATE KEY UPDATE {updatelist}
""".format(
table=delimit(table, delims),
fields=",".join([delimit(x, delims) for x in fieldlist]),
placeholders=",".join(["?"] * len(fieldlist)),
updatelist=",".join(
["{field}=VALUES({field})".format(field=delimit(x, delims))
for x in fieldlist]
),
) | [
"def",
"get_sql_insert_or_update",
"(",
"table",
":",
"str",
",",
"fieldlist",
":",
"Sequence",
"[",
"str",
"]",
",",
"delims",
":",
"Tuple",
"[",
"str",
",",
"str",
"]",
"=",
"(",
"\"\"",
",",
"\"\"",
")",
")",
"->",
"str",
":",
"# http://stackoverflow.com/questions/4205181",
"return",
"\"\"\"\n INSERT INTO {table} ({fields})\n VALUES ({placeholders})\n ON DUPLICATE KEY UPDATE {updatelist}\n \"\"\"",
".",
"format",
"(",
"table",
"=",
"delimit",
"(",
"table",
",",
"delims",
")",
",",
"fields",
"=",
"\",\"",
".",
"join",
"(",
"[",
"delimit",
"(",
"x",
",",
"delims",
")",
"for",
"x",
"in",
"fieldlist",
"]",
")",
",",
"placeholders",
"=",
"\",\"",
".",
"join",
"(",
"[",
"\"?\"",
"]",
"*",
"len",
"(",
"fieldlist",
")",
")",
",",
"updatelist",
"=",
"\",\"",
".",
"join",
"(",
"[",
"\"{field}=VALUES({field})\"",
".",
"format",
"(",
"field",
"=",
"delimit",
"(",
"x",
",",
"delims",
")",
")",
"for",
"x",
"in",
"fieldlist",
"]",
")",
",",
")"
] | Returns ?-marked SQL for an INSERT-or-if-duplicate-key-UPDATE statement. | [
"Returns",
"?",
"-",
"marked",
"SQL",
"for",
"an",
"INSERT",
"-",
"or",
"-",
"if",
"-",
"duplicate",
"-",
"key",
"-",
"UPDATE",
"statement",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L937-L955 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | get_sql_insert_without_first_field | def get_sql_insert_without_first_field(
table: str,
fieldlist: Sequence[str],
delims: Tuple[str, str] = ("", "")) -> str:
"""Returns ?-marked SQL for an INSERT statement, ignoring the first field
(typically, the PK)."""
return get_sql_insert(table, fieldlist[1:], delims) | python | def get_sql_insert_without_first_field(
table: str,
fieldlist: Sequence[str],
delims: Tuple[str, str] = ("", "")) -> str:
"""Returns ?-marked SQL for an INSERT statement, ignoring the first field
(typically, the PK)."""
return get_sql_insert(table, fieldlist[1:], delims) | [
"def",
"get_sql_insert_without_first_field",
"(",
"table",
":",
"str",
",",
"fieldlist",
":",
"Sequence",
"[",
"str",
"]",
",",
"delims",
":",
"Tuple",
"[",
"str",
",",
"str",
"]",
"=",
"(",
"\"\"",
",",
"\"\"",
")",
")",
"->",
"str",
":",
"return",
"get_sql_insert",
"(",
"table",
",",
"fieldlist",
"[",
"1",
":",
"]",
",",
"delims",
")"
] | Returns ?-marked SQL for an INSERT statement, ignoring the first field
(typically, the PK). | [
"Returns",
"?",
"-",
"marked",
"SQL",
"for",
"an",
"INSERT",
"statement",
"ignoring",
"the",
"first",
"field",
"(",
"typically",
"the",
"PK",
")",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L958-L964 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | get_sql_update_by_first_field | def get_sql_update_by_first_field(table: str,
fieldlist: Sequence[str],
delims: Tuple[str, str] = ("", "")) -> str:
"""Returns SQL for an UPDATE statement, to update all fields except the
first field (PK) using the PK as the key."""
return (
"UPDATE " + delimit(table, delims) +
" SET " +
",".join([delimit(x, delims) + "=?" for x in fieldlist[1:]]) +
" WHERE " + delimit(fieldlist[0], delims) + "=?"
) | python | def get_sql_update_by_first_field(table: str,
fieldlist: Sequence[str],
delims: Tuple[str, str] = ("", "")) -> str:
"""Returns SQL for an UPDATE statement, to update all fields except the
first field (PK) using the PK as the key."""
return (
"UPDATE " + delimit(table, delims) +
" SET " +
",".join([delimit(x, delims) + "=?" for x in fieldlist[1:]]) +
" WHERE " + delimit(fieldlist[0], delims) + "=?"
) | [
"def",
"get_sql_update_by_first_field",
"(",
"table",
":",
"str",
",",
"fieldlist",
":",
"Sequence",
"[",
"str",
"]",
",",
"delims",
":",
"Tuple",
"[",
"str",
",",
"str",
"]",
"=",
"(",
"\"\"",
",",
"\"\"",
")",
")",
"->",
"str",
":",
"return",
"(",
"\"UPDATE \"",
"+",
"delimit",
"(",
"table",
",",
"delims",
")",
"+",
"\" SET \"",
"+",
"\",\"",
".",
"join",
"(",
"[",
"delimit",
"(",
"x",
",",
"delims",
")",
"+",
"\"=?\"",
"for",
"x",
"in",
"fieldlist",
"[",
"1",
":",
"]",
"]",
")",
"+",
"\" WHERE \"",
"+",
"delimit",
"(",
"fieldlist",
"[",
"0",
"]",
",",
"delims",
")",
"+",
"\"=?\"",
")"
] | Returns SQL for an UPDATE statement, to update all fields except the
first field (PK) using the PK as the key. | [
"Returns",
"SQL",
"for",
"an",
"UPDATE",
"statement",
"to",
"update",
"all",
"fields",
"except",
"the",
"first",
"field",
"(",
"PK",
")",
"using",
"the",
"PK",
"as",
"the",
"key",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L967-L977 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | sql_dequote_string | def sql_dequote_string(s: str) -> str:
"""Reverses sql_quote_string."""
if len(s) < 2:
# Something wrong.
return s
s = s[1:-1] # strip off the surrounding quotes
return s.replace("''", "'") | python | def sql_dequote_string(s: str) -> str:
"""Reverses sql_quote_string."""
if len(s) < 2:
# Something wrong.
return s
s = s[1:-1] # strip off the surrounding quotes
return s.replace("''", "'") | [
"def",
"sql_dequote_string",
"(",
"s",
":",
"str",
")",
"->",
"str",
":",
"if",
"len",
"(",
"s",
")",
"<",
"2",
":",
"# Something wrong.",
"return",
"s",
"s",
"=",
"s",
"[",
"1",
":",
"-",
"1",
"]",
"# strip off the surrounding quotes",
"return",
"s",
".",
"replace",
"(",
"\"''\"",
",",
"\"'\"",
")"
] | Reverses sql_quote_string. | [
"Reverses",
"sql_quote_string",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L985-L991 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | datetime2literal_rnc | def datetime2literal_rnc(d: datetime.datetime, c: Optional[Dict]) -> str:
"""Format a DateTime object as something MySQL will actually accept."""
# dt = d.strftime("%Y-%m-%d %H:%M:%S")
# ... can fail with e.g.
# ValueError: year=1850 is before 1900; the datetime strftime() methods
# require year >= 1900
# http://stackoverflow.com/questions/10263956
dt = d.isoformat(" ")
# noinspection PyArgumentList
return _mysql.string_literal(dt, c) | python | def datetime2literal_rnc(d: datetime.datetime, c: Optional[Dict]) -> str:
"""Format a DateTime object as something MySQL will actually accept."""
# dt = d.strftime("%Y-%m-%d %H:%M:%S")
# ... can fail with e.g.
# ValueError: year=1850 is before 1900; the datetime strftime() methods
# require year >= 1900
# http://stackoverflow.com/questions/10263956
dt = d.isoformat(" ")
# noinspection PyArgumentList
return _mysql.string_literal(dt, c) | [
"def",
"datetime2literal_rnc",
"(",
"d",
":",
"datetime",
".",
"datetime",
",",
"c",
":",
"Optional",
"[",
"Dict",
"]",
")",
"->",
"str",
":",
"# dt = d.strftime(\"%Y-%m-%d %H:%M:%S\")",
"# ... can fail with e.g.",
"# ValueError: year=1850 is before 1900; the datetime strftime() methods",
"# require year >= 1900",
"# http://stackoverflow.com/questions/10263956",
"dt",
"=",
"d",
".",
"isoformat",
"(",
"\" \"",
")",
"# noinspection PyArgumentList",
"return",
"_mysql",
".",
"string_literal",
"(",
"dt",
",",
"c",
")"
] | Format a DateTime object as something MySQL will actually accept. | [
"Format",
"a",
"DateTime",
"object",
"as",
"something",
"MySQL",
"will",
"actually",
"accept",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L994-L1003 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | full_datatype_to_mysql | def full_datatype_to_mysql(d: str) -> str:
"""Converts a full datatype, e.g. INT, VARCHAR(10), VARCHAR(MAX), to a
MySQL equivalent."""
d = d.upper()
(s, length) = split_long_sqltype(d)
if d in ["VARCHAR(MAX)", "NVARCHAR(MAX)"]:
# http://wiki.ispirer.com/sqlways/mysql/data-types/longtext
return "LONGTEXT"
elif d in ["VARBINARY(MAX)"] or s in ["IMAGE"]:
# http://wiki.ispirer.com/sqlways/mysql/data-types/varbinary
return "LONGBLOB"
else:
return d | python | def full_datatype_to_mysql(d: str) -> str:
"""Converts a full datatype, e.g. INT, VARCHAR(10), VARCHAR(MAX), to a
MySQL equivalent."""
d = d.upper()
(s, length) = split_long_sqltype(d)
if d in ["VARCHAR(MAX)", "NVARCHAR(MAX)"]:
# http://wiki.ispirer.com/sqlways/mysql/data-types/longtext
return "LONGTEXT"
elif d in ["VARBINARY(MAX)"] or s in ["IMAGE"]:
# http://wiki.ispirer.com/sqlways/mysql/data-types/varbinary
return "LONGBLOB"
else:
return d | [
"def",
"full_datatype_to_mysql",
"(",
"d",
":",
"str",
")",
"->",
"str",
":",
"d",
"=",
"d",
".",
"upper",
"(",
")",
"(",
"s",
",",
"length",
")",
"=",
"split_long_sqltype",
"(",
"d",
")",
"if",
"d",
"in",
"[",
"\"VARCHAR(MAX)\"",
",",
"\"NVARCHAR(MAX)\"",
"]",
":",
"# http://wiki.ispirer.com/sqlways/mysql/data-types/longtext",
"return",
"\"LONGTEXT\"",
"elif",
"d",
"in",
"[",
"\"VARBINARY(MAX)\"",
"]",
"or",
"s",
"in",
"[",
"\"IMAGE\"",
"]",
":",
"# http://wiki.ispirer.com/sqlways/mysql/data-types/varbinary",
"return",
"\"LONGBLOB\"",
"else",
":",
"return",
"d"
] | Converts a full datatype, e.g. INT, VARCHAR(10), VARCHAR(MAX), to a
MySQL equivalent. | [
"Converts",
"a",
"full",
"datatype",
"e",
".",
"g",
".",
"INT",
"VARCHAR",
"(",
"10",
")",
"VARCHAR",
"(",
"MAX",
")",
"to",
"a",
"MySQL",
"equivalent",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L1006-L1018 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | debug_object | def debug_object(obj: T) -> str:
"""Prints key/value pairs for an object's dictionary."""
pairs = []
for k, v in vars(obj).items():
pairs.append(u"{}={}".format(k, v))
return u", ".join(pairs) | python | def debug_object(obj: T) -> str:
"""Prints key/value pairs for an object's dictionary."""
pairs = []
for k, v in vars(obj).items():
pairs.append(u"{}={}".format(k, v))
return u", ".join(pairs) | [
"def",
"debug_object",
"(",
"obj",
":",
"T",
")",
"->",
"str",
":",
"pairs",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"vars",
"(",
"obj",
")",
".",
"items",
"(",
")",
":",
"pairs",
".",
"append",
"(",
"u\"{}={}\"",
".",
"format",
"(",
"k",
",",
"v",
")",
")",
"return",
"u\", \"",
".",
"join",
"(",
"pairs",
")"
] | Prints key/value pairs for an object's dictionary. | [
"Prints",
"key",
"/",
"value",
"pairs",
"for",
"an",
"object",
"s",
"dictionary",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L1025-L1030 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | dump_database_object | def dump_database_object(obj: T, fieldlist: Iterable[str]) -> None:
"""Prints key/value pairs for an object's dictionary."""
log.info(_LINE_EQUALS)
log.info("DUMP OF: {}", obj)
for f in fieldlist:
log.info(u"{f}: {v}", f=f, v=getattr(obj, f))
log.info(_LINE_EQUALS) | python | def dump_database_object(obj: T, fieldlist: Iterable[str]) -> None:
"""Prints key/value pairs for an object's dictionary."""
log.info(_LINE_EQUALS)
log.info("DUMP OF: {}", obj)
for f in fieldlist:
log.info(u"{f}: {v}", f=f, v=getattr(obj, f))
log.info(_LINE_EQUALS) | [
"def",
"dump_database_object",
"(",
"obj",
":",
"T",
",",
"fieldlist",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"None",
":",
"log",
".",
"info",
"(",
"_LINE_EQUALS",
")",
"log",
".",
"info",
"(",
"\"DUMP OF: {}\"",
",",
"obj",
")",
"for",
"f",
"in",
"fieldlist",
":",
"log",
".",
"info",
"(",
"u\"{f}: {v}\"",
",",
"f",
"=",
"f",
",",
"v",
"=",
"getattr",
"(",
"obj",
",",
"f",
")",
")",
"log",
".",
"info",
"(",
"_LINE_EQUALS",
")"
] | Prints key/value pairs for an object's dictionary. | [
"Prints",
"key",
"/",
"value",
"pairs",
"for",
"an",
"object",
"s",
"dictionary",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L1033-L1039 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | assign_from_list | def assign_from_list(obj: T,
fieldlist: Sequence[str],
valuelist: Sequence[any]) -> None:
"""Within "obj", assigns the values from the value list to the fields in
the fieldlist."""
if len(fieldlist) != len(valuelist):
raise AssertionError("assign_from_list: fieldlist and valuelist of "
"different length")
for i in range(len(valuelist)):
setattr(obj, fieldlist[i], valuelist[i]) | python | def assign_from_list(obj: T,
fieldlist: Sequence[str],
valuelist: Sequence[any]) -> None:
"""Within "obj", assigns the values from the value list to the fields in
the fieldlist."""
if len(fieldlist) != len(valuelist):
raise AssertionError("assign_from_list: fieldlist and valuelist of "
"different length")
for i in range(len(valuelist)):
setattr(obj, fieldlist[i], valuelist[i]) | [
"def",
"assign_from_list",
"(",
"obj",
":",
"T",
",",
"fieldlist",
":",
"Sequence",
"[",
"str",
"]",
",",
"valuelist",
":",
"Sequence",
"[",
"any",
"]",
")",
"->",
"None",
":",
"if",
"len",
"(",
"fieldlist",
")",
"!=",
"len",
"(",
"valuelist",
")",
":",
"raise",
"AssertionError",
"(",
"\"assign_from_list: fieldlist and valuelist of \"",
"\"different length\"",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"valuelist",
")",
")",
":",
"setattr",
"(",
"obj",
",",
"fieldlist",
"[",
"i",
"]",
",",
"valuelist",
"[",
"i",
"]",
")"
] | Within "obj", assigns the values from the value list to the fields in
the fieldlist. | [
"Within",
"obj",
"assigns",
"the",
"values",
"from",
"the",
"value",
"list",
"to",
"the",
"fields",
"in",
"the",
"fieldlist",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L1042-L1051 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | create_object_from_list | def create_object_from_list(cls: Type,
fieldlist: Sequence[str],
valuelist: Sequence[Any],
*args, **kwargs) -> T:
"""
Create an object by instantiating ``cls(*args, **kwargs)`` and assigning the
values in ``valuelist`` to the fields in ``fieldlist``.
If ``construct_with_pk`` is ``True``, initialize with
``cls(valuelist[0], *args, **kwargs)``
and assign the values in ``valuelist[1:]`` to ``fieldlist[1:]``.
Note: in Python 3, we could define as
.. code-block:: none
...(... valuelist, *args, construct_with_pk=False, **kwargs):
but not in Python 2, and this is meant to be back-compatible.
"""
construct_with_pk = kwargs.pop('construct_with_pk', False)
# print("construct_with_pk: {}".format(construct_with_pk))
# print("args: {}".format(args))
# print("kwargs: {}".format(kwargs))
if construct_with_pk:
obj = cls(valuelist[0], *args, **kwargs)
assign_from_list(obj, fieldlist[1:], valuelist[1:])
else:
obj = cls(*args, **kwargs)
assign_from_list(obj, fieldlist, valuelist)
return obj | python | def create_object_from_list(cls: Type,
fieldlist: Sequence[str],
valuelist: Sequence[Any],
*args, **kwargs) -> T:
"""
Create an object by instantiating ``cls(*args, **kwargs)`` and assigning the
values in ``valuelist`` to the fields in ``fieldlist``.
If ``construct_with_pk`` is ``True``, initialize with
``cls(valuelist[0], *args, **kwargs)``
and assign the values in ``valuelist[1:]`` to ``fieldlist[1:]``.
Note: in Python 3, we could define as
.. code-block:: none
...(... valuelist, *args, construct_with_pk=False, **kwargs):
but not in Python 2, and this is meant to be back-compatible.
"""
construct_with_pk = kwargs.pop('construct_with_pk', False)
# print("construct_with_pk: {}".format(construct_with_pk))
# print("args: {}".format(args))
# print("kwargs: {}".format(kwargs))
if construct_with_pk:
obj = cls(valuelist[0], *args, **kwargs)
assign_from_list(obj, fieldlist[1:], valuelist[1:])
else:
obj = cls(*args, **kwargs)
assign_from_list(obj, fieldlist, valuelist)
return obj | [
"def",
"create_object_from_list",
"(",
"cls",
":",
"Type",
",",
"fieldlist",
":",
"Sequence",
"[",
"str",
"]",
",",
"valuelist",
":",
"Sequence",
"[",
"Any",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"T",
":",
"construct_with_pk",
"=",
"kwargs",
".",
"pop",
"(",
"'construct_with_pk'",
",",
"False",
")",
"# print(\"construct_with_pk: {}\".format(construct_with_pk))",
"# print(\"args: {}\".format(args))",
"# print(\"kwargs: {}\".format(kwargs))",
"if",
"construct_with_pk",
":",
"obj",
"=",
"cls",
"(",
"valuelist",
"[",
"0",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"assign_from_list",
"(",
"obj",
",",
"fieldlist",
"[",
"1",
":",
"]",
",",
"valuelist",
"[",
"1",
":",
"]",
")",
"else",
":",
"obj",
"=",
"cls",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"assign_from_list",
"(",
"obj",
",",
"fieldlist",
",",
"valuelist",
")",
"return",
"obj"
] | Create an object by instantiating ``cls(*args, **kwargs)`` and assigning the
values in ``valuelist`` to the fields in ``fieldlist``.
If ``construct_with_pk`` is ``True``, initialize with
``cls(valuelist[0], *args, **kwargs)``
and assign the values in ``valuelist[1:]`` to ``fieldlist[1:]``.
Note: in Python 3, we could define as
.. code-block:: none
...(... valuelist, *args, construct_with_pk=False, **kwargs):
but not in Python 2, and this is meant to be back-compatible. | [
"Create",
"an",
"object",
"by",
"instantiating",
"cls",
"(",
"*",
"args",
"**",
"kwargs",
")",
"and",
"assigning",
"the",
"values",
"in",
"valuelist",
"to",
"the",
"fields",
"in",
"fieldlist",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L1054-L1084 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | blank_object | def blank_object(obj: T, fieldlist: Sequence[str]) -> None:
"""Within "obj", sets all fields in the fieldlist to None."""
for f in fieldlist:
setattr(obj, f, None) | python | def blank_object(obj: T, fieldlist: Sequence[str]) -> None:
"""Within "obj", sets all fields in the fieldlist to None."""
for f in fieldlist:
setattr(obj, f, None) | [
"def",
"blank_object",
"(",
"obj",
":",
"T",
",",
"fieldlist",
":",
"Sequence",
"[",
"str",
"]",
")",
"->",
"None",
":",
"for",
"f",
"in",
"fieldlist",
":",
"setattr",
"(",
"obj",
",",
"f",
",",
"None",
")"
] | Within "obj", sets all fields in the fieldlist to None. | [
"Within",
"obj",
"sets",
"all",
"fields",
"in",
"the",
"fieldlist",
"to",
"None",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L1087-L1090 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | debug_query_result | def debug_query_result(rows: Sequence[Any]) -> None:
"""Writes a query result to the log."""
log.info("Retrieved {} rows", len(rows))
for i in range(len(rows)):
log.info("Row {}: {}", i, rows[i]) | python | def debug_query_result(rows: Sequence[Any]) -> None:
"""Writes a query result to the log."""
log.info("Retrieved {} rows", len(rows))
for i in range(len(rows)):
log.info("Row {}: {}", i, rows[i]) | [
"def",
"debug_query_result",
"(",
"rows",
":",
"Sequence",
"[",
"Any",
"]",
")",
"->",
"None",
":",
"log",
".",
"info",
"(",
"\"Retrieved {} rows\"",
",",
"len",
"(",
"rows",
")",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"rows",
")",
")",
":",
"log",
".",
"info",
"(",
"\"Row {}: {}\"",
",",
"i",
",",
"rows",
"[",
"i",
"]",
")"
] | Writes a query result to the log. | [
"Writes",
"a",
"query",
"result",
"to",
"the",
"log",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L1093-L1097 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | create_database_mysql | def create_database_mysql(database: str,
user: str,
password: str,
server: str = "localhost",
port: int = 3306,
charset: str = "utf8",
collate: str = "utf8_general_ci",
use_unicode: bool = True) -> bool:
"""Connects via PyMySQL/MySQLdb and creates a database."""
con = mysql.connect(
host=server,
port=port,
user=user,
passwd=password,
charset=charset,
use_unicode=use_unicode
)
sql = ("CREATE DATABASE IF NOT EXISTS {} DEFAULT CHARACTER SET {} "
"DEFAULT COLLATE {}").format(
database,
charset,
collate
)
cursor = con.cursor()
debug_sql(sql)
cursor.execute(sql)
log.info("Created database {}", database)
return True | python | def create_database_mysql(database: str,
user: str,
password: str,
server: str = "localhost",
port: int = 3306,
charset: str = "utf8",
collate: str = "utf8_general_ci",
use_unicode: bool = True) -> bool:
"""Connects via PyMySQL/MySQLdb and creates a database."""
con = mysql.connect(
host=server,
port=port,
user=user,
passwd=password,
charset=charset,
use_unicode=use_unicode
)
sql = ("CREATE DATABASE IF NOT EXISTS {} DEFAULT CHARACTER SET {} "
"DEFAULT COLLATE {}").format(
database,
charset,
collate
)
cursor = con.cursor()
debug_sql(sql)
cursor.execute(sql)
log.info("Created database {}", database)
return True | [
"def",
"create_database_mysql",
"(",
"database",
":",
"str",
",",
"user",
":",
"str",
",",
"password",
":",
"str",
",",
"server",
":",
"str",
"=",
"\"localhost\"",
",",
"port",
":",
"int",
"=",
"3306",
",",
"charset",
":",
"str",
"=",
"\"utf8\"",
",",
"collate",
":",
"str",
"=",
"\"utf8_general_ci\"",
",",
"use_unicode",
":",
"bool",
"=",
"True",
")",
"->",
"bool",
":",
"con",
"=",
"mysql",
".",
"connect",
"(",
"host",
"=",
"server",
",",
"port",
"=",
"port",
",",
"user",
"=",
"user",
",",
"passwd",
"=",
"password",
",",
"charset",
"=",
"charset",
",",
"use_unicode",
"=",
"use_unicode",
")",
"sql",
"=",
"(",
"\"CREATE DATABASE IF NOT EXISTS {} DEFAULT CHARACTER SET {} \"",
"\"DEFAULT COLLATE {}\"",
")",
".",
"format",
"(",
"database",
",",
"charset",
",",
"collate",
")",
"cursor",
"=",
"con",
".",
"cursor",
"(",
")",
"debug_sql",
"(",
"sql",
")",
"cursor",
".",
"execute",
"(",
"sql",
")",
"log",
".",
"info",
"(",
"\"Created database {}\"",
",",
"database",
")",
"return",
"True"
] | Connects via PyMySQL/MySQLdb and creates a database. | [
"Connects",
"via",
"PyMySQL",
"/",
"MySQLdb",
"and",
"creates",
"a",
"database",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L1398-L1425 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | add_master_user_mysql | def add_master_user_mysql(database: str,
root_user: str,
root_password: str,
new_user: str,
new_password: str,
server: str = "localhost",
port: int = 3306,
charset: str = "utf8",
use_unicode: bool = True,
localhost_only: bool = True) -> None:
"""Connects via PyMySQL/MySQLdb and creates a database superuser."""
con = mysql.connect(
host=server,
port=port,
user=root_user,
passwd=root_password,
charset=charset,
use_unicode=use_unicode
)
wherefrom = "localhost" if localhost_only else "%"
sql = ("GRANT ALL PRIVILEGES ON {}.* TO '{}'@'{}' "
"IDENTIFIED BY '{}'").format(
database,
new_user,
wherefrom,
new_password
)
cursor = con.cursor()
debug_sql(sql)
cursor.execute(sql)
log.info("Added master user {} to database {}", new_user, database) | python | def add_master_user_mysql(database: str,
root_user: str,
root_password: str,
new_user: str,
new_password: str,
server: str = "localhost",
port: int = 3306,
charset: str = "utf8",
use_unicode: bool = True,
localhost_only: bool = True) -> None:
"""Connects via PyMySQL/MySQLdb and creates a database superuser."""
con = mysql.connect(
host=server,
port=port,
user=root_user,
passwd=root_password,
charset=charset,
use_unicode=use_unicode
)
wherefrom = "localhost" if localhost_only else "%"
sql = ("GRANT ALL PRIVILEGES ON {}.* TO '{}'@'{}' "
"IDENTIFIED BY '{}'").format(
database,
new_user,
wherefrom,
new_password
)
cursor = con.cursor()
debug_sql(sql)
cursor.execute(sql)
log.info("Added master user {} to database {}", new_user, database) | [
"def",
"add_master_user_mysql",
"(",
"database",
":",
"str",
",",
"root_user",
":",
"str",
",",
"root_password",
":",
"str",
",",
"new_user",
":",
"str",
",",
"new_password",
":",
"str",
",",
"server",
":",
"str",
"=",
"\"localhost\"",
",",
"port",
":",
"int",
"=",
"3306",
",",
"charset",
":",
"str",
"=",
"\"utf8\"",
",",
"use_unicode",
":",
"bool",
"=",
"True",
",",
"localhost_only",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"con",
"=",
"mysql",
".",
"connect",
"(",
"host",
"=",
"server",
",",
"port",
"=",
"port",
",",
"user",
"=",
"root_user",
",",
"passwd",
"=",
"root_password",
",",
"charset",
"=",
"charset",
",",
"use_unicode",
"=",
"use_unicode",
")",
"wherefrom",
"=",
"\"localhost\"",
"if",
"localhost_only",
"else",
"\"%\"",
"sql",
"=",
"(",
"\"GRANT ALL PRIVILEGES ON {}.* TO '{}'@'{}' \"",
"\"IDENTIFIED BY '{}'\"",
")",
".",
"format",
"(",
"database",
",",
"new_user",
",",
"wherefrom",
",",
"new_password",
")",
"cursor",
"=",
"con",
".",
"cursor",
"(",
")",
"debug_sql",
"(",
"sql",
")",
"cursor",
".",
"execute",
"(",
"sql",
")",
"log",
".",
"info",
"(",
"\"Added master user {} to database {}\"",
",",
"new_user",
",",
"database",
")"
] | Connects via PyMySQL/MySQLdb and creates a database superuser. | [
"Connects",
"via",
"PyMySQL",
"/",
"MySQLdb",
"and",
"creates",
"a",
"database",
"superuser",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L1428-L1458 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | Flavour.describe_table | def describe_table(cls,
db: DATABASE_SUPPORTER_FWD_REF,
table: str) -> List[List[Any]]:
"""Returns details on a specific table."""
raise RuntimeError(_MSG_NO_FLAVOUR) | python | def describe_table(cls,
db: DATABASE_SUPPORTER_FWD_REF,
table: str) -> List[List[Any]]:
"""Returns details on a specific table."""
raise RuntimeError(_MSG_NO_FLAVOUR) | [
"def",
"describe_table",
"(",
"cls",
",",
"db",
":",
"DATABASE_SUPPORTER_FWD_REF",
",",
"table",
":",
"str",
")",
"->",
"List",
"[",
"List",
"[",
"Any",
"]",
"]",
":",
"raise",
"RuntimeError",
"(",
"_MSG_NO_FLAVOUR",
")"
] | Returns details on a specific table. | [
"Returns",
"details",
"on",
"a",
"specific",
"table",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L308-L312 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | Flavour.fetch_column_names | def fetch_column_names(cls,
db: DATABASE_SUPPORTER_FWD_REF,
table: str) -> List[str]:
"""Returns all column names for a table."""
raise RuntimeError(_MSG_NO_FLAVOUR) | python | def fetch_column_names(cls,
db: DATABASE_SUPPORTER_FWD_REF,
table: str) -> List[str]:
"""Returns all column names for a table."""
raise RuntimeError(_MSG_NO_FLAVOUR) | [
"def",
"fetch_column_names",
"(",
"cls",
",",
"db",
":",
"DATABASE_SUPPORTER_FWD_REF",
",",
"table",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"raise",
"RuntimeError",
"(",
"_MSG_NO_FLAVOUR",
")"
] | Returns all column names for a table. | [
"Returns",
"all",
"column",
"names",
"for",
"a",
"table",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L315-L319 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | Flavour.get_datatype | def get_datatype(cls,
db: DATABASE_SUPPORTER_FWD_REF,
table: str,
column: str) -> str:
"""Returns database SQL datatype for a column: e.g. VARCHAR."""
raise RuntimeError(_MSG_NO_FLAVOUR) | python | def get_datatype(cls,
db: DATABASE_SUPPORTER_FWD_REF,
table: str,
column: str) -> str:
"""Returns database SQL datatype for a column: e.g. VARCHAR."""
raise RuntimeError(_MSG_NO_FLAVOUR) | [
"def",
"get_datatype",
"(",
"cls",
",",
"db",
":",
"DATABASE_SUPPORTER_FWD_REF",
",",
"table",
":",
"str",
",",
"column",
":",
"str",
")",
"->",
"str",
":",
"raise",
"RuntimeError",
"(",
"_MSG_NO_FLAVOUR",
")"
] | Returns database SQL datatype for a column: e.g. VARCHAR. | [
"Returns",
"database",
"SQL",
"datatype",
"for",
"a",
"column",
":",
"e",
".",
"g",
".",
"VARCHAR",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L322-L327 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | MySQL.is_read_only | def is_read_only(cls,
db: DATABASE_SUPPORTER_FWD_REF,
logger: logging.Logger = None) -> bool:
"""Do we have read-only access?"""
def convert_enums(row_):
# All these columns are of type enum('N', 'Y');
# https://dev.mysql.com/doc/refman/5.0/en/enum.html
return [True if x == 'Y' else (False if x == 'N' else None)
for x in row_]
# 1. Check per-database privileges.
# We don't check SELECT privileges. We're just trying to ensure
# nothing dangerous is present - for ANY database.
# If we get an exception
try:
sql = """
SELECT db,
/* must not have: */
Insert_priv, Update_priv, Delete_priv,
Create_priv, Drop_priv, Index_priv, Alter_priv,
Lock_tables_priv, Create_view_priv,
Create_routine_priv, Alter_routine_priv,
Execute_priv, Event_priv, Trigger_priv
FROM mysql.db
WHERE
CONCAT(user, '@', host) = CURRENT_USER()
"""
rows = db.fetchall(sql)
for row in rows:
dbname = row[0]
prohibited = convert_enums(row[1:])
if any(prohibited):
if logger:
logger.debug(
"MySQL.is_read_only(): FAIL: database privileges "
"wrong: dbname={}, prohibited={}".format(
dbname, prohibited
)
)
return False
except mysql.OperationalError:
# Probably: error 1142, "SELECT command denied to user 'xxx'@'yyy'
# for table 'db'". This would be OK.
pass
# 2. Global privileges, e.g. as held by root
try:
sql = """
SELECT /* must not have: */
Insert_priv, Update_priv, Delete_priv,
Create_priv, Drop_priv,
Reload_priv, Shutdown_priv,
Process_priv, File_priv, Grant_priv,
Index_priv, Alter_priv,
Show_db_priv, Super_priv,
Lock_tables_priv, Execute_priv,
Repl_slave_priv, Repl_client_priv,
Create_view_priv,
Create_routine_priv, Alter_routine_priv,
Create_user_priv,
Event_priv, Trigger_priv,
Create_tablespace_priv
FROM mysql.user
WHERE
CONCAT(user, '@', host) = CURRENT_USER()
"""
rows = db.fetchall(sql)
if not rows or len(rows) > 1:
return False
prohibited = convert_enums(rows[0])
if any(prohibited):
if logger:
logger.debug(
"MySQL.is_read_only(): FAIL: GLOBAL privileges "
"wrong: prohibited={}".format(prohibited))
return False
except mysql.OperationalError:
# Probably: error 1142, "SELECT command denied to user 'xxx'@'yyy'
# for table 'user'". This would be OK.
pass
return True | python | def is_read_only(cls,
db: DATABASE_SUPPORTER_FWD_REF,
logger: logging.Logger = None) -> bool:
"""Do we have read-only access?"""
def convert_enums(row_):
# All these columns are of type enum('N', 'Y');
# https://dev.mysql.com/doc/refman/5.0/en/enum.html
return [True if x == 'Y' else (False if x == 'N' else None)
for x in row_]
# 1. Check per-database privileges.
# We don't check SELECT privileges. We're just trying to ensure
# nothing dangerous is present - for ANY database.
# If we get an exception
try:
sql = """
SELECT db,
/* must not have: */
Insert_priv, Update_priv, Delete_priv,
Create_priv, Drop_priv, Index_priv, Alter_priv,
Lock_tables_priv, Create_view_priv,
Create_routine_priv, Alter_routine_priv,
Execute_priv, Event_priv, Trigger_priv
FROM mysql.db
WHERE
CONCAT(user, '@', host) = CURRENT_USER()
"""
rows = db.fetchall(sql)
for row in rows:
dbname = row[0]
prohibited = convert_enums(row[1:])
if any(prohibited):
if logger:
logger.debug(
"MySQL.is_read_only(): FAIL: database privileges "
"wrong: dbname={}, prohibited={}".format(
dbname, prohibited
)
)
return False
except mysql.OperationalError:
# Probably: error 1142, "SELECT command denied to user 'xxx'@'yyy'
# for table 'db'". This would be OK.
pass
# 2. Global privileges, e.g. as held by root
try:
sql = """
SELECT /* must not have: */
Insert_priv, Update_priv, Delete_priv,
Create_priv, Drop_priv,
Reload_priv, Shutdown_priv,
Process_priv, File_priv, Grant_priv,
Index_priv, Alter_priv,
Show_db_priv, Super_priv,
Lock_tables_priv, Execute_priv,
Repl_slave_priv, Repl_client_priv,
Create_view_priv,
Create_routine_priv, Alter_routine_priv,
Create_user_priv,
Event_priv, Trigger_priv,
Create_tablespace_priv
FROM mysql.user
WHERE
CONCAT(user, '@', host) = CURRENT_USER()
"""
rows = db.fetchall(sql)
if not rows or len(rows) > 1:
return False
prohibited = convert_enums(rows[0])
if any(prohibited):
if logger:
logger.debug(
"MySQL.is_read_only(): FAIL: GLOBAL privileges "
"wrong: prohibited={}".format(prohibited))
return False
except mysql.OperationalError:
# Probably: error 1142, "SELECT command denied to user 'xxx'@'yyy'
# for table 'user'". This would be OK.
pass
return True | [
"def",
"is_read_only",
"(",
"cls",
",",
"db",
":",
"DATABASE_SUPPORTER_FWD_REF",
",",
"logger",
":",
"logging",
".",
"Logger",
"=",
"None",
")",
"->",
"bool",
":",
"def",
"convert_enums",
"(",
"row_",
")",
":",
"# All these columns are of type enum('N', 'Y');",
"# https://dev.mysql.com/doc/refman/5.0/en/enum.html",
"return",
"[",
"True",
"if",
"x",
"==",
"'Y'",
"else",
"(",
"False",
"if",
"x",
"==",
"'N'",
"else",
"None",
")",
"for",
"x",
"in",
"row_",
"]",
"# 1. Check per-database privileges.",
"# We don't check SELECT privileges. We're just trying to ensure",
"# nothing dangerous is present - for ANY database.",
"# If we get an exception",
"try",
":",
"sql",
"=",
"\"\"\"\n SELECT db,\n /* must not have: */\n Insert_priv, Update_priv, Delete_priv,\n Create_priv, Drop_priv, Index_priv, Alter_priv,\n Lock_tables_priv, Create_view_priv,\n Create_routine_priv, Alter_routine_priv,\n Execute_priv, Event_priv, Trigger_priv\n FROM mysql.db\n WHERE\n CONCAT(user, '@', host) = CURRENT_USER()\n \"\"\"",
"rows",
"=",
"db",
".",
"fetchall",
"(",
"sql",
")",
"for",
"row",
"in",
"rows",
":",
"dbname",
"=",
"row",
"[",
"0",
"]",
"prohibited",
"=",
"convert_enums",
"(",
"row",
"[",
"1",
":",
"]",
")",
"if",
"any",
"(",
"prohibited",
")",
":",
"if",
"logger",
":",
"logger",
".",
"debug",
"(",
"\"MySQL.is_read_only(): FAIL: database privileges \"",
"\"wrong: dbname={}, prohibited={}\"",
".",
"format",
"(",
"dbname",
",",
"prohibited",
")",
")",
"return",
"False",
"except",
"mysql",
".",
"OperationalError",
":",
"# Probably: error 1142, \"SELECT command denied to user 'xxx'@'yyy'",
"# for table 'db'\". This would be OK.",
"pass",
"# 2. Global privileges, e.g. as held by root",
"try",
":",
"sql",
"=",
"\"\"\"\n SELECT /* must not have: */\n Insert_priv, Update_priv, Delete_priv,\n Create_priv, Drop_priv,\n Reload_priv, Shutdown_priv,\n Process_priv, File_priv, Grant_priv,\n Index_priv, Alter_priv,\n Show_db_priv, Super_priv,\n Lock_tables_priv, Execute_priv,\n Repl_slave_priv, Repl_client_priv,\n Create_view_priv,\n Create_routine_priv, Alter_routine_priv,\n Create_user_priv,\n Event_priv, Trigger_priv,\n Create_tablespace_priv\n FROM mysql.user\n WHERE\n CONCAT(user, '@', host) = CURRENT_USER()\n \"\"\"",
"rows",
"=",
"db",
".",
"fetchall",
"(",
"sql",
")",
"if",
"not",
"rows",
"or",
"len",
"(",
"rows",
")",
">",
"1",
":",
"return",
"False",
"prohibited",
"=",
"convert_enums",
"(",
"rows",
"[",
"0",
"]",
")",
"if",
"any",
"(",
"prohibited",
")",
":",
"if",
"logger",
":",
"logger",
".",
"debug",
"(",
"\"MySQL.is_read_only(): FAIL: GLOBAL privileges \"",
"\"wrong: prohibited={}\"",
".",
"format",
"(",
"prohibited",
")",
")",
"return",
"False",
"except",
"mysql",
".",
"OperationalError",
":",
"# Probably: error 1142, \"SELECT command denied to user 'xxx'@'yyy'",
"# for table 'user'\". This would be OK.",
"pass",
"return",
"True"
] | Do we have read-only access? | [
"Do",
"we",
"have",
"read",
"-",
"only",
"access?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L652-L734 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.connect | def connect(self,
engine: str = None,
interface: str = None,
host: str = None,
port: int = None,
database: str = None,
driver: str = None,
dsn: str = None,
odbc_connection_string: str = None,
user: str = None,
password: str = None,
autocommit: bool = True,
charset: str = "utf8",
use_unicode: bool = True) -> bool:
"""
engine: access, mysql, sqlserver
interface: mysql, odbc, jdbc
"""
# Catch all exceptions, so the error-catcher never shows a password.
# Note also that higher-level things may catch exceptions, so use the
# logger as well.
try:
return self._connect(
engine=engine, interface=interface,
host=host, port=port, database=database,
driver=driver, dsn=dsn,
odbc_connection_string=odbc_connection_string,
user=user, password=password,
autocommit=autocommit, charset=charset,
use_unicode=use_unicode)
except Exception as e:
self.reraise_connection_exception(e) | python | def connect(self,
engine: str = None,
interface: str = None,
host: str = None,
port: int = None,
database: str = None,
driver: str = None,
dsn: str = None,
odbc_connection_string: str = None,
user: str = None,
password: str = None,
autocommit: bool = True,
charset: str = "utf8",
use_unicode: bool = True) -> bool:
"""
engine: access, mysql, sqlserver
interface: mysql, odbc, jdbc
"""
# Catch all exceptions, so the error-catcher never shows a password.
# Note also that higher-level things may catch exceptions, so use the
# logger as well.
try:
return self._connect(
engine=engine, interface=interface,
host=host, port=port, database=database,
driver=driver, dsn=dsn,
odbc_connection_string=odbc_connection_string,
user=user, password=password,
autocommit=autocommit, charset=charset,
use_unicode=use_unicode)
except Exception as e:
self.reraise_connection_exception(e) | [
"def",
"connect",
"(",
"self",
",",
"engine",
":",
"str",
"=",
"None",
",",
"interface",
":",
"str",
"=",
"None",
",",
"host",
":",
"str",
"=",
"None",
",",
"port",
":",
"int",
"=",
"None",
",",
"database",
":",
"str",
"=",
"None",
",",
"driver",
":",
"str",
"=",
"None",
",",
"dsn",
":",
"str",
"=",
"None",
",",
"odbc_connection_string",
":",
"str",
"=",
"None",
",",
"user",
":",
"str",
"=",
"None",
",",
"password",
":",
"str",
"=",
"None",
",",
"autocommit",
":",
"bool",
"=",
"True",
",",
"charset",
":",
"str",
"=",
"\"utf8\"",
",",
"use_unicode",
":",
"bool",
"=",
"True",
")",
"->",
"bool",
":",
"# Catch all exceptions, so the error-catcher never shows a password.",
"# Note also that higher-level things may catch exceptions, so use the",
"# logger as well.",
"try",
":",
"return",
"self",
".",
"_connect",
"(",
"engine",
"=",
"engine",
",",
"interface",
"=",
"interface",
",",
"host",
"=",
"host",
",",
"port",
"=",
"port",
",",
"database",
"=",
"database",
",",
"driver",
"=",
"driver",
",",
"dsn",
"=",
"dsn",
",",
"odbc_connection_string",
"=",
"odbc_connection_string",
",",
"user",
"=",
"user",
",",
"password",
"=",
"password",
",",
"autocommit",
"=",
"autocommit",
",",
"charset",
"=",
"charset",
",",
"use_unicode",
"=",
"use_unicode",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"reraise_connection_exception",
"(",
"e",
")"
] | engine: access, mysql, sqlserver
interface: mysql, odbc, jdbc | [
"engine",
":",
"access",
"mysql",
"sqlserver",
"interface",
":",
"mysql",
"odbc",
"jdbc"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L1615-L1647 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.ping | def ping(self) -> None:
"""Pings a database connection, reconnecting if necessary."""
if self.db is None or self.db_pythonlib not in [PYTHONLIB_MYSQLDB,
PYTHONLIB_PYMYSQL]:
return
try:
self.db.ping(True) # test connection; reconnect upon failure
# ... should auto-reconnect; however, it seems to fail the first
# time, then work the next time.
# Exception (the first time) is:
# <class '_mysql_exceptions.OperationalError'>:
# (2006, 'MySQL server has gone away')
# http://mail.python.org/pipermail/python-list/2008-February/
# 474598.html
except mysql.OperationalError: # loss of connection
self.db = None
self.connect_to_database_mysql(
self._database, self._user, self._password, self._server,
self._port, self._charset, self._use_unicode) | python | def ping(self) -> None:
"""Pings a database connection, reconnecting if necessary."""
if self.db is None or self.db_pythonlib not in [PYTHONLIB_MYSQLDB,
PYTHONLIB_PYMYSQL]:
return
try:
self.db.ping(True) # test connection; reconnect upon failure
# ... should auto-reconnect; however, it seems to fail the first
# time, then work the next time.
# Exception (the first time) is:
# <class '_mysql_exceptions.OperationalError'>:
# (2006, 'MySQL server has gone away')
# http://mail.python.org/pipermail/python-list/2008-February/
# 474598.html
except mysql.OperationalError: # loss of connection
self.db = None
self.connect_to_database_mysql(
self._database, self._user, self._password, self._server,
self._port, self._charset, self._use_unicode) | [
"def",
"ping",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"db",
"is",
"None",
"or",
"self",
".",
"db_pythonlib",
"not",
"in",
"[",
"PYTHONLIB_MYSQLDB",
",",
"PYTHONLIB_PYMYSQL",
"]",
":",
"return",
"try",
":",
"self",
".",
"db",
".",
"ping",
"(",
"True",
")",
"# test connection; reconnect upon failure",
"# ... should auto-reconnect; however, it seems to fail the first",
"# time, then work the next time.",
"# Exception (the first time) is:",
"# <class '_mysql_exceptions.OperationalError'>:",
"# (2006, 'MySQL server has gone away')",
"# http://mail.python.org/pipermail/python-list/2008-February/",
"# 474598.html",
"except",
"mysql",
".",
"OperationalError",
":",
"# loss of connection",
"self",
".",
"db",
"=",
"None",
"self",
".",
"connect_to_database_mysql",
"(",
"self",
".",
"_database",
",",
"self",
".",
"_user",
",",
"self",
".",
"_password",
",",
"self",
".",
"_server",
",",
"self",
".",
"_port",
",",
"self",
".",
"_charset",
",",
"self",
".",
"_use_unicode",
")"
] | Pings a database connection, reconnecting if necessary. | [
"Pings",
"a",
"database",
"connection",
"reconnecting",
"if",
"necessary",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L1931-L1949 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.connect_to_database_odbc_mysql | def connect_to_database_odbc_mysql(self,
database: str,
user: str,
password: str,
server: str = "localhost",
port: int = 3306,
driver: str = "{MySQL ODBC 5.1 Driver}",
autocommit: bool = True) -> None:
"""Connects to a MySQL database via ODBC."""
self.connect(engine=ENGINE_MYSQL, interface=INTERFACE_ODBC,
database=database, user=user, password=password,
host=server, port=port, driver=driver,
autocommit=autocommit) | python | def connect_to_database_odbc_mysql(self,
database: str,
user: str,
password: str,
server: str = "localhost",
port: int = 3306,
driver: str = "{MySQL ODBC 5.1 Driver}",
autocommit: bool = True) -> None:
"""Connects to a MySQL database via ODBC."""
self.connect(engine=ENGINE_MYSQL, interface=INTERFACE_ODBC,
database=database, user=user, password=password,
host=server, port=port, driver=driver,
autocommit=autocommit) | [
"def",
"connect_to_database_odbc_mysql",
"(",
"self",
",",
"database",
":",
"str",
",",
"user",
":",
"str",
",",
"password",
":",
"str",
",",
"server",
":",
"str",
"=",
"\"localhost\"",
",",
"port",
":",
"int",
"=",
"3306",
",",
"driver",
":",
"str",
"=",
"\"{MySQL ODBC 5.1 Driver}\"",
",",
"autocommit",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"self",
".",
"connect",
"(",
"engine",
"=",
"ENGINE_MYSQL",
",",
"interface",
"=",
"INTERFACE_ODBC",
",",
"database",
"=",
"database",
",",
"user",
"=",
"user",
",",
"password",
"=",
"password",
",",
"host",
"=",
"server",
",",
"port",
"=",
"port",
",",
"driver",
"=",
"driver",
",",
"autocommit",
"=",
"autocommit",
")"
] | Connects to a MySQL database via ODBC. | [
"Connects",
"to",
"a",
"MySQL",
"database",
"via",
"ODBC",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L1969-L1981 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.connect_to_database_odbc_sqlserver | def connect_to_database_odbc_sqlserver(self,
odbc_connection_string: str = None,
dsn: str = None,
database: str = None,
user: str = None,
password: str = None,
server: str = "localhost",
driver: str = "{SQL Server}",
autocommit: bool = True) -> None:
"""Connects to an SQL Server database via ODBC."""
self.connect(engine=ENGINE_SQLSERVER, interface=INTERFACE_ODBC,
odbc_connection_string=odbc_connection_string,
dsn=dsn,
database=database, user=user, password=password,
host=server, driver=driver,
autocommit=autocommit) | python | def connect_to_database_odbc_sqlserver(self,
odbc_connection_string: str = None,
dsn: str = None,
database: str = None,
user: str = None,
password: str = None,
server: str = "localhost",
driver: str = "{SQL Server}",
autocommit: bool = True) -> None:
"""Connects to an SQL Server database via ODBC."""
self.connect(engine=ENGINE_SQLSERVER, interface=INTERFACE_ODBC,
odbc_connection_string=odbc_connection_string,
dsn=dsn,
database=database, user=user, password=password,
host=server, driver=driver,
autocommit=autocommit) | [
"def",
"connect_to_database_odbc_sqlserver",
"(",
"self",
",",
"odbc_connection_string",
":",
"str",
"=",
"None",
",",
"dsn",
":",
"str",
"=",
"None",
",",
"database",
":",
"str",
"=",
"None",
",",
"user",
":",
"str",
"=",
"None",
",",
"password",
":",
"str",
"=",
"None",
",",
"server",
":",
"str",
"=",
"\"localhost\"",
",",
"driver",
":",
"str",
"=",
"\"{SQL Server}\"",
",",
"autocommit",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"self",
".",
"connect",
"(",
"engine",
"=",
"ENGINE_SQLSERVER",
",",
"interface",
"=",
"INTERFACE_ODBC",
",",
"odbc_connection_string",
"=",
"odbc_connection_string",
",",
"dsn",
"=",
"dsn",
",",
"database",
"=",
"database",
",",
"user",
"=",
"user",
",",
"password",
"=",
"password",
",",
"host",
"=",
"server",
",",
"driver",
"=",
"driver",
",",
"autocommit",
"=",
"autocommit",
")"
] | Connects to an SQL Server database via ODBC. | [
"Connects",
"to",
"an",
"SQL",
"Server",
"database",
"via",
"ODBC",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L1983-L1998 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.connect_to_database_odbc_access | def connect_to_database_odbc_access(self,
dsn: str,
autocommit: bool = True) -> None:
"""Connects to an Access database via ODBC, with the DSN
prespecified."""
self.connect(engine=ENGINE_ACCESS, interface=INTERFACE_ODBC,
dsn=dsn, autocommit=autocommit) | python | def connect_to_database_odbc_access(self,
dsn: str,
autocommit: bool = True) -> None:
"""Connects to an Access database via ODBC, with the DSN
prespecified."""
self.connect(engine=ENGINE_ACCESS, interface=INTERFACE_ODBC,
dsn=dsn, autocommit=autocommit) | [
"def",
"connect_to_database_odbc_access",
"(",
"self",
",",
"dsn",
":",
"str",
",",
"autocommit",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"self",
".",
"connect",
"(",
"engine",
"=",
"ENGINE_ACCESS",
",",
"interface",
"=",
"INTERFACE_ODBC",
",",
"dsn",
"=",
"dsn",
",",
"autocommit",
"=",
"autocommit",
")"
] | Connects to an Access database via ODBC, with the DSN
prespecified. | [
"Connects",
"to",
"an",
"Access",
"database",
"via",
"ODBC",
"with",
"the",
"DSN",
"prespecified",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2000-L2006 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.localize_sql | def localize_sql(self, sql: str) -> str:
"""Translates ?-placeholder SQL to appropriate dialect.
For example, MySQLdb uses %s rather than ?.
"""
# pyodbc seems happy with ? now (pyodbc.paramstyle is 'qmark');
# using ? is much simpler, because we may want to use % with LIKE
# fields or (in my case) with date formatting strings for
# STR_TO_DATE().
# If you get this wrong, you may see "not all arguments converted
# during string formatting";
# http://stackoverflow.com/questions/9337134
if self.db_pythonlib in [PYTHONLIB_PYMYSQL, PYTHONLIB_MYSQLDB]:
# These engines use %, so we need to convert ? to %, without
# breaking literal % values.
sql = _PERCENT_REGEX.sub("%%", sql)
# ... replace all % with %% first
sql = _QUERY_VALUE_REGEX.sub("%s", sql)
# ... replace all ? with %s in the SQL
# Otherwise: engine uses ?, so we don't have to fiddle.
return sql | python | def localize_sql(self, sql: str) -> str:
"""Translates ?-placeholder SQL to appropriate dialect.
For example, MySQLdb uses %s rather than ?.
"""
# pyodbc seems happy with ? now (pyodbc.paramstyle is 'qmark');
# using ? is much simpler, because we may want to use % with LIKE
# fields or (in my case) with date formatting strings for
# STR_TO_DATE().
# If you get this wrong, you may see "not all arguments converted
# during string formatting";
# http://stackoverflow.com/questions/9337134
if self.db_pythonlib in [PYTHONLIB_PYMYSQL, PYTHONLIB_MYSQLDB]:
# These engines use %, so we need to convert ? to %, without
# breaking literal % values.
sql = _PERCENT_REGEX.sub("%%", sql)
# ... replace all % with %% first
sql = _QUERY_VALUE_REGEX.sub("%s", sql)
# ... replace all ? with %s in the SQL
# Otherwise: engine uses ?, so we don't have to fiddle.
return sql | [
"def",
"localize_sql",
"(",
"self",
",",
"sql",
":",
"str",
")",
"->",
"str",
":",
"# pyodbc seems happy with ? now (pyodbc.paramstyle is 'qmark');",
"# using ? is much simpler, because we may want to use % with LIKE",
"# fields or (in my case) with date formatting strings for",
"# STR_TO_DATE().",
"# If you get this wrong, you may see \"not all arguments converted",
"# during string formatting\";",
"# http://stackoverflow.com/questions/9337134",
"if",
"self",
".",
"db_pythonlib",
"in",
"[",
"PYTHONLIB_PYMYSQL",
",",
"PYTHONLIB_MYSQLDB",
"]",
":",
"# These engines use %, so we need to convert ? to %, without",
"# breaking literal % values.",
"sql",
"=",
"_PERCENT_REGEX",
".",
"sub",
"(",
"\"%%\"",
",",
"sql",
")",
"# ... replace all % with %% first",
"sql",
"=",
"_QUERY_VALUE_REGEX",
".",
"sub",
"(",
"\"%s\"",
",",
"sql",
")",
"# ... replace all ? with %s in the SQL",
"# Otherwise: engine uses ?, so we don't have to fiddle.",
"return",
"sql"
] | Translates ?-placeholder SQL to appropriate dialect.
For example, MySQLdb uses %s rather than ?. | [
"Translates",
"?",
"-",
"placeholder",
"SQL",
"to",
"appropriate",
"dialect",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2029-L2049 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.insert_record | def insert_record(self,
table: str,
fields: Sequence[str],
values: Sequence[Any],
update_on_duplicate_key: bool = False) -> int:
"""Inserts a record into database, table "table", using the list of
fieldnames and the list of values. Returns the new PK (or None)."""
self.ensure_db_open()
if len(fields) != len(values):
raise AssertionError("Field/value mismatch")
if update_on_duplicate_key:
sql = get_sql_insert_or_update(table, fields, self.get_delims())
else:
sql = get_sql_insert(table, fields, self.get_delims())
sql = self.localize_sql(sql)
log.debug("About to insert_record with SQL template: " + sql)
try:
cursor = self.db.cursor()
debug_sql(sql, values)
cursor.execute(sql, values)
# ... binds the placeholders (?, %s) to values in the process
new_pk = get_pk_of_last_insert(cursor)
log.debug("Record inserted.")
return new_pk
except: # nopep8
log.exception("insert_record: Failed to insert record.")
raise | python | def insert_record(self,
table: str,
fields: Sequence[str],
values: Sequence[Any],
update_on_duplicate_key: bool = False) -> int:
"""Inserts a record into database, table "table", using the list of
fieldnames and the list of values. Returns the new PK (or None)."""
self.ensure_db_open()
if len(fields) != len(values):
raise AssertionError("Field/value mismatch")
if update_on_duplicate_key:
sql = get_sql_insert_or_update(table, fields, self.get_delims())
else:
sql = get_sql_insert(table, fields, self.get_delims())
sql = self.localize_sql(sql)
log.debug("About to insert_record with SQL template: " + sql)
try:
cursor = self.db.cursor()
debug_sql(sql, values)
cursor.execute(sql, values)
# ... binds the placeholders (?, %s) to values in the process
new_pk = get_pk_of_last_insert(cursor)
log.debug("Record inserted.")
return new_pk
except: # nopep8
log.exception("insert_record: Failed to insert record.")
raise | [
"def",
"insert_record",
"(",
"self",
",",
"table",
":",
"str",
",",
"fields",
":",
"Sequence",
"[",
"str",
"]",
",",
"values",
":",
"Sequence",
"[",
"Any",
"]",
",",
"update_on_duplicate_key",
":",
"bool",
"=",
"False",
")",
"->",
"int",
":",
"self",
".",
"ensure_db_open",
"(",
")",
"if",
"len",
"(",
"fields",
")",
"!=",
"len",
"(",
"values",
")",
":",
"raise",
"AssertionError",
"(",
"\"Field/value mismatch\"",
")",
"if",
"update_on_duplicate_key",
":",
"sql",
"=",
"get_sql_insert_or_update",
"(",
"table",
",",
"fields",
",",
"self",
".",
"get_delims",
"(",
")",
")",
"else",
":",
"sql",
"=",
"get_sql_insert",
"(",
"table",
",",
"fields",
",",
"self",
".",
"get_delims",
"(",
")",
")",
"sql",
"=",
"self",
".",
"localize_sql",
"(",
"sql",
")",
"log",
".",
"debug",
"(",
"\"About to insert_record with SQL template: \"",
"+",
"sql",
")",
"try",
":",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"debug_sql",
"(",
"sql",
",",
"values",
")",
"cursor",
".",
"execute",
"(",
"sql",
",",
"values",
")",
"# ... binds the placeholders (?, %s) to values in the process",
"new_pk",
"=",
"get_pk_of_last_insert",
"(",
"cursor",
")",
"log",
".",
"debug",
"(",
"\"Record inserted.\"",
")",
"return",
"new_pk",
"except",
":",
"# nopep8",
"log",
".",
"exception",
"(",
"\"insert_record: Failed to insert record.\"",
")",
"raise"
] | Inserts a record into database, table "table", using the list of
fieldnames and the list of values. Returns the new PK (or None). | [
"Inserts",
"a",
"record",
"into",
"database",
"table",
"table",
"using",
"the",
"list",
"of",
"fieldnames",
"and",
"the",
"list",
"of",
"values",
".",
"Returns",
"the",
"new",
"PK",
"(",
"or",
"None",
")",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2084-L2110 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.insert_record_by_fieldspecs_with_values | def insert_record_by_fieldspecs_with_values(
self,
table: str,
fieldspeclist: FIELDSPECLIST_TYPE) -> int:
"""Inserts a record into the database using a list of fieldspecs having
their value stored under the 'value' key.
"""
fields = []
values = []
for fs in fieldspeclist:
fields.append(fs["name"])
values.append(fs["value"])
return self.insert_record(table, fields, values) | python | def insert_record_by_fieldspecs_with_values(
self,
table: str,
fieldspeclist: FIELDSPECLIST_TYPE) -> int:
"""Inserts a record into the database using a list of fieldspecs having
their value stored under the 'value' key.
"""
fields = []
values = []
for fs in fieldspeclist:
fields.append(fs["name"])
values.append(fs["value"])
return self.insert_record(table, fields, values) | [
"def",
"insert_record_by_fieldspecs_with_values",
"(",
"self",
",",
"table",
":",
"str",
",",
"fieldspeclist",
":",
"FIELDSPECLIST_TYPE",
")",
"->",
"int",
":",
"fields",
"=",
"[",
"]",
"values",
"=",
"[",
"]",
"for",
"fs",
"in",
"fieldspeclist",
":",
"fields",
".",
"append",
"(",
"fs",
"[",
"\"name\"",
"]",
")",
"values",
".",
"append",
"(",
"fs",
"[",
"\"value\"",
"]",
")",
"return",
"self",
".",
"insert_record",
"(",
"table",
",",
"fields",
",",
"values",
")"
] | Inserts a record into the database using a list of fieldspecs having
their value stored under the 'value' key. | [
"Inserts",
"a",
"record",
"into",
"the",
"database",
"using",
"a",
"list",
"of",
"fieldspecs",
"having",
"their",
"value",
"stored",
"under",
"the",
"value",
"key",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2112-L2124 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.insert_record_by_dict | def insert_record_by_dict(self,
table: str,
valuedict: Dict[str, Any]) -> Optional[int]:
"""Inserts a record into database, table "table", using a dictionary
containing field/value mappings. Returns the new PK (or None)."""
if not valuedict:
return None
n = len(valuedict)
fields = []
args = []
for f, v in valuedict.items():
fields.append(self.delimit(f))
args.append(v)
query = """
INSERT INTO {table}
({fields})
VALUES ({placeholders})
""".format(
table=table,
fields=",".join(fields),
placeholders=",".join(["?"]*n)
)
query = self.localize_sql(query)
log.debug("About to insert_record_by_dict with SQL template: " + query)
try:
cursor = self.db.cursor()
debug_sql(query, args)
cursor.execute(query, args)
new_pk = get_pk_of_last_insert(cursor)
log.debug("Record inserted.")
return new_pk
except: # nopep8
log.exception("insert_record_by_dict: Failed to insert record.")
raise | python | def insert_record_by_dict(self,
table: str,
valuedict: Dict[str, Any]) -> Optional[int]:
"""Inserts a record into database, table "table", using a dictionary
containing field/value mappings. Returns the new PK (or None)."""
if not valuedict:
return None
n = len(valuedict)
fields = []
args = []
for f, v in valuedict.items():
fields.append(self.delimit(f))
args.append(v)
query = """
INSERT INTO {table}
({fields})
VALUES ({placeholders})
""".format(
table=table,
fields=",".join(fields),
placeholders=",".join(["?"]*n)
)
query = self.localize_sql(query)
log.debug("About to insert_record_by_dict with SQL template: " + query)
try:
cursor = self.db.cursor()
debug_sql(query, args)
cursor.execute(query, args)
new_pk = get_pk_of_last_insert(cursor)
log.debug("Record inserted.")
return new_pk
except: # nopep8
log.exception("insert_record_by_dict: Failed to insert record.")
raise | [
"def",
"insert_record_by_dict",
"(",
"self",
",",
"table",
":",
"str",
",",
"valuedict",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"if",
"not",
"valuedict",
":",
"return",
"None",
"n",
"=",
"len",
"(",
"valuedict",
")",
"fields",
"=",
"[",
"]",
"args",
"=",
"[",
"]",
"for",
"f",
",",
"v",
"in",
"valuedict",
".",
"items",
"(",
")",
":",
"fields",
".",
"append",
"(",
"self",
".",
"delimit",
"(",
"f",
")",
")",
"args",
".",
"append",
"(",
"v",
")",
"query",
"=",
"\"\"\"\n INSERT INTO {table}\n ({fields})\n VALUES ({placeholders})\n \"\"\"",
".",
"format",
"(",
"table",
"=",
"table",
",",
"fields",
"=",
"\",\"",
".",
"join",
"(",
"fields",
")",
",",
"placeholders",
"=",
"\",\"",
".",
"join",
"(",
"[",
"\"?\"",
"]",
"*",
"n",
")",
")",
"query",
"=",
"self",
".",
"localize_sql",
"(",
"query",
")",
"log",
".",
"debug",
"(",
"\"About to insert_record_by_dict with SQL template: \"",
"+",
"query",
")",
"try",
":",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"debug_sql",
"(",
"query",
",",
"args",
")",
"cursor",
".",
"execute",
"(",
"query",
",",
"args",
")",
"new_pk",
"=",
"get_pk_of_last_insert",
"(",
"cursor",
")",
"log",
".",
"debug",
"(",
"\"Record inserted.\"",
")",
"return",
"new_pk",
"except",
":",
"# nopep8",
"log",
".",
"exception",
"(",
"\"insert_record_by_dict: Failed to insert record.\"",
")",
"raise"
] | Inserts a record into database, table "table", using a dictionary
containing field/value mappings. Returns the new PK (or None). | [
"Inserts",
"a",
"record",
"into",
"database",
"table",
"table",
"using",
"a",
"dictionary",
"containing",
"field",
"/",
"value",
"mappings",
".",
"Returns",
"the",
"new",
"PK",
"(",
"or",
"None",
")",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2126-L2159 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.insert_multiple_records | def insert_multiple_records(self,
table: str,
fields: Sequence[str],
records: Sequence[Sequence[Any]]) -> int:
"""Inserts a record into database, table "table", using the list of
fieldnames and the list of records (each a list of values).
Returns number of rows affected."""
self.ensure_db_open()
sql = self.localize_sql(get_sql_insert(table, fields,
self.get_delims()))
log.debug("About to insert multiple records with SQL template: " + sql)
try:
cursor = self.db.cursor()
debug_sql(sql, records)
cursor.executemany(sql, records)
# ... binds the placeholders (?, %s) to values in the process
# http://www.python.org/dev/peps/pep-0249/
log.debug("Records inserted.")
return cursor.rowcount
except: # nopep8
log.exception("insert_multiple_records: Failed to insert records.")
raise | python | def insert_multiple_records(self,
table: str,
fields: Sequence[str],
records: Sequence[Sequence[Any]]) -> int:
"""Inserts a record into database, table "table", using the list of
fieldnames and the list of records (each a list of values).
Returns number of rows affected."""
self.ensure_db_open()
sql = self.localize_sql(get_sql_insert(table, fields,
self.get_delims()))
log.debug("About to insert multiple records with SQL template: " + sql)
try:
cursor = self.db.cursor()
debug_sql(sql, records)
cursor.executemany(sql, records)
# ... binds the placeholders (?, %s) to values in the process
# http://www.python.org/dev/peps/pep-0249/
log.debug("Records inserted.")
return cursor.rowcount
except: # nopep8
log.exception("insert_multiple_records: Failed to insert records.")
raise | [
"def",
"insert_multiple_records",
"(",
"self",
",",
"table",
":",
"str",
",",
"fields",
":",
"Sequence",
"[",
"str",
"]",
",",
"records",
":",
"Sequence",
"[",
"Sequence",
"[",
"Any",
"]",
"]",
")",
"->",
"int",
":",
"self",
".",
"ensure_db_open",
"(",
")",
"sql",
"=",
"self",
".",
"localize_sql",
"(",
"get_sql_insert",
"(",
"table",
",",
"fields",
",",
"self",
".",
"get_delims",
"(",
")",
")",
")",
"log",
".",
"debug",
"(",
"\"About to insert multiple records with SQL template: \"",
"+",
"sql",
")",
"try",
":",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"debug_sql",
"(",
"sql",
",",
"records",
")",
"cursor",
".",
"executemany",
"(",
"sql",
",",
"records",
")",
"# ... binds the placeholders (?, %s) to values in the process",
"# http://www.python.org/dev/peps/pep-0249/",
"log",
".",
"debug",
"(",
"\"Records inserted.\"",
")",
"return",
"cursor",
".",
"rowcount",
"except",
":",
"# nopep8",
"log",
".",
"exception",
"(",
"\"insert_multiple_records: Failed to insert records.\"",
")",
"raise"
] | Inserts a record into database, table "table", using the list of
fieldnames and the list of records (each a list of values).
Returns number of rows affected. | [
"Inserts",
"a",
"record",
"into",
"database",
"table",
"table",
"using",
"the",
"list",
"of",
"fieldnames",
"and",
"the",
"list",
"of",
"records",
"(",
"each",
"a",
"list",
"of",
"values",
")",
".",
"Returns",
"number",
"of",
"rows",
"affected",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2161-L2182 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.db_exec_with_cursor | def db_exec_with_cursor(self, cursor, sql: str, *args) -> int:
"""Executes SQL on a supplied cursor, with "?" placeholders,
substituting in the arguments. Returns number of rows affected."""
sql = self.localize_sql(sql)
try:
debug_sql(sql, args)
cursor.execute(sql, args)
return cursor.rowcount
except: # nopep8
log.exception("db_exec_with_cursor: SQL was: " + sql)
raise | python | def db_exec_with_cursor(self, cursor, sql: str, *args) -> int:
"""Executes SQL on a supplied cursor, with "?" placeholders,
substituting in the arguments. Returns number of rows affected."""
sql = self.localize_sql(sql)
try:
debug_sql(sql, args)
cursor.execute(sql, args)
return cursor.rowcount
except: # nopep8
log.exception("db_exec_with_cursor: SQL was: " + sql)
raise | [
"def",
"db_exec_with_cursor",
"(",
"self",
",",
"cursor",
",",
"sql",
":",
"str",
",",
"*",
"args",
")",
"->",
"int",
":",
"sql",
"=",
"self",
".",
"localize_sql",
"(",
"sql",
")",
"try",
":",
"debug_sql",
"(",
"sql",
",",
"args",
")",
"cursor",
".",
"execute",
"(",
"sql",
",",
"args",
")",
"return",
"cursor",
".",
"rowcount",
"except",
":",
"# nopep8",
"log",
".",
"exception",
"(",
"\"db_exec_with_cursor: SQL was: \"",
"+",
"sql",
")",
"raise"
] | Executes SQL on a supplied cursor, with "?" placeholders,
substituting in the arguments. Returns number of rows affected. | [
"Executes",
"SQL",
"on",
"a",
"supplied",
"cursor",
"with",
"?",
"placeholders",
"substituting",
"in",
"the",
"arguments",
".",
"Returns",
"number",
"of",
"rows",
"affected",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2184-L2194 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.db_exec | def db_exec(self, sql: str, *args) -> int:
"""Executes SQL (with "?" placeholders for arguments)."""
self.ensure_db_open()
cursor = self.db.cursor()
return self.db_exec_with_cursor(cursor, sql, *args) | python | def db_exec(self, sql: str, *args) -> int:
"""Executes SQL (with "?" placeholders for arguments)."""
self.ensure_db_open()
cursor = self.db.cursor()
return self.db_exec_with_cursor(cursor, sql, *args) | [
"def",
"db_exec",
"(",
"self",
",",
"sql",
":",
"str",
",",
"*",
"args",
")",
"->",
"int",
":",
"self",
".",
"ensure_db_open",
"(",
")",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"return",
"self",
".",
"db_exec_with_cursor",
"(",
"cursor",
",",
"sql",
",",
"*",
"args",
")"
] | Executes SQL (with "?" placeholders for arguments). | [
"Executes",
"SQL",
"(",
"with",
"?",
"placeholders",
"for",
"arguments",
")",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2202-L2206 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.db_exec_and_commit | def db_exec_and_commit(self, sql: str, *args) -> int:
"""Execute SQL and commit."""
rowcount = self.db_exec(sql, *args)
self.commit()
return rowcount | python | def db_exec_and_commit(self, sql: str, *args) -> int:
"""Execute SQL and commit."""
rowcount = self.db_exec(sql, *args)
self.commit()
return rowcount | [
"def",
"db_exec_and_commit",
"(",
"self",
",",
"sql",
":",
"str",
",",
"*",
"args",
")",
"->",
"int",
":",
"rowcount",
"=",
"self",
".",
"db_exec",
"(",
"sql",
",",
"*",
"args",
")",
"self",
".",
"commit",
"(",
")",
"return",
"rowcount"
] | Execute SQL and commit. | [
"Execute",
"SQL",
"and",
"commit",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2208-L2212 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.db_exec_literal | def db_exec_literal(self, sql: str) -> int:
"""Executes SQL without modification. Returns rowcount."""
self.ensure_db_open()
cursor = self.db.cursor()
debug_sql(sql)
try:
cursor.execute(sql)
return cursor.rowcount
except: # nopep8
log.exception("db_exec_literal: SQL was: " + sql)
raise | python | def db_exec_literal(self, sql: str) -> int:
"""Executes SQL without modification. Returns rowcount."""
self.ensure_db_open()
cursor = self.db.cursor()
debug_sql(sql)
try:
cursor.execute(sql)
return cursor.rowcount
except: # nopep8
log.exception("db_exec_literal: SQL was: " + sql)
raise | [
"def",
"db_exec_literal",
"(",
"self",
",",
"sql",
":",
"str",
")",
"->",
"int",
":",
"self",
".",
"ensure_db_open",
"(",
")",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"debug_sql",
"(",
"sql",
")",
"try",
":",
"cursor",
".",
"execute",
"(",
"sql",
")",
"return",
"cursor",
".",
"rowcount",
"except",
":",
"# nopep8",
"log",
".",
"exception",
"(",
"\"db_exec_literal: SQL was: \"",
"+",
"sql",
")",
"raise"
] | Executes SQL without modification. Returns rowcount. | [
"Executes",
"SQL",
"without",
"modification",
".",
"Returns",
"rowcount",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2214-L2224 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fetchvalue | def fetchvalue(self, sql: str, *args) -> Optional[Any]:
"""Executes SQL; returns the first value of the first row, or None."""
row = self.fetchone(sql, *args)
if row is None:
return None
return row[0] | python | def fetchvalue(self, sql: str, *args) -> Optional[Any]:
"""Executes SQL; returns the first value of the first row, or None."""
row = self.fetchone(sql, *args)
if row is None:
return None
return row[0] | [
"def",
"fetchvalue",
"(",
"self",
",",
"sql",
":",
"str",
",",
"*",
"args",
")",
"->",
"Optional",
"[",
"Any",
"]",
":",
"row",
"=",
"self",
".",
"fetchone",
"(",
"sql",
",",
"*",
"args",
")",
"if",
"row",
"is",
"None",
":",
"return",
"None",
"return",
"row",
"[",
"0",
"]"
] | Executes SQL; returns the first value of the first row, or None. | [
"Executes",
"SQL",
";",
"returns",
"the",
"first",
"value",
"of",
"the",
"first",
"row",
"or",
"None",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2240-L2245 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fetchone | def fetchone(self, sql: str, *args) -> Optional[Sequence[Any]]:
"""Executes SQL; returns the first row, or None."""
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
return cursor.fetchone()
except: # nopep8
log.exception("fetchone: SQL was: " + sql)
raise | python | def fetchone(self, sql: str, *args) -> Optional[Sequence[Any]]:
"""Executes SQL; returns the first row, or None."""
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
return cursor.fetchone()
except: # nopep8
log.exception("fetchone: SQL was: " + sql)
raise | [
"def",
"fetchone",
"(",
"self",
",",
"sql",
":",
"str",
",",
"*",
"args",
")",
"->",
"Optional",
"[",
"Sequence",
"[",
"Any",
"]",
"]",
":",
"self",
".",
"ensure_db_open",
"(",
")",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"self",
".",
"db_exec_with_cursor",
"(",
"cursor",
",",
"sql",
",",
"*",
"args",
")",
"try",
":",
"return",
"cursor",
".",
"fetchone",
"(",
")",
"except",
":",
"# nopep8",
"log",
".",
"exception",
"(",
"\"fetchone: SQL was: \"",
"+",
"sql",
")",
"raise"
] | Executes SQL; returns the first row, or None. | [
"Executes",
"SQL",
";",
"returns",
"the",
"first",
"row",
"or",
"None",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2247-L2256 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fetchall | def fetchall(self, sql: str, *args) -> Sequence[Sequence[Any]]:
"""Executes SQL; returns all rows, or []."""
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
rows = cursor.fetchall()
return rows
except: # nopep8
log.exception("fetchall: SQL was: " + sql)
raise | python | def fetchall(self, sql: str, *args) -> Sequence[Sequence[Any]]:
"""Executes SQL; returns all rows, or []."""
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
rows = cursor.fetchall()
return rows
except: # nopep8
log.exception("fetchall: SQL was: " + sql)
raise | [
"def",
"fetchall",
"(",
"self",
",",
"sql",
":",
"str",
",",
"*",
"args",
")",
"->",
"Sequence",
"[",
"Sequence",
"[",
"Any",
"]",
"]",
":",
"self",
".",
"ensure_db_open",
"(",
")",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"self",
".",
"db_exec_with_cursor",
"(",
"cursor",
",",
"sql",
",",
"*",
"args",
")",
"try",
":",
"rows",
"=",
"cursor",
".",
"fetchall",
"(",
")",
"return",
"rows",
"except",
":",
"# nopep8",
"log",
".",
"exception",
"(",
"\"fetchall: SQL was: \"",
"+",
"sql",
")",
"raise"
] | Executes SQL; returns all rows, or []. | [
"Executes",
"SQL",
";",
"returns",
"all",
"rows",
"or",
"[]",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2258-L2268 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.gen_fetchall | def gen_fetchall(self, sql: str, *args) -> Iterator[Sequence[Any]]:
"""fetchall() as a generator."""
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
row = cursor.fetchone()
while row is not None:
yield row
row = cursor.fetchone()
except: # nopep8
log.exception("gen_fetchall: SQL was: " + sql)
raise | python | def gen_fetchall(self, sql: str, *args) -> Iterator[Sequence[Any]]:
"""fetchall() as a generator."""
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
row = cursor.fetchone()
while row is not None:
yield row
row = cursor.fetchone()
except: # nopep8
log.exception("gen_fetchall: SQL was: " + sql)
raise | [
"def",
"gen_fetchall",
"(",
"self",
",",
"sql",
":",
"str",
",",
"*",
"args",
")",
"->",
"Iterator",
"[",
"Sequence",
"[",
"Any",
"]",
"]",
":",
"self",
".",
"ensure_db_open",
"(",
")",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"self",
".",
"db_exec_with_cursor",
"(",
"cursor",
",",
"sql",
",",
"*",
"args",
")",
"try",
":",
"row",
"=",
"cursor",
".",
"fetchone",
"(",
")",
"while",
"row",
"is",
"not",
"None",
":",
"yield",
"row",
"row",
"=",
"cursor",
".",
"fetchone",
"(",
")",
"except",
":",
"# nopep8",
"log",
".",
"exception",
"(",
"\"gen_fetchall: SQL was: \"",
"+",
"sql",
")",
"raise"
] | fetchall() as a generator. | [
"fetchall",
"()",
"as",
"a",
"generator",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2270-L2282 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fetchall_with_fieldnames | def fetchall_with_fieldnames(self, sql: str, *args) \
-> Tuple[Sequence[Sequence[Any]], Sequence[str]]:
"""Executes SQL; returns (rows, fieldnames)."""
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
rows = cursor.fetchall()
fieldnames = [i[0] for i in cursor.description]
return rows, fieldnames
except: # nopep8
log.exception("fetchall_with_fieldnames: SQL was: " + sql)
raise | python | def fetchall_with_fieldnames(self, sql: str, *args) \
-> Tuple[Sequence[Sequence[Any]], Sequence[str]]:
"""Executes SQL; returns (rows, fieldnames)."""
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
rows = cursor.fetchall()
fieldnames = [i[0] for i in cursor.description]
return rows, fieldnames
except: # nopep8
log.exception("fetchall_with_fieldnames: SQL was: " + sql)
raise | [
"def",
"fetchall_with_fieldnames",
"(",
"self",
",",
"sql",
":",
"str",
",",
"*",
"args",
")",
"->",
"Tuple",
"[",
"Sequence",
"[",
"Sequence",
"[",
"Any",
"]",
"]",
",",
"Sequence",
"[",
"str",
"]",
"]",
":",
"self",
".",
"ensure_db_open",
"(",
")",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"self",
".",
"db_exec_with_cursor",
"(",
"cursor",
",",
"sql",
",",
"*",
"args",
")",
"try",
":",
"rows",
"=",
"cursor",
".",
"fetchall",
"(",
")",
"fieldnames",
"=",
"[",
"i",
"[",
"0",
"]",
"for",
"i",
"in",
"cursor",
".",
"description",
"]",
"return",
"rows",
",",
"fieldnames",
"except",
":",
"# nopep8",
"log",
".",
"exception",
"(",
"\"fetchall_with_fieldnames: SQL was: \"",
"+",
"sql",
")",
"raise"
] | Executes SQL; returns (rows, fieldnames). | [
"Executes",
"SQL",
";",
"returns",
"(",
"rows",
"fieldnames",
")",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2298-L2310 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fetchall_as_dictlist | def fetchall_as_dictlist(self, sql: str, *args) -> List[Dict[str, Any]]:
"""Executes SQL; returns list of dictionaries, where each dict contains
fieldname/value pairs."""
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
rows = cursor.fetchall()
fieldnames = [i[0] for i in cursor.description]
dictlist = []
for r in rows:
dictlist.append(dict(zip(fieldnames, r)))
return dictlist
except: # nopep8
log.exception("fetchall_as_dictlist: SQL was: " + sql)
raise | python | def fetchall_as_dictlist(self, sql: str, *args) -> List[Dict[str, Any]]:
"""Executes SQL; returns list of dictionaries, where each dict contains
fieldname/value pairs."""
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
rows = cursor.fetchall()
fieldnames = [i[0] for i in cursor.description]
dictlist = []
for r in rows:
dictlist.append(dict(zip(fieldnames, r)))
return dictlist
except: # nopep8
log.exception("fetchall_as_dictlist: SQL was: " + sql)
raise | [
"def",
"fetchall_as_dictlist",
"(",
"self",
",",
"sql",
":",
"str",
",",
"*",
"args",
")",
"->",
"List",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"self",
".",
"ensure_db_open",
"(",
")",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"self",
".",
"db_exec_with_cursor",
"(",
"cursor",
",",
"sql",
",",
"*",
"args",
")",
"try",
":",
"rows",
"=",
"cursor",
".",
"fetchall",
"(",
")",
"fieldnames",
"=",
"[",
"i",
"[",
"0",
"]",
"for",
"i",
"in",
"cursor",
".",
"description",
"]",
"dictlist",
"=",
"[",
"]",
"for",
"r",
"in",
"rows",
":",
"dictlist",
".",
"append",
"(",
"dict",
"(",
"zip",
"(",
"fieldnames",
",",
"r",
")",
")",
")",
"return",
"dictlist",
"except",
":",
"# nopep8",
"log",
".",
"exception",
"(",
"\"fetchall_as_dictlist: SQL was: \"",
"+",
"sql",
")",
"raise"
] | Executes SQL; returns list of dictionaries, where each dict contains
fieldname/value pairs. | [
"Executes",
"SQL",
";",
"returns",
"list",
"of",
"dictionaries",
"where",
"each",
"dict",
"contains",
"fieldname",
"/",
"value",
"pairs",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2312-L2327 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fetchallfirstvalues | def fetchallfirstvalues(self, sql: str, *args) -> List[Any]:
"""Executes SQL; returns list of first values of each row."""
rows = self.fetchall(sql, *args)
return [row[0] for row in rows] | python | def fetchallfirstvalues(self, sql: str, *args) -> List[Any]:
"""Executes SQL; returns list of first values of each row."""
rows = self.fetchall(sql, *args)
return [row[0] for row in rows] | [
"def",
"fetchallfirstvalues",
"(",
"self",
",",
"sql",
":",
"str",
",",
"*",
"args",
")",
"->",
"List",
"[",
"Any",
"]",
":",
"rows",
"=",
"self",
".",
"fetchall",
"(",
"sql",
",",
"*",
"args",
")",
"return",
"[",
"row",
"[",
"0",
"]",
"for",
"row",
"in",
"rows",
"]"
] | Executes SQL; returns list of first values of each row. | [
"Executes",
"SQL",
";",
"returns",
"list",
"of",
"first",
"values",
"of",
"each",
"row",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2329-L2332 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fetch_fieldnames | def fetch_fieldnames(self, sql: str, *args) -> List[str]:
"""Executes SQL; returns just the output fieldnames."""
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
return [i[0] for i in cursor.description]
except: # nopep8
log.exception("fetch_fieldnames: SQL was: " + sql)
raise | python | def fetch_fieldnames(self, sql: str, *args) -> List[str]:
"""Executes SQL; returns just the output fieldnames."""
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
return [i[0] for i in cursor.description]
except: # nopep8
log.exception("fetch_fieldnames: SQL was: " + sql)
raise | [
"def",
"fetch_fieldnames",
"(",
"self",
",",
"sql",
":",
"str",
",",
"*",
"args",
")",
"->",
"List",
"[",
"str",
"]",
":",
"self",
".",
"ensure_db_open",
"(",
")",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"self",
".",
"db_exec_with_cursor",
"(",
"cursor",
",",
"sql",
",",
"*",
"args",
")",
"try",
":",
"return",
"[",
"i",
"[",
"0",
"]",
"for",
"i",
"in",
"cursor",
".",
"description",
"]",
"except",
":",
"# nopep8",
"log",
".",
"exception",
"(",
"\"fetch_fieldnames: SQL was: \"",
"+",
"sql",
")",
"raise"
] | Executes SQL; returns just the output fieldnames. | [
"Executes",
"SQL",
";",
"returns",
"just",
"the",
"output",
"fieldnames",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2334-L2343 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.count_where | def count_where(self, table: str, wheredict: Dict[str, Any] = None) -> int:
"""Counts rows in a table, given a set of WHERE criteria (ANDed),
returning a count."""
sql = "SELECT COUNT(*) FROM " + self.delimit(table)
if wheredict is not None:
sql += " WHERE " + " AND ".join([
self.delimit(k) + "=?"
for k in wheredict.keys()
])
whereargs = wheredict.values()
count = self.fetchone(sql, *whereargs)[0]
else:
count = self.fetchone(sql)[0]
return count | python | def count_where(self, table: str, wheredict: Dict[str, Any] = None) -> int:
"""Counts rows in a table, given a set of WHERE criteria (ANDed),
returning a count."""
sql = "SELECT COUNT(*) FROM " + self.delimit(table)
if wheredict is not None:
sql += " WHERE " + " AND ".join([
self.delimit(k) + "=?"
for k in wheredict.keys()
])
whereargs = wheredict.values()
count = self.fetchone(sql, *whereargs)[0]
else:
count = self.fetchone(sql)[0]
return count | [
"def",
"count_where",
"(",
"self",
",",
"table",
":",
"str",
",",
"wheredict",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"None",
")",
"->",
"int",
":",
"sql",
"=",
"\"SELECT COUNT(*) FROM \"",
"+",
"self",
".",
"delimit",
"(",
"table",
")",
"if",
"wheredict",
"is",
"not",
"None",
":",
"sql",
"+=",
"\" WHERE \"",
"+",
"\" AND \"",
".",
"join",
"(",
"[",
"self",
".",
"delimit",
"(",
"k",
")",
"+",
"\"=?\"",
"for",
"k",
"in",
"wheredict",
".",
"keys",
"(",
")",
"]",
")",
"whereargs",
"=",
"wheredict",
".",
"values",
"(",
")",
"count",
"=",
"self",
".",
"fetchone",
"(",
"sql",
",",
"*",
"whereargs",
")",
"[",
"0",
"]",
"else",
":",
"count",
"=",
"self",
".",
"fetchone",
"(",
"sql",
")",
"[",
"0",
"]",
"return",
"count"
] | Counts rows in a table, given a set of WHERE criteria (ANDed),
returning a count. | [
"Counts",
"rows",
"in",
"a",
"table",
"given",
"a",
"set",
"of",
"WHERE",
"criteria",
"(",
"ANDed",
")",
"returning",
"a",
"count",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2345-L2358 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.does_row_exist | def does_row_exist(self, table: str, field: str, value: Any) -> bool:
"""Checks for the existence of a record by a single field (typically a
PK)."""
sql = ("SELECT COUNT(*) FROM " + self.delimit(table) +
" WHERE " + self.delimit(field) + "=?")
row = self.fetchone(sql, value)
return True if row[0] >= 1 else False | python | def does_row_exist(self, table: str, field: str, value: Any) -> bool:
"""Checks for the existence of a record by a single field (typically a
PK)."""
sql = ("SELECT COUNT(*) FROM " + self.delimit(table) +
" WHERE " + self.delimit(field) + "=?")
row = self.fetchone(sql, value)
return True if row[0] >= 1 else False | [
"def",
"does_row_exist",
"(",
"self",
",",
"table",
":",
"str",
",",
"field",
":",
"str",
",",
"value",
":",
"Any",
")",
"->",
"bool",
":",
"sql",
"=",
"(",
"\"SELECT COUNT(*) FROM \"",
"+",
"self",
".",
"delimit",
"(",
"table",
")",
"+",
"\" WHERE \"",
"+",
"self",
".",
"delimit",
"(",
"field",
")",
"+",
"\"=?\"",
")",
"row",
"=",
"self",
".",
"fetchone",
"(",
"sql",
",",
"value",
")",
"return",
"True",
"if",
"row",
"[",
"0",
"]",
">=",
"1",
"else",
"False"
] | Checks for the existence of a record by a single field (typically a
PK). | [
"Checks",
"for",
"the",
"existence",
"of",
"a",
"record",
"by",
"a",
"single",
"field",
"(",
"typically",
"a",
"PK",
")",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2360-L2366 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.delete_by_field | def delete_by_field(self, table: str, field: str, value: Any) -> int:
"""Deletes all records where "field" is "value"."""
sql = ("DELETE FROM " + self.delimit(table) +
" WHERE " + self.delimit(field) + "=?")
return self.db_exec(sql, value) | python | def delete_by_field(self, table: str, field: str, value: Any) -> int:
"""Deletes all records where "field" is "value"."""
sql = ("DELETE FROM " + self.delimit(table) +
" WHERE " + self.delimit(field) + "=?")
return self.db_exec(sql, value) | [
"def",
"delete_by_field",
"(",
"self",
",",
"table",
":",
"str",
",",
"field",
":",
"str",
",",
"value",
":",
"Any",
")",
"->",
"int",
":",
"sql",
"=",
"(",
"\"DELETE FROM \"",
"+",
"self",
".",
"delimit",
"(",
"table",
")",
"+",
"\" WHERE \"",
"+",
"self",
".",
"delimit",
"(",
"field",
")",
"+",
"\"=?\"",
")",
"return",
"self",
".",
"db_exec",
"(",
"sql",
",",
"value",
")"
] | Deletes all records where "field" is "value". | [
"Deletes",
"all",
"records",
"where",
"field",
"is",
"value",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2368-L2372 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fetch_object_from_db_by_pk | def fetch_object_from_db_by_pk(self,
obj: Any,
table: str,
fieldlist: Sequence[str],
pkvalue: Any) -> bool:
"""Fetches object from database table by PK value. Writes back to
object. Returns True/False for success/failure."""
if pkvalue is None:
blank_object(obj, fieldlist)
return False
row = self.fetchone(
get_sql_select_all_non_pk_fields_by_pk(table, fieldlist,
self.get_delims()),
pkvalue
)
if row is None:
blank_object(obj, fieldlist)
return False
setattr(obj, fieldlist[0], pkvalue) # set PK value of obj
assign_from_list(obj, fieldlist[1:], row) # set non-PK values of obj
return True | python | def fetch_object_from_db_by_pk(self,
obj: Any,
table: str,
fieldlist: Sequence[str],
pkvalue: Any) -> bool:
"""Fetches object from database table by PK value. Writes back to
object. Returns True/False for success/failure."""
if pkvalue is None:
blank_object(obj, fieldlist)
return False
row = self.fetchone(
get_sql_select_all_non_pk_fields_by_pk(table, fieldlist,
self.get_delims()),
pkvalue
)
if row is None:
blank_object(obj, fieldlist)
return False
setattr(obj, fieldlist[0], pkvalue) # set PK value of obj
assign_from_list(obj, fieldlist[1:], row) # set non-PK values of obj
return True | [
"def",
"fetch_object_from_db_by_pk",
"(",
"self",
",",
"obj",
":",
"Any",
",",
"table",
":",
"str",
",",
"fieldlist",
":",
"Sequence",
"[",
"str",
"]",
",",
"pkvalue",
":",
"Any",
")",
"->",
"bool",
":",
"if",
"pkvalue",
"is",
"None",
":",
"blank_object",
"(",
"obj",
",",
"fieldlist",
")",
"return",
"False",
"row",
"=",
"self",
".",
"fetchone",
"(",
"get_sql_select_all_non_pk_fields_by_pk",
"(",
"table",
",",
"fieldlist",
",",
"self",
".",
"get_delims",
"(",
")",
")",
",",
"pkvalue",
")",
"if",
"row",
"is",
"None",
":",
"blank_object",
"(",
"obj",
",",
"fieldlist",
")",
"return",
"False",
"setattr",
"(",
"obj",
",",
"fieldlist",
"[",
"0",
"]",
",",
"pkvalue",
")",
"# set PK value of obj",
"assign_from_list",
"(",
"obj",
",",
"fieldlist",
"[",
"1",
":",
"]",
",",
"row",
")",
"# set non-PK values of obj",
"return",
"True"
] | Fetches object from database table by PK value. Writes back to
object. Returns True/False for success/failure. | [
"Fetches",
"object",
"from",
"database",
"table",
"by",
"PK",
"value",
".",
"Writes",
"back",
"to",
"object",
".",
"Returns",
"True",
"/",
"False",
"for",
"success",
"/",
"failure",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2378-L2398 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fetch_object_from_db_by_other_field | def fetch_object_from_db_by_other_field(self,
obj: Any,
table: str,
fieldlist: Sequence[str],
keyname: str,
keyvalue: Any) -> bool:
"""Fetches object from database table by a field specified by
keyname/keyvalue. Writes back to object. Returns True/False for
success/failure."""
row = self.fetchone(
get_sql_select_all_fields_by_key(table, fieldlist, keyname,
self.get_delims()),
keyvalue
)
if row is None:
blank_object(obj, fieldlist)
return False
assign_from_list(obj, fieldlist, row)
return True | python | def fetch_object_from_db_by_other_field(self,
obj: Any,
table: str,
fieldlist: Sequence[str],
keyname: str,
keyvalue: Any) -> bool:
"""Fetches object from database table by a field specified by
keyname/keyvalue. Writes back to object. Returns True/False for
success/failure."""
row = self.fetchone(
get_sql_select_all_fields_by_key(table, fieldlist, keyname,
self.get_delims()),
keyvalue
)
if row is None:
blank_object(obj, fieldlist)
return False
assign_from_list(obj, fieldlist, row)
return True | [
"def",
"fetch_object_from_db_by_other_field",
"(",
"self",
",",
"obj",
":",
"Any",
",",
"table",
":",
"str",
",",
"fieldlist",
":",
"Sequence",
"[",
"str",
"]",
",",
"keyname",
":",
"str",
",",
"keyvalue",
":",
"Any",
")",
"->",
"bool",
":",
"row",
"=",
"self",
".",
"fetchone",
"(",
"get_sql_select_all_fields_by_key",
"(",
"table",
",",
"fieldlist",
",",
"keyname",
",",
"self",
".",
"get_delims",
"(",
")",
")",
",",
"keyvalue",
")",
"if",
"row",
"is",
"None",
":",
"blank_object",
"(",
"obj",
",",
"fieldlist",
")",
"return",
"False",
"assign_from_list",
"(",
"obj",
",",
"fieldlist",
",",
"row",
")",
"return",
"True"
] | Fetches object from database table by a field specified by
keyname/keyvalue. Writes back to object. Returns True/False for
success/failure. | [
"Fetches",
"object",
"from",
"database",
"table",
"by",
"a",
"field",
"specified",
"by",
"keyname",
"/",
"keyvalue",
".",
"Writes",
"back",
"to",
"object",
".",
"Returns",
"True",
"/",
"False",
"for",
"success",
"/",
"failure",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2400-L2418 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fetch_all_objects_from_db | def fetch_all_objects_from_db(self,
cls: Type[T],
table: str,
fieldlist: Sequence[str],
construct_with_pk: bool,
*args) -> List[T]:
"""Fetches all objects from a table, returning an array of objects of
class cls."""
return self.fetch_all_objects_from_db_where(
cls, table, fieldlist, construct_with_pk, None, *args) | python | def fetch_all_objects_from_db(self,
cls: Type[T],
table: str,
fieldlist: Sequence[str],
construct_with_pk: bool,
*args) -> List[T]:
"""Fetches all objects from a table, returning an array of objects of
class cls."""
return self.fetch_all_objects_from_db_where(
cls, table, fieldlist, construct_with_pk, None, *args) | [
"def",
"fetch_all_objects_from_db",
"(",
"self",
",",
"cls",
":",
"Type",
"[",
"T",
"]",
",",
"table",
":",
"str",
",",
"fieldlist",
":",
"Sequence",
"[",
"str",
"]",
",",
"construct_with_pk",
":",
"bool",
",",
"*",
"args",
")",
"->",
"List",
"[",
"T",
"]",
":",
"return",
"self",
".",
"fetch_all_objects_from_db_where",
"(",
"cls",
",",
"table",
",",
"fieldlist",
",",
"construct_with_pk",
",",
"None",
",",
"*",
"args",
")"
] | Fetches all objects from a table, returning an array of objects of
class cls. | [
"Fetches",
"all",
"objects",
"from",
"a",
"table",
"returning",
"an",
"array",
"of",
"objects",
"of",
"class",
"cls",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2420-L2429 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fetch_all_objects_from_db_by_pklist | def fetch_all_objects_from_db_by_pklist(self,
cls: Type,
table: str,
fieldlist: Sequence[str],
pklist: Sequence[Any],
construct_with_pk: bool,
*args) -> List[T]:
"""Fetches all objects from a table, given a list of PKs."""
objarray = []
for pk in pklist:
if construct_with_pk:
obj = cls(pk, *args) # should do its own fetching
else:
obj = cls(*args)
self.fetch_object_from_db_by_pk(obj, table, fieldlist, pk)
objarray.append(obj)
return objarray | python | def fetch_all_objects_from_db_by_pklist(self,
cls: Type,
table: str,
fieldlist: Sequence[str],
pklist: Sequence[Any],
construct_with_pk: bool,
*args) -> List[T]:
"""Fetches all objects from a table, given a list of PKs."""
objarray = []
for pk in pklist:
if construct_with_pk:
obj = cls(pk, *args) # should do its own fetching
else:
obj = cls(*args)
self.fetch_object_from_db_by_pk(obj, table, fieldlist, pk)
objarray.append(obj)
return objarray | [
"def",
"fetch_all_objects_from_db_by_pklist",
"(",
"self",
",",
"cls",
":",
"Type",
",",
"table",
":",
"str",
",",
"fieldlist",
":",
"Sequence",
"[",
"str",
"]",
",",
"pklist",
":",
"Sequence",
"[",
"Any",
"]",
",",
"construct_with_pk",
":",
"bool",
",",
"*",
"args",
")",
"->",
"List",
"[",
"T",
"]",
":",
"objarray",
"=",
"[",
"]",
"for",
"pk",
"in",
"pklist",
":",
"if",
"construct_with_pk",
":",
"obj",
"=",
"cls",
"(",
"pk",
",",
"*",
"args",
")",
"# should do its own fetching",
"else",
":",
"obj",
"=",
"cls",
"(",
"*",
"args",
")",
"self",
".",
"fetch_object_from_db_by_pk",
"(",
"obj",
",",
"table",
",",
"fieldlist",
",",
"pk",
")",
"objarray",
".",
"append",
"(",
"obj",
")",
"return",
"objarray"
] | Fetches all objects from a table, given a list of PKs. | [
"Fetches",
"all",
"objects",
"from",
"a",
"table",
"given",
"a",
"list",
"of",
"PKs",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2431-L2447 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fetch_all_objects_from_db_where | def fetch_all_objects_from_db_where(self,
cls: Type[T],
table: str,
fieldlist: Sequence[str],
construct_with_pk: bool,
wheredict: Optional[Dict[str, Any]],
*args) -> List[T]:
"""
Fetches all objects from a table, given a set of WHERE criteria
(ANDed), returning an array of objects of class cls.
As usual here, the first field in the fieldlist must be the PK.
"""
sql = (
"SELECT " + ",".join([self.delimit(x) for x in fieldlist]) +
" FROM " + self.delimit(table)
)
whereargs = []
if wheredict is not None:
sql += " WHERE " + " AND ".join([
self.delimit(k) + "=?"
for k in wheredict.keys()
])
whereargs = wheredict.values()
rows = self.fetchall(sql, *whereargs)
objects = []
for row in rows:
objects.append(
create_object_from_list(cls, fieldlist, row, *args,
construct_with_pk=construct_with_pk))
return objects | python | def fetch_all_objects_from_db_where(self,
cls: Type[T],
table: str,
fieldlist: Sequence[str],
construct_with_pk: bool,
wheredict: Optional[Dict[str, Any]],
*args) -> List[T]:
"""
Fetches all objects from a table, given a set of WHERE criteria
(ANDed), returning an array of objects of class cls.
As usual here, the first field in the fieldlist must be the PK.
"""
sql = (
"SELECT " + ",".join([self.delimit(x) for x in fieldlist]) +
" FROM " + self.delimit(table)
)
whereargs = []
if wheredict is not None:
sql += " WHERE " + " AND ".join([
self.delimit(k) + "=?"
for k in wheredict.keys()
])
whereargs = wheredict.values()
rows = self.fetchall(sql, *whereargs)
objects = []
for row in rows:
objects.append(
create_object_from_list(cls, fieldlist, row, *args,
construct_with_pk=construct_with_pk))
return objects | [
"def",
"fetch_all_objects_from_db_where",
"(",
"self",
",",
"cls",
":",
"Type",
"[",
"T",
"]",
",",
"table",
":",
"str",
",",
"fieldlist",
":",
"Sequence",
"[",
"str",
"]",
",",
"construct_with_pk",
":",
"bool",
",",
"wheredict",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
",",
"*",
"args",
")",
"->",
"List",
"[",
"T",
"]",
":",
"sql",
"=",
"(",
"\"SELECT \"",
"+",
"\",\"",
".",
"join",
"(",
"[",
"self",
".",
"delimit",
"(",
"x",
")",
"for",
"x",
"in",
"fieldlist",
"]",
")",
"+",
"\" FROM \"",
"+",
"self",
".",
"delimit",
"(",
"table",
")",
")",
"whereargs",
"=",
"[",
"]",
"if",
"wheredict",
"is",
"not",
"None",
":",
"sql",
"+=",
"\" WHERE \"",
"+",
"\" AND \"",
".",
"join",
"(",
"[",
"self",
".",
"delimit",
"(",
"k",
")",
"+",
"\"=?\"",
"for",
"k",
"in",
"wheredict",
".",
"keys",
"(",
")",
"]",
")",
"whereargs",
"=",
"wheredict",
".",
"values",
"(",
")",
"rows",
"=",
"self",
".",
"fetchall",
"(",
"sql",
",",
"*",
"whereargs",
")",
"objects",
"=",
"[",
"]",
"for",
"row",
"in",
"rows",
":",
"objects",
".",
"append",
"(",
"create_object_from_list",
"(",
"cls",
",",
"fieldlist",
",",
"row",
",",
"*",
"args",
",",
"construct_with_pk",
"=",
"construct_with_pk",
")",
")",
"return",
"objects"
] | Fetches all objects from a table, given a set of WHERE criteria
(ANDed), returning an array of objects of class cls.
As usual here, the first field in the fieldlist must be the PK. | [
"Fetches",
"all",
"objects",
"from",
"a",
"table",
"given",
"a",
"set",
"of",
"WHERE",
"criteria",
"(",
"ANDed",
")",
"returning",
"an",
"array",
"of",
"objects",
"of",
"class",
"cls",
".",
"As",
"usual",
"here",
"the",
"first",
"field",
"in",
"the",
"fieldlist",
"must",
"be",
"the",
"PK",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2471-L2500 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.insert_object_into_db_pk_known | def insert_object_into_db_pk_known(self,
obj: Any,
table: str,
fieldlist: Sequence[str]) -> None:
"""Inserts object into database table, with PK (first field) already
known."""
pkvalue = getattr(obj, fieldlist[0])
if pkvalue is None:
raise AssertionError("insert_object_intoto_db_pk_known called "
"without PK")
valuelist = []
for f in fieldlist:
valuelist.append(getattr(obj, f))
self.db_exec(
get_sql_insert(table, fieldlist, self.get_delims()),
*valuelist
) | python | def insert_object_into_db_pk_known(self,
obj: Any,
table: str,
fieldlist: Sequence[str]) -> None:
"""Inserts object into database table, with PK (first field) already
known."""
pkvalue = getattr(obj, fieldlist[0])
if pkvalue is None:
raise AssertionError("insert_object_intoto_db_pk_known called "
"without PK")
valuelist = []
for f in fieldlist:
valuelist.append(getattr(obj, f))
self.db_exec(
get_sql_insert(table, fieldlist, self.get_delims()),
*valuelist
) | [
"def",
"insert_object_into_db_pk_known",
"(",
"self",
",",
"obj",
":",
"Any",
",",
"table",
":",
"str",
",",
"fieldlist",
":",
"Sequence",
"[",
"str",
"]",
")",
"->",
"None",
":",
"pkvalue",
"=",
"getattr",
"(",
"obj",
",",
"fieldlist",
"[",
"0",
"]",
")",
"if",
"pkvalue",
"is",
"None",
":",
"raise",
"AssertionError",
"(",
"\"insert_object_intoto_db_pk_known called \"",
"\"without PK\"",
")",
"valuelist",
"=",
"[",
"]",
"for",
"f",
"in",
"fieldlist",
":",
"valuelist",
".",
"append",
"(",
"getattr",
"(",
"obj",
",",
"f",
")",
")",
"self",
".",
"db_exec",
"(",
"get_sql_insert",
"(",
"table",
",",
"fieldlist",
",",
"self",
".",
"get_delims",
"(",
")",
")",
",",
"*",
"valuelist",
")"
] | Inserts object into database table, with PK (first field) already
known. | [
"Inserts",
"object",
"into",
"database",
"table",
"with",
"PK",
"(",
"first",
"field",
")",
"already",
"known",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2502-L2518 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.insert_object_into_db_pk_unknown | def insert_object_into_db_pk_unknown(self,
obj: Any,
table: str,
fieldlist: Sequence[str]) -> None:
"""Inserts object into database table, with PK (first field) initially
unknown (and subsequently set in the object from the database)."""
self.ensure_db_open()
valuelist = []
for f in fieldlist[1:]:
valuelist.append(getattr(obj, f))
cursor = self.db.cursor()
self.db_exec_with_cursor(
cursor,
get_sql_insert_without_first_field(table, fieldlist,
self.get_delims()),
*valuelist
)
pkvalue = get_pk_of_last_insert(cursor)
setattr(obj, fieldlist[0], pkvalue) | python | def insert_object_into_db_pk_unknown(self,
obj: Any,
table: str,
fieldlist: Sequence[str]) -> None:
"""Inserts object into database table, with PK (first field) initially
unknown (and subsequently set in the object from the database)."""
self.ensure_db_open()
valuelist = []
for f in fieldlist[1:]:
valuelist.append(getattr(obj, f))
cursor = self.db.cursor()
self.db_exec_with_cursor(
cursor,
get_sql_insert_without_first_field(table, fieldlist,
self.get_delims()),
*valuelist
)
pkvalue = get_pk_of_last_insert(cursor)
setattr(obj, fieldlist[0], pkvalue) | [
"def",
"insert_object_into_db_pk_unknown",
"(",
"self",
",",
"obj",
":",
"Any",
",",
"table",
":",
"str",
",",
"fieldlist",
":",
"Sequence",
"[",
"str",
"]",
")",
"->",
"None",
":",
"self",
".",
"ensure_db_open",
"(",
")",
"valuelist",
"=",
"[",
"]",
"for",
"f",
"in",
"fieldlist",
"[",
"1",
":",
"]",
":",
"valuelist",
".",
"append",
"(",
"getattr",
"(",
"obj",
",",
"f",
")",
")",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"self",
".",
"db_exec_with_cursor",
"(",
"cursor",
",",
"get_sql_insert_without_first_field",
"(",
"table",
",",
"fieldlist",
",",
"self",
".",
"get_delims",
"(",
")",
")",
",",
"*",
"valuelist",
")",
"pkvalue",
"=",
"get_pk_of_last_insert",
"(",
"cursor",
")",
"setattr",
"(",
"obj",
",",
"fieldlist",
"[",
"0",
"]",
",",
"pkvalue",
")"
] | Inserts object into database table, with PK (first field) initially
unknown (and subsequently set in the object from the database). | [
"Inserts",
"object",
"into",
"database",
"table",
"with",
"PK",
"(",
"first",
"field",
")",
"initially",
"unknown",
"(",
"and",
"subsequently",
"set",
"in",
"the",
"object",
"from",
"the",
"database",
")",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2520-L2538 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.update_object_in_db | def update_object_in_db(self,
obj: Any,
table: str,
fieldlist: Sequence[str]) -> None:
"""Updates an object in the database (saves it to the database, where
it exists there already)."""
self.ensure_db_open()
pkvalue = getattr(obj, fieldlist[0])
valuelist = []
# Non-PK fields first
for f in fieldlist[1:]:
valuelist.append(getattr(obj, f))
# Then PK
valuelist.append(pkvalue)
cursor = self.db.cursor()
self.db_exec_with_cursor(
cursor,
get_sql_update_by_first_field(table, fieldlist, self.get_delims()),
*valuelist
) | python | def update_object_in_db(self,
obj: Any,
table: str,
fieldlist: Sequence[str]) -> None:
"""Updates an object in the database (saves it to the database, where
it exists there already)."""
self.ensure_db_open()
pkvalue = getattr(obj, fieldlist[0])
valuelist = []
# Non-PK fields first
for f in fieldlist[1:]:
valuelist.append(getattr(obj, f))
# Then PK
valuelist.append(pkvalue)
cursor = self.db.cursor()
self.db_exec_with_cursor(
cursor,
get_sql_update_by_first_field(table, fieldlist, self.get_delims()),
*valuelist
) | [
"def",
"update_object_in_db",
"(",
"self",
",",
"obj",
":",
"Any",
",",
"table",
":",
"str",
",",
"fieldlist",
":",
"Sequence",
"[",
"str",
"]",
")",
"->",
"None",
":",
"self",
".",
"ensure_db_open",
"(",
")",
"pkvalue",
"=",
"getattr",
"(",
"obj",
",",
"fieldlist",
"[",
"0",
"]",
")",
"valuelist",
"=",
"[",
"]",
"# Non-PK fields first",
"for",
"f",
"in",
"fieldlist",
"[",
"1",
":",
"]",
":",
"valuelist",
".",
"append",
"(",
"getattr",
"(",
"obj",
",",
"f",
")",
")",
"# Then PK",
"valuelist",
".",
"append",
"(",
"pkvalue",
")",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"self",
".",
"db_exec_with_cursor",
"(",
"cursor",
",",
"get_sql_update_by_first_field",
"(",
"table",
",",
"fieldlist",
",",
"self",
".",
"get_delims",
"(",
")",
")",
",",
"*",
"valuelist",
")"
] | Updates an object in the database (saves it to the database, where
it exists there already). | [
"Updates",
"an",
"object",
"in",
"the",
"database",
"(",
"saves",
"it",
"to",
"the",
"database",
"where",
"it",
"exists",
"there",
"already",
")",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2540-L2559 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.save_object_to_db | def save_object_to_db(self,
obj: Any,
table: str,
fieldlist: Sequence[str],
is_new_record: bool) -> None:
"""Saves a object to the database, inserting or updating as
necessary."""
if is_new_record:
pkvalue = getattr(obj, fieldlist[0])
if pkvalue is None:
self.insert_object_into_db_pk_unknown(obj, table, fieldlist)
else:
self.insert_object_into_db_pk_known(obj, table, fieldlist)
else:
self.update_object_in_db(obj, table, fieldlist) | python | def save_object_to_db(self,
obj: Any,
table: str,
fieldlist: Sequence[str],
is_new_record: bool) -> None:
"""Saves a object to the database, inserting or updating as
necessary."""
if is_new_record:
pkvalue = getattr(obj, fieldlist[0])
if pkvalue is None:
self.insert_object_into_db_pk_unknown(obj, table, fieldlist)
else:
self.insert_object_into_db_pk_known(obj, table, fieldlist)
else:
self.update_object_in_db(obj, table, fieldlist) | [
"def",
"save_object_to_db",
"(",
"self",
",",
"obj",
":",
"Any",
",",
"table",
":",
"str",
",",
"fieldlist",
":",
"Sequence",
"[",
"str",
"]",
",",
"is_new_record",
":",
"bool",
")",
"->",
"None",
":",
"if",
"is_new_record",
":",
"pkvalue",
"=",
"getattr",
"(",
"obj",
",",
"fieldlist",
"[",
"0",
"]",
")",
"if",
"pkvalue",
"is",
"None",
":",
"self",
".",
"insert_object_into_db_pk_unknown",
"(",
"obj",
",",
"table",
",",
"fieldlist",
")",
"else",
":",
"self",
".",
"insert_object_into_db_pk_known",
"(",
"obj",
",",
"table",
",",
"fieldlist",
")",
"else",
":",
"self",
".",
"update_object_in_db",
"(",
"obj",
",",
"table",
",",
"fieldlist",
")"
] | Saves a object to the database, inserting or updating as
necessary. | [
"Saves",
"a",
"object",
"to",
"the",
"database",
"inserting",
"or",
"updating",
"as",
"necessary",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2561-L2575 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.index_exists | def index_exists(self, table: str, indexname: str) -> bool:
"""Does an index exist? (Specific to MySQL.)"""
# MySQL:
sql = ("SELECT COUNT(*) FROM information_schema.statistics"
" WHERE table_name=? AND index_name=?")
row = self.fetchone(sql, table, indexname)
return True if row[0] >= 1 else False | python | def index_exists(self, table: str, indexname: str) -> bool:
"""Does an index exist? (Specific to MySQL.)"""
# MySQL:
sql = ("SELECT COUNT(*) FROM information_schema.statistics"
" WHERE table_name=? AND index_name=?")
row = self.fetchone(sql, table, indexname)
return True if row[0] >= 1 else False | [
"def",
"index_exists",
"(",
"self",
",",
"table",
":",
"str",
",",
"indexname",
":",
"str",
")",
"->",
"bool",
":",
"# MySQL:",
"sql",
"=",
"(",
"\"SELECT COUNT(*) FROM information_schema.statistics\"",
"\" WHERE table_name=? AND index_name=?\"",
")",
"row",
"=",
"self",
".",
"fetchone",
"(",
"sql",
",",
"table",
",",
"indexname",
")",
"return",
"True",
"if",
"row",
"[",
"0",
"]",
">=",
"1",
"else",
"False"
] | Does an index exist? (Specific to MySQL.) | [
"Does",
"an",
"index",
"exist?",
"(",
"Specific",
"to",
"MySQL",
".",
")"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2581-L2587 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.create_index | def create_index(self,
table: str,
field: str,
nchars: int = None,
indexname: str = None,
unique: bool = False) -> Optional[int]:
"""Creates an index (default name _idx_FIELDNAME), unless it exists
already."""
limit = ""
if nchars is not None:
limit = "({})".format(nchars)
if indexname is None:
indexname = "_idx_{}".format(field)
if self.index_exists(table, indexname):
return None
uniquestr = "UNIQUE" if unique else ""
sql = (
"CREATE {unique} INDEX {indexname} "
"ON {table} ({field}{limit})".format(
unique=uniquestr,
indexname=indexname,
table=table,
field=field,
limit=limit,
)
)
return self.db_exec(sql) | python | def create_index(self,
table: str,
field: str,
nchars: int = None,
indexname: str = None,
unique: bool = False) -> Optional[int]:
"""Creates an index (default name _idx_FIELDNAME), unless it exists
already."""
limit = ""
if nchars is not None:
limit = "({})".format(nchars)
if indexname is None:
indexname = "_idx_{}".format(field)
if self.index_exists(table, indexname):
return None
uniquestr = "UNIQUE" if unique else ""
sql = (
"CREATE {unique} INDEX {indexname} "
"ON {table} ({field}{limit})".format(
unique=uniquestr,
indexname=indexname,
table=table,
field=field,
limit=limit,
)
)
return self.db_exec(sql) | [
"def",
"create_index",
"(",
"self",
",",
"table",
":",
"str",
",",
"field",
":",
"str",
",",
"nchars",
":",
"int",
"=",
"None",
",",
"indexname",
":",
"str",
"=",
"None",
",",
"unique",
":",
"bool",
"=",
"False",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"limit",
"=",
"\"\"",
"if",
"nchars",
"is",
"not",
"None",
":",
"limit",
"=",
"\"({})\"",
".",
"format",
"(",
"nchars",
")",
"if",
"indexname",
"is",
"None",
":",
"indexname",
"=",
"\"_idx_{}\"",
".",
"format",
"(",
"field",
")",
"if",
"self",
".",
"index_exists",
"(",
"table",
",",
"indexname",
")",
":",
"return",
"None",
"uniquestr",
"=",
"\"UNIQUE\"",
"if",
"unique",
"else",
"\"\"",
"sql",
"=",
"(",
"\"CREATE {unique} INDEX {indexname} \"",
"\"ON {table} ({field}{limit})\"",
".",
"format",
"(",
"unique",
"=",
"uniquestr",
",",
"indexname",
"=",
"indexname",
",",
"table",
"=",
"table",
",",
"field",
"=",
"field",
",",
"limit",
"=",
"limit",
",",
")",
")",
"return",
"self",
".",
"db_exec",
"(",
"sql",
")"
] | Creates an index (default name _idx_FIELDNAME), unless it exists
already. | [
"Creates",
"an",
"index",
"(",
"default",
"name",
"_idx_FIELDNAME",
")",
"unless",
"it",
"exists",
"already",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2589-L2615 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.create_index_from_fieldspec | def create_index_from_fieldspec(self,
table: str,
fieldspec: FIELDSPEC_TYPE,
indexname: str = None) -> None:
"""Calls create_index based on a fieldspec, if the fieldspec has
indexed = True."""
if "indexed" in fieldspec and fieldspec["indexed"]:
if "index_nchar" in fieldspec:
nchar = fieldspec["index_nchar"]
else:
nchar = None
self.create_index(table, fieldspec["name"], nchar,
indexname=indexname) | python | def create_index_from_fieldspec(self,
table: str,
fieldspec: FIELDSPEC_TYPE,
indexname: str = None) -> None:
"""Calls create_index based on a fieldspec, if the fieldspec has
indexed = True."""
if "indexed" in fieldspec and fieldspec["indexed"]:
if "index_nchar" in fieldspec:
nchar = fieldspec["index_nchar"]
else:
nchar = None
self.create_index(table, fieldspec["name"], nchar,
indexname=indexname) | [
"def",
"create_index_from_fieldspec",
"(",
"self",
",",
"table",
":",
"str",
",",
"fieldspec",
":",
"FIELDSPEC_TYPE",
",",
"indexname",
":",
"str",
"=",
"None",
")",
"->",
"None",
":",
"if",
"\"indexed\"",
"in",
"fieldspec",
"and",
"fieldspec",
"[",
"\"indexed\"",
"]",
":",
"if",
"\"index_nchar\"",
"in",
"fieldspec",
":",
"nchar",
"=",
"fieldspec",
"[",
"\"index_nchar\"",
"]",
"else",
":",
"nchar",
"=",
"None",
"self",
".",
"create_index",
"(",
"table",
",",
"fieldspec",
"[",
"\"name\"",
"]",
",",
"nchar",
",",
"indexname",
"=",
"indexname",
")"
] | Calls create_index based on a fieldspec, if the fieldspec has
indexed = True. | [
"Calls",
"create_index",
"based",
"on",
"a",
"fieldspec",
"if",
"the",
"fieldspec",
"has",
"indexed",
"=",
"True",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2617-L2629 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.create_fulltext_index | def create_fulltext_index(self,
table: str,
field: str,
indexname: str = None) -> Optional[int]:
"""Creates a FULLTEXT index (default name _idxft_FIELDNAME), unless it
exists already. See:
http://dev.mysql.com/doc/refman/5.6/en/innodb-fulltext-index.html
http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
"""
if indexname is None:
indexname = "_idxft_{}".format(field)
if self.index_exists(table, indexname):
return None
sql = "CREATE FULLTEXT INDEX {} ON {} ({})".format(indexname, table,
field)
return self.db_exec(sql) | python | def create_fulltext_index(self,
table: str,
field: str,
indexname: str = None) -> Optional[int]:
"""Creates a FULLTEXT index (default name _idxft_FIELDNAME), unless it
exists already. See:
http://dev.mysql.com/doc/refman/5.6/en/innodb-fulltext-index.html
http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
"""
if indexname is None:
indexname = "_idxft_{}".format(field)
if self.index_exists(table, indexname):
return None
sql = "CREATE FULLTEXT INDEX {} ON {} ({})".format(indexname, table,
field)
return self.db_exec(sql) | [
"def",
"create_fulltext_index",
"(",
"self",
",",
"table",
":",
"str",
",",
"field",
":",
"str",
",",
"indexname",
":",
"str",
"=",
"None",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"if",
"indexname",
"is",
"None",
":",
"indexname",
"=",
"\"_idxft_{}\"",
".",
"format",
"(",
"field",
")",
"if",
"self",
".",
"index_exists",
"(",
"table",
",",
"indexname",
")",
":",
"return",
"None",
"sql",
"=",
"\"CREATE FULLTEXT INDEX {} ON {} ({})\"",
".",
"format",
"(",
"indexname",
",",
"table",
",",
"field",
")",
"return",
"self",
".",
"db_exec",
"(",
"sql",
")"
] | Creates a FULLTEXT index (default name _idxft_FIELDNAME), unless it
exists already. See:
http://dev.mysql.com/doc/refman/5.6/en/innodb-fulltext-index.html
http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html | [
"Creates",
"a",
"FULLTEXT",
"index",
"(",
"default",
"name",
"_idxft_FIELDNAME",
")",
"unless",
"it",
"exists",
"already",
".",
"See",
":"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2631-L2647 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fielddefsql_from_fieldspec | def fielddefsql_from_fieldspec(fieldspec: FIELDSPEC_TYPE) -> str:
"""Returns SQL fragment to define a field."""
sql = fieldspec["name"] + " " + fieldspec["sqltype"]
if "notnull" in fieldspec and fieldspec["notnull"]:
sql += " NOT NULL"
if "autoincrement" in fieldspec and fieldspec["autoincrement"]:
sql += " AUTO_INCREMENT"
if "pk" in fieldspec and fieldspec["pk"]:
sql += " PRIMARY KEY"
else:
if "unique" in fieldspec and fieldspec["unique"]:
sql += " UNIQUE"
if "comment" in fieldspec:
sql += " COMMENT " + sql_quote_string(fieldspec["comment"])
return sql | python | def fielddefsql_from_fieldspec(fieldspec: FIELDSPEC_TYPE) -> str:
"""Returns SQL fragment to define a field."""
sql = fieldspec["name"] + " " + fieldspec["sqltype"]
if "notnull" in fieldspec and fieldspec["notnull"]:
sql += " NOT NULL"
if "autoincrement" in fieldspec and fieldspec["autoincrement"]:
sql += " AUTO_INCREMENT"
if "pk" in fieldspec and fieldspec["pk"]:
sql += " PRIMARY KEY"
else:
if "unique" in fieldspec and fieldspec["unique"]:
sql += " UNIQUE"
if "comment" in fieldspec:
sql += " COMMENT " + sql_quote_string(fieldspec["comment"])
return sql | [
"def",
"fielddefsql_from_fieldspec",
"(",
"fieldspec",
":",
"FIELDSPEC_TYPE",
")",
"->",
"str",
":",
"sql",
"=",
"fieldspec",
"[",
"\"name\"",
"]",
"+",
"\" \"",
"+",
"fieldspec",
"[",
"\"sqltype\"",
"]",
"if",
"\"notnull\"",
"in",
"fieldspec",
"and",
"fieldspec",
"[",
"\"notnull\"",
"]",
":",
"sql",
"+=",
"\" NOT NULL\"",
"if",
"\"autoincrement\"",
"in",
"fieldspec",
"and",
"fieldspec",
"[",
"\"autoincrement\"",
"]",
":",
"sql",
"+=",
"\" AUTO_INCREMENT\"",
"if",
"\"pk\"",
"in",
"fieldspec",
"and",
"fieldspec",
"[",
"\"pk\"",
"]",
":",
"sql",
"+=",
"\" PRIMARY KEY\"",
"else",
":",
"if",
"\"unique\"",
"in",
"fieldspec",
"and",
"fieldspec",
"[",
"\"unique\"",
"]",
":",
"sql",
"+=",
"\" UNIQUE\"",
"if",
"\"comment\"",
"in",
"fieldspec",
":",
"sql",
"+=",
"\" COMMENT \"",
"+",
"sql_quote_string",
"(",
"fieldspec",
"[",
"\"comment\"",
"]",
")",
"return",
"sql"
] | Returns SQL fragment to define a field. | [
"Returns",
"SQL",
"fragment",
"to",
"define",
"a",
"field",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2665-L2679 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fielddefsql_from_fieldspeclist | def fielddefsql_from_fieldspeclist(
self, fieldspeclist: FIELDSPECLIST_TYPE) -> str:
"""Returns list of field-defining SQL fragments."""
return ",".join([
self.fielddefsql_from_fieldspec(x)
for x in fieldspeclist
]) | python | def fielddefsql_from_fieldspeclist(
self, fieldspeclist: FIELDSPECLIST_TYPE) -> str:
"""Returns list of field-defining SQL fragments."""
return ",".join([
self.fielddefsql_from_fieldspec(x)
for x in fieldspeclist
]) | [
"def",
"fielddefsql_from_fieldspeclist",
"(",
"self",
",",
"fieldspeclist",
":",
"FIELDSPECLIST_TYPE",
")",
"->",
"str",
":",
"return",
"\",\"",
".",
"join",
"(",
"[",
"self",
".",
"fielddefsql_from_fieldspec",
"(",
"x",
")",
"for",
"x",
"in",
"fieldspeclist",
"]",
")"
] | Returns list of field-defining SQL fragments. | [
"Returns",
"list",
"of",
"field",
"-",
"defining",
"SQL",
"fragments",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2681-L2687 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fieldspec_subset_by_name | def fieldspec_subset_by_name(
fieldspeclist: FIELDSPECLIST_TYPE,
fieldnames: Container[str]) -> FIELDSPECLIST_TYPE:
"""Returns a subset of the fieldspecs matching the fieldnames list."""
result = []
for x in fieldspeclist:
if x["name"] in fieldnames:
result.append(x)
return result | python | def fieldspec_subset_by_name(
fieldspeclist: FIELDSPECLIST_TYPE,
fieldnames: Container[str]) -> FIELDSPECLIST_TYPE:
"""Returns a subset of the fieldspecs matching the fieldnames list."""
result = []
for x in fieldspeclist:
if x["name"] in fieldnames:
result.append(x)
return result | [
"def",
"fieldspec_subset_by_name",
"(",
"fieldspeclist",
":",
"FIELDSPECLIST_TYPE",
",",
"fieldnames",
":",
"Container",
"[",
"str",
"]",
")",
"->",
"FIELDSPECLIST_TYPE",
":",
"result",
"=",
"[",
"]",
"for",
"x",
"in",
"fieldspeclist",
":",
"if",
"x",
"[",
"\"name\"",
"]",
"in",
"fieldnames",
":",
"result",
".",
"append",
"(",
"x",
")",
"return",
"result"
] | Returns a subset of the fieldspecs matching the fieldnames list. | [
"Returns",
"a",
"subset",
"of",
"the",
"fieldspecs",
"matching",
"the",
"fieldnames",
"list",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2690-L2698 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.table_exists | def table_exists(self, tablename: str) -> bool:
"""Does the table exist?"""
# information_schema is ANSI standard
sql = """
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_name=?
AND table_schema={}
""".format(self.get_current_schema_expr())
row = self.fetchone(sql, tablename)
return True if row[0] >= 1 else False | python | def table_exists(self, tablename: str) -> bool:
"""Does the table exist?"""
# information_schema is ANSI standard
sql = """
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_name=?
AND table_schema={}
""".format(self.get_current_schema_expr())
row = self.fetchone(sql, tablename)
return True if row[0] >= 1 else False | [
"def",
"table_exists",
"(",
"self",
",",
"tablename",
":",
"str",
")",
"->",
"bool",
":",
"# information_schema is ANSI standard",
"sql",
"=",
"\"\"\"\n SELECT COUNT(*)\n FROM information_schema.tables\n WHERE table_name=?\n AND table_schema={}\n \"\"\"",
".",
"format",
"(",
"self",
".",
"get_current_schema_expr",
"(",
")",
")",
"row",
"=",
"self",
".",
"fetchone",
"(",
"sql",
",",
"tablename",
")",
"return",
"True",
"if",
"row",
"[",
"0",
"]",
">=",
"1",
"else",
"False"
] | Does the table exist? | [
"Does",
"the",
"table",
"exist?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2704-L2714 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.column_exists | def column_exists(self, tablename: str, column: str) -> bool:
"""Does the column exist?"""
sql = """
SELECT COUNT(*)
FROM information_schema.columns
WHERE table_name=?
AND column_name=?
AND table_schema={}
""".format(self.get_current_schema_expr())
row = self.fetchone(sql, tablename, column)
return True if row[0] >= 1 else False | python | def column_exists(self, tablename: str, column: str) -> bool:
"""Does the column exist?"""
sql = """
SELECT COUNT(*)
FROM information_schema.columns
WHERE table_name=?
AND column_name=?
AND table_schema={}
""".format(self.get_current_schema_expr())
row = self.fetchone(sql, tablename, column)
return True if row[0] >= 1 else False | [
"def",
"column_exists",
"(",
"self",
",",
"tablename",
":",
"str",
",",
"column",
":",
"str",
")",
"->",
"bool",
":",
"sql",
"=",
"\"\"\"\n SELECT COUNT(*)\n FROM information_schema.columns\n WHERE table_name=?\n AND column_name=?\n AND table_schema={}\n \"\"\"",
".",
"format",
"(",
"self",
".",
"get_current_schema_expr",
"(",
")",
")",
"row",
"=",
"self",
".",
"fetchone",
"(",
"sql",
",",
"tablename",
",",
"column",
")",
"return",
"True",
"if",
"row",
"[",
"0",
"]",
">=",
"1",
"else",
"False"
] | Does the column exist? | [
"Does",
"the",
"column",
"exist?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2716-L2726 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.drop_table | def drop_table(self, tablename: str) -> int:
"""Drops a table. Use caution!"""
sql = "DROP TABLE IF EXISTS {}".format(tablename)
log.info("Dropping table " + tablename + " (ignore any warning here)")
return self.db_exec_literal(sql) | python | def drop_table(self, tablename: str) -> int:
"""Drops a table. Use caution!"""
sql = "DROP TABLE IF EXISTS {}".format(tablename)
log.info("Dropping table " + tablename + " (ignore any warning here)")
return self.db_exec_literal(sql) | [
"def",
"drop_table",
"(",
"self",
",",
"tablename",
":",
"str",
")",
"->",
"int",
":",
"sql",
"=",
"\"DROP TABLE IF EXISTS {}\"",
".",
"format",
"(",
"tablename",
")",
"log",
".",
"info",
"(",
"\"Dropping table \"",
"+",
"tablename",
"+",
"\" (ignore any warning here)\"",
")",
"return",
"self",
".",
"db_exec_literal",
"(",
"sql",
")"
] | Drops a table. Use caution! | [
"Drops",
"a",
"table",
".",
"Use",
"caution!"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2728-L2732 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.drop_view | def drop_view(self, viewname: str) -> int:
"""Drops a view."""
sql = "DROP VIEW IF EXISTS {}".format(viewname)
log.info("Dropping view " + viewname + " (ignore any warning here)")
return self.db_exec_literal(sql) | python | def drop_view(self, viewname: str) -> int:
"""Drops a view."""
sql = "DROP VIEW IF EXISTS {}".format(viewname)
log.info("Dropping view " + viewname + " (ignore any warning here)")
return self.db_exec_literal(sql) | [
"def",
"drop_view",
"(",
"self",
",",
"viewname",
":",
"str",
")",
"->",
"int",
":",
"sql",
"=",
"\"DROP VIEW IF EXISTS {}\"",
".",
"format",
"(",
"viewname",
")",
"log",
".",
"info",
"(",
"\"Dropping view \"",
"+",
"viewname",
"+",
"\" (ignore any warning here)\"",
")",
"return",
"self",
".",
"db_exec_literal",
"(",
"sql",
")"
] | Drops a view. | [
"Drops",
"a",
"view",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2734-L2738 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.make_table | def make_table(self,
tablename: str,
fieldspeclist: FIELDSPECLIST_TYPE,
dynamic: bool = False,
compressed: bool = False) -> Optional[int]:
"""Makes a table, if it doesn't already exist."""
if self.table_exists(tablename):
log.info("Skipping creation of table " + tablename +
" (already exists)")
return None
if not self.is_mysql():
dynamic = False
compressed = False
# http://dev.mysql.com/doc/refman/5.5/en/innodb-compression-usage.html
sql = """
CREATE TABLE IF NOT EXISTS {tablename}
({fieldspecs})
{dynamic}
{compressed}
""".format(
tablename=tablename,
fieldspecs=self.fielddefsql_from_fieldspeclist(fieldspeclist),
dynamic="ROW_FORMAT=DYNAMIC" if dynamic else "",
compressed="ROW_FORMAT=COMPRESSED" if compressed else "",
)
log.info("Creating table " + tablename)
return self.db_exec_literal(sql) | python | def make_table(self,
tablename: str,
fieldspeclist: FIELDSPECLIST_TYPE,
dynamic: bool = False,
compressed: bool = False) -> Optional[int]:
"""Makes a table, if it doesn't already exist."""
if self.table_exists(tablename):
log.info("Skipping creation of table " + tablename +
" (already exists)")
return None
if not self.is_mysql():
dynamic = False
compressed = False
# http://dev.mysql.com/doc/refman/5.5/en/innodb-compression-usage.html
sql = """
CREATE TABLE IF NOT EXISTS {tablename}
({fieldspecs})
{dynamic}
{compressed}
""".format(
tablename=tablename,
fieldspecs=self.fielddefsql_from_fieldspeclist(fieldspeclist),
dynamic="ROW_FORMAT=DYNAMIC" if dynamic else "",
compressed="ROW_FORMAT=COMPRESSED" if compressed else "",
)
log.info("Creating table " + tablename)
return self.db_exec_literal(sql) | [
"def",
"make_table",
"(",
"self",
",",
"tablename",
":",
"str",
",",
"fieldspeclist",
":",
"FIELDSPECLIST_TYPE",
",",
"dynamic",
":",
"bool",
"=",
"False",
",",
"compressed",
":",
"bool",
"=",
"False",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"if",
"self",
".",
"table_exists",
"(",
"tablename",
")",
":",
"log",
".",
"info",
"(",
"\"Skipping creation of table \"",
"+",
"tablename",
"+",
"\" (already exists)\"",
")",
"return",
"None",
"if",
"not",
"self",
".",
"is_mysql",
"(",
")",
":",
"dynamic",
"=",
"False",
"compressed",
"=",
"False",
"# http://dev.mysql.com/doc/refman/5.5/en/innodb-compression-usage.html",
"sql",
"=",
"\"\"\"\n CREATE TABLE IF NOT EXISTS {tablename}\n ({fieldspecs})\n {dynamic}\n {compressed}\n \"\"\"",
".",
"format",
"(",
"tablename",
"=",
"tablename",
",",
"fieldspecs",
"=",
"self",
".",
"fielddefsql_from_fieldspeclist",
"(",
"fieldspeclist",
")",
",",
"dynamic",
"=",
"\"ROW_FORMAT=DYNAMIC\"",
"if",
"dynamic",
"else",
"\"\"",
",",
"compressed",
"=",
"\"ROW_FORMAT=COMPRESSED\"",
"if",
"compressed",
"else",
"\"\"",
",",
")",
"log",
".",
"info",
"(",
"\"Creating table \"",
"+",
"tablename",
")",
"return",
"self",
".",
"db_exec_literal",
"(",
"sql",
")"
] | Makes a table, if it doesn't already exist. | [
"Makes",
"a",
"table",
"if",
"it",
"doesn",
"t",
"already",
"exist",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2740-L2766 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.rename_table | def rename_table(self, from_table: str, to_table: str) -> Optional[int]:
"""Renames a table. MySQL-specific."""
if not self.table_exists(from_table):
log.info("Skipping renaming of table " + from_table +
" (doesn't exist)")
return None
if self.table_exists(to_table):
raise RuntimeError("Can't rename table {} to {}: destination "
"already exists!".format(from_table, to_table))
log.info("Renaming table {} to {}", from_table, to_table)
sql = "RENAME TABLE {} TO {}".format(from_table, to_table)
return self.db_exec_literal(sql) | python | def rename_table(self, from_table: str, to_table: str) -> Optional[int]:
"""Renames a table. MySQL-specific."""
if not self.table_exists(from_table):
log.info("Skipping renaming of table " + from_table +
" (doesn't exist)")
return None
if self.table_exists(to_table):
raise RuntimeError("Can't rename table {} to {}: destination "
"already exists!".format(from_table, to_table))
log.info("Renaming table {} to {}", from_table, to_table)
sql = "RENAME TABLE {} TO {}".format(from_table, to_table)
return self.db_exec_literal(sql) | [
"def",
"rename_table",
"(",
"self",
",",
"from_table",
":",
"str",
",",
"to_table",
":",
"str",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"if",
"not",
"self",
".",
"table_exists",
"(",
"from_table",
")",
":",
"log",
".",
"info",
"(",
"\"Skipping renaming of table \"",
"+",
"from_table",
"+",
"\" (doesn't exist)\"",
")",
"return",
"None",
"if",
"self",
".",
"table_exists",
"(",
"to_table",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Can't rename table {} to {}: destination \"",
"\"already exists!\"",
".",
"format",
"(",
"from_table",
",",
"to_table",
")",
")",
"log",
".",
"info",
"(",
"\"Renaming table {} to {}\"",
",",
"from_table",
",",
"to_table",
")",
"sql",
"=",
"\"RENAME TABLE {} TO {}\"",
".",
"format",
"(",
"from_table",
",",
"to_table",
")",
"return",
"self",
".",
"db_exec_literal",
"(",
"sql",
")"
] | Renames a table. MySQL-specific. | [
"Renames",
"a",
"table",
".",
"MySQL",
"-",
"specific",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2768-L2779 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.add_column | def add_column(self, tablename: str, fieldspec: FIELDSPEC_TYPE) -> int:
"""Adds a column to an existing table."""
sql = "ALTER TABLE {} ADD COLUMN {}".format(
tablename, self.fielddefsql_from_fieldspec(fieldspec))
log.info(sql)
return self.db_exec_literal(sql) | python | def add_column(self, tablename: str, fieldspec: FIELDSPEC_TYPE) -> int:
"""Adds a column to an existing table."""
sql = "ALTER TABLE {} ADD COLUMN {}".format(
tablename, self.fielddefsql_from_fieldspec(fieldspec))
log.info(sql)
return self.db_exec_literal(sql) | [
"def",
"add_column",
"(",
"self",
",",
"tablename",
":",
"str",
",",
"fieldspec",
":",
"FIELDSPEC_TYPE",
")",
"->",
"int",
":",
"sql",
"=",
"\"ALTER TABLE {} ADD COLUMN {}\"",
".",
"format",
"(",
"tablename",
",",
"self",
".",
"fielddefsql_from_fieldspec",
"(",
"fieldspec",
")",
")",
"log",
".",
"info",
"(",
"sql",
")",
"return",
"self",
".",
"db_exec_literal",
"(",
"sql",
")"
] | Adds a column to an existing table. | [
"Adds",
"a",
"column",
"to",
"an",
"existing",
"table",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2781-L2786 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.drop_column | def drop_column(self, tablename: str, fieldname: str) -> int:
"""Drops (deletes) a column from an existing table."""
sql = "ALTER TABLE {} DROP COLUMN {}".format(tablename, fieldname)
log.info(sql)
return self.db_exec_literal(sql) | python | def drop_column(self, tablename: str, fieldname: str) -> int:
"""Drops (deletes) a column from an existing table."""
sql = "ALTER TABLE {} DROP COLUMN {}".format(tablename, fieldname)
log.info(sql)
return self.db_exec_literal(sql) | [
"def",
"drop_column",
"(",
"self",
",",
"tablename",
":",
"str",
",",
"fieldname",
":",
"str",
")",
"->",
"int",
":",
"sql",
"=",
"\"ALTER TABLE {} DROP COLUMN {}\"",
".",
"format",
"(",
"tablename",
",",
"fieldname",
")",
"log",
".",
"info",
"(",
"sql",
")",
"return",
"self",
".",
"db_exec_literal",
"(",
"sql",
")"
] | Drops (deletes) a column from an existing table. | [
"Drops",
"(",
"deletes",
")",
"a",
"column",
"from",
"an",
"existing",
"table",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2788-L2792 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.modify_column_if_table_exists | def modify_column_if_table_exists(self,
tablename: str,
fieldname: str,
newdef: str) -> Optional[int]:
"""Alters a column's definition without renaming it."""
if not self.table_exists(tablename):
return None
sql = "ALTER TABLE {t} MODIFY COLUMN {field} {newdef}".format(
t=tablename,
field=fieldname,
newdef=newdef
)
log.info(sql)
return self.db_exec_literal(sql) | python | def modify_column_if_table_exists(self,
tablename: str,
fieldname: str,
newdef: str) -> Optional[int]:
"""Alters a column's definition without renaming it."""
if not self.table_exists(tablename):
return None
sql = "ALTER TABLE {t} MODIFY COLUMN {field} {newdef}".format(
t=tablename,
field=fieldname,
newdef=newdef
)
log.info(sql)
return self.db_exec_literal(sql) | [
"def",
"modify_column_if_table_exists",
"(",
"self",
",",
"tablename",
":",
"str",
",",
"fieldname",
":",
"str",
",",
"newdef",
":",
"str",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"if",
"not",
"self",
".",
"table_exists",
"(",
"tablename",
")",
":",
"return",
"None",
"sql",
"=",
"\"ALTER TABLE {t} MODIFY COLUMN {field} {newdef}\"",
".",
"format",
"(",
"t",
"=",
"tablename",
",",
"field",
"=",
"fieldname",
",",
"newdef",
"=",
"newdef",
")",
"log",
".",
"info",
"(",
"sql",
")",
"return",
"self",
".",
"db_exec_literal",
"(",
"sql",
")"
] | Alters a column's definition without renaming it. | [
"Alters",
"a",
"column",
"s",
"definition",
"without",
"renaming",
"it",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2794-L2807 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.change_column_if_table_exists | def change_column_if_table_exists(self,
tablename: str,
oldfieldname: str,
newfieldname: str,
newdef: str) -> Optional[int]:
"""Renames a column and alters its definition."""
if not self.table_exists(tablename):
return None
if not self.column_exists(tablename, oldfieldname):
return None
sql = "ALTER TABLE {t} CHANGE COLUMN {old} {new} {newdef}".format(
t=tablename,
old=oldfieldname,
new=newfieldname,
newdef=newdef,
)
log.info(sql)
return self.db_exec_literal(sql) | python | def change_column_if_table_exists(self,
tablename: str,
oldfieldname: str,
newfieldname: str,
newdef: str) -> Optional[int]:
"""Renames a column and alters its definition."""
if not self.table_exists(tablename):
return None
if not self.column_exists(tablename, oldfieldname):
return None
sql = "ALTER TABLE {t} CHANGE COLUMN {old} {new} {newdef}".format(
t=tablename,
old=oldfieldname,
new=newfieldname,
newdef=newdef,
)
log.info(sql)
return self.db_exec_literal(sql) | [
"def",
"change_column_if_table_exists",
"(",
"self",
",",
"tablename",
":",
"str",
",",
"oldfieldname",
":",
"str",
",",
"newfieldname",
":",
"str",
",",
"newdef",
":",
"str",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"if",
"not",
"self",
".",
"table_exists",
"(",
"tablename",
")",
":",
"return",
"None",
"if",
"not",
"self",
".",
"column_exists",
"(",
"tablename",
",",
"oldfieldname",
")",
":",
"return",
"None",
"sql",
"=",
"\"ALTER TABLE {t} CHANGE COLUMN {old} {new} {newdef}\"",
".",
"format",
"(",
"t",
"=",
"tablename",
",",
"old",
"=",
"oldfieldname",
",",
"new",
"=",
"newfieldname",
",",
"newdef",
"=",
"newdef",
",",
")",
"log",
".",
"info",
"(",
"sql",
")",
"return",
"self",
".",
"db_exec_literal",
"(",
"sql",
")"
] | Renames a column and alters its definition. | [
"Renames",
"a",
"column",
"and",
"alters",
"its",
"definition",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2809-L2826 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.create_or_update_table | def create_or_update_table(self,
tablename: str,
fieldspeclist: FIELDSPECLIST_TYPE,
drop_superfluous_columns: bool = False,
dynamic: bool = False,
compressed: bool = False) -> None:
"""
- Make table, if it doesn't exist.
- Add fields that aren't there.
- Warn about superfluous fields, but don't delete them, unless
``drop_superfluous_columns == True``.
- Make indexes, if requested.
"""
# 1. Make table, if it doesn't exist
self.make_table(tablename, fieldspeclist, dynamic=dynamic,
compressed=compressed)
# 2. Are all the fields there?
# ... copes fine with fieldnames coming back in Unicode and being
# compared to str
fields_in_db = set(self.fetch_column_names(tablename))
desired_fieldnames = set(
self.fieldnames_from_fieldspeclist(fieldspeclist))
missing_fieldnames = desired_fieldnames - fields_in_db
missing_fieldspecs = self.fieldspec_subset_by_name(fieldspeclist,
missing_fieldnames)
for f in missing_fieldspecs:
self.add_column(tablename, f)
# 3. Anything superfluous?
superfluous_fieldnames = fields_in_db - desired_fieldnames
for f in superfluous_fieldnames:
if drop_superfluous_columns:
log.warning("... dropping superfluous field: " + f)
self.drop_column(tablename, f)
else:
log.warning("... superfluous field (ignored): " + f)
# 4. Make indexes, if some have been requested:
for fs in fieldspeclist:
self.create_index_from_fieldspec(tablename, fs) | python | def create_or_update_table(self,
tablename: str,
fieldspeclist: FIELDSPECLIST_TYPE,
drop_superfluous_columns: bool = False,
dynamic: bool = False,
compressed: bool = False) -> None:
"""
- Make table, if it doesn't exist.
- Add fields that aren't there.
- Warn about superfluous fields, but don't delete them, unless
``drop_superfluous_columns == True``.
- Make indexes, if requested.
"""
# 1. Make table, if it doesn't exist
self.make_table(tablename, fieldspeclist, dynamic=dynamic,
compressed=compressed)
# 2. Are all the fields there?
# ... copes fine with fieldnames coming back in Unicode and being
# compared to str
fields_in_db = set(self.fetch_column_names(tablename))
desired_fieldnames = set(
self.fieldnames_from_fieldspeclist(fieldspeclist))
missing_fieldnames = desired_fieldnames - fields_in_db
missing_fieldspecs = self.fieldspec_subset_by_name(fieldspeclist,
missing_fieldnames)
for f in missing_fieldspecs:
self.add_column(tablename, f)
# 3. Anything superfluous?
superfluous_fieldnames = fields_in_db - desired_fieldnames
for f in superfluous_fieldnames:
if drop_superfluous_columns:
log.warning("... dropping superfluous field: " + f)
self.drop_column(tablename, f)
else:
log.warning("... superfluous field (ignored): " + f)
# 4. Make indexes, if some have been requested:
for fs in fieldspeclist:
self.create_index_from_fieldspec(tablename, fs) | [
"def",
"create_or_update_table",
"(",
"self",
",",
"tablename",
":",
"str",
",",
"fieldspeclist",
":",
"FIELDSPECLIST_TYPE",
",",
"drop_superfluous_columns",
":",
"bool",
"=",
"False",
",",
"dynamic",
":",
"bool",
"=",
"False",
",",
"compressed",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"# 1. Make table, if it doesn't exist",
"self",
".",
"make_table",
"(",
"tablename",
",",
"fieldspeclist",
",",
"dynamic",
"=",
"dynamic",
",",
"compressed",
"=",
"compressed",
")",
"# 2. Are all the fields there?",
"# ... copes fine with fieldnames coming back in Unicode and being",
"# compared to str",
"fields_in_db",
"=",
"set",
"(",
"self",
".",
"fetch_column_names",
"(",
"tablename",
")",
")",
"desired_fieldnames",
"=",
"set",
"(",
"self",
".",
"fieldnames_from_fieldspeclist",
"(",
"fieldspeclist",
")",
")",
"missing_fieldnames",
"=",
"desired_fieldnames",
"-",
"fields_in_db",
"missing_fieldspecs",
"=",
"self",
".",
"fieldspec_subset_by_name",
"(",
"fieldspeclist",
",",
"missing_fieldnames",
")",
"for",
"f",
"in",
"missing_fieldspecs",
":",
"self",
".",
"add_column",
"(",
"tablename",
",",
"f",
")",
"# 3. Anything superfluous?",
"superfluous_fieldnames",
"=",
"fields_in_db",
"-",
"desired_fieldnames",
"for",
"f",
"in",
"superfluous_fieldnames",
":",
"if",
"drop_superfluous_columns",
":",
"log",
".",
"warning",
"(",
"\"... dropping superfluous field: \"",
"+",
"f",
")",
"self",
".",
"drop_column",
"(",
"tablename",
",",
"f",
")",
"else",
":",
"log",
".",
"warning",
"(",
"\"... superfluous field (ignored): \"",
"+",
"f",
")",
"# 4. Make indexes, if some have been requested:",
"for",
"fs",
"in",
"fieldspeclist",
":",
"self",
".",
"create_index_from_fieldspec",
"(",
"tablename",
",",
"fs",
")"
] | - Make table, if it doesn't exist.
- Add fields that aren't there.
- Warn about superfluous fields, but don't delete them, unless
``drop_superfluous_columns == True``.
- Make indexes, if requested. | [
"-",
"Make",
"table",
"if",
"it",
"doesn",
"t",
"exist",
".",
"-",
"Add",
"fields",
"that",
"aren",
"t",
"there",
".",
"-",
"Warn",
"about",
"superfluous",
"fields",
"but",
"don",
"t",
"delete",
"them",
"unless",
"drop_superfluous_columns",
"==",
"True",
".",
"-",
"Make",
"indexes",
"if",
"requested",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2828-L2869 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.describe_table | def describe_table(self, table: str) -> List[List[Any]]:
"""Returns details on a specific table."""
return self.flavour.describe_table(self, table) | python | def describe_table(self, table: str) -> List[List[Any]]:
"""Returns details on a specific table."""
return self.flavour.describe_table(self, table) | [
"def",
"describe_table",
"(",
"self",
",",
"table",
":",
"str",
")",
"->",
"List",
"[",
"List",
"[",
"Any",
"]",
"]",
":",
"return",
"self",
".",
"flavour",
".",
"describe_table",
"(",
"self",
",",
"table",
")"
] | Returns details on a specific table. | [
"Returns",
"details",
"on",
"a",
"specific",
"table",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2883-L2885 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fetch_column_names | def fetch_column_names(self, table: str) -> List[str]:
"""Returns all column names for a table."""
return self.flavour.fetch_column_names(self, table) | python | def fetch_column_names(self, table: str) -> List[str]:
"""Returns all column names for a table."""
return self.flavour.fetch_column_names(self, table) | [
"def",
"fetch_column_names",
"(",
"self",
",",
"table",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"self",
".",
"flavour",
".",
"fetch_column_names",
"(",
"self",
",",
"table",
")"
] | Returns all column names for a table. | [
"Returns",
"all",
"column",
"names",
"for",
"a",
"table",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2887-L2889 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.get_datatype | def get_datatype(self, table: str, column: str) -> str:
"""Returns database SQL datatype for a column: e.g. VARCHAR."""
return self.flavour.get_datatype(self, table, column).upper() | python | def get_datatype(self, table: str, column: str) -> str:
"""Returns database SQL datatype for a column: e.g. VARCHAR."""
return self.flavour.get_datatype(self, table, column).upper() | [
"def",
"get_datatype",
"(",
"self",
",",
"table",
":",
"str",
",",
"column",
":",
"str",
")",
"->",
"str",
":",
"return",
"self",
".",
"flavour",
".",
"get_datatype",
"(",
"self",
",",
"table",
",",
"column",
")",
".",
"upper",
"(",
")"
] | Returns database SQL datatype for a column: e.g. VARCHAR. | [
"Returns",
"database",
"SQL",
"datatype",
"for",
"a",
"column",
":",
"e",
".",
"g",
".",
"VARCHAR",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2891-L2893 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.get_column_type | def get_column_type(self, table: str, column: str) -> str:
"""Returns database SQL datatype for a column, e.g. VARCHAR(50)."""
return self.flavour.get_column_type(self, table, column).upper() | python | def get_column_type(self, table: str, column: str) -> str:
"""Returns database SQL datatype for a column, e.g. VARCHAR(50)."""
return self.flavour.get_column_type(self, table, column).upper() | [
"def",
"get_column_type",
"(",
"self",
",",
"table",
":",
"str",
",",
"column",
":",
"str",
")",
"->",
"str",
":",
"return",
"self",
".",
"flavour",
".",
"get_column_type",
"(",
"self",
",",
"table",
",",
"column",
")",
".",
"upper",
"(",
")"
] | Returns database SQL datatype for a column, e.g. VARCHAR(50). | [
"Returns",
"database",
"SQL",
"datatype",
"for",
"a",
"column",
"e",
".",
"g",
".",
"VARCHAR",
"(",
"50",
")",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2895-L2897 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.get_comment | def get_comment(self, table: str, column: str) -> str:
"""Returns database SQL comment for a column."""
return self.flavour.get_comment(self, table, column) | python | def get_comment(self, table: str, column: str) -> str:
"""Returns database SQL comment for a column."""
return self.flavour.get_comment(self, table, column) | [
"def",
"get_comment",
"(",
"self",
",",
"table",
":",
"str",
",",
"column",
":",
"str",
")",
"->",
"str",
":",
"return",
"self",
".",
"flavour",
".",
"get_comment",
"(",
"self",
",",
"table",
",",
"column",
")"
] | Returns database SQL comment for a column. | [
"Returns",
"database",
"SQL",
"comment",
"for",
"a",
"column",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2899-L2901 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.debug_query | def debug_query(self, sql: str, *args) -> None:
"""Executes SQL and writes the result to the log."""
rows = self.fetchall(sql, *args)
debug_query_result(rows) | python | def debug_query(self, sql: str, *args) -> None:
"""Executes SQL and writes the result to the log."""
rows = self.fetchall(sql, *args)
debug_query_result(rows) | [
"def",
"debug_query",
"(",
"self",
",",
"sql",
":",
"str",
",",
"*",
"args",
")",
"->",
"None",
":",
"rows",
"=",
"self",
".",
"fetchall",
"(",
"sql",
",",
"*",
"args",
")",
"debug_query_result",
"(",
"rows",
")"
] | Executes SQL and writes the result to the log. | [
"Executes",
"SQL",
"and",
"writes",
"the",
"result",
"to",
"the",
"log",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2903-L2906 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.wipe_table | def wipe_table(self, table: str) -> int:
"""Delete all records from a table. Use caution!"""
sql = "DELETE FROM " + self.delimit(table)
return self.db_exec(sql) | python | def wipe_table(self, table: str) -> int:
"""Delete all records from a table. Use caution!"""
sql = "DELETE FROM " + self.delimit(table)
return self.db_exec(sql) | [
"def",
"wipe_table",
"(",
"self",
",",
"table",
":",
"str",
")",
"->",
"int",
":",
"sql",
"=",
"\"DELETE FROM \"",
"+",
"self",
".",
"delimit",
"(",
"table",
")",
"return",
"self",
".",
"db_exec",
"(",
"sql",
")"
] | Delete all records from a table. Use caution! | [
"Delete",
"all",
"records",
"from",
"a",
"table",
".",
"Use",
"caution!"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2908-L2911 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.create_or_replace_primary_key | def create_or_replace_primary_key(self,
table: str,
fieldnames: Sequence[str]) -> int:
"""Make a primary key, or replace it if it exists."""
# *** create_or_replace_primary_key: Uses code specific to MySQL
sql = """
SELECT COUNT(*)
FROM information_schema.table_constraints
WHERE table_name=?
AND table_schema={}
AND constraint_name='PRIMARY'
""".format(self.get_current_schema_expr())
# http://forums.mysql.com/read.php?10,114742,114748#msg-114748
row = self.fetchone(sql, table)
has_pk_already = True if row[0] >= 1 else False
drop_pk_if_exists = " DROP PRIMARY KEY," if has_pk_already else ""
fieldlist = ",".join([self.delimit(f) for f in fieldnames])
sql = ("ALTER TABLE " + self.delimit(table) +
drop_pk_if_exists +
" ADD PRIMARY KEY(" + fieldlist + ")")
# http://stackoverflow.com/questions/8859353
return self.db_exec(sql) | python | def create_or_replace_primary_key(self,
table: str,
fieldnames: Sequence[str]) -> int:
"""Make a primary key, or replace it if it exists."""
# *** create_or_replace_primary_key: Uses code specific to MySQL
sql = """
SELECT COUNT(*)
FROM information_schema.table_constraints
WHERE table_name=?
AND table_schema={}
AND constraint_name='PRIMARY'
""".format(self.get_current_schema_expr())
# http://forums.mysql.com/read.php?10,114742,114748#msg-114748
row = self.fetchone(sql, table)
has_pk_already = True if row[0] >= 1 else False
drop_pk_if_exists = " DROP PRIMARY KEY," if has_pk_already else ""
fieldlist = ",".join([self.delimit(f) for f in fieldnames])
sql = ("ALTER TABLE " + self.delimit(table) +
drop_pk_if_exists +
" ADD PRIMARY KEY(" + fieldlist + ")")
# http://stackoverflow.com/questions/8859353
return self.db_exec(sql) | [
"def",
"create_or_replace_primary_key",
"(",
"self",
",",
"table",
":",
"str",
",",
"fieldnames",
":",
"Sequence",
"[",
"str",
"]",
")",
"->",
"int",
":",
"# *** create_or_replace_primary_key: Uses code specific to MySQL",
"sql",
"=",
"\"\"\"\n SELECT COUNT(*)\n FROM information_schema.table_constraints\n WHERE table_name=?\n AND table_schema={}\n AND constraint_name='PRIMARY'\n \"\"\"",
".",
"format",
"(",
"self",
".",
"get_current_schema_expr",
"(",
")",
")",
"# http://forums.mysql.com/read.php?10,114742,114748#msg-114748",
"row",
"=",
"self",
".",
"fetchone",
"(",
"sql",
",",
"table",
")",
"has_pk_already",
"=",
"True",
"if",
"row",
"[",
"0",
"]",
">=",
"1",
"else",
"False",
"drop_pk_if_exists",
"=",
"\" DROP PRIMARY KEY,\"",
"if",
"has_pk_already",
"else",
"\"\"",
"fieldlist",
"=",
"\",\"",
".",
"join",
"(",
"[",
"self",
".",
"delimit",
"(",
"f",
")",
"for",
"f",
"in",
"fieldnames",
"]",
")",
"sql",
"=",
"(",
"\"ALTER TABLE \"",
"+",
"self",
".",
"delimit",
"(",
"table",
")",
"+",
"drop_pk_if_exists",
"+",
"\" ADD PRIMARY KEY(\"",
"+",
"fieldlist",
"+",
"\")\"",
")",
"# http://stackoverflow.com/questions/8859353",
"return",
"self",
".",
"db_exec",
"(",
"sql",
")"
] | Make a primary key, or replace it if it exists. | [
"Make",
"a",
"primary",
"key",
"or",
"replace",
"it",
"if",
"it",
"exists",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2913-L2934 |
davenquinn/Attitude | attitude/error/axes.py | noise_covariance | def noise_covariance(fit, dof=2, **kw):
"""
Covariance taking into account the 'noise covariance' of the data.
This is technically more realistic for continuously sampled data.
From Faber, 1993
"""
ev = fit.eigenvalues
measurement_noise = ev[-1]/(fit.n-dof)
return 4*ev*measurement_noise | python | def noise_covariance(fit, dof=2, **kw):
"""
Covariance taking into account the 'noise covariance' of the data.
This is technically more realistic for continuously sampled data.
From Faber, 1993
"""
ev = fit.eigenvalues
measurement_noise = ev[-1]/(fit.n-dof)
return 4*ev*measurement_noise | [
"def",
"noise_covariance",
"(",
"fit",
",",
"dof",
"=",
"2",
",",
"*",
"*",
"kw",
")",
":",
"ev",
"=",
"fit",
".",
"eigenvalues",
"measurement_noise",
"=",
"ev",
"[",
"-",
"1",
"]",
"/",
"(",
"fit",
".",
"n",
"-",
"dof",
")",
"return",
"4",
"*",
"ev",
"*",
"measurement_noise"
] | Covariance taking into account the 'noise covariance' of the data.
This is technically more realistic for continuously sampled data.
From Faber, 1993 | [
"Covariance",
"taking",
"into",
"account",
"the",
"noise",
"covariance",
"of",
"the",
"data",
".",
"This",
"is",
"technically",
"more",
"realistic",
"for",
"continuously",
"sampled",
"data",
".",
"From",
"Faber",
"1993"
] | train | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/error/axes.py#L31-L40 |
davenquinn/Attitude | attitude/error/axes.py | angular_errors | def angular_errors(hyp_axes):
"""
Minimum and maximum angular errors
corresponding to 1st and 2nd axes
of PCA distribution.
Ordered as [minimum, maximum] angular error.
"""
# Not quite sure why this is sqrt but it is empirically correct
ax = N.sqrt(hyp_axes)
return tuple(N.arctan2(ax[-1],ax[:-1])) | python | def angular_errors(hyp_axes):
"""
Minimum and maximum angular errors
corresponding to 1st and 2nd axes
of PCA distribution.
Ordered as [minimum, maximum] angular error.
"""
# Not quite sure why this is sqrt but it is empirically correct
ax = N.sqrt(hyp_axes)
return tuple(N.arctan2(ax[-1],ax[:-1])) | [
"def",
"angular_errors",
"(",
"hyp_axes",
")",
":",
"# Not quite sure why this is sqrt but it is empirically correct",
"ax",
"=",
"N",
".",
"sqrt",
"(",
"hyp_axes",
")",
"return",
"tuple",
"(",
"N",
".",
"arctan2",
"(",
"ax",
"[",
"-",
"1",
"]",
",",
"ax",
"[",
":",
"-",
"1",
"]",
")",
")"
] | Minimum and maximum angular errors
corresponding to 1st and 2nd axes
of PCA distribution.
Ordered as [minimum, maximum] angular error. | [
"Minimum",
"and",
"maximum",
"angular",
"errors",
"corresponding",
"to",
"1st",
"and",
"2nd",
"axes",
"of",
"PCA",
"distribution",
"."
] | train | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/error/axes.py#L67-L77 |
davenquinn/Attitude | attitude/error/axes.py | statistical_axes | def statistical_axes(fit, **kw):
"""
Hyperbolic error using a statistical process (either sampling
or noise errors)
Integrates covariance with error level
and degrees of freedom for plotting
confidence intervals.
Degrees of freedom is set to 2, which is the
relevant number of independent dimensions
to planar fitting of *a priori* centered data.
"""
method = kw.pop('method', 'noise')
confidence_level = kw.pop('confidence_level', 0.95)
dof = kw.pop('dof',2)
nominal = fit.eigenvalues
if method == 'sampling':
cov = sampling_covariance(fit,**kw)
elif method == 'noise':
cov = noise_covariance(fit,**kw)
if kw.pop('chisq', False):
# Model the incorrect behaviour of using the
# Chi2 distribution instead of the Fisher
# distribution (which is a measure of the
# ratio between the two).
z = chi2.ppf(confidence_level,dof)
else:
z = fisher_statistic(fit.n,confidence_level,dof=dof)
# Apply two fisher F parameters (one along each axis)
# Since we apply to each axis without division,
# it is as if we are applying N.sqrt(2*F) to the entire
# distribution, aligning us with (Francq, 2014)
err = z*N.sqrt(cov)
return apply_error_scaling(nominal, err, n=fit.n, **kw) | python | def statistical_axes(fit, **kw):
"""
Hyperbolic error using a statistical process (either sampling
or noise errors)
Integrates covariance with error level
and degrees of freedom for plotting
confidence intervals.
Degrees of freedom is set to 2, which is the
relevant number of independent dimensions
to planar fitting of *a priori* centered data.
"""
method = kw.pop('method', 'noise')
confidence_level = kw.pop('confidence_level', 0.95)
dof = kw.pop('dof',2)
nominal = fit.eigenvalues
if method == 'sampling':
cov = sampling_covariance(fit,**kw)
elif method == 'noise':
cov = noise_covariance(fit,**kw)
if kw.pop('chisq', False):
# Model the incorrect behaviour of using the
# Chi2 distribution instead of the Fisher
# distribution (which is a measure of the
# ratio between the two).
z = chi2.ppf(confidence_level,dof)
else:
z = fisher_statistic(fit.n,confidence_level,dof=dof)
# Apply two fisher F parameters (one along each axis)
# Since we apply to each axis without division,
# it is as if we are applying N.sqrt(2*F) to the entire
# distribution, aligning us with (Francq, 2014)
err = z*N.sqrt(cov)
return apply_error_scaling(nominal, err, n=fit.n, **kw) | [
"def",
"statistical_axes",
"(",
"fit",
",",
"*",
"*",
"kw",
")",
":",
"method",
"=",
"kw",
".",
"pop",
"(",
"'method'",
",",
"'noise'",
")",
"confidence_level",
"=",
"kw",
".",
"pop",
"(",
"'confidence_level'",
",",
"0.95",
")",
"dof",
"=",
"kw",
".",
"pop",
"(",
"'dof'",
",",
"2",
")",
"nominal",
"=",
"fit",
".",
"eigenvalues",
"if",
"method",
"==",
"'sampling'",
":",
"cov",
"=",
"sampling_covariance",
"(",
"fit",
",",
"*",
"*",
"kw",
")",
"elif",
"method",
"==",
"'noise'",
":",
"cov",
"=",
"noise_covariance",
"(",
"fit",
",",
"*",
"*",
"kw",
")",
"if",
"kw",
".",
"pop",
"(",
"'chisq'",
",",
"False",
")",
":",
"# Model the incorrect behaviour of using the",
"# Chi2 distribution instead of the Fisher",
"# distribution (which is a measure of the",
"# ratio between the two).",
"z",
"=",
"chi2",
".",
"ppf",
"(",
"confidence_level",
",",
"dof",
")",
"else",
":",
"z",
"=",
"fisher_statistic",
"(",
"fit",
".",
"n",
",",
"confidence_level",
",",
"dof",
"=",
"dof",
")",
"# Apply two fisher F parameters (one along each axis)",
"# Since we apply to each axis without division,",
"# it is as if we are applying N.sqrt(2*F) to the entire",
"# distribution, aligning us with (Francq, 2014)",
"err",
"=",
"z",
"*",
"N",
".",
"sqrt",
"(",
"cov",
")",
"return",
"apply_error_scaling",
"(",
"nominal",
",",
"err",
",",
"n",
"=",
"fit",
".",
"n",
",",
"*",
"*",
"kw",
")"
] | Hyperbolic error using a statistical process (either sampling
or noise errors)
Integrates covariance with error level
and degrees of freedom for plotting
confidence intervals.
Degrees of freedom is set to 2, which is the
relevant number of independent dimensions
to planar fitting of *a priori* centered data. | [
"Hyperbolic",
"error",
"using",
"a",
"statistical",
"process",
"(",
"either",
"sampling",
"or",
"noise",
"errors",
")"
] | train | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/error/axes.py#L108-L146 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/alembic_ops.py | create_view | def create_view(operations, operation):
"""
Implements ``CREATE VIEW``.
Args:
operations: instance of ``alembic.operations.base.Operations``
operation: instance of :class:`.ReversibleOp`
Returns:
``None``
"""
operations.execute("CREATE VIEW %s AS %s" % (
operation.target.name,
operation.target.sqltext
)) | python | def create_view(operations, operation):
"""
Implements ``CREATE VIEW``.
Args:
operations: instance of ``alembic.operations.base.Operations``
operation: instance of :class:`.ReversibleOp`
Returns:
``None``
"""
operations.execute("CREATE VIEW %s AS %s" % (
operation.target.name,
operation.target.sqltext
)) | [
"def",
"create_view",
"(",
"operations",
",",
"operation",
")",
":",
"operations",
".",
"execute",
"(",
"\"CREATE VIEW %s AS %s\"",
"%",
"(",
"operation",
".",
"target",
".",
"name",
",",
"operation",
".",
"target",
".",
"sqltext",
")",
")"
] | Implements ``CREATE VIEW``.
Args:
operations: instance of ``alembic.operations.base.Operations``
operation: instance of :class:`.ReversibleOp`
Returns:
``None`` | [
"Implements",
"CREATE",
"VIEW",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/alembic_ops.py#L195-L209 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/alembic_ops.py | create_sp | def create_sp(operations, operation):
"""
Implements ``CREATE FUNCTION``.
Args:
operations: instance of ``alembic.operations.base.Operations``
operation: instance of :class:`.ReversibleOp`
Returns:
``None``
"""
operations.execute(
"CREATE FUNCTION %s %s" % (
operation.target.name, operation.target.sqltext
)
) | python | def create_sp(operations, operation):
"""
Implements ``CREATE FUNCTION``.
Args:
operations: instance of ``alembic.operations.base.Operations``
operation: instance of :class:`.ReversibleOp`
Returns:
``None``
"""
operations.execute(
"CREATE FUNCTION %s %s" % (
operation.target.name, operation.target.sqltext
)
) | [
"def",
"create_sp",
"(",
"operations",
",",
"operation",
")",
":",
"operations",
".",
"execute",
"(",
"\"CREATE FUNCTION %s %s\"",
"%",
"(",
"operation",
".",
"target",
".",
"name",
",",
"operation",
".",
"target",
".",
"sqltext",
")",
")"
] | Implements ``CREATE FUNCTION``.
Args:
operations: instance of ``alembic.operations.base.Operations``
operation: instance of :class:`.ReversibleOp`
Returns:
``None`` | [
"Implements",
"CREATE",
"FUNCTION",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/alembic_ops.py#L228-L243 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.