1
from __future__ import absolute_import, division
6
from . import LockBase, NotLocked, NotMyLock, LockTimeout, AlreadyLocked
8
class SQLiteLockFile(LockBase):
9
"Demonstrate SQL-based locking."
12
_fd, testdb = tempfile.mkstemp()
17
def __init__(self, path, threaded=True):
19
>>> lock = SQLiteLockFile('somefile')
20
>>> lock = SQLiteLockFile('somefile', threaded=False)
22
LockBase.__init__(self, path, threaded)
23
self.lock_file = unicode(self.lock_file)
24
self.unique_name = unicode(self.unique_name)
27
self.connection = sqlite3.connect(SQLiteLockFile.testdb)
29
c = self.connection.cursor()
31
c.execute("create table locks"
33
" lock_file varchar(32),"
34
" unique_name varchar(32)"
36
except sqlite3.OperationalError:
39
self.connection.commit()
41
atexit.register(os.unlink, SQLiteLockFile.testdb)
43
def acquire(self, timeout=None):
44
end_time = time.time()
45
if timeout is not None and timeout > 0:
55
cursor = self.connection.cursor()
58
if not self.is_locked():
59
# Not locked. Try to lock it.
60
cursor.execute("insert into locks"
61
" (lock_file, unique_name)"
64
(self.lock_file, self.unique_name))
65
self.connection.commit()
67
# Check to see if we are the only lock holder.
68
cursor.execute("select * from locks"
69
" where unique_name = ?",
71
rows = cursor.fetchall()
73
# Nope. Someone else got there. Remove our lock.
74
cursor.execute("delete from locks"
75
" where unique_name = ?",
77
self.connection.commit()
79
# Yup. We're done, so go home.
82
# Check to see if we are the only lock holder.
83
cursor.execute("select * from locks"
84
" where unique_name = ?",
86
rows = cursor.fetchall()
88
# We're the locker, so go home.
91
# Maybe we should wait a bit longer.
92
if timeout is not None and time.time() > end_time:
97
# Someone else has the lock and we are impatient..
100
# Well, okay. We'll give it a bit longer.
104
if not self.is_locked():
106
if not self.i_am_locking():
107
raise NotMyLock((self._who_is_locking(), self.unique_name))
108
cursor = self.connection.cursor()
109
cursor.execute("delete from locks"
110
" where unique_name = ?",
112
self.connection.commit()
114
def _who_is_locking(self):
115
cursor = self.connection.cursor()
116
cursor.execute("select unique_name from locks"
117
" where lock_file = ?",
119
return cursor.fetchone()[0]
122
cursor = self.connection.cursor()
123
cursor.execute("select * from locks"
124
" where lock_file = ?",
126
rows = cursor.fetchall()
129
def i_am_locking(self):
130
cursor = self.connection.cursor()
131
cursor.execute("select * from locks"
132
" where lock_file = ?"
133
" and unique_name = ?",
134
(self.lock_file, self.unique_name))
135
return not not cursor.fetchall()
137
def break_lock(self):
138
cursor = self.connection.cursor()
139
cursor.execute("delete from locks"
140
" where lock_file = ?",
142
self.connection.commit()