# Path: pystil/context.py
# class url(object):
#     def __init__(self, url):
#         self.url = url
# 
#     def __call__(self, cls):
#         pystil.add_handlers(
#             r'.*$',
#             (unnamed_url(self.url, cls, name=cls.__name__),)
#         )
#         return cls
# 
# MESSAGE_QUEUE = Queue()
# 
# @property
# def log(self):
#     return log
# 
# class Hdr(RequestHandler):
#     @property
#     def db(self):
#         return self.application.db
# 
#     @property
#     def log(self):
#         return log
# 
#     def prepare(self):
#         if not self.get_secure_cookie('_pystil_site'):
#             self.log.info('Setting secure cookie')
#             self.set_secure_cookie('_pystil_site', 'local|' + str(uuid4()))
# 
#     def on_finish(self):
#         self.db.rollback()
# 
# Path: pystil/db.py
# class CriterionView(Base):
#     __tablename__ = 'criterion_view'
# 
#     id = integer(pkey=True)
#     uuid = string()
#     browser_name = string()
#     hash = string()
#     host = string()
#     browser_version = string()
#     client_tz_offset = integer()
#     date = datetime()
#     last_visit = datetime()
#     ip = string()
#     language = string()
#     page = string()
#     platform = string()
#     query = string()
#     referrer = string()
#     pretty_referrer = string()
#     referrer_domain = string()
#     site = string()
#     size = string()
#     time = Column(Interval)
#     country = string()
#     country_code = string()
#     city = string()
#     lat = decimal()
#     lng = decimal()
#     asn = string()
# 
#     browser_name_version = string()
#     day = date_column()
#     hour = integer()
#     subdomain = string()
#     domain = string()
# 
# Path: pystil/utils.py
# def visit_to_table_line(visit):
#     html = '<tr data-visit-uuid="%s">' % visit.uuid
#     for key in [
#             'date', 'host', 'ip', 'country',
#             'city', 'page', 'referrer']:
#         val = getattr(visit, key)
#         title = None
#         if val:
#             if key == 'date':
#                 val = val.strftime('%Y-%m-%d %H:%M:%S')
#             if key == 'referrer':
#                 title = val
#                 val = parse_referrer(val, True, True)
#         else:
#             val = ''
#         title = title or val
#         html += '<td title="%s">' % title
#         html += '<a href="/criterion/%s/%s">' % (key, val)
#         html += val
#         html += '</>'
#         html += '</td>'
#     html += ('<td>'
#              '<a href="/visit/%d"><i class="icon-search"></i></a>'
#              '</td>' % visit.id)
#     html += '</tr>'
#     return html


from tornado.websocket import WebSocketHandler
from pystil.context import url, MESSAGE_QUEUE, log, Hdr
from pystil.db import CriterionView as Visit
from tornado.options import options
from tornado.ioloop import IOLoop
from psycopg2.extensions import POLL_OK, POLL_READ, POLL_WRITE
from sqlalchemy.sql.compiler import SQLCompiler
from sqlalchemy.sql.expression import between
from pystil.utils import visit_to_table_line
from sqlalchemy import func
from datetime import datetime, timedelta
from functools import partial
import psycopg2
import momoko
                    self.execute, query, parameters))
        if not self.ws_connection:
            return
        self.state = 'executing'
        self.write_message('BEGIN|Searching')
        self.connection = self.momoko_connection.connection
        self.cursor = self.connection.cursor(
            cursor_factory=psycopg2.extras.NamedTupleCursor)
        self.cursor.execute(
            'BEGIN;'
            'DECLARE visit_cur SCROLL CURSOR FOR '
            '%s;'
            'SELECT null as id;' % query, parameters)
            # 'FETCH FORWARD 1 FROM visit_cur;' % query, parameters)
        self.momoko_connection.ioloop.add_handler(
            self.momoko_connection.fileno,
            self.io_callback,
            IOLoop.WRITE)

    def io_callback(self, fd=None, events=None):
        try:
            state = self.connection.poll()
        except psycopg2.extensions.QueryCanceledError:
            log.info('Canceling request %r' % self, exc_info=True)
            self.cursor.execute('ROLLBACK -- CANCEL')
            self.state = 'terminated'
        except (psycopg2.Warning, psycopg2.Error):
            log.exception('Poll error')
            self.momoko_connection.ioloop.remove_handler(
                self.momoko_connection.fileno)

# Path: pystil/context.py
# class url(object):
#     def __init__(self, url):
#         self.url = url
# 
#     def __call__(self, cls):
#         pystil.add_handlers(
#             r'.*$',
#             (unnamed_url(self.url, cls, name=cls.__name__),)
#         )
#         return cls
# 
# MESSAGE_QUEUE = Queue()
# 
# @property
# def log(self):
#     return log
# 
# class Hdr(RequestHandler):
#     @property
#     def db(self):
#         return self.application.db
# 
#     @property
#     def log(self):
#         return log
# 
#     def prepare(self):
#         if not self.get_secure_cookie('_pystil_site'):
#             self.log.info('Setting secure cookie')
#             self.set_secure_cookie('_pystil_site', 'local|' + str(uuid4()))
# 
#     def on_finish(self):
#         self.db.rollback()
# 
# Path: pystil/db.py
# class CriterionView(Base):
#     __tablename__ = 'criterion_view'
# 
#     id = integer(pkey=True)
#     uuid = string()
#     browser_name = string()
#     hash = string()
#     host = string()
#     browser_version = string()
#     client_tz_offset = integer()
#     date = datetime()
#     last_visit = datetime()
#     ip = string()
#     language = string()
#     page = string()
#     platform = string()
#     query = string()
#     referrer = string()
#     pretty_referrer = string()
#     referrer_domain = string()
#     site = string()
#     size = string()
#     time = Column(Interval)
#     country = string()
#     country_code = string()
#     city = string()
#     lat = decimal()
#     lng = decimal()
#     asn = string()
# 
#     browser_name_version = string()
#     day = date_column()
#     hour = integer()
#     subdomain = string()
#     domain = string()
# 
# Path: pystil/utils.py
# def visit_to_table_line(visit):
#     html = '<tr data-visit-uuid="%s">' % visit.uuid
#     for key in [
#             'date', 'host', 'ip', 'country',
#             'city', 'page', 'referrer']:
#         val = getattr(visit, key)
#         title = None
#         if val:
#             if key == 'date':
#                 val = val.strftime('%Y-%m-%d %H:%M:%S')
#             if key == 'referrer':
#                 title = val
#                 val = parse_referrer(val, True, True)
#         else:
#             val = ''
#         title = title or val
#         html += '<td title="%s">' % title
#         html += '<a href="/criterion/%s/%s">' % (key, val)
#         html += val
#         html += '</>'
#         html += '</td>'
#     html += ('<td>'
#              '<a href="/visit/%d"><i class="icon-search"></i></a>'
#              '</td>' % visit.id)
#     html += '</tr>'
#     return html


# Path: pystil/websocket.py
from tornado.websocket import WebSocketHandler
from pystil.context import url, MESSAGE_QUEUE, log, Hdr
from pystil.db import CriterionView as Visit
from tornado.options import options
from tornado.ioloop import IOLoop
from psycopg2.extensions import POLL_OK, POLL_READ, POLL_WRITE
from sqlalchemy.sql.compiler import SQLCompiler
from sqlalchemy.sql.expression import between
from pystil.utils import visit_to_table_line
from sqlalchemy import func
from datetime import datetime, timedelta
from functools import partial
import psycopg2
import momoko

                    self.execute, query, parameters))
        if not self.ws_connection:
            return
        self.state = 'executing'
        self.write_message('BEGIN|Searching')
        self.connection = self.momoko_connection.connection
        self.cursor = self.connection.cursor(
            cursor_factory=psycopg2.extras.NamedTupleCursor)
        self.cursor.execute(
            'BEGIN;'
            'DECLARE visit_cur SCROLL CURSOR FOR '
            '%s;'
            'SELECT null as id;' % query, parameters)
            # 'FETCH FORWARD 1 FROM visit_cur;' % query, parameters)
        self.momoko_connection.ioloop.add_handler(
            self.momoko_connection.fileno,
            self.io_callback,
            IOLoop.WRITE)

    def io_callback(self, fd=None, events=None):
        try:
            state = self.connection.poll()
        except psycopg2.extensions.QueryCanceledError:
            log.info('Canceling request %r' % self, exc_info=True)
            self.cursor.execute('ROLLBACK -- CANCEL')
            self.state = 'terminated'
        except (psycopg2.Warning, psycopg2.Error):
            log.exception('Poll error')
            self.momoko_connection.ioloop.remove_handler(
                self.momoko_connection.fileno)

            raise