diff options
author | Marko Kreen | 2011-12-22 09:16:04 +0000 |
---|---|---|
committer | Marko Kreen | 2011-12-22 09:16:04 +0000 |
commit | 865c520e2a86f9e9dafbdc759feffefcf0889f07 (patch) | |
tree | 63f3e489d7bf03dea8d48686ce6b012a4c0626fb | |
parent | c461f063a1b4e8755b1e47fb26737c3042dba1de (diff) |
make_pgarray(): convert python list to postgres array
-rw-r--r-- | python/skytools/__init__.py | 1 | ||||
-rw-r--r-- | python/skytools/quoting.py | 40 |
2 files changed, 41 insertions, 0 deletions
diff --git a/python/skytools/__init__.py b/python/skytools/__init__.py index c424051d..b816cd76 100644 --- a/python/skytools/__init__.py +++ b/python/skytools/__init__.py @@ -53,6 +53,7 @@ _symbols = { 'db_urlencode': 'skytools.quoting:db_urlencode', 'json_decode': 'skytools.quoting:json_decode', 'json_encode': 'skytools.quoting:json_encode', + 'make_pgarray': 'skytools.quoting:make_pgarray', 'quote_bytea_copy': 'skytools.quoting:quote_bytea_copy', 'quote_bytea_literal': 'skytools.quoting:quote_bytea_literal', 'quote_bytea_raw': 'skytools.quoting:quote_bytea_raw', diff --git a/python/skytools/quoting.py b/python/skytools/quoting.py index f4dba12c..bb1263a6 100644 --- a/python/skytools/quoting.py +++ b/python/skytools/quoting.py @@ -14,6 +14,7 @@ __all__ = [ "quote_ident", "quote_fqident", "quote_json", "unescape_copy", "unquote_ident", "unquote_fqident", "json_encode", "json_decode", + "make_pgarray", ] try: @@ -192,6 +193,45 @@ def json_decode(s): """ return json.loads(s) +# +# Create Postgres array +# + +# any chars not in "good" set? main bad ones: [ ,{}\"] +_pgarray_bad_rx = r"[^0-9a-z_.%&=()<>*/+-]" +_pgarray_bad_rc = None + +def _quote_pgarray_elem(s): + if s is None: + return 'NULL' + s = str(s) + if _pgarray_bad_rc.search(s): + s = s.replace('\\', '\\\\') + return '"' + s.replace('"', r'\"') + '"' + elif not s: + return '""' + return s + +def make_pgarray(lst): + r"""Formats Python list as Postgres array. + Reverse of parse_pgarray(). + + >>> make_pgarray([]) + '{}' + >>> make_pgarray(['foo_3',1,'',None]) + '{foo_3,1,"",NULL}' + >>> make_pgarray([None,',','\\',"'",'"',"{","}",'_']) + '{NULL,",","\\\\","\'","\\"","{","}",_}' + """ + + global _pgarray_bad_rc + if _pgarray_bad_rc is None: + _pgarray_bad_rc = re.compile(_pgarray_bad_rx) + + items = [_quote_pgarray_elem(v) for v in lst] + return '{' + ','.join(items) + '}' + + if __name__ == '__main__': import doctest doctest.testmod() |