Project

General

Profile

1 13 aaronmk
# XML-database conversion
2
3 2418 aaronmk
import copy
4 16 aaronmk
import re
5 13 aaronmk
from xml.dom import Node
6
7 446 aaronmk
import exc
8 2436 aaronmk
import Parser
9 46 aaronmk
import sql
10 3077 aaronmk
import sql_io
11 2268 aaronmk
import sql_gen
12 84 aaronmk
import strings
13 133 aaronmk
import util
14 46 aaronmk
import xml_dom
15 2113 aaronmk
import xml_func
16 2436 aaronmk
import xpath
17 13 aaronmk
18 139 aaronmk
def name_of(node): return re.sub(r'^.*\.', r'', node.tagName)
19 16 aaronmk
20 13 aaronmk
ptr_suffix = '_id'
21
22 138 aaronmk
def is_ptr(node_name): return node_name.lower().endswith(ptr_suffix)
23 13 aaronmk
24 172 aaronmk
def ptr_type_guess(node_name):
25 13 aaronmk
    assert is_ptr(node_name)
26
    return node_name[:-len(ptr_suffix)]
27
28
def ptr_target(node):
29
    assert is_ptr(name_of(node))
30 2113 aaronmk
    return xml_dom.value_node(node)
31 13 aaronmk
32
def find_by_name(node, name):
33 46 aaronmk
    for parent in xml_dom.NodeParentIter(node):
34 13 aaronmk
        if name_of(parent) == name: return parent
35
        else:
36 46 aaronmk
            for child in xml_dom.NodeElemIter(parent):
37 16 aaronmk
                child_name = name_of(child)
38 13 aaronmk
                if is_ptr(child_name):
39 172 aaronmk
                    target = ptr_target(child)
40
                    if target.tagName == name: return target
41 13 aaronmk
                elif child_name == name: return child
42
    return None
43
44 1850 aaronmk
def get(db, node, limit=None, start=None):
45
    def pkey(table): return sql.pkey(db, table)
46 126 aaronmk
47 141 aaronmk
    node = node.firstChild
48 135 aaronmk
    table = name_of(node)
49
    pkey_ = pkey(table)
50
51
    fields = []
52
    conds = {}
53 133 aaronmk
    for child in xml_dom.NodeElemIter(node):
54 135 aaronmk
        child_name = name_of(child)
55
        if xml_dom.is_empty(child): fields.append(child_name)
56
        elif xml_dom.is_text(child): conds[child_name] = xml_dom.value(child)
57
        else: raise Exception('Joins not supported yet')
58
    id_ = xml_dom.get_id(node)
59 1836 aaronmk
    if id_ != None: conds[pkey(table)] = id_ # replace any existing pkey value
60 135 aaronmk
    if fields == []: fields.append(pkey_)
61 133 aaronmk
62 864 aaronmk
    return sql.select(db, table, fields, conds, limit, start)
63 126 aaronmk
64 2039 aaronmk
class ColRef:
65
    '''A reference to a table column'''
66
    def __init__(self, name, idx):
67
        self.name = name
68
        self.idx = idx
69
70
    def __str__(self): return self.name
71
72 3114 aaronmk
# Controls when and how put_table() will partition the input table
73 3145 aaronmk
partition_size = 500000 # rows
74 3114 aaronmk
75 2177 aaronmk
input_col_prefix = '$'
76
77 2549 aaronmk
put_table_special_funcs = set(['_simplifyPath'])
78
79 3622 aaronmk
def put_table(db, node, in_table, in_row_ct_ref=None, row_ins_ct_ref=None,
80
    limit=None, start=0, on_error=exc.raise_, col_defaults={}):
81 1996 aaronmk
    '''
82 1998 aaronmk
    @param node The XML tree that transforms the input to the output. Similar to
83 2177 aaronmk
        put()'s node param, but with the input column name prefixed by
84
        input_col_prefix in place of the column value.
85 3194 aaronmk
    @return sql_gen.Col Where the pkeys (from INSERT RETURNING) are made
86 2067 aaronmk
        available
87 1998 aaronmk
    '''
88 2418 aaronmk
    in_table = sql_gen.as_Table(in_table)
89 3113 aaronmk
    in_table.set_srcs([in_table], overwrite=False)
90 3184 aaronmk
    db.src = str(in_table)
91 2418 aaronmk
92 3621 aaronmk
    db.autoanalyze = True # but don't do this in row-based import
93
    db.autoexplain = True # but don't do this in row-based import
94 3107 aaronmk
95 3625 aaronmk
    # Import col_defaults
96
    for col, node_ in col_defaults.items():
97 3650 aaronmk
        col_defaults[col] = put(db, node_, row_ins_ct_ref, on_error)
98 3621 aaronmk
99 3620 aaronmk
    # Subset and partition in_table
100
    # OK to do even if table already the right size because it takes <1 sec.
101 3625 aaronmk
    full_in_table = in_table
102 3621 aaronmk
    total = 0
103
    while limit == None or total < limit:
104
        # Adjust partition size if last partition
105
        this_limit = partition_size
106
        if limit != None: this_limit = min(this_limit, limit - total)
107 3268 aaronmk
108 3621 aaronmk
        # Row # is interally 0-based, but 1-based to the user
109
        db.log_debug('********** Partition: rows '+str(start+1)+'-'
110
            +str(start+this_limit)+' **********', level=1.2)
111 3122 aaronmk
112 3621 aaronmk
        # Subset in_table
113
        in_table = copy.copy(full_in_table) # don't modify input!
114
        in_table.name = str(in_table) # prepend schema
115
        cur = sql.run_query_into(db, sql.mk_select(db, full_in_table,
116
            limit=this_limit, start=start), into=in_table, add_pkey_=True)
117
            # full_in_table will be shadowed (hidden) by created temp table
118 3121 aaronmk
119 3621 aaronmk
        this_ct = cur.rowcount
120
        total += this_ct
121
        start += this_ct # advance start to fetch next set
122
        if this_ct == 0: break # in_table size is multiple of partition_size
123
124
        # Recurse
125 3650 aaronmk
        pkeys_loc = put(db, node, row_ins_ct_ref, on_error,
126 3649 aaronmk
            col_defaults, in_table)
127 3621 aaronmk
        if in_row_ct_ref != None: in_row_ct_ref[0] += this_ct
128
129
        sql.empty_temp(db, in_table)
130
131
        if this_ct < partition_size: break # partial partition = last
132
133
        # Work around PostgreSQL's temp table disk space leak
134
        db.reconnect()
135 3114 aaronmk
136 3621 aaronmk
    return pkeys_loc
137
138 3650 aaronmk
def put(db, node, row_ins_ct_ref=None, on_error=exc.raise_,
139 3649 aaronmk
    col_defaults={}, in_table=None, parent_ids_loc=None, next=None):
140 3650 aaronmk
    def put_(node, in_row_ct_ref=None):
141
        return put(db, node, row_ins_ct_ref, on_error, col_defaults,
142 3649 aaronmk
            in_table, parent_ids_loc, next)
143 3621 aaronmk
144 3646 aaronmk
    def on_error_(e):
145
        exc.add_msg(e, 'node:\n'+str(node))
146
        on_error(e)
147
148 2551 aaronmk
    is_func = xml_func.is_func(node)
149 2005 aaronmk
    out_table = name_of(node)
150 2432 aaronmk
151
    # Divide children into fields and children with fkeys to parent
152 2005 aaronmk
    row = {}
153
    children = []
154
    for child in xml_dom.NodeElemIter(node):
155
        child_name = name_of(child)
156
        if xml_dom.is_empty(child): row[child_name] = None
157
        elif xml_dom.is_text(child):
158
            row[child_name] = strings.to_unicode(xml_dom.value(child))
159 2113 aaronmk
        else:
160
            child_value = xml_dom.value_node(child)
161 2434 aaronmk
            if is_func or is_ptr(child_name) or xml_func.is_func(child_value):
162 2432 aaronmk
                row[child_name] = child_value
163 2113 aaronmk
            else: children.append(child)
164 2434 aaronmk
165
    # Special handling for structural XML functions
166
    if out_table == '_simplifyPath':
167 2436 aaronmk
        # Parse args
168
        def wrap_e(e): raise xml_func.SyntaxError(e)
169 2434 aaronmk
        try:
170 3650 aaronmk
            next = row['next'] # modifies outer next var used by put_()
171 2434 aaronmk
            require = row['require']
172
            path = row['path']
173 2436 aaronmk
        except KeyError, e: wrap_e(e)
174
        try: next = xpath.parse(next)
175
        except Parser.SyntaxError, e: wrap_e(e)
176
        try: next = next[0].name
177
        except IndexError, e: wrap_e(e)
178 2434 aaronmk
179 3650 aaronmk
        return put_(path)
180 2434 aaronmk
181 3624 aaronmk
    in_tables = []
182
    no_empty = set()
183
    if in_table != None:
184
        in_tables.append(in_table)
185
        no_empty.add(in_table)
186 2966 aaronmk
187 3107 aaronmk
    def pkey(table): return sql.pkey(db, table, True)
188
189 2177 aaronmk
    # Add fkey to parent
190
    if parent_ids_loc != None:
191 3601 aaronmk
        if sql_gen.is_table_col(parent_ids_loc):
192
            no_empty.add(parent_ids_loc.table)
193 2177 aaronmk
        parent_ptr = node.getAttribute('fkey')
194
        if parent_ptr == '': parent_ptr = pkey(name_of(node.parentNode))
195
        row[parent_ptr] = parent_ids_loc
196
197 2060 aaronmk
    # Divide fields into input columns and literal values
198 2506 aaronmk
    parent_ids_loc = None # applies to this section
199 2060 aaronmk
    for out_col, value in row.iteritems():
200 2432 aaronmk
        # Handle forward pointers
201 3650 aaronmk
        if xml_dom.is_node(value): row[out_col] = value = put_(value)
202 2432 aaronmk
203
        # Translate values
204 2268 aaronmk
        if isinstance(value, sql_gen.Col): # value is temp table column
205
            in_tables.append(value.table)
206 2177 aaronmk
        elif util.is_str(value) and value.startswith(input_col_prefix):
207
            # value is input column
208 2272 aaronmk
            row[out_col] = sql_gen.Col(strings.remove_prefix(input_col_prefix,
209 2313 aaronmk
                value), in_table)
210 3428 aaronmk
        else: # value is literal value
211 2323 aaronmk
            row[out_col] = sql_gen.NamedCol(out_col, value)
212 2060 aaronmk
213
    # Insert node
214 3077 aaronmk
    pkeys_loc = sql_io.put_table(db, out_table, in_tables, row, row_ins_ct_ref,
215 3646 aaronmk
        next, col_defaults, on_error_)
216 2060 aaronmk
217 2975 aaronmk
    sql.empty_temp(db, set(in_tables) - no_empty)
218 2966 aaronmk
219 2177 aaronmk
    # Insert children with fkeys to parent
220 2506 aaronmk
    parent_ids_loc = pkeys_loc # applies to this section
221 3650 aaronmk
    for child in children: put_(child)
222 2177 aaronmk
223 2133 aaronmk
    return pkeys_loc