diff lemuriformes/url2sql.py @ 17:4793f99b73e0

[lemuriformes] utility functions
author Jeff Hammel <k0scist@gmail.com>
date Sun, 10 Dec 2017 17:42:52 -0800
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/lemuriformes/url2sql.py	Sun Dec 10 17:42:52 2017 -0800
@@ -0,0 +1,40 @@
+"""
+instantiate a SQL interface from a URL
+"""
+
+from urlparse import urlparse
+
+# Local imports of types;  messy, currently
+from .db import MySQLConnection
+from .cli import ConfigurationParser
+from .csv2sqlite import  SQLiteConnection
+
+sql_types = {'mysql': MySQLConnection,
+             'sqlite': SQLiteConnection
+}
+
+ports = {'mysql': 3306,
+}
+
+
+def url2sql(url):
+    """instantiate SQL connection based on URL"""
+
+    # parse URL
+    parsed = urlparse(url)
+
+    if parsed.scheme not in sql_types:
+        raise AssertionError("Unsupported SQL connector type: '{}'".format(parsed.scheme))
+
+    default_port = ports.get(parsed.scheme)
+
+    # instantiate MySQL connection
+    if parsed.scheme == 'mysql':
+        conn_data = dict(host=parsed.hostname,
+                         user=parsed.username,
+                         password=parsed.password,
+                         port=parsed.port or default_port,
+                         db=parsed.path.strip('/'))
+    elif parsed.scheme == 'sqlite':
+        conn_data = dict(db_file=parsed.path)
+    return sql_types[parsed.scheme](**conn_data)