41
60
from pysqlite2 import dbapi2 as sqlite3
42
61
check_pysqlite_version(sqlite3)
44
warning('Needs at least Python2.5 or Python2.4 with the pysqlite2 '
63
trace.warning('Needs at least Python2.5 or Python2.4 with the pysqlite2 '
46
65
raise bzrlib.errors.BzrError("missing sqlite library")
68
_mapdbs = threading.local()
70
"""Get a cache for this thread's db connections."""
73
except AttributeError:
49
78
class GitShaMap(object):
51
def __init__(self, transport):
52
self.transport = transport
53
self.db = sqlite3.connect(
54
os.path.join(self.transport.local_abspath("."), "git.db"))
79
"""Git<->Bzr revision id mapping database."""
81
def add_entry(self, sha, type, type_data):
82
"""Add a new entry to the database.
84
raise NotImplementedError(self.add_entry)
86
def add_entries(self, entries):
87
"""Add multiple new entries to the database.
92
def lookup_tree(self, fileid, revid):
93
"""Lookup the SHA of a git tree."""
94
raise NotImplementedError(self.lookup_tree)
96
def lookup_blob(self, fileid, revid):
97
"""Lookup a blob by the fileid it has in a bzr revision."""
98
raise NotImplementedError(self.lookup_blob)
100
def lookup_git_sha(self, sha):
101
"""Lookup a Git sha in the database.
103
:param sha: Git object sha
104
:return: (type, type_data) with type_data:
105
revision: revid, tree sha
107
raise NotImplementedError(self.lookup_git_sha)
110
"""List the revision ids known."""
111
raise NotImplementedError(self.revids)
114
"""List the SHA1s."""
115
raise NotImplementedError(self.sha1s)
118
"""Commit any pending changes."""
121
class DictGitShaMap(GitShaMap):
126
def add_entry(self, sha, type, type_data):
127
self.dict[sha] = (type, type_data)
129
def lookup_git_sha(self, sha):
130
return self.dict[sha]
132
def lookup_tree(self, fileid, revid):
133
for k, v in self.dict.iteritems():
134
if v == ("tree", (fileid, revid)):
136
raise KeyError((fileid, revid))
138
def lookup_blob(self, fileid, revid):
139
for k, v in self.dict.iteritems():
140
if v == ("blob", (fileid, revid)):
142
raise KeyError((fileid, revid))
145
for key, (type, type_data) in self.dict.iteritems():
150
return self.dict.iterkeys()
153
class SqliteGitShaMap(GitShaMap):
155
def __init__(self, path=None):
158
self.db = sqlite3.connect(":memory:")
160
if not mapdbs().has_key(path):
161
mapdbs()[path] = sqlite3.connect(path)
162
self.db = mapdbs()[path]
55
163
self.db.executescript("""
56
164
create table if not exists commits(sha1 text, revid text, tree_sha text);
57
165
create index if not exists commit_sha1 on commits(sha1);
166
create unique index if not exists commit_revid on commits(revid);
58
167
create table if not exists blobs(sha1 text, fileid text, revid text);
59
168
create index if not exists blobs_sha1 on blobs(sha1);
169
create unique index if not exists blobs_fileid_revid on blobs(fileid, revid);
60
170
create table if not exists trees(sha1 text, fileid text, revid text);
61
171
create index if not exists trees_sha1 on trees(sha1);
172
create unique index if not exists trees_fileid_revid on trees(fileid, revid);
64
def _parent_lookup(self, revid):
65
return self.db.execute("select sha1 from commits where revid = ?", (revid,)).fetchone()[0].encode("utf-8")
176
def from_repository(cls, repository):
178
transport = getattr(repository, "_transport", None)
179
if transport is not None:
180
return cls(os.path.join(transport.local_abspath("."), "git.db"))
181
except bzrlib.errors.NotLocalUrl:
183
return cls(os.path.join(get_cache_dir(), "remote.db"))
185
def lookup_commit(self, revid):
186
row = self.db.execute("select sha1 from commits where revid = ?", (revid,)).fetchone()
188
return row[0].encode("utf-8")
194
def add_entries(self, entries):
197
for sha, type, type_data in entries:
198
assert isinstance(type_data[0], str)
199
assert isinstance(type_data[1], str)
200
entry = (sha.decode("utf-8"), type_data[0].decode("utf-8"),
201
type_data[1].decode("utf-8"))
209
self.db.executemany("replace into trees (sha1, fileid, revid) values (?, ?, ?)", trees)
211
self.db.executemany("replace into blobs (sha1, fileid, revid) values (?, ?, ?)", blobs)
67
214
def add_entry(self, sha, type, type_data):
68
215
"""Add a new entry to the database.
71
218
assert isinstance(sha, str), "type was %r" % sha
72
219
if type == "commit":
73
220
self.db.execute("replace into commits (sha1, revid, tree_sha) values (?, ?, ?)", (sha, type_data[0], type_data[1]))
75
self.db.execute("replace into blobs (sha1, fileid, revid) values (?, ?, ?)", (sha, type_data[0], type_data[1]))
77
self.db.execute("replace into trees (sha1, fileid, revid) values (?, ?, ?)", (sha, type_data[0], type_data[1]))
221
elif type in ("blob", "tree"):
222
self.db.execute("replace into %ss (sha1, fileid, revid) values (?, ?, ?)" % type, (sha, type_data[0], type_data[1]))
79
224
raise AssertionError("Unknown type %s" % type)
226
def lookup_tree(self, fileid, revid):
227
row = self.db.execute("select sha1 from trees where fileid = ? and revid = ?", (fileid,revid)).fetchone()
229
raise KeyError((fileid, revid))
230
return row[0].encode("utf-8")
232
def lookup_blob(self, fileid, revid):
233
row = self.db.execute("select sha1 from blobs where fileid = ? and revid = ?", (fileid, revid)).fetchone()
235
raise KeyError((fileid, revid))
236
return row[0].encode("utf-8")
81
238
def lookup_git_sha(self, sha):
82
239
"""Lookup a Git sha in the database.
85
242
:return: (type, type_data) with type_data:
86
243
revision: revid, tree sha
245
def format(type, row):
246
return (type, (row[0].encode("utf-8"), row[1].encode("utf-8")))
88
247
row = self.db.execute("select revid, tree_sha from commits where sha1 = ?", (sha,)).fetchone()
89
248
if row is not None:
90
return ("commit", row)
249
return format("commit", row)
91
250
row = self.db.execute("select fileid, revid from blobs where sha1 = ?", (sha,)).fetchone()
92
251
if row is not None:
252
return format("blob", row)
94
253
row = self.db.execute("select fileid, revid from trees where sha1 = ?", (sha,)).fetchone()
95
254
if row is not None:
255
return format("tree", row)
97
256
raise KeyError(sha)
259
"""List the revision ids known."""
100
260
for row in self.db.execute("select revid from commits").fetchall():
261
yield row[0].encode("utf-8")
264
"""List the SHA1s."""
265
for table in ("blobs", "commits", "trees"):
266
for row in self.db.execute("select sha1 from %s" % table).fetchall():
267
yield row[0].encode("utf-8")
271
TDB_HASH_SIZE = 50000
274
class TdbGitShaMap(GitShaMap):
275
"""SHA Map that uses a TDB database.
279
"git <sha1>" -> "<type> <type-data1> <type-data2>"
280
"commit revid" -> "<sha1> <tree-id>"
281
"tree fileid revid" -> "<sha1>"
282
"blob fileid revid" -> "<sha1>"
285
def __init__(self, path=None):
291
if not mapdbs().has_key(path):
292
mapdbs()[path] = tdb.Tdb(path, TDB_HASH_SIZE, tdb.DEFAULT,
293
os.O_RDWR|os.O_CREAT)
294
self.db = mapdbs()[path]
295
if not "version" in self.db:
296
self.db["version"] = str(TDB_MAP_VERSION)
298
if int(self.db["version"]) != TDB_MAP_VERSION:
299
trace.warning("SHA Map is incompatible (%s -> %d), rebuilding database.",
300
self.db["version"], TDB_MAP_VERSION)
302
self.db["version"] = str(TDB_MAP_VERSION)
305
def from_repository(cls, repository):
307
transport = getattr(repository, "_transport", None)
308
if transport is not None:
309
return cls(os.path.join(transport.local_abspath("."), "git.tdb"))
310
except bzrlib.errors.NotLocalUrl:
312
return cls(os.path.join(get_cache_dir(), "remote.tdb"))
314
def lookup_commit(self, revid):
315
return sha_to_hex(self.db["commit\0" + revid][:20])
320
def add_entry(self, hexsha, type, type_data):
321
"""Add a new entry to the database.
326
sha = hex_to_sha(hexsha)
327
self.db["git\0" + sha] = "\0".join((type, type_data[0], type_data[1]))
329
self.db["commit\0" + type_data[0]] = "\0".join((sha, type_data[1]))
331
self.db["\0".join((type, type_data[0], type_data[1]))] = sha
333
def lookup_tree(self, fileid, revid):
334
sha = self.db["\0".join(("tree", fileid, revid))]
338
return sha_to_hex(sha)
340
def lookup_blob(self, fileid, revid):
341
return sha_to_hex(self.db["\0".join(("blob", fileid, revid))])
343
def lookup_git_sha(self, sha):
344
"""Lookup a Git sha in the database.
346
:param sha: Git object sha
347
:return: (type, type_data) with type_data:
348
revision: revid, tree sha
351
sha = hex_to_sha(sha)
352
data = self.db["git\0" + sha].split("\0")
353
return (data[0], (data[1], data[2]))
356
"""List the revision ids known."""
357
for key in self.db.iterkeys():
358
if key.startswith("commit\0"):
362
"""List the SHA1s."""
363
for key in self.db.iterkeys():
364
if key.startswith("git\0"):
365
yield sha_to_hex(key[4:])