Skip to content

Instantly share code, notes, and snippets.

@renegarcia
Created July 11, 2023 17:57
Show Gist options
  • Save renegarcia/e4728d5fe71e024aba9783995f056797 to your computer and use it in GitHub Desktop.
Save renegarcia/e4728d5fe71e024aba9783995f056797 to your computer and use it in GitHub Desktop.
Fbexport Query - Exports queries from an Firebird database

Fbexport Query

Exports queries from an Firebird database. This is a wrapper for fbexport. See the section on configuration if it is not in your PATH.

Usage

usage: fbexport-query.py [-h] [--out OUT] db sql

positional arguments:
  db          Database location.
  sql         File with SQL query to execute.

options:
  -h, --help  show this help message and exit
  --out OUT   Output location. Use '-' for stdout (default).

Finding fbexport

fbexport-query first tries to read the location of fbexport from an environment variable named FBEXPORT. If unsuccessful, it tries to read it from a file named CONFIG.ini, whose structure is simply

[DEFAULT]
FBEXPORT = /path/to/fbexport

then it tries to find it in the system PATH, raising an FbexportError if none of the methods above succeeded.

# Rename to CONFIG.ini if using this file to add the path to fbexport
[DEFAULT]
# Update with the path to fbexport
FBEXPORT = /path/to/fbexport
from subprocess import run
from argparse import ArgumentParser
from os import environ
from configparser import ConfigParser
import shutil
FBEXPORT_KEY = "FBEXPORT"
CONFIG_FNAME = "CONFIG.ini"
FBCOMMAND = [
"-Sc",
"-J",
"Y-M-D",
"-H",
"",
"-U",
"sysdba",
"-P",
"masterkey",
]
class FbexportError(Exception):
pass
def find_fbexport() -> str:
try:
fbexport = environ[FBEXPORT_KEY]
except KeyError:
config = ConfigParser()
config.read(CONFIG_FNAME)
try:
fbexport = config["DEFAULT"][FBEXPORT_KEY]
except KeyError:
fbexport = shutil.which("fbexport")
if fbexport is None:
raise FbexportError("fbexport not found.")
return fbexport
def run_query(db: str, query: str, out: str):
fbexport = find_fbexport()
command = [fbexport]
for token in FBCOMMAND:
command.append(token)
command.append("-D")
command.append(db)
command.append("-Q")
command.append(query)
command.append("-F")
command.append(out)
run(command)
def main():
parser = ArgumentParser("fbexport-query.py")
parser.add_argument("db", help="Database location.")
parser.add_argument("sql", help="File with SQL query to execute.")
parser.add_argument(
"--out", help="Output location. Use '-' for stdout (default).", default="-"
)
args = parser.parse_args()
with open(args.sql) as f:
query = f.read()
run_query(args.db, query, args.out)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment