"""
    MoinMoin - Execute a SQL statement

    Copyright (c) 2003 by Paul Moore <pf_moore@yahoo.co.uk>
    All rights reserved, see COPYING for details.

    [[SQL(select * from emp)]] will display a table of the results of the SQL

    To configure the connection type, use two variables in moin_config.py:

    macro_sql_module = '<name of DB API 2.o compliant module>'
    macro_sql_connect_args = ['args', 'for', 'module', 'connect', 'call']

    For example,

    macro_sql_module = 'cx_Oracle'
    macro_sql_connect_args = ['scott', 'tiger', 'test']
"""

# Imports
from MoinMoin import config, wikiutil
from MoinMoin.util.dataset import TupleDataset, Column
from MoinMoin.widget.browser import DataBrowserWidget

def my_import(name):
    mod = __import__(name)
    components = name.split('.')
    for comp in components[1:]:
        mod = getattr(mod, comp)
    return mod

def execute(macro, args):
    _ = macro.request.getText
    fmt = macro.formatter

    # TEMP: Execute the SQL
    mod = my_import(config.macro_sql_module)
    try:
	cn = mod.connect(*config.macro_sql_connect_args)
	c = cn.cursor()
	c.execute(args)
	desc = c.description
	rows = c.fetchall()
	c.close()
	cn.close()
    except mod.Error, err:
	return "<b>There was an error executing the SQL:<b><br>" + \
	       args + "<br>" + str(err)

    # create data description
    data = TupleDataset()
    data.columns = []
    for col in desc:
        data.columns.append(Column(col[0], label=_(col[0])))

    # iterate over the rowset
    for row in rows:
        data.addRow(tuple(row))

    # display table
    if data:
        browser = DataBrowserWidget(macro.request)
        browser.setData(data)
        return browser.toHTML()

    return ''

