From 30c9fcb131c1c492e1c020efd634f1aef0ed023a 2011-08-04 22:56:40 From: MinRK Date: 2011-08-04 22:56:40 Subject: [PATCH] add get_session_info to HistoryManager for querying session table Also set detect_types flags on the connection, so timestamps are retrieved as datetime objects. Associated type checking test included. --- diff --git a/IPython/core/history.py b/IPython/core/history.py index d2ae229..029d2ba 100644 --- a/IPython/core/history.py +++ b/IPython/core/history.py @@ -129,7 +129,8 @@ class HistoryManager(Configurable): def init_db(self): """Connect to the database, and create tables if necessary.""" - self.db = sqlite3.connect(self.hist_file) + # use detect_types so that timestamps return datetime objects + self.db = sqlite3.connect(self.hist_file, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES) self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer primary key autoincrement, start timestamp, end timestamp, num_cmds integer, remark text)""") @@ -213,6 +214,33 @@ class HistoryManager(Configurable): return cur + def get_session_info(self, session=0): + """get info about a session + + Parameters + ---------- + + session : int + Session number to retrieve. The current session is 0, and negative + numbers count back from current session, so -1 is previous session. + + Returns + ------- + + (session_id [int], start [datetime], end [datetime], num_cmds [int], remark [unicode]) + + Sessions that are running or did not exit cleanly will have `end=None` + and `num_cmds=None`. + + """ + + if session <= 0: + session += self.session_number + + query = "SELECT * from sessions where session == ?" + return self.db.execute(query, (session,)).fetchone() + + def get_tail(self, n=10, raw=True, output=False, include_latest=False): """Get the last n lines from the history database. diff --git a/IPython/core/tests/test_history.py b/IPython/core/tests/test_history.py index 9a74a4e..1cbacd2 100644 --- a/IPython/core/tests/test_history.py +++ b/IPython/core/tests/test_history.py @@ -9,7 +9,7 @@ import os import sys import unittest - +from datetime import datetime # third party import nose.tools as nt @@ -107,3 +107,8 @@ def test_magic_rerun(): nt.assert_equal(ip.user_ns["a"], 11) ip.run_cell("%rerun") nt.assert_equal(ip.user_ns["a"], 12) + +def test_timestamp_type(): + ip = get_ipython() + info = ip.history_manager.get_session_info() + nt.assert_true(isinstance(info[1], datetime))