# XML-database conversion

import copy
import re
from xml.dom import Node

import dicts
import exc
import Parser
import sql
import sql_io
import sql_gen
import strings
import util
import xml_dom
import xml_func
import xpath

def name_of(node): return re.sub(r'^.*\.', r'', node.tagName)

ptr_suffix = '_id'

def is_ptr(node_name): return node_name.lower().endswith(ptr_suffix)

def ptr_type_guess(node_name):
    assert is_ptr(node_name)
    return node_name[:-len(ptr_suffix)]

def ptr_target(node):
    assert is_ptr(name_of(node))
    return xml_dom.value_node(node)

def find_by_name(node, name):
    for parent in xml_dom.NodeParentIter(node):
        if name_of(parent) == name: return parent
        else:
            for child in xml_dom.NodeElemIter(parent):
                child_name = name_of(child)
                if is_ptr(child_name):
                    target = ptr_target(child)
                    if target.tagName == name: return target
                elif child_name == name: return child
    return None

class ColRef:
    '''A reference to a table column'''
    def __init__(self, name, idx):
        self.name = name
        self.idx = idx
    
    def __str__(self): return self.name

input_col_prefix = xml_func.var_name_prefix

put_special_funcs = set(['_setDefault', '_simplifyPath'])

no_parent_ids_loc = object() # tells put() there is no parent_ids_loc

def put(db, node, row_ins_ct_ref=None, on_error=exc.reraise, col_defaults=None,
    in_table=None, parent_ids_loc=no_parent_ids_loc, next=None):
    '''
    @param node To use an entire XML document, pass root.firstChild.
    '''
    if node == None: return None # when no rows, root.firstChild == None
    elif xml_dom.is_text_node(node): return xml_dom.value(node)
    
    if col_defaults == None: col_defaults = {}
    
    def put_(node):
        if util.is_str(node): return node
        return put(db, node, row_ins_ct_ref, on_error, col_defaults, in_table,
            parent_ids_loc, next)
    
    def augment_error(e): exc.add_msg(e, 'node:\n'+strings.ustr(node))
    def on_error_(e):
        augment_error(e)
        on_error(e)
    
    def wrap_e(e):
        augment_error(e)
        raise xml_func.SyntaxError(e)
    
    is_func = xml_func.is_func(node)
    out_table = name_of(node)
    
    # Divide children into fields and children with fkeys to parent
    row = dicts.OnceOnlyDict()
    children = []
    try:
        for child in xml_dom.NodeElemIter(node):
            child_name = name_of(child)
            if xml_dom.is_empty(child): row[child_name] = None
            elif xml_dom.is_text(child):
                row[child_name] = strings.to_unicode(xml_dom.value(child))
            else:
                child_value = xml_dom.value_node(child)
                if ((is_func or is_ptr(child_name)
                    or xml_func.is_func(child_value))
                    and not xml_func.is_func(child)):
                    row[child_name] = child_value
                else: children.append(child)
    except dicts.KeyExistsError, e: wrap_e(e)
    
    # Special handling for structural XML functions
    if out_table == '_setDefault':
        # Parse args
        try: path = row.pop('path')
        except KeyError, e: wrap_e(e)
        
        col_defaults = dicts.MergeDict(dicts.WrapDict(put_, row), col_defaults)
        return put_(path)
    elif out_table == '_simplifyPath':
        # Parse args
        try:
            next = row['next'] # modifies outer next var used by put_()
            path = row['path']
        except KeyError, e: wrap_e(e)
        try: next = xpath.parse(next)
        except Parser.SyntaxError, e: wrap_e(e)
        try: next = next[0].name
        except IndexError, e: wrap_e(e)
        
        return put_(path)
    
    is_literals = in_table == None
    in_tables = []
    no_empty = set()
    if not is_literals:
        in_tables.append(in_table)
        no_empty.add(in_table)
    
    def pkey_name(table): return sql.pkey_name(db, table, True)
    
    # Add fkey to parent
    if parent_ids_loc is not no_parent_ids_loc:
        if sql_gen.is_table_col(parent_ids_loc):
            no_empty.add(parent_ids_loc.table)
        parent_ptr = node.getAttribute('fkey')
        if parent_ptr == '': parent_ptr = pkey_name(name_of(node.parentNode))
        row[parent_ptr] = parent_ids_loc
    
    # Parse input columns
    row = row.inner # now allow keys to be overwritten
    for out_col, value in row.iteritems():
        if (not is_literals and util.is_str(value)
            and value.startswith(input_col_prefix)): # value is input column
            row[out_col] = sql_gen.Col(strings.remove_prefix(input_col_prefix,
                value), in_table)
    
    # Optimizations for structural XML functions
    if out_table == '_alt': # return first arg if non-NULL
        args = row.items()
        args.sort()
        out_col, value = min(args) # first arg
        if xml_dom.is_node(value): row[out_col] = value = put_(value)
        if not sql_gen.is_nullable(db, value): return value
    
    # Process values
    parent_ids_loc = no_parent_ids_loc # applies to this section
    for out_col, value in row.iteritems():
        # Handle forward pointers
        if xml_dom.is_node(value): row[out_col] = value = put_(value)
        
        # Translate values
        if isinstance(value, sql_gen.Col): # value is table column
            assert sql_gen.is_table_col(value)
            if value.table is not in_table: in_tables.append(value.table)
        else: # value is literal value
            row[out_col] = sql_gen.NamedCol(out_col, value)
    
    # Insert node
    try: pkeys_loc = sql_io.put_table(db, out_table, in_tables, row,
        row_ins_ct_ref, next, col_defaults, on_error_)
    except Exception, e:
        augment_error(e)
        raise
    if sql_gen.is_table_col(pkeys_loc): no_empty.add(pkeys_loc.table)
    
    sql.empty_temp(db, set(in_tables) - no_empty)
    
    # Insert children with fkeys to parent
    parent_ids_loc = pkeys_loc # applies to this section
    for child in children: put_(child)
    
    return pkeys_loc

def get(db, node, limit=None, start=None):
    def pkey_name(table): return sql.pkey_name(db, table)
    
    node = node.firstChild
    table = name_of(node)
    pkey_ = pkey_name(table)
    
    fields = []
    conds = {}
    for child in xml_dom.NodeElemIter(node):
        child_name = name_of(child)
        if xml_dom.is_empty(child): fields.append(child_name)
        elif xml_dom.is_text(child): conds[child_name] = xml_dom.value(child)
        else: raise Exception('Joins not supported yet')
    id_ = xml_dom.get_id(node)
    if id_ != None: conds[pkey_name(table)] = id_ # replace any existing value
    if fields == []: fields.append(pkey_)
    
    return sql.select(db, table, fields, conds, limit, start)

# Controls when and how put_table() will partition the input table
partition_size = 1000000 # rows; must be >= NCBI.nodes size

def put_table(db, node, in_table, in_row_ct_ref=None, row_ins_ct_ref=None,
    limit=None, start=0, on_error=exc.reraise, col_defaults={},
    partition_size=partition_size):
    '''
    @param node The XML tree that transforms the input to the output. Similar to
        put()'s node param, but with the input column name prefixed by
        input_col_prefix in place of the column value.
    @return sql_gen.Col Where the pkeys (from INSERT RETURNING) are made
        available
    '''
    if in_table == None:
        return put(db, node, row_ins_ct_ref, on_error, col_defaults)
    
    in_table = sql_gen.as_Table(in_table)
    sql_io.mk_errors_table(db, in_table)
    in_table.set_srcs([in_table], overwrite=False)
    db.src = strings.ustr(in_table)
    
    db.autoexplain = True # but don't do this in row-based import
    
    # Subset and partition in_table
    # OK to do even if table already the right size because it takes <1 sec.
    full_in_table = in_table
    pkeys_loc = None # used if loop is never executed
    total = 0
    while limit == None or total < limit:
        # Adjust partition size if last partition
        this_limit = partition_size
        if limit != None: this_limit = min(this_limit, limit - total)
        
        # Row # is interally 0-based, but 1-based to the user
        db.log_debug('********** Partition: rows '+str(start+1)+'-'
            +str(start+this_limit)+' **********', level=1.2)
        
        # Subset in_table
        in_table = sql_gen.Table(strings.ustr(full_in_table),
            srcs=full_in_table.srcs, is_temp=True) # prepend schema to name
        sql.copy_table_struct(db, full_in_table, in_table)
        try: sql.add_row_num(db, in_table, 'row_num')
        except sql.DatabaseErrors: pass # already has pkey
        cur = sql.insert_select(db, in_table, None, sql.mk_select(db,
            full_in_table, limit=this_limit, start=start))
        
        this_ct = cur.rowcount
        total += this_ct
        start += this_ct # advance start to fetch next set
        if this_ct == 0: break # in_table size is multiple of partition_size
        
        # Import data
        pkeys_loc = put(db, node, row_ins_ct_ref, on_error, col_defaults,
            in_table)
        if in_row_ct_ref != None: in_row_ct_ref[0] += this_ct
        
        sql.empty_temp(db, in_table)
        
        if this_ct < partition_size: break # partial partition = last
        
        # Work around PostgreSQL's temp table disk space leak
        db.reconnect()
    
    return pkeys_loc
