Project

General

Profile

1
# XML-database conversion
2

    
3
import copy
4
import re
5
from xml.dom import Node
6

    
7
import exc
8
import Parser
9
import sql
10
import sql_io
11
import sql_gen
12
import strings
13
import util
14
import xml_dom
15
import xml_func
16
import xpath
17

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

    
20
ptr_suffix = '_id'
21

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

    
24
def ptr_type_guess(node_name):
25
    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
    return xml_dom.value_node(node)
31

    
32
def find_by_name(node, name):
33
    for parent in xml_dom.NodeParentIter(node):
34
        if name_of(parent) == name: return parent
35
        else:
36
            for child in xml_dom.NodeElemIter(parent):
37
                child_name = name_of(child)
38
                if is_ptr(child_name):
39
                    target = ptr_target(child)
40
                    if target.tagName == name: return target
41
                elif child_name == name: return child
42
    return None
43

    
44
def get(db, node, limit=None, start=None):
45
    def pkey(table): return sql.pkey(db, table)
46
    
47
    node = node.firstChild
48
    table = name_of(node)
49
    pkey_ = pkey(table)
50
    
51
    fields = []
52
    conds = {}
53
    for child in xml_dom.NodeElemIter(node):
54
        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
    if id_ != None: conds[pkey(table)] = id_ # replace any existing pkey value
60
    if fields == []: fields.append(pkey_)
61
    
62
    return sql.select(db, table, fields, conds, limit, start)
63

    
64
def put(db, node, row_ct_ref=None, on_error=exc.raise_, pool=None,
65
    store_ids=False, parent_id=None):
66
    return _put_table_part(db, node, None, row_ct_ref, on_error)
67

    
68
class ColRef:
69
    '''A reference to a table column'''
70
    def __init__(self, name, idx):
71
        self.name = name
72
        self.idx = idx
73
    
74
    def __str__(self): return self.name
75

    
76
# Controls when and how put_table() will partition the input table
77
partition_size = 500000 # rows
78

    
79
input_col_prefix = '$'
80

    
81
put_table_special_funcs = set(['_simplifyPath'])
82

    
83
def put_table(db, node, in_table, in_row_ct_ref=None, row_ins_ct_ref=None,
84
    limit=None, start=0, on_error=exc.raise_, col_defaults={}):
85
    '''
86
    @param node The XML tree that transforms the input to the output. Similar to
87
        put()'s node param, but with the input column name prefixed by
88
        input_col_prefix in place of the column value.
89
    @return sql_gen.Col Where the pkeys (from INSERT RETURNING) are made
90
        available
91
    '''
92
    in_table = sql_gen.as_Table(in_table)
93
    in_table.set_srcs([in_table], overwrite=False)
94
    db.src = str(in_table)
95
    
96
    db.autoanalyze = True # but don't do this in row-based import
97
    db.autoexplain = True # but don't do this in row-based import
98
    
99
    # Import col_defaults
100
    for col, node_ in col_defaults.items():
101
        col_defaults[col] = _put_table_part(db, node_, None, row_ins_ct_ref,
102
            on_error)
103
    
104
    # Subset and partition in_table
105
    # OK to do even if table already the right size because it takes <1 sec.
106
    full_in_table = in_table
107
    total = 0
108
    while limit == None or total < limit:
109
        # Adjust partition size if last partition
110
        this_limit = partition_size
111
        if limit != None: this_limit = min(this_limit, limit - total)
112
        
113
        # Row # is interally 0-based, but 1-based to the user
114
        db.log_debug('********** Partition: rows '+str(start+1)+'-'
115
            +str(start+this_limit)+' **********', level=1.2)
116
        
117
        # Subset in_table
118
        in_table = copy.copy(full_in_table) # don't modify input!
119
        in_table.name = str(in_table) # prepend schema
120
        cur = sql.run_query_into(db, sql.mk_select(db, full_in_table,
121
            limit=this_limit, start=start), into=in_table, add_pkey_=True)
122
            # full_in_table will be shadowed (hidden) by created temp table
123
        
124
        this_ct = cur.rowcount
125
        total += this_ct
126
        start += this_ct # advance start to fetch next set
127
        if this_ct == 0: break # in_table size is multiple of partition_size
128
        
129
        # Recurse
130
        pkeys_loc = _put_table_part(db, node, in_table, row_ins_ct_ref,
131
            on_error, col_defaults)
132
        if in_row_ct_ref != None: in_row_ct_ref[0] += this_ct
133
        
134
        sql.empty_temp(db, in_table)
135
        
136
        if this_ct < partition_size: break # partial partition = last
137
        
138
        # Work around PostgreSQL's temp table disk space leak
139
        db.reconnect()
140
    
141
    return pkeys_loc
142

    
143
def _put_table_part(db, node, in_table=None, row_ins_ct_ref=None,
144
    on_error=exc.raise_, col_defaults={}, parent_ids_loc=None, next=None):
145
    '''Helper function for put_table() only; should not be called directly'''
146
    def put_table_(node, in_row_ct_ref=None):
147
        return _put_table_part(db, node, in_table, row_ins_ct_ref, on_error,
148
            col_defaults, parent_ids_loc, next)
149
    
150
    def on_error_(e):
151
        exc.add_msg(e, 'node:\n'+str(node))
152
        on_error(e)
153
    
154
    is_func = xml_func.is_func(node)
155
    out_table = name_of(node)
156
    
157
    # Divide children into fields and children with fkeys to parent
158
    row = {}
159
    children = []
160
    for child in xml_dom.NodeElemIter(node):
161
        child_name = name_of(child)
162
        if xml_dom.is_empty(child): row[child_name] = None
163
        elif xml_dom.is_text(child):
164
            row[child_name] = strings.to_unicode(xml_dom.value(child))
165
        else:
166
            child_value = xml_dom.value_node(child)
167
            if is_func or is_ptr(child_name) or xml_func.is_func(child_value):
168
                row[child_name] = child_value
169
            else: children.append(child)
170
    
171
    # Special handling for structural XML functions
172
    if out_table == '_simplifyPath':
173
        # Parse args
174
        def wrap_e(e): raise xml_func.SyntaxError(e)
175
        try:
176
            next = row['next'] # modifies outer next var used by put_table_()
177
            require = row['require']
178
            path = row['path']
179
        except KeyError, e: wrap_e(e)
180
        try: next = xpath.parse(next)
181
        except Parser.SyntaxError, e: wrap_e(e)
182
        try: next = next[0].name
183
        except IndexError, e: wrap_e(e)
184
        
185
        return put_table_(path)
186
    
187
    in_tables = []
188
    no_empty = set()
189
    if in_table != None:
190
        in_tables.append(in_table)
191
        no_empty.add(in_table)
192
    
193
    def pkey(table): return sql.pkey(db, table, True)
194
    
195
    # Add fkey to parent
196
    if parent_ids_loc != None:
197
        if sql_gen.is_table_col(parent_ids_loc):
198
            no_empty.add(parent_ids_loc.table)
199
        parent_ptr = node.getAttribute('fkey')
200
        if parent_ptr == '': parent_ptr = pkey(name_of(node.parentNode))
201
        row[parent_ptr] = parent_ids_loc
202
    
203
    # Divide fields into input columns and literal values
204
    parent_ids_loc = None # applies to this section
205
    for out_col, value in row.iteritems():
206
        # Handle forward pointers
207
        if xml_dom.is_node(value): row[out_col] = value = put_table_(value)
208
        
209
        # Translate values
210
        if isinstance(value, sql_gen.Col): # value is temp table column
211
            in_tables.append(value.table)
212
        elif util.is_str(value) and value.startswith(input_col_prefix):
213
            # value is input column
214
            row[out_col] = sql_gen.Col(strings.remove_prefix(input_col_prefix,
215
                value), in_table)
216
        else: # value is literal value
217
            row[out_col] = sql_gen.NamedCol(out_col, value)
218
    
219
    # Insert node
220
    pkeys_loc = sql_io.put_table(db, out_table, in_tables, row, row_ins_ct_ref,
221
        next, col_defaults, on_error_)
222
    
223
    sql.empty_temp(db, set(in_tables) - no_empty)
224
    
225
    # Insert children with fkeys to parent
226
    parent_ids_loc = pkeys_loc # applies to this section
227
    for child in children: put_table_(child)
228
    
229
    return pkeys_loc
(9-9/37)