1#!/usr/bin/env python3
 2
 3"""Retrievals from the FDF_EVENTS table."""
 4
 5from chart.db.connection import db_connect
 6
 7TABLENAME = 'FDF_EVENTS'
 8db_conn = db_connect(TABLENAME)
 9
10
11def find_fdfevents(fields,
12                   sid=None,
13                   start_time=None,
14                   stop_time=None,
15                   orbit=None,
16                   names=None,
17                   extra=None,
18                   order_by='start_time',
19                   targets=None):
20    """ Retrieve data from the FDFEVENTS table.
21    Args:
22        fields : list of select instances
23        sid : Source ID
24        start_time : sensing start time (datetime)
25        stop_time : sensing stop time (datetime)
26        orbit (int): orbit number
27        names : list of table names to be filtered
28        extra : list of extra information to be filtered
29        order_by : list results according to this parameter
30        targets (list of str): list of table 'target' parameter
31
32    Returns:
33        Cursor.
34    """
35
36    bindvars = {}
37    clauses = []
38
39    if sid is not None:
40        clauses.append(sid.sql_sys_where_bind(TABLENAME))
41        bindvars.update(sid.bind_sys_where(TABLENAME))
42
43    if start_time is not None:
44        clauses.append('start_time>=:start_time')
45        bindvars['start_time'] = start_time
46
47    if stop_time is not None:
48        clauses.append('stop_time<:stop_time')
49        bindvars['stop_time'] = stop_time
50
51    if orbit is not None:
52        clauses.append('orbit=:orbit')
53        bindvars['orbit'] = orbit
54
55    if names is not None:
56        clauses.append('name in ({names})'.format(names=','.join("'{n}'".
57                    format(n=n) for n in names)))
58
59    if extra is not None:
60        clauses.append('extra in ({extra})'.format(extra=','.join("'{n}'".
61                    format(n=n) for n in extra)))
62
63    if targets is not None:
64        clauses.append('target in ({targets})'.format
65                (targets=','.join("'{t}'".format(t=t) for t in targets)))
66
67    return db_conn.query('SELECT {fields} FROM FDF_EVENTS {where} {ordering}'.format(
68        fields=','.join(fields),
69        where='' if len(clauses) == 0 else (' WHERE ' + ' AND '.join(clauses)),
70        ordering='' if order_by is None else 'ORDER BY {o}'.format(o=order_by)),
71                 **bindvars)