##// END OF EJS Templates
Backport PR #11054: MAINT: Update locate_profile import to avoid warning...
Thomas Kluyver -
Show More
@@ -1,912 +1,912 b''
1 """ History related magics and functionality """
1 """ History related magics and functionality """
2
2
3 # Copyright (c) IPython Development Team.
3 # Copyright (c) IPython Development Team.
4 # Distributed under the terms of the Modified BSD License.
4 # Distributed under the terms of the Modified BSD License.
5
5
6 from __future__ import print_function
6 from __future__ import print_function
7
7
8 import atexit
8 import atexit
9 import datetime
9 import datetime
10 import os
10 import os
11 import re
11 import re
12 try:
12 try:
13 import sqlite3
13 import sqlite3
14 except ImportError:
14 except ImportError:
15 try:
15 try:
16 from pysqlite2 import dbapi2 as sqlite3
16 from pysqlite2 import dbapi2 as sqlite3
17 except ImportError:
17 except ImportError:
18 sqlite3 = None
18 sqlite3 = None
19 import threading
19 import threading
20
20
21 from traitlets.config.configurable import LoggingConfigurable
21 from traitlets.config.configurable import LoggingConfigurable
22 from decorator import decorator
22 from decorator import decorator
23 from IPython.utils.decorators import undoc
23 from IPython.utils.decorators import undoc
24 from IPython.utils.path import locate_profile
24 from IPython.paths import locate_profile
25 from IPython.utils import py3compat
25 from IPython.utils import py3compat
26 from traitlets import (
26 from traitlets import (
27 Any, Bool, Dict, Instance, Integer, List, Unicode, TraitError,
27 Any, Bool, Dict, Instance, Integer, List, Unicode, TraitError,
28 default, observe,
28 default, observe,
29 )
29 )
30 from warnings import warn
30 from warnings import warn
31
31
32 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
33 # Classes and functions
33 # Classes and functions
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35
35
36 @undoc
36 @undoc
37 class DummyDB(object):
37 class DummyDB(object):
38 """Dummy DB that will act as a black hole for history.
38 """Dummy DB that will act as a black hole for history.
39
39
40 Only used in the absence of sqlite"""
40 Only used in the absence of sqlite"""
41 def execute(*args, **kwargs):
41 def execute(*args, **kwargs):
42 return []
42 return []
43
43
44 def commit(self, *args, **kwargs):
44 def commit(self, *args, **kwargs):
45 pass
45 pass
46
46
47 def __enter__(self, *args, **kwargs):
47 def __enter__(self, *args, **kwargs):
48 pass
48 pass
49
49
50 def __exit__(self, *args, **kwargs):
50 def __exit__(self, *args, **kwargs):
51 pass
51 pass
52
52
53
53
54 @decorator
54 @decorator
55 def needs_sqlite(f, self, *a, **kw):
55 def needs_sqlite(f, self, *a, **kw):
56 """Decorator: return an empty list in the absence of sqlite."""
56 """Decorator: return an empty list in the absence of sqlite."""
57 if sqlite3 is None or not self.enabled:
57 if sqlite3 is None or not self.enabled:
58 return []
58 return []
59 else:
59 else:
60 return f(self, *a, **kw)
60 return f(self, *a, **kw)
61
61
62
62
63 if sqlite3 is not None:
63 if sqlite3 is not None:
64 DatabaseError = sqlite3.DatabaseError
64 DatabaseError = sqlite3.DatabaseError
65 OperationalError = sqlite3.OperationalError
65 OperationalError = sqlite3.OperationalError
66 else:
66 else:
67 @undoc
67 @undoc
68 class DatabaseError(Exception):
68 class DatabaseError(Exception):
69 "Dummy exception when sqlite could not be imported. Should never occur."
69 "Dummy exception when sqlite could not be imported. Should never occur."
70
70
71 @undoc
71 @undoc
72 class OperationalError(Exception):
72 class OperationalError(Exception):
73 "Dummy exception when sqlite could not be imported. Should never occur."
73 "Dummy exception when sqlite could not be imported. Should never occur."
74
74
75 # use 16kB as threshold for whether a corrupt history db should be saved
75 # use 16kB as threshold for whether a corrupt history db should be saved
76 # that should be at least 100 entries or so
76 # that should be at least 100 entries or so
77 _SAVE_DB_SIZE = 16384
77 _SAVE_DB_SIZE = 16384
78
78
79 @decorator
79 @decorator
80 def catch_corrupt_db(f, self, *a, **kw):
80 def catch_corrupt_db(f, self, *a, **kw):
81 """A decorator which wraps HistoryAccessor method calls to catch errors from
81 """A decorator which wraps HistoryAccessor method calls to catch errors from
82 a corrupt SQLite database, move the old database out of the way, and create
82 a corrupt SQLite database, move the old database out of the way, and create
83 a new one.
83 a new one.
84
84
85 We avoid clobbering larger databases because this may be triggered due to filesystem issues,
85 We avoid clobbering larger databases because this may be triggered due to filesystem issues,
86 not just a corrupt file.
86 not just a corrupt file.
87 """
87 """
88 try:
88 try:
89 return f(self, *a, **kw)
89 return f(self, *a, **kw)
90 except (DatabaseError, OperationalError) as e:
90 except (DatabaseError, OperationalError) as e:
91 self._corrupt_db_counter += 1
91 self._corrupt_db_counter += 1
92 self.log.error("Failed to open SQLite history %s (%s).", self.hist_file, e)
92 self.log.error("Failed to open SQLite history %s (%s).", self.hist_file, e)
93 if self.hist_file != ':memory:':
93 if self.hist_file != ':memory:':
94 if self._corrupt_db_counter > self._corrupt_db_limit:
94 if self._corrupt_db_counter > self._corrupt_db_limit:
95 self.hist_file = ':memory:'
95 self.hist_file = ':memory:'
96 self.log.error("Failed to load history too many times, history will not be saved.")
96 self.log.error("Failed to load history too many times, history will not be saved.")
97 elif os.path.isfile(self.hist_file):
97 elif os.path.isfile(self.hist_file):
98 # move the file out of the way
98 # move the file out of the way
99 base, ext = os.path.splitext(self.hist_file)
99 base, ext = os.path.splitext(self.hist_file)
100 size = os.stat(self.hist_file).st_size
100 size = os.stat(self.hist_file).st_size
101 if size >= _SAVE_DB_SIZE:
101 if size >= _SAVE_DB_SIZE:
102 # if there's significant content, avoid clobbering
102 # if there's significant content, avoid clobbering
103 now = datetime.datetime.now().isoformat().replace(':', '.')
103 now = datetime.datetime.now().isoformat().replace(':', '.')
104 newpath = base + '-corrupt-' + now + ext
104 newpath = base + '-corrupt-' + now + ext
105 # don't clobber previous corrupt backups
105 # don't clobber previous corrupt backups
106 for i in range(100):
106 for i in range(100):
107 if not os.path.isfile(newpath):
107 if not os.path.isfile(newpath):
108 break
108 break
109 else:
109 else:
110 newpath = base + '-corrupt-' + now + (u'-%i' % i) + ext
110 newpath = base + '-corrupt-' + now + (u'-%i' % i) + ext
111 else:
111 else:
112 # not much content, possibly empty; don't worry about clobbering
112 # not much content, possibly empty; don't worry about clobbering
113 # maybe we should just delete it?
113 # maybe we should just delete it?
114 newpath = base + '-corrupt' + ext
114 newpath = base + '-corrupt' + ext
115 os.rename(self.hist_file, newpath)
115 os.rename(self.hist_file, newpath)
116 self.log.error("History file was moved to %s and a new file created.", newpath)
116 self.log.error("History file was moved to %s and a new file created.", newpath)
117 self.init_db()
117 self.init_db()
118 return []
118 return []
119 else:
119 else:
120 # Failed with :memory:, something serious is wrong
120 # Failed with :memory:, something serious is wrong
121 raise
121 raise
122
122
123 class HistoryAccessorBase(LoggingConfigurable):
123 class HistoryAccessorBase(LoggingConfigurable):
124 """An abstract class for History Accessors """
124 """An abstract class for History Accessors """
125
125
126 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
126 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
127 raise NotImplementedError
127 raise NotImplementedError
128
128
129 def search(self, pattern="*", raw=True, search_raw=True,
129 def search(self, pattern="*", raw=True, search_raw=True,
130 output=False, n=None, unique=False):
130 output=False, n=None, unique=False):
131 raise NotImplementedError
131 raise NotImplementedError
132
132
133 def get_range(self, session, start=1, stop=None, raw=True,output=False):
133 def get_range(self, session, start=1, stop=None, raw=True,output=False):
134 raise NotImplementedError
134 raise NotImplementedError
135
135
136 def get_range_by_str(self, rangestr, raw=True, output=False):
136 def get_range_by_str(self, rangestr, raw=True, output=False):
137 raise NotImplementedError
137 raise NotImplementedError
138
138
139
139
140 class HistoryAccessor(HistoryAccessorBase):
140 class HistoryAccessor(HistoryAccessorBase):
141 """Access the history database without adding to it.
141 """Access the history database without adding to it.
142
142
143 This is intended for use by standalone history tools. IPython shells use
143 This is intended for use by standalone history tools. IPython shells use
144 HistoryManager, below, which is a subclass of this."""
144 HistoryManager, below, which is a subclass of this."""
145
145
146 # counter for init_db retries, so we don't keep trying over and over
146 # counter for init_db retries, so we don't keep trying over and over
147 _corrupt_db_counter = 0
147 _corrupt_db_counter = 0
148 # after two failures, fallback on :memory:
148 # after two failures, fallback on :memory:
149 _corrupt_db_limit = 2
149 _corrupt_db_limit = 2
150
150
151 # String holding the path to the history file
151 # String holding the path to the history file
152 hist_file = Unicode(
152 hist_file = Unicode(
153 help="""Path to file to use for SQLite history database.
153 help="""Path to file to use for SQLite history database.
154
154
155 By default, IPython will put the history database in the IPython
155 By default, IPython will put the history database in the IPython
156 profile directory. If you would rather share one history among
156 profile directory. If you would rather share one history among
157 profiles, you can set this value in each, so that they are consistent.
157 profiles, you can set this value in each, so that they are consistent.
158
158
159 Due to an issue with fcntl, SQLite is known to misbehave on some NFS
159 Due to an issue with fcntl, SQLite is known to misbehave on some NFS
160 mounts. If you see IPython hanging, try setting this to something on a
160 mounts. If you see IPython hanging, try setting this to something on a
161 local disk, e.g::
161 local disk, e.g::
162
162
163 ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite
163 ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite
164
164
165 you can also use the specific value `:memory:` (including the colon
165 you can also use the specific value `:memory:` (including the colon
166 at both end but not the back ticks), to avoid creating an history file.
166 at both end but not the back ticks), to avoid creating an history file.
167
167
168 """).tag(config=True)
168 """).tag(config=True)
169
169
170 enabled = Bool(True,
170 enabled = Bool(True,
171 help="""enable the SQLite history
171 help="""enable the SQLite history
172
172
173 set enabled=False to disable the SQLite history,
173 set enabled=False to disable the SQLite history,
174 in which case there will be no stored history, no SQLite connection,
174 in which case there will be no stored history, no SQLite connection,
175 and no background saving thread. This may be necessary in some
175 and no background saving thread. This may be necessary in some
176 threaded environments where IPython is embedded.
176 threaded environments where IPython is embedded.
177 """
177 """
178 ).tag(config=True)
178 ).tag(config=True)
179
179
180 connection_options = Dict(
180 connection_options = Dict(
181 help="""Options for configuring the SQLite connection
181 help="""Options for configuring the SQLite connection
182
182
183 These options are passed as keyword args to sqlite3.connect
183 These options are passed as keyword args to sqlite3.connect
184 when establishing database conenctions.
184 when establishing database conenctions.
185 """
185 """
186 ).tag(config=True)
186 ).tag(config=True)
187
187
188 # The SQLite database
188 # The SQLite database
189 db = Any()
189 db = Any()
190 @observe('db')
190 @observe('db')
191 def _db_changed(self, change):
191 def _db_changed(self, change):
192 """validate the db, since it can be an Instance of two different types"""
192 """validate the db, since it can be an Instance of two different types"""
193 new = change['new']
193 new = change['new']
194 connection_types = (DummyDB,)
194 connection_types = (DummyDB,)
195 if sqlite3 is not None:
195 if sqlite3 is not None:
196 connection_types = (DummyDB, sqlite3.Connection)
196 connection_types = (DummyDB, sqlite3.Connection)
197 if not isinstance(new, connection_types):
197 if not isinstance(new, connection_types):
198 msg = "%s.db must be sqlite3 Connection or DummyDB, not %r" % \
198 msg = "%s.db must be sqlite3 Connection or DummyDB, not %r" % \
199 (self.__class__.__name__, new)
199 (self.__class__.__name__, new)
200 raise TraitError(msg)
200 raise TraitError(msg)
201
201
202 def __init__(self, profile='default', hist_file=u'', **traits):
202 def __init__(self, profile='default', hist_file=u'', **traits):
203 """Create a new history accessor.
203 """Create a new history accessor.
204
204
205 Parameters
205 Parameters
206 ----------
206 ----------
207 profile : str
207 profile : str
208 The name of the profile from which to open history.
208 The name of the profile from which to open history.
209 hist_file : str
209 hist_file : str
210 Path to an SQLite history database stored by IPython. If specified,
210 Path to an SQLite history database stored by IPython. If specified,
211 hist_file overrides profile.
211 hist_file overrides profile.
212 config : :class:`~traitlets.config.loader.Config`
212 config : :class:`~traitlets.config.loader.Config`
213 Config object. hist_file can also be set through this.
213 Config object. hist_file can also be set through this.
214 """
214 """
215 # We need a pointer back to the shell for various tasks.
215 # We need a pointer back to the shell for various tasks.
216 super(HistoryAccessor, self).__init__(**traits)
216 super(HistoryAccessor, self).__init__(**traits)
217 # defer setting hist_file from kwarg until after init,
217 # defer setting hist_file from kwarg until after init,
218 # otherwise the default kwarg value would clobber any value
218 # otherwise the default kwarg value would clobber any value
219 # set by config
219 # set by config
220 if hist_file:
220 if hist_file:
221 self.hist_file = hist_file
221 self.hist_file = hist_file
222
222
223 if self.hist_file == u'':
223 if self.hist_file == u'':
224 # No one has set the hist_file, yet.
224 # No one has set the hist_file, yet.
225 self.hist_file = self._get_hist_file_name(profile)
225 self.hist_file = self._get_hist_file_name(profile)
226
226
227 if sqlite3 is None and self.enabled:
227 if sqlite3 is None and self.enabled:
228 warn("IPython History requires SQLite, your history will not be saved")
228 warn("IPython History requires SQLite, your history will not be saved")
229 self.enabled = False
229 self.enabled = False
230
230
231 self.init_db()
231 self.init_db()
232
232
233 def _get_hist_file_name(self, profile='default'):
233 def _get_hist_file_name(self, profile='default'):
234 """Find the history file for the given profile name.
234 """Find the history file for the given profile name.
235
235
236 This is overridden by the HistoryManager subclass, to use the shell's
236 This is overridden by the HistoryManager subclass, to use the shell's
237 active profile.
237 active profile.
238
238
239 Parameters
239 Parameters
240 ----------
240 ----------
241 profile : str
241 profile : str
242 The name of a profile which has a history file.
242 The name of a profile which has a history file.
243 """
243 """
244 return os.path.join(locate_profile(profile), 'history.sqlite')
244 return os.path.join(locate_profile(profile), 'history.sqlite')
245
245
246 @catch_corrupt_db
246 @catch_corrupt_db
247 def init_db(self):
247 def init_db(self):
248 """Connect to the database, and create tables if necessary."""
248 """Connect to the database, and create tables if necessary."""
249 if not self.enabled:
249 if not self.enabled:
250 self.db = DummyDB()
250 self.db = DummyDB()
251 return
251 return
252
252
253 # use detect_types so that timestamps return datetime objects
253 # use detect_types so that timestamps return datetime objects
254 kwargs = dict(detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
254 kwargs = dict(detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
255 kwargs.update(self.connection_options)
255 kwargs.update(self.connection_options)
256 self.db = sqlite3.connect(self.hist_file, **kwargs)
256 self.db = sqlite3.connect(self.hist_file, **kwargs)
257 self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
257 self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
258 primary key autoincrement, start timestamp,
258 primary key autoincrement, start timestamp,
259 end timestamp, num_cmds integer, remark text)""")
259 end timestamp, num_cmds integer, remark text)""")
260 self.db.execute("""CREATE TABLE IF NOT EXISTS history
260 self.db.execute("""CREATE TABLE IF NOT EXISTS history
261 (session integer, line integer, source text, source_raw text,
261 (session integer, line integer, source text, source_raw text,
262 PRIMARY KEY (session, line))""")
262 PRIMARY KEY (session, line))""")
263 # Output history is optional, but ensure the table's there so it can be
263 # Output history is optional, but ensure the table's there so it can be
264 # enabled later.
264 # enabled later.
265 self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
265 self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
266 (session integer, line integer, output text,
266 (session integer, line integer, output text,
267 PRIMARY KEY (session, line))""")
267 PRIMARY KEY (session, line))""")
268 self.db.commit()
268 self.db.commit()
269 # success! reset corrupt db count
269 # success! reset corrupt db count
270 self._corrupt_db_counter = 0
270 self._corrupt_db_counter = 0
271
271
272 def writeout_cache(self):
272 def writeout_cache(self):
273 """Overridden by HistoryManager to dump the cache before certain
273 """Overridden by HistoryManager to dump the cache before certain
274 database lookups."""
274 database lookups."""
275 pass
275 pass
276
276
277 ## -------------------------------
277 ## -------------------------------
278 ## Methods for retrieving history:
278 ## Methods for retrieving history:
279 ## -------------------------------
279 ## -------------------------------
280 def _run_sql(self, sql, params, raw=True, output=False):
280 def _run_sql(self, sql, params, raw=True, output=False):
281 """Prepares and runs an SQL query for the history database.
281 """Prepares and runs an SQL query for the history database.
282
282
283 Parameters
283 Parameters
284 ----------
284 ----------
285 sql : str
285 sql : str
286 Any filtering expressions to go after SELECT ... FROM ...
286 Any filtering expressions to go after SELECT ... FROM ...
287 params : tuple
287 params : tuple
288 Parameters passed to the SQL query (to replace "?")
288 Parameters passed to the SQL query (to replace "?")
289 raw, output : bool
289 raw, output : bool
290 See :meth:`get_range`
290 See :meth:`get_range`
291
291
292 Returns
292 Returns
293 -------
293 -------
294 Tuples as :meth:`get_range`
294 Tuples as :meth:`get_range`
295 """
295 """
296 toget = 'source_raw' if raw else 'source'
296 toget = 'source_raw' if raw else 'source'
297 sqlfrom = "history"
297 sqlfrom = "history"
298 if output:
298 if output:
299 sqlfrom = "history LEFT JOIN output_history USING (session, line)"
299 sqlfrom = "history LEFT JOIN output_history USING (session, line)"
300 toget = "history.%s, output_history.output" % toget
300 toget = "history.%s, output_history.output" % toget
301 cur = self.db.execute("SELECT session, line, %s FROM %s " %\
301 cur = self.db.execute("SELECT session, line, %s FROM %s " %\
302 (toget, sqlfrom) + sql, params)
302 (toget, sqlfrom) + sql, params)
303 if output: # Regroup into 3-tuples, and parse JSON
303 if output: # Regroup into 3-tuples, and parse JSON
304 return ((ses, lin, (py3compat.cast_unicode_py2(inp), py3compat.cast_unicode_py2(out)))
304 return ((ses, lin, (py3compat.cast_unicode_py2(inp), py3compat.cast_unicode_py2(out)))
305 for ses, lin, inp, out in cur)
305 for ses, lin, inp, out in cur)
306 return cur
306 return cur
307
307
308 @needs_sqlite
308 @needs_sqlite
309 @catch_corrupt_db
309 @catch_corrupt_db
310 def get_session_info(self, session):
310 def get_session_info(self, session):
311 """Get info about a session.
311 """Get info about a session.
312
312
313 Parameters
313 Parameters
314 ----------
314 ----------
315
315
316 session : int
316 session : int
317 Session number to retrieve.
317 Session number to retrieve.
318
318
319 Returns
319 Returns
320 -------
320 -------
321
321
322 session_id : int
322 session_id : int
323 Session ID number
323 Session ID number
324 start : datetime
324 start : datetime
325 Timestamp for the start of the session.
325 Timestamp for the start of the session.
326 end : datetime
326 end : datetime
327 Timestamp for the end of the session, or None if IPython crashed.
327 Timestamp for the end of the session, or None if IPython crashed.
328 num_cmds : int
328 num_cmds : int
329 Number of commands run, or None if IPython crashed.
329 Number of commands run, or None if IPython crashed.
330 remark : unicode
330 remark : unicode
331 A manually set description.
331 A manually set description.
332 """
332 """
333 query = "SELECT * from sessions where session == ?"
333 query = "SELECT * from sessions where session == ?"
334 return self.db.execute(query, (session,)).fetchone()
334 return self.db.execute(query, (session,)).fetchone()
335
335
336 @catch_corrupt_db
336 @catch_corrupt_db
337 def get_last_session_id(self):
337 def get_last_session_id(self):
338 """Get the last session ID currently in the database.
338 """Get the last session ID currently in the database.
339
339
340 Within IPython, this should be the same as the value stored in
340 Within IPython, this should be the same as the value stored in
341 :attr:`HistoryManager.session_number`.
341 :attr:`HistoryManager.session_number`.
342 """
342 """
343 for record in self.get_tail(n=1, include_latest=True):
343 for record in self.get_tail(n=1, include_latest=True):
344 return record[0]
344 return record[0]
345
345
346 @catch_corrupt_db
346 @catch_corrupt_db
347 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
347 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
348 """Get the last n lines from the history database.
348 """Get the last n lines from the history database.
349
349
350 Parameters
350 Parameters
351 ----------
351 ----------
352 n : int
352 n : int
353 The number of lines to get
353 The number of lines to get
354 raw, output : bool
354 raw, output : bool
355 See :meth:`get_range`
355 See :meth:`get_range`
356 include_latest : bool
356 include_latest : bool
357 If False (default), n+1 lines are fetched, and the latest one
357 If False (default), n+1 lines are fetched, and the latest one
358 is discarded. This is intended to be used where the function
358 is discarded. This is intended to be used where the function
359 is called by a user command, which it should not return.
359 is called by a user command, which it should not return.
360
360
361 Returns
361 Returns
362 -------
362 -------
363 Tuples as :meth:`get_range`
363 Tuples as :meth:`get_range`
364 """
364 """
365 self.writeout_cache()
365 self.writeout_cache()
366 if not include_latest:
366 if not include_latest:
367 n += 1
367 n += 1
368 cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
368 cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
369 (n,), raw=raw, output=output)
369 (n,), raw=raw, output=output)
370 if not include_latest:
370 if not include_latest:
371 return reversed(list(cur)[1:])
371 return reversed(list(cur)[1:])
372 return reversed(list(cur))
372 return reversed(list(cur))
373
373
374 @catch_corrupt_db
374 @catch_corrupt_db
375 def search(self, pattern="*", raw=True, search_raw=True,
375 def search(self, pattern="*", raw=True, search_raw=True,
376 output=False, n=None, unique=False):
376 output=False, n=None, unique=False):
377 """Search the database using unix glob-style matching (wildcards
377 """Search the database using unix glob-style matching (wildcards
378 * and ?).
378 * and ?).
379
379
380 Parameters
380 Parameters
381 ----------
381 ----------
382 pattern : str
382 pattern : str
383 The wildcarded pattern to match when searching
383 The wildcarded pattern to match when searching
384 search_raw : bool
384 search_raw : bool
385 If True, search the raw input, otherwise, the parsed input
385 If True, search the raw input, otherwise, the parsed input
386 raw, output : bool
386 raw, output : bool
387 See :meth:`get_range`
387 See :meth:`get_range`
388 n : None or int
388 n : None or int
389 If an integer is given, it defines the limit of
389 If an integer is given, it defines the limit of
390 returned entries.
390 returned entries.
391 unique : bool
391 unique : bool
392 When it is true, return only unique entries.
392 When it is true, return only unique entries.
393
393
394 Returns
394 Returns
395 -------
395 -------
396 Tuples as :meth:`get_range`
396 Tuples as :meth:`get_range`
397 """
397 """
398 tosearch = "source_raw" if search_raw else "source"
398 tosearch = "source_raw" if search_raw else "source"
399 if output:
399 if output:
400 tosearch = "history." + tosearch
400 tosearch = "history." + tosearch
401 self.writeout_cache()
401 self.writeout_cache()
402 sqlform = "WHERE %s GLOB ?" % tosearch
402 sqlform = "WHERE %s GLOB ?" % tosearch
403 params = (pattern,)
403 params = (pattern,)
404 if unique:
404 if unique:
405 sqlform += ' GROUP BY {0}'.format(tosearch)
405 sqlform += ' GROUP BY {0}'.format(tosearch)
406 if n is not None:
406 if n is not None:
407 sqlform += " ORDER BY session DESC, line DESC LIMIT ?"
407 sqlform += " ORDER BY session DESC, line DESC LIMIT ?"
408 params += (n,)
408 params += (n,)
409 elif unique:
409 elif unique:
410 sqlform += " ORDER BY session, line"
410 sqlform += " ORDER BY session, line"
411 cur = self._run_sql(sqlform, params, raw=raw, output=output)
411 cur = self._run_sql(sqlform, params, raw=raw, output=output)
412 if n is not None:
412 if n is not None:
413 return reversed(list(cur))
413 return reversed(list(cur))
414 return cur
414 return cur
415
415
416 @catch_corrupt_db
416 @catch_corrupt_db
417 def get_range(self, session, start=1, stop=None, raw=True,output=False):
417 def get_range(self, session, start=1, stop=None, raw=True,output=False):
418 """Retrieve input by session.
418 """Retrieve input by session.
419
419
420 Parameters
420 Parameters
421 ----------
421 ----------
422 session : int
422 session : int
423 Session number to retrieve.
423 Session number to retrieve.
424 start : int
424 start : int
425 First line to retrieve.
425 First line to retrieve.
426 stop : int
426 stop : int
427 End of line range (excluded from output itself). If None, retrieve
427 End of line range (excluded from output itself). If None, retrieve
428 to the end of the session.
428 to the end of the session.
429 raw : bool
429 raw : bool
430 If True, return untranslated input
430 If True, return untranslated input
431 output : bool
431 output : bool
432 If True, attempt to include output. This will be 'real' Python
432 If True, attempt to include output. This will be 'real' Python
433 objects for the current session, or text reprs from previous
433 objects for the current session, or text reprs from previous
434 sessions if db_log_output was enabled at the time. Where no output
434 sessions if db_log_output was enabled at the time. Where no output
435 is found, None is used.
435 is found, None is used.
436
436
437 Returns
437 Returns
438 -------
438 -------
439 entries
439 entries
440 An iterator over the desired lines. Each line is a 3-tuple, either
440 An iterator over the desired lines. Each line is a 3-tuple, either
441 (session, line, input) if output is False, or
441 (session, line, input) if output is False, or
442 (session, line, (input, output)) if output is True.
442 (session, line, (input, output)) if output is True.
443 """
443 """
444 if stop:
444 if stop:
445 lineclause = "line >= ? AND line < ?"
445 lineclause = "line >= ? AND line < ?"
446 params = (session, start, stop)
446 params = (session, start, stop)
447 else:
447 else:
448 lineclause = "line>=?"
448 lineclause = "line>=?"
449 params = (session, start)
449 params = (session, start)
450
450
451 return self._run_sql("WHERE session==? AND %s" % lineclause,
451 return self._run_sql("WHERE session==? AND %s" % lineclause,
452 params, raw=raw, output=output)
452 params, raw=raw, output=output)
453
453
454 def get_range_by_str(self, rangestr, raw=True, output=False):
454 def get_range_by_str(self, rangestr, raw=True, output=False):
455 """Get lines of history from a string of ranges, as used by magic
455 """Get lines of history from a string of ranges, as used by magic
456 commands %hist, %save, %macro, etc.
456 commands %hist, %save, %macro, etc.
457
457
458 Parameters
458 Parameters
459 ----------
459 ----------
460 rangestr : str
460 rangestr : str
461 A string specifying ranges, e.g. "5 ~2/1-4". See
461 A string specifying ranges, e.g. "5 ~2/1-4". See
462 :func:`magic_history` for full details.
462 :func:`magic_history` for full details.
463 raw, output : bool
463 raw, output : bool
464 As :meth:`get_range`
464 As :meth:`get_range`
465
465
466 Returns
466 Returns
467 -------
467 -------
468 Tuples as :meth:`get_range`
468 Tuples as :meth:`get_range`
469 """
469 """
470 for sess, s, e in extract_hist_ranges(rangestr):
470 for sess, s, e in extract_hist_ranges(rangestr):
471 for line in self.get_range(sess, s, e, raw=raw, output=output):
471 for line in self.get_range(sess, s, e, raw=raw, output=output):
472 yield line
472 yield line
473
473
474
474
475 class HistoryManager(HistoryAccessor):
475 class HistoryManager(HistoryAccessor):
476 """A class to organize all history-related functionality in one place.
476 """A class to organize all history-related functionality in one place.
477 """
477 """
478 # Public interface
478 # Public interface
479
479
480 # An instance of the IPython shell we are attached to
480 # An instance of the IPython shell we are attached to
481 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
481 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
482 allow_none=True)
482 allow_none=True)
483 # Lists to hold processed and raw history. These start with a blank entry
483 # Lists to hold processed and raw history. These start with a blank entry
484 # so that we can index them starting from 1
484 # so that we can index them starting from 1
485 input_hist_parsed = List([""])
485 input_hist_parsed = List([""])
486 input_hist_raw = List([""])
486 input_hist_raw = List([""])
487 # A list of directories visited during session
487 # A list of directories visited during session
488 dir_hist = List()
488 dir_hist = List()
489 @default('dir_hist')
489 @default('dir_hist')
490 def _dir_hist_default(self):
490 def _dir_hist_default(self):
491 try:
491 try:
492 return [py3compat.getcwd()]
492 return [py3compat.getcwd()]
493 except OSError:
493 except OSError:
494 return []
494 return []
495
495
496 # A dict of output history, keyed with ints from the shell's
496 # A dict of output history, keyed with ints from the shell's
497 # execution count.
497 # execution count.
498 output_hist = Dict()
498 output_hist = Dict()
499 # The text/plain repr of outputs.
499 # The text/plain repr of outputs.
500 output_hist_reprs = Dict()
500 output_hist_reprs = Dict()
501
501
502 # The number of the current session in the history database
502 # The number of the current session in the history database
503 session_number = Integer()
503 session_number = Integer()
504
504
505 db_log_output = Bool(False,
505 db_log_output = Bool(False,
506 help="Should the history database include output? (default: no)"
506 help="Should the history database include output? (default: no)"
507 ).tag(config=True)
507 ).tag(config=True)
508 db_cache_size = Integer(0,
508 db_cache_size = Integer(0,
509 help="Write to database every x commands (higher values save disk access & power).\n"
509 help="Write to database every x commands (higher values save disk access & power).\n"
510 "Values of 1 or less effectively disable caching."
510 "Values of 1 or less effectively disable caching."
511 ).tag(config=True)
511 ).tag(config=True)
512 # The input and output caches
512 # The input and output caches
513 db_input_cache = List()
513 db_input_cache = List()
514 db_output_cache = List()
514 db_output_cache = List()
515
515
516 # History saving in separate thread
516 # History saving in separate thread
517 save_thread = Instance('IPython.core.history.HistorySavingThread',
517 save_thread = Instance('IPython.core.history.HistorySavingThread',
518 allow_none=True)
518 allow_none=True)
519 try: # Event is a function returning an instance of _Event...
519 try: # Event is a function returning an instance of _Event...
520 save_flag = Instance(threading._Event, allow_none=True)
520 save_flag = Instance(threading._Event, allow_none=True)
521 except AttributeError: # ...until Python 3.3, when it's a class.
521 except AttributeError: # ...until Python 3.3, when it's a class.
522 save_flag = Instance(threading.Event, allow_none=True)
522 save_flag = Instance(threading.Event, allow_none=True)
523
523
524 # Private interface
524 # Private interface
525 # Variables used to store the three last inputs from the user. On each new
525 # Variables used to store the three last inputs from the user. On each new
526 # history update, we populate the user's namespace with these, shifted as
526 # history update, we populate the user's namespace with these, shifted as
527 # necessary.
527 # necessary.
528 _i00 = Unicode(u'')
528 _i00 = Unicode(u'')
529 _i = Unicode(u'')
529 _i = Unicode(u'')
530 _ii = Unicode(u'')
530 _ii = Unicode(u'')
531 _iii = Unicode(u'')
531 _iii = Unicode(u'')
532
532
533 # A regex matching all forms of the exit command, so that we don't store
533 # A regex matching all forms of the exit command, so that we don't store
534 # them in the history (it's annoying to rewind the first entry and land on
534 # them in the history (it's annoying to rewind the first entry and land on
535 # an exit call).
535 # an exit call).
536 _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$")
536 _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$")
537
537
538 def __init__(self, shell=None, config=None, **traits):
538 def __init__(self, shell=None, config=None, **traits):
539 """Create a new history manager associated with a shell instance.
539 """Create a new history manager associated with a shell instance.
540 """
540 """
541 # We need a pointer back to the shell for various tasks.
541 # We need a pointer back to the shell for various tasks.
542 super(HistoryManager, self).__init__(shell=shell, config=config,
542 super(HistoryManager, self).__init__(shell=shell, config=config,
543 **traits)
543 **traits)
544 self.save_flag = threading.Event()
544 self.save_flag = threading.Event()
545 self.db_input_cache_lock = threading.Lock()
545 self.db_input_cache_lock = threading.Lock()
546 self.db_output_cache_lock = threading.Lock()
546 self.db_output_cache_lock = threading.Lock()
547
547
548 try:
548 try:
549 self.new_session()
549 self.new_session()
550 except OperationalError:
550 except OperationalError:
551 self.log.error("Failed to create history session in %s. History will not be saved.",
551 self.log.error("Failed to create history session in %s. History will not be saved.",
552 self.hist_file, exc_info=True)
552 self.hist_file, exc_info=True)
553 self.hist_file = ':memory:'
553 self.hist_file = ':memory:'
554
554
555 if self.enabled and self.hist_file != ':memory:':
555 if self.enabled and self.hist_file != ':memory:':
556 self.save_thread = HistorySavingThread(self)
556 self.save_thread = HistorySavingThread(self)
557 self.save_thread.start()
557 self.save_thread.start()
558
558
559 def _get_hist_file_name(self, profile=None):
559 def _get_hist_file_name(self, profile=None):
560 """Get default history file name based on the Shell's profile.
560 """Get default history file name based on the Shell's profile.
561
561
562 The profile parameter is ignored, but must exist for compatibility with
562 The profile parameter is ignored, but must exist for compatibility with
563 the parent class."""
563 the parent class."""
564 profile_dir = self.shell.profile_dir.location
564 profile_dir = self.shell.profile_dir.location
565 return os.path.join(profile_dir, 'history.sqlite')
565 return os.path.join(profile_dir, 'history.sqlite')
566
566
567 @needs_sqlite
567 @needs_sqlite
568 def new_session(self, conn=None):
568 def new_session(self, conn=None):
569 """Get a new session number."""
569 """Get a new session number."""
570 if conn is None:
570 if conn is None:
571 conn = self.db
571 conn = self.db
572
572
573 with conn:
573 with conn:
574 cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
574 cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
575 NULL, "") """, (datetime.datetime.now(),))
575 NULL, "") """, (datetime.datetime.now(),))
576 self.session_number = cur.lastrowid
576 self.session_number = cur.lastrowid
577
577
578 def end_session(self):
578 def end_session(self):
579 """Close the database session, filling in the end time and line count."""
579 """Close the database session, filling in the end time and line count."""
580 self.writeout_cache()
580 self.writeout_cache()
581 with self.db:
581 with self.db:
582 self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
582 self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
583 session==?""", (datetime.datetime.now(),
583 session==?""", (datetime.datetime.now(),
584 len(self.input_hist_parsed)-1, self.session_number))
584 len(self.input_hist_parsed)-1, self.session_number))
585 self.session_number = 0
585 self.session_number = 0
586
586
587 def name_session(self, name):
587 def name_session(self, name):
588 """Give the current session a name in the history database."""
588 """Give the current session a name in the history database."""
589 with self.db:
589 with self.db:
590 self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
590 self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
591 (name, self.session_number))
591 (name, self.session_number))
592
592
593 def reset(self, new_session=True):
593 def reset(self, new_session=True):
594 """Clear the session history, releasing all object references, and
594 """Clear the session history, releasing all object references, and
595 optionally open a new session."""
595 optionally open a new session."""
596 self.output_hist.clear()
596 self.output_hist.clear()
597 # The directory history can't be completely empty
597 # The directory history can't be completely empty
598 self.dir_hist[:] = [py3compat.getcwd()]
598 self.dir_hist[:] = [py3compat.getcwd()]
599
599
600 if new_session:
600 if new_session:
601 if self.session_number:
601 if self.session_number:
602 self.end_session()
602 self.end_session()
603 self.input_hist_parsed[:] = [""]
603 self.input_hist_parsed[:] = [""]
604 self.input_hist_raw[:] = [""]
604 self.input_hist_raw[:] = [""]
605 self.new_session()
605 self.new_session()
606
606
607 # ------------------------------
607 # ------------------------------
608 # Methods for retrieving history
608 # Methods for retrieving history
609 # ------------------------------
609 # ------------------------------
610 def get_session_info(self, session=0):
610 def get_session_info(self, session=0):
611 """Get info about a session.
611 """Get info about a session.
612
612
613 Parameters
613 Parameters
614 ----------
614 ----------
615
615
616 session : int
616 session : int
617 Session number to retrieve. The current session is 0, and negative
617 Session number to retrieve. The current session is 0, and negative
618 numbers count back from current session, so -1 is the previous session.
618 numbers count back from current session, so -1 is the previous session.
619
619
620 Returns
620 Returns
621 -------
621 -------
622
622
623 session_id : int
623 session_id : int
624 Session ID number
624 Session ID number
625 start : datetime
625 start : datetime
626 Timestamp for the start of the session.
626 Timestamp for the start of the session.
627 end : datetime
627 end : datetime
628 Timestamp for the end of the session, or None if IPython crashed.
628 Timestamp for the end of the session, or None if IPython crashed.
629 num_cmds : int
629 num_cmds : int
630 Number of commands run, or None if IPython crashed.
630 Number of commands run, or None if IPython crashed.
631 remark : unicode
631 remark : unicode
632 A manually set description.
632 A manually set description.
633 """
633 """
634 if session <= 0:
634 if session <= 0:
635 session += self.session_number
635 session += self.session_number
636
636
637 return super(HistoryManager, self).get_session_info(session=session)
637 return super(HistoryManager, self).get_session_info(session=session)
638
638
639 def _get_range_session(self, start=1, stop=None, raw=True, output=False):
639 def _get_range_session(self, start=1, stop=None, raw=True, output=False):
640 """Get input and output history from the current session. Called by
640 """Get input and output history from the current session. Called by
641 get_range, and takes similar parameters."""
641 get_range, and takes similar parameters."""
642 input_hist = self.input_hist_raw if raw else self.input_hist_parsed
642 input_hist = self.input_hist_raw if raw else self.input_hist_parsed
643
643
644 n = len(input_hist)
644 n = len(input_hist)
645 if start < 0:
645 if start < 0:
646 start += n
646 start += n
647 if not stop or (stop > n):
647 if not stop or (stop > n):
648 stop = n
648 stop = n
649 elif stop < 0:
649 elif stop < 0:
650 stop += n
650 stop += n
651
651
652 for i in range(start, stop):
652 for i in range(start, stop):
653 if output:
653 if output:
654 line = (input_hist[i], self.output_hist_reprs.get(i))
654 line = (input_hist[i], self.output_hist_reprs.get(i))
655 else:
655 else:
656 line = input_hist[i]
656 line = input_hist[i]
657 yield (0, i, line)
657 yield (0, i, line)
658
658
659 def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
659 def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
660 """Retrieve input by session.
660 """Retrieve input by session.
661
661
662 Parameters
662 Parameters
663 ----------
663 ----------
664 session : int
664 session : int
665 Session number to retrieve. The current session is 0, and negative
665 Session number to retrieve. The current session is 0, and negative
666 numbers count back from current session, so -1 is previous session.
666 numbers count back from current session, so -1 is previous session.
667 start : int
667 start : int
668 First line to retrieve.
668 First line to retrieve.
669 stop : int
669 stop : int
670 End of line range (excluded from output itself). If None, retrieve
670 End of line range (excluded from output itself). If None, retrieve
671 to the end of the session.
671 to the end of the session.
672 raw : bool
672 raw : bool
673 If True, return untranslated input
673 If True, return untranslated input
674 output : bool
674 output : bool
675 If True, attempt to include output. This will be 'real' Python
675 If True, attempt to include output. This will be 'real' Python
676 objects for the current session, or text reprs from previous
676 objects for the current session, or text reprs from previous
677 sessions if db_log_output was enabled at the time. Where no output
677 sessions if db_log_output was enabled at the time. Where no output
678 is found, None is used.
678 is found, None is used.
679
679
680 Returns
680 Returns
681 -------
681 -------
682 entries
682 entries
683 An iterator over the desired lines. Each line is a 3-tuple, either
683 An iterator over the desired lines. Each line is a 3-tuple, either
684 (session, line, input) if output is False, or
684 (session, line, input) if output is False, or
685 (session, line, (input, output)) if output is True.
685 (session, line, (input, output)) if output is True.
686 """
686 """
687 if session <= 0:
687 if session <= 0:
688 session += self.session_number
688 session += self.session_number
689 if session==self.session_number: # Current session
689 if session==self.session_number: # Current session
690 return self._get_range_session(start, stop, raw, output)
690 return self._get_range_session(start, stop, raw, output)
691 return super(HistoryManager, self).get_range(session, start, stop, raw,
691 return super(HistoryManager, self).get_range(session, start, stop, raw,
692 output)
692 output)
693
693
694 ## ----------------------------
694 ## ----------------------------
695 ## Methods for storing history:
695 ## Methods for storing history:
696 ## ----------------------------
696 ## ----------------------------
697 def store_inputs(self, line_num, source, source_raw=None):
697 def store_inputs(self, line_num, source, source_raw=None):
698 """Store source and raw input in history and create input cache
698 """Store source and raw input in history and create input cache
699 variables ``_i*``.
699 variables ``_i*``.
700
700
701 Parameters
701 Parameters
702 ----------
702 ----------
703 line_num : int
703 line_num : int
704 The prompt number of this input.
704 The prompt number of this input.
705
705
706 source : str
706 source : str
707 Python input.
707 Python input.
708
708
709 source_raw : str, optional
709 source_raw : str, optional
710 If given, this is the raw input without any IPython transformations
710 If given, this is the raw input without any IPython transformations
711 applied to it. If not given, ``source`` is used.
711 applied to it. If not given, ``source`` is used.
712 """
712 """
713 if source_raw is None:
713 if source_raw is None:
714 source_raw = source
714 source_raw = source
715 source = source.rstrip('\n')
715 source = source.rstrip('\n')
716 source_raw = source_raw.rstrip('\n')
716 source_raw = source_raw.rstrip('\n')
717
717
718 # do not store exit/quit commands
718 # do not store exit/quit commands
719 if self._exit_re.match(source_raw.strip()):
719 if self._exit_re.match(source_raw.strip()):
720 return
720 return
721
721
722 self.input_hist_parsed.append(source)
722 self.input_hist_parsed.append(source)
723 self.input_hist_raw.append(source_raw)
723 self.input_hist_raw.append(source_raw)
724
724
725 with self.db_input_cache_lock:
725 with self.db_input_cache_lock:
726 self.db_input_cache.append((line_num, source, source_raw))
726 self.db_input_cache.append((line_num, source, source_raw))
727 # Trigger to flush cache and write to DB.
727 # Trigger to flush cache and write to DB.
728 if len(self.db_input_cache) >= self.db_cache_size:
728 if len(self.db_input_cache) >= self.db_cache_size:
729 self.save_flag.set()
729 self.save_flag.set()
730
730
731 # update the auto _i variables
731 # update the auto _i variables
732 self._iii = self._ii
732 self._iii = self._ii
733 self._ii = self._i
733 self._ii = self._i
734 self._i = self._i00
734 self._i = self._i00
735 self._i00 = source_raw
735 self._i00 = source_raw
736
736
737 # hackish access to user namespace to create _i1,_i2... dynamically
737 # hackish access to user namespace to create _i1,_i2... dynamically
738 new_i = '_i%s' % line_num
738 new_i = '_i%s' % line_num
739 to_main = {'_i': self._i,
739 to_main = {'_i': self._i,
740 '_ii': self._ii,
740 '_ii': self._ii,
741 '_iii': self._iii,
741 '_iii': self._iii,
742 new_i : self._i00 }
742 new_i : self._i00 }
743
743
744 if self.shell is not None:
744 if self.shell is not None:
745 self.shell.push(to_main, interactive=False)
745 self.shell.push(to_main, interactive=False)
746
746
747 def store_output(self, line_num):
747 def store_output(self, line_num):
748 """If database output logging is enabled, this saves all the
748 """If database output logging is enabled, this saves all the
749 outputs from the indicated prompt number to the database. It's
749 outputs from the indicated prompt number to the database. It's
750 called by run_cell after code has been executed.
750 called by run_cell after code has been executed.
751
751
752 Parameters
752 Parameters
753 ----------
753 ----------
754 line_num : int
754 line_num : int
755 The line number from which to save outputs
755 The line number from which to save outputs
756 """
756 """
757 if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
757 if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
758 return
758 return
759 output = self.output_hist_reprs[line_num]
759 output = self.output_hist_reprs[line_num]
760
760
761 with self.db_output_cache_lock:
761 with self.db_output_cache_lock:
762 self.db_output_cache.append((line_num, output))
762 self.db_output_cache.append((line_num, output))
763 if self.db_cache_size <= 1:
763 if self.db_cache_size <= 1:
764 self.save_flag.set()
764 self.save_flag.set()
765
765
766 def _writeout_input_cache(self, conn):
766 def _writeout_input_cache(self, conn):
767 with conn:
767 with conn:
768 for line in self.db_input_cache:
768 for line in self.db_input_cache:
769 conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)",
769 conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)",
770 (self.session_number,)+line)
770 (self.session_number,)+line)
771
771
772 def _writeout_output_cache(self, conn):
772 def _writeout_output_cache(self, conn):
773 with conn:
773 with conn:
774 for line in self.db_output_cache:
774 for line in self.db_output_cache:
775 conn.execute("INSERT INTO output_history VALUES (?, ?, ?)",
775 conn.execute("INSERT INTO output_history VALUES (?, ?, ?)",
776 (self.session_number,)+line)
776 (self.session_number,)+line)
777
777
778 @needs_sqlite
778 @needs_sqlite
779 def writeout_cache(self, conn=None):
779 def writeout_cache(self, conn=None):
780 """Write any entries in the cache to the database."""
780 """Write any entries in the cache to the database."""
781 if conn is None:
781 if conn is None:
782 conn = self.db
782 conn = self.db
783
783
784 with self.db_input_cache_lock:
784 with self.db_input_cache_lock:
785 try:
785 try:
786 self._writeout_input_cache(conn)
786 self._writeout_input_cache(conn)
787 except sqlite3.IntegrityError:
787 except sqlite3.IntegrityError:
788 self.new_session(conn)
788 self.new_session(conn)
789 print("ERROR! Session/line number was not unique in",
789 print("ERROR! Session/line number was not unique in",
790 "database. History logging moved to new session",
790 "database. History logging moved to new session",
791 self.session_number)
791 self.session_number)
792 try:
792 try:
793 # Try writing to the new session. If this fails, don't
793 # Try writing to the new session. If this fails, don't
794 # recurse
794 # recurse
795 self._writeout_input_cache(conn)
795 self._writeout_input_cache(conn)
796 except sqlite3.IntegrityError:
796 except sqlite3.IntegrityError:
797 pass
797 pass
798 finally:
798 finally:
799 self.db_input_cache = []
799 self.db_input_cache = []
800
800
801 with self.db_output_cache_lock:
801 with self.db_output_cache_lock:
802 try:
802 try:
803 self._writeout_output_cache(conn)
803 self._writeout_output_cache(conn)
804 except sqlite3.IntegrityError:
804 except sqlite3.IntegrityError:
805 print("!! Session/line number for output was not unique",
805 print("!! Session/line number for output was not unique",
806 "in database. Output will not be stored.")
806 "in database. Output will not be stored.")
807 finally:
807 finally:
808 self.db_output_cache = []
808 self.db_output_cache = []
809
809
810
810
811 class HistorySavingThread(threading.Thread):
811 class HistorySavingThread(threading.Thread):
812 """This thread takes care of writing history to the database, so that
812 """This thread takes care of writing history to the database, so that
813 the UI isn't held up while that happens.
813 the UI isn't held up while that happens.
814
814
815 It waits for the HistoryManager's save_flag to be set, then writes out
815 It waits for the HistoryManager's save_flag to be set, then writes out
816 the history cache. The main thread is responsible for setting the flag when
816 the history cache. The main thread is responsible for setting the flag when
817 the cache size reaches a defined threshold."""
817 the cache size reaches a defined threshold."""
818 daemon = True
818 daemon = True
819 stop_now = False
819 stop_now = False
820 enabled = True
820 enabled = True
821 def __init__(self, history_manager):
821 def __init__(self, history_manager):
822 super(HistorySavingThread, self).__init__(name="IPythonHistorySavingThread")
822 super(HistorySavingThread, self).__init__(name="IPythonHistorySavingThread")
823 self.history_manager = history_manager
823 self.history_manager = history_manager
824 self.enabled = history_manager.enabled
824 self.enabled = history_manager.enabled
825 atexit.register(self.stop)
825 atexit.register(self.stop)
826
826
827 @needs_sqlite
827 @needs_sqlite
828 def run(self):
828 def run(self):
829 # We need a separate db connection per thread:
829 # We need a separate db connection per thread:
830 try:
830 try:
831 self.db = sqlite3.connect(self.history_manager.hist_file,
831 self.db = sqlite3.connect(self.history_manager.hist_file,
832 **self.history_manager.connection_options
832 **self.history_manager.connection_options
833 )
833 )
834 while True:
834 while True:
835 self.history_manager.save_flag.wait()
835 self.history_manager.save_flag.wait()
836 if self.stop_now:
836 if self.stop_now:
837 self.db.close()
837 self.db.close()
838 return
838 return
839 self.history_manager.save_flag.clear()
839 self.history_manager.save_flag.clear()
840 self.history_manager.writeout_cache(self.db)
840 self.history_manager.writeout_cache(self.db)
841 except Exception as e:
841 except Exception as e:
842 print(("The history saving thread hit an unexpected error (%s)."
842 print(("The history saving thread hit an unexpected error (%s)."
843 "History will not be written to the database.") % repr(e))
843 "History will not be written to the database.") % repr(e))
844
844
845 def stop(self):
845 def stop(self):
846 """This can be called from the main thread to safely stop this thread.
846 """This can be called from the main thread to safely stop this thread.
847
847
848 Note that it does not attempt to write out remaining history before
848 Note that it does not attempt to write out remaining history before
849 exiting. That should be done by calling the HistoryManager's
849 exiting. That should be done by calling the HistoryManager's
850 end_session method."""
850 end_session method."""
851 self.stop_now = True
851 self.stop_now = True
852 self.history_manager.save_flag.set()
852 self.history_manager.save_flag.set()
853 self.join()
853 self.join()
854
854
855
855
856 # To match, e.g. ~5/8-~2/3
856 # To match, e.g. ~5/8-~2/3
857 range_re = re.compile(r"""
857 range_re = re.compile(r"""
858 ((?P<startsess>~?\d+)/)?
858 ((?P<startsess>~?\d+)/)?
859 (?P<start>\d+)?
859 (?P<start>\d+)?
860 ((?P<sep>[\-:])
860 ((?P<sep>[\-:])
861 ((?P<endsess>~?\d+)/)?
861 ((?P<endsess>~?\d+)/)?
862 (?P<end>\d+))?
862 (?P<end>\d+))?
863 $""", re.VERBOSE)
863 $""", re.VERBOSE)
864
864
865
865
866 def extract_hist_ranges(ranges_str):
866 def extract_hist_ranges(ranges_str):
867 """Turn a string of history ranges into 3-tuples of (session, start, stop).
867 """Turn a string of history ranges into 3-tuples of (session, start, stop).
868
868
869 Examples
869 Examples
870 --------
870 --------
871 >>> list(extract_hist_ranges("~8/5-~7/4 2"))
871 >>> list(extract_hist_ranges("~8/5-~7/4 2"))
872 [(-8, 5, None), (-7, 1, 5), (0, 2, 3)]
872 [(-8, 5, None), (-7, 1, 5), (0, 2, 3)]
873 """
873 """
874 for range_str in ranges_str.split():
874 for range_str in ranges_str.split():
875 rmatch = range_re.match(range_str)
875 rmatch = range_re.match(range_str)
876 if not rmatch:
876 if not rmatch:
877 continue
877 continue
878 start = rmatch.group("start")
878 start = rmatch.group("start")
879 if start:
879 if start:
880 start = int(start)
880 start = int(start)
881 end = rmatch.group("end")
881 end = rmatch.group("end")
882 # If no end specified, get (a, a + 1)
882 # If no end specified, get (a, a + 1)
883 end = int(end) if end else start + 1
883 end = int(end) if end else start + 1
884 else: # start not specified
884 else: # start not specified
885 if not rmatch.group('startsess'): # no startsess
885 if not rmatch.group('startsess'): # no startsess
886 continue
886 continue
887 start = 1
887 start = 1
888 end = None # provide the entire session hist
888 end = None # provide the entire session hist
889
889
890 if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
890 if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
891 end += 1
891 end += 1
892 startsess = rmatch.group("startsess") or "0"
892 startsess = rmatch.group("startsess") or "0"
893 endsess = rmatch.group("endsess") or startsess
893 endsess = rmatch.group("endsess") or startsess
894 startsess = int(startsess.replace("~","-"))
894 startsess = int(startsess.replace("~","-"))
895 endsess = int(endsess.replace("~","-"))
895 endsess = int(endsess.replace("~","-"))
896 assert endsess >= startsess, "start session must be earlier than end session"
896 assert endsess >= startsess, "start session must be earlier than end session"
897
897
898 if endsess == startsess:
898 if endsess == startsess:
899 yield (startsess, start, end)
899 yield (startsess, start, end)
900 continue
900 continue
901 # Multiple sessions in one range:
901 # Multiple sessions in one range:
902 yield (startsess, start, None)
902 yield (startsess, start, None)
903 for sess in range(startsess+1, endsess):
903 for sess in range(startsess+1, endsess):
904 yield (sess, 1, None)
904 yield (sess, 1, None)
905 yield (endsess, 1, end)
905 yield (endsess, 1, end)
906
906
907
907
908 def _format_lineno(session, line):
908 def _format_lineno(session, line):
909 """Helper function to format line numbers properly."""
909 """Helper function to format line numbers properly."""
910 if session == 0:
910 if session == 0:
911 return str(line)
911 return str(line)
912 return "%s#%s" % (session, line)
912 return "%s#%s" % (session, line)
General Comments 0
You need to be logged in to leave comments. Login now