def run_q(cnx, q, args, fetch=False, commit=True):
    """
    :param cnx: The database connection to use.
    :param q: The query string to run.
    :param args: Parameters to insert into query template if q is a template.
    :param fetch: True if this query produces a result and the function should perform and return fetchall()
    :return:
    """
    #debug_message("run_q: q = " + q)
    ut.debug_message("Q = " + q)
    ut.debug_message("Args = ", args)

    result = None

    try:
        cursor = cnx.cursor()
        result = cursor.execute(q, args)
        if fetch:
            result = cursor.fetchall()
        if commit:
            cnx.commit()
    except pymysql_exceptions as original_e:
        #print("dffutils.run_q got exception = ", original_e)
        raise (original_e)

    return result
Example #2
0
def add_to_cache(key, value):
    """

    :param key: A valid Redis key string.
    :param value: A Python dictionary to add to cache.
    :return: None
    """
    k = key
    ut.debug_message("Adding key = ", k)
    ut.debug_message("Adding data", value)
    r.hmset(k, value)
Example #3
0
def compute_key(resource, template, fields):
    """

    :param resource: The name of a resource, i.e. database table name.
    :param template: A query template for finding a resource in a table.
    :param fields: List of fields to retrieve, e.g. project clause.
    :return: A valid Redis key that for storing/retrieving a map from the Redis cache.
    """
    ut.debug_message("Resource = ", resource)
    ut.debug_message("Template = ", template)
    ut.debug_message("Fields = ", fields)

    t = None
    f = None

    if template is not None:
        """
        Convert the query template to a string form of p1=v1,p2=v2, ...
        """
        # print("Items = ", template.items())
        t = template.items()
        # print("t = ", t)
        t = tuple(t)
        # print("t = ", t)
        sorted(t, key=itemgetter(1))
        ts = [str(e[0]) + "=" + str(e[1]) for e in t]
        t = ",".join(ts)

    if fields is not None:
        """
        Convert a fields list into a string of the form f=f1,f2,...
        """
        f = sorted(fields)
        f = "f=" + (",".join(f))

    if f is not None or t is not None:
        """
        There is a convention in Redis that a collection of resources if of the form 
        collection_name:key_value. If there is a sub-key representing the template or fields selector,
        add a ':' to the end of the resource name.
        """
        result = resource + ":"
    else:
        result = resource

    # Add template string to key if it exists.
    if t is not None:
        result += t

    # If there is a fields list, add it to the key. Add a "," to separate from template string
    # if there is a template string.
    if f is not None and t is not None:
        result += "," + f
    elif f is not None and t is None:
        result += f

    return result