|
| 1 | +"""Python bindings for libfsqlf.""" |
| 2 | + |
| 3 | + |
| 4 | +from ctypes import CDLL, POINTER, c_char_p, c_int, c_void_p, byref |
| 5 | + |
| 6 | + |
| 7 | +class Fsqlf(object): |
| 8 | + """Ctypes wrapper around libfsqlf. |
| 9 | +
|
| 10 | + Example: |
| 11 | +
|
| 12 | + >>> with Fsqlf("~/fsqlf/builds/linux-x86/bin/libfsqlf.so") as fsqlf: |
| 13 | + >>> print(fsqlf.format(" select 4 from t where x in (select 1);")) |
| 14 | + SELECT |
| 15 | + 4 |
| 16 | + FROM t |
| 17 | + WHERE x IN |
| 18 | + ( |
| 19 | + SELECT |
| 20 | + 1 |
| 21 | + ) |
| 22 | + ; |
| 23 | + """ |
| 24 | + |
| 25 | + def __init__(self, libpath=None): |
| 26 | + """Initialize formatter. |
| 27 | +
|
| 28 | + Note: Library allocates memory during `__init__`, |
| 29 | + so corresponding `cleanup` call is needed to release the memory. |
| 30 | + (Or use `with` syntax to make cleanup automatically) |
| 31 | +
|
| 32 | + """ |
| 33 | + # Specify ctypes stuff. |
| 34 | + self._lib = CDLL(libpath) |
| 35 | + self._lib.fsqlf_kwmap_init.argtypes = [POINTER(c_void_p)] |
| 36 | + self._lib.fsqlf_kwmap_destroy.argtypes = [c_void_p] |
| 37 | + self._lib.fsqlf_format_bytes.argtypes = [c_void_p, c_char_p, c_int, POINTER(c_char_p)] |
| 38 | + |
| 39 | + # Init the keyword configuration. |
| 40 | + self._kwmap = c_void_p() |
| 41 | + self._lib.fsqlf_kwmap_init(byref(self._kwmap)) |
| 42 | + |
| 43 | + def format(self, sql_query): |
| 44 | + """Format sql query.""" |
| 45 | + result = c_char_p() |
| 46 | + self._lib.fsqlf_format_bytes(self._kwmap, c_char_p(sql_query), len(sql_query), byref(result)); |
| 47 | + return result.value |
| 48 | + |
| 49 | + def cleanup(self): |
| 50 | + """Free-up memory allocated during initialization. |
| 51 | +
|
| 52 | + Formatter is not usable after cleanup. |
| 53 | + """ |
| 54 | + self._lib.fsqlf_kwmap_destroy(self._kwmap) |
| 55 | + |
| 56 | + def __enter__(self): |
| 57 | + return self |
| 58 | + |
| 59 | + def __exit__(self, type, value, tb): |
| 60 | + self.cleanup() |
| 61 | + |
| 62 | + |
| 63 | +def format(sql_query, libpath): |
| 64 | + """Format sql query. |
| 65 | +
|
| 66 | + Convenience function that initializes and destroys formatter on each call. |
| 67 | + """ |
| 68 | + with Fsqlf(libpath) as fsqlf: |
| 69 | + print(fsqlf.format(sql_query)) |
0 commit comments