How to use the invenio.dbquery.run_sql function in invenio

To help you get started, we’ve selected a few invenio examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github inveniosoftware / invenio / modules / websubmit / lib / websubmitadmin_regression_tests.py View on Github external
def insert_submission_dump(dump):
    """Helper function to insert submisson dump via run_sql()"""
    for sql_statement in dump.replace(r'\"', '"').splitlines():
        if sql_statement:
            run_sql(sql_statement)
github inveniosoftware / invenio / modules / webcomment / lib / webcomment.py View on Github external
    @type selected_display_format_option: string
    @ln: language
    @type ln: string
    """
    query_params = ""
    nb_total_pages = 0

    if selected_display_format_option in ('rc', 'co'):
        nb_total_results = run_sql("SELECT count(id) from cmtRECORDCOMMENT WHERE id_user=%s AND star_score = 0", \
                                   (user_info['uid'], ))[0][0]
    else:
        if selected_order_by_option in ('grlf', 'grof'):
            nb_total_results = run_sql("SELECT count(distinct(id_bibrec)) from cmtRECORDCOMMENT WHERE id_user=%s AND star_score = 0", \
                                       (user_info['uid'], ))[0][0]
        else:
            nb_total_results = run_sql("SELECT count(id_bibrec) from cmtRECORDCOMMENT WHERE id_user=%s AND star_score = 0", \
                                       (user_info['uid'], ))[0][0]
    if page_number < 1:
        page_number = 1

    if selected_display_number_option != 'all' and \
           not selected_display_number_option.isdigit():
        # must be some garbage
        selected_display_number_option = 'all'

    query = ''
    if selected_order_by_option == "lcf":
        query_params += " ORDER BY date_creation DESC"
    elif selected_order_by_option == "ocf":
        query_params += " ORDER BY date_creation ASC"
    elif selected_order_by_option == "grlf":
        query = "SELECT cmt.id_bibrec, cmt.id, cmt.date_creation, cmt.body, cmt.status, cmt.in_reply_to_id_cmtRECORDCOMMENT FROM cmtRECORDCOMMENT as cmt left join (SELECT max(date_creation) as maxdatecreation, id_bibrec FROM cmtRECORDCOMMENT WHERE id_user=%s AND star_score = 0 GROUP BY id_bibrec) as grp on cmt.id_bibrec = grp.id_bibrec WHERE id_user=%s AND star_score = 0 ORDER BY grp.maxdatecreation DESC, cmt.date_creation DESC"
github inveniosoftware / invenio / modules / websession / lib / inveniogc.py View on Github external
def clean_bibedit_cache():
    """Deletes experied bibedit cache entries"""
    datecut = datetime.datetime.now() - datetime.timedelta(days=CFG_MAX_ATIME_BIBEDIT_TMP)
    datecut_str = datecut.strftime("%Y-%m-%d %H:%M:%S")
    run_sql("DELETE FROM bibEDITCACHE WHERE post_date < %s", [datecut_str])
github inveniosoftware / invenio / modules / bibcirculation / lib / bibcirculation_dblayer.py View on Github external
loan_period, status, expected_arrival_date):

    """
    Add a new copy

    barcode: identify the item. It is the primary key of the table
             crcITEM.

    recid: identify the record. It is also the primary key of
       the table bibrec.

    library_id: identify the library. It is also the primary key of
                the table crcLIBRARY.
    """

    run_sql("""insert into crcITEM (barcode, id_bibrec, id_crcLIBRARY,
                                collection, location, description, loan_period,
                                status, expected_arrival_date, creation_date,
                                modification_date)
                values (%s, %s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW())""",
            (barcode, recid, library_id, collection, location, description or '-',
             loan_period, status, expected_arrival_date))
github inveniosoftware / invenio / modules / webaccess / lib / access_control_mailcookie.py View on Github external
def mail_cookie_check_common(cookie, delete=False):
    """Retrieve data pointed by a cookie, returning a tuple (kind, params) or None
    if the cookie is not valid or is expired"""
    try:
        password = cookie[:16]+cookie[-16:]
        cookie_id = int(cookie[16:-16], 16)
    except Exception, e:
        raise InvenioWebAccessMailCookieError, "Cookie not valid: %s" % e
    try:
        res = run_sql("SELECT kind, AES_DECRYPT(data,%s), onetime, status FROM accMAILCOOKIE WHERE "
            "id=%s AND expiration>=NOW()", (password, cookie_id), run_on_slave=True)
        if not res:
            raise StandardError
    except StandardError:
        raise InvenioWebAccessMailCookieError, "Cookie doesn't exist"
    (kind, data, onetime, status) = res[0]
    (kind_check, params, expiration, onetime_check) = loads(data)
    if not (kind == kind_check and onetime == onetime_check):
        raise InvenioWebAccessMailCookieError, "Cookie is corrupted"
    if status == 'D':
        raise InvenioWebAccessMailCookieDeletedError, "Cookie has been deleted"
    if onetime or delete:
        run_sql("UPDATE accMAILCOOKIE SET status='D' WHERE id=%s", (cookie_id, ))
    return (kind, params)
github inveniosoftware / invenio / modules / websubmit / lib / websubmitadmin_dblayer.py View on Github external
def update_step_score_doctypesubmission_function(doctype, action, function, oldstep, oldscore, newstep, newscore):
    numrows_function = get_number_functions_doctypesubmission_functionname_step_score(doctype=doctype, action=action,
                                                                                      function=function, step=oldstep, score=oldscore)
    if numrows_function == 1:
        q = """UPDATE sbmFUNCTIONS SET step=%s, score=%s WHERE doctype=%s AND action=%s AND function=%s AND step=%s AND score=%s"""
        run_sql(q, (newstep, newscore, doctype, action, function, oldstep, oldscore))
        return 0  ## Everything OK
    else:
        ## Everything NOT OK - perhaps this function doesn't exist at this posn - cannot update
        return 1
github inveniosoftware / invenio / modules / webbasket / lib / webbasket_migration_kit.py View on Github external
def __drop_baskets():
    """"""
    query1 = "DROP TABLE basket"
    run_sql(query1)
    query2 = "DROP TABLE user_basket"
    run_sql(query2)
    query3 = "DROP TABLE basket_record"
    run_sql(query3)
github inveniosoftware / invenio / modules / bibauthorid / lib / bibauthorid_dbinterface.py View on Github external
def check_claim_inspireid_contradiction():
    iids10x = run_sql("select id from bib10x where tag = '100__i'")
    iids70x = run_sql("select id from bib70x where tag = '700__i'")

    refs10x = set(x[0] for x in run_sql("select id from bib10x where tag = '100__a'"))
    refs70x = set(x[0] for x in run_sql("select id from bib70x where tag = '700__a'"))

    if iids10x:
        iids10x = list_2_SQL_str(iids10x, lambda x: str(x[0]))

        iids10x = run_sql("select id_bibxxx, id_bibrec, field_number "
                          "from bibrec_bib10x "
                          "where id_bibxxx in %s"
                          % iids10x)

        iids10x = ((row[0], [(ref, rec) for ref, rec in run_sql(
                                "select id_bibxxx, id_bibrec "
                                "from bibrec_bib10x "
                                "where id_bibrec = '%s' "
                                "and field_number = '%s'"
                                % row[1:])
github inveniosoftware / invenio / modules / miscutil / lib / inveniocfg.py View on Github external
"""
    Detect and print system details such as Apache/Python/MySQL
    versions etc.  Useful for debugging problems on various OS.
    """
    import MySQLdb
    print ">>> Going to detect system details..."
    print "* Hostname: " + socket.gethostname()
    print "* Invenio version: " + conf.get("Invenio", "CFG_VERSION")
    print "* Python version: " + sys.version.replace("\n", " ")
    print "* Apache version: " + ";\n                  ".join(detect_apache_version())
    print "* MySQLdb version: " + MySQLdb.__version__
    try:
        from invenio.dbquery import run_sql
        print "* MySQL version:"
        for key, val in run_sql("SHOW VARIABLES LIKE 'version%'") + \
                run_sql("SHOW VARIABLES LIKE 'charact%'") + \
                run_sql("SHOW VARIABLES LIKE 'collat%'"):
            if False:
                print "    - %s: %s" % (key, val)
            elif key in ['version',
                         'character_set_client',
                         'character_set_connection',
                         'character_set_database',
                         'character_set_results',
                         'character_set_server',
                         'character_set_system',
                         'collation_connection',
                         'collation_database',
                         'collation_server']:
                print "    - %s: %s" % (key, val)
    except ImportError:
        print "* ERROR: cannot import dbquery"
github inveniosoftware / invenio / modules / bibupload / lib / bibupload.py View on Github external
def insert_record_bibxxx(tag, value, pretend=False):
    """Insert the record into bibxxx"""
    # determine into which table one should insert the record
    table_name = 'bib'+tag[0:2]+'x'

    # check if the tag, value combination exists in the table
    query = """SELECT id,value FROM %s """ % table_name
    query += """ WHERE tag=%s AND value=%s"""
    params = (tag, value)
    try:
        res = run_sql(query, params)
    except Error, error:
        write_message("   Error during the insert_record_bibxxx function : %s "
            % error, verbose=1, stream=sys.stderr)

    # Note: compare now the found values one by one and look for
    # string binary equality (e.g. to respect lowercase/uppercase
    # match), regardless of the charset etc settings.  Ideally we
    # could use a BINARY operator in the above SELECT statement, but
    # we would have to check compatibility on various MySQLdb versions
    # etc; this approach checks all matched values in Python, not in
    # MySQL, which is less cool, but more conservative, so it should
    # work better on most setups.
    for row in res:
        row_id = row[0]
        row_value = row[1]
        if row_value == value: