My favorites | Sign in
Project Home Downloads Wiki Issues Source
Checkout   Browse   Changes    
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# Rename bulkloader progress/result db and its corresponding internal keying.
import sqlite3
from sys import stderr
from pdb import runcall

SIGNATURE_TABLE_NAME = None
def get_signature_table_name():
global SIGNATURE_TABLE_NAME
try: from google.appengine.tools.bulkloader import SIGNATURE_TABLE_NAME
except ImportError:
SIGNATURE_TABLE_NAME = 'bulkloader_database_signature'

return SIGNATURE_TABLE_NAME

def parse_signature(sigstring):
data = {}
for line in sigstring.split('\n'):
line = line.strip()
colon = line.find(':')
if colon >= 0:
name = line[:colon].strip()
value = line[colon+1:].strip()
if name:
data[str(name)] = str(value)

return data

def read_signature(conn):
u = conn.cursor()
u.execute('select value from %s limit 1' % get_signature_table_name())

return u.fetchone()[0]

def change_signature(conn, signature):
old_sig = read_signature(conn)
conn.execute('delete from %s where value = ?' % get_signature_table_name(),
(old_sig,))

conn.execute('insert into %s (value) values (?)' % get_signature_table_name(),
(signature,))

conn.commit()

def load_signature(conn):
sigstring = read_signature(conn)
if sigstring:
return parse_signature(sigstring)

from google.appengine.tools.bulkloader import _MakeSignature

# How does result_db_line acquire 'result_db: ' value if download is rendered as False?!?
## def _MakeSignature(app_id=None,
## url=None,
## kind=None,
## db_filename=None,
## perform_map=None,
## download=None,
## has_header=None,
## result_db_filename=None,
## dump=None,
## restore=None):
## """Returns a string that identifies the important options for the database."""
## if download:
## result_db_line = 'result_db: %s' % result_db_filename
## else:
## result_db_line = ''
## return u"""
## app_id: %s
## url: %s
## kind: %s
## download: %s
## map: %s
## dump: %s
## restore: %s
## progress_db: %s
## has_header: %s
## %s
## """ % (app_id, url, kind, download, perform_map, dump, restore, db_filename,
## has_header, result_db_line)

def build_signature(sig):
# result_db_line = 'result_db: %s' % sig['result_db_filename']
# result_db_line = sig.get('result_db', '')
result_db_line = ''

sigstring = _MakeSignature(app_id = sig['app_id'],
url = sig['url'],
kind = sig['kind'],
db_filename = sig['progress_db'],
perform_map = sig['map'],
download = sig['download'],
has_header = sig['has_header'],
result_db_filename = result_db_line,
dump = sig['dump'],
restore = sig['restore'])

# XXX HACK XXX
sigstring = sigstring.replace('result_db: ', '')

# !! Actually, the
# XXX Why does error show it in one order and the ResumeError in another?
# bulkloader.py:1656

return sigstring

_sqlite_master_table_name = 'SQLite_Master'
_sqlite_master_table_name = 'sqlite_master'

def detect_db_file_type(conn):
u = conn.cursor()
u.execute('select name from %s' % _sqlite_master_table_name)

for table_name in u.fetchall():
table_name = table_name[0]

if table_name in ('progress', 'result'):
return str(table_name)

def replace_db_name_kind(string, kind = '', db_file_type = ''):
# todo: normpath?
return str(string.replace('$KIND', kind).replace('$DB_FILE_TYPE', db_file_type))

from os import rename as rename_file
from sys import exc_info
from errno import ENOENT, EEXIST
from os.path import dirname
from os import makedirs

def ensureDirectoryExists(path):
try: makedirs(path)
except OSError, e:
if e.args[0] != EEXIST:
(etype, value, tb) = exc_info()
raise etype, value, tb
else:
print 'Created %r' % path

def doRenameFile(old_filename, new_filename):
ensureDirectoryExists(dirname(new_filename))

try: rename_file(old_filename, new_filename)
except OSError, e:
if e.args[0] == ENOENT:
return False

(etype, value, tb) = exc_info()
raise etype, value, tb
else:
print 'Moved %r into %r' % (old_filename, new_filename)

return True

class DbFile:
def __init__(self, filename, conn = None):
self.filename = filename
self.conn = conn

self.open_database()
conn = self.conn

self.db_file_type = detect_db_file_type(conn)
self.signature = load_signature(conn)

def close_database(self):
if self.conn is not None:
self.conn.close()
self.conn = None

def open_database(self):
if self.conn is None:
self.conn = sqlite3.connect(self.filename)

def build_signature(self):
return build_signature(self.signature)

def get_signature_value(self, name):
return str(self.signature.get(name))
def __getitem__(self, name):
return self.get_signature_value(name)

def get_kind(self):
return self['kind']
def get_progress_db(self):
return self['progress_db']

def change_progress_db(self, new_filename, interpolate = False, rename = False):
if interpolate:
new_filename = replace_db_name_kind(new_filename, self.get_kind(),
self.db_file_type)

if new_filename == self.get_progress_db():
return

self.signature['progress_db'] = str(new_filename)
change_signature(self.conn, self.build_signature())

if rename:
self.close_database()
try:
if doRenameFile(self.filename, new_filename):
self.filename = new_filename
finally:
self.open_database()

def inspection(self):
return '\n'.join([self.filename, self.db_file_type, '---',
self.build_signature()])

def get_db_filelist(options, args):
if options.db_file:
yield options.db_file

for dbfile in args:
yield dbfile

def process_db_file(dbfile, options):
db = DbFile(dbfile)

new_db_name = options.new_db_name_template
if new_db_name:
print 'Changing: %r ...' % db.filename
db.change_progress_db(new_db_name, interpolate = True,
rename = options.rename_db_file)

if options.examine:
from my.interactive import examine
examine(db = db, globals = globals())

if options.inspect:
print db.inspection()
if new_db_name:
print 'new-db-name-template: %r' % new_db_name

if options.simple_inspection:
print '%s: %s (%s)' % (db.filename, db.db_file_type, db.get_progress_db())

from traceback import print_exc as full_traceback
from sys import exc_info

def simple_error_display():
(etype, value, tb) = exc_info()
print '%s: %s' % (str(etype), str(value))

def main(argv = None):
from optparse import OptionParser
parser = OptionParser()
parser.add_option('--db-file')
parser.add_option('--new-db-name-template', '--new-db-name')
parser.add_option('-M', '--rename-db-file', action = 'store_true')

parser.add_option('-e', '--examine', action = 'store_true')
parser.add_option('-i', '--inspect', action = 'store_true')

parser.add_option('--simple-inspection', action = 'store_true')
parser.add_option('--full-traceback', action = 'store_true')

(options, args) = parser.parse_args(argv)
nr = 0
for dbfile in get_db_filelist(options, args):
nr += 1

try: process_db_file(dbfile, options)
except:
if options.full_traceback:
full_traceback()
else:
simple_error_display()

if not nr:
parser.print_usage(stderr)

# Determine tables:
#
# CREATE TABLE bulkloader_database_signature (value TEXT not null);
#
# app_id: cbanis
# url: http://localhost:8080/gae/remote_api
# kind: MobileSpecialSetting
# download: False
# map: False
# dump: False
# restore: False
# progress_db: bulkloader-progress-20100628.212108.sql3
# has_header: False
#
# CREATE TABLE progress (id integer primary key autoincrement,
# state integer not null,
# kind text not null,
# key_start INTEGER,
# key_end INTEGER);
#
# CREATE TABLE result (id BLOB primary key,
# value BLOB not null,
# sort_key BLOB);

# Generally the filename will describe the table, but in this case,
# use db introspection somehow to check for progress or result tables.

# Parse signature data to glean the entity kind name for rebuilding the
# workfile in its qualified directory structure.

# options.new_db_name_template

if __name__ == '__main__':
main()

Change log

r29 by cbanis on Jul 12, 2010   Diff
Added dev_appserver debug patch
Go to: 
Project members, sign in to write a code review

Older revisions

r21 by cbanis on Jun 29, 2010   Diff
Made renaming (most) entirely
reliable, ensuring directory
creation... ignoring/reraising errors
properly.
r20 by cbanis on Jun 29, 2010   Diff
Added simpler inspection.  Stacking of
dbfile options, and safe error
reporting.  Added
examine_devappserver_datastore.py
r19 by cbanis on Jun 29, 2010   Diff
Added rename_bulkload_workfiles tool
All revisions of this file

File info

Size: 9723 bytes, 305 lines

File properties

svn:executable
*
Powered by Google Project Hosting