view lemuriformes/url2sql.py @ 18:56596902e9ae default tip

add some setup + tests
author Jeff Hammel <k0scist@gmail.com>
date Sun, 10 Dec 2017 17:57:03 -0800
parents 4793f99b73e0
children
line wrap: on
line source

"""
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)