Example #1
0
        def __getattr__(self, name):
            """Get attr."""
            # Perform custom logic here
            if name == "__file__":
                return __file__
            elif name == "__path__":
                return os.path.dirname(__file__)
            try:
                from invenio_base.helpers import utf8ifier

                warnings.warn("Usage of invenio.config.{0} is deprecated".format(name), RemovedInInvenio23Warning)
                return utf8ifier(self.wrapped[name])
            except Exception:
                pass
def run_sql(sql, param=None, n=0, with_desc=False, with_dict=False,
            run_on_slave=False, connection=None):
    """Run SQL on the server with PARAM and return result.

    :param param: tuple of string params to insert in the query (see
    notes below)
    :param n: number of tuples in result (0 for unbounded)
    :param with_desc: if True, will return a DB API 7-tuple describing
    columns in query.
    :param with_dict: if True, will return a list of dictionaries
    composed of column-value pairs
    :param connection: if provided, uses the given connection.
    :return: If SELECT, SHOW, DESCRIBE statements, return tuples of data,
    followed by description if parameter with_desc is
    provided.
    If SELECT and with_dict=True, return a list of dictionaries
    composed of column-value pairs, followed by description
    if parameter with_desc is provided.
    If INSERT, return last row id.
    Otherwise return SQL result as provided by database.

    @note: When the site is closed for maintenance (as governed by the
    config variable CFG_ACCESS_CONTROL_LEVEL_SITE), do not attempt
    to run any SQL queries but return empty list immediately.
    Useful to be able to have the website up while MySQL database
    is down for maintenance, hot copies, table repairs, etc.
    @note: In case of problems, exceptions are returned according to
    the Python DB API 2.0.  The client code can import them from
    this file and catch them.
    """
    if cfg['CFG_ACCESS_CONTROL_LEVEL_SITE'] == 3:
        # do not connect to the database as the site is closed for maintenance:
        return []
    elif cfg['CFG_ACCESS_CONTROL_LEVEL_SITE'] > 0:
        # Read only website
        if not sql.upper().startswith("SELECT") and \
                not sql.upper().startswith("SHOW"):
            return

    if param:
        param = tuple(param)

    # FIXME port database slave support
    dbhost = cfg['CFG_DATABASE_HOST']
    if run_on_slave and cfg['CFG_DATABASE_SLAVE']:
        dbhost = cfg['CFG_DATABASE_SLAVE']

    if 'sql-logger' in cfg.get('CFG_DEVEL_TOOLS', []):
        log_sql_query(dbhost, sql, param)

    gc.disable()
    engine = db.engine.execution_options(use_unicode=0)
    sql = sql.replace('`', '"')
    current_app.logger.info(sql)
    if param is None:
        cur = engine.execute(sql.replace('%', '%%'))
    else:
        cur = engine.execute(sql, (param, ))
    gc.enable()

    if string.upper(string.split(sql)[0]) in \
            ("SELECT", "SHOW", "DESC", "DESCRIBE"):
        if n:
            recset = cur.fetchmany(n)
        else:
            recset = cur.fetchall()

        from invenio_base.helpers import utf8ifier
        recset = map(dict if with_dict else tuple, recset)
        recset = utf8ifier(recset)

        if with_desc:
            return recset, cur.description
        else:
            return recset
    else:
        if string.upper(string.split(sql)[0]) == "INSERT":
            return cur.lastrowid
        return cur
Example #3
0
def run_sql(sql,
            param=None,
            n=0,
            with_desc=False,
            with_dict=False,
            run_on_slave=False,
            connection=None):
    """Run SQL on the server with PARAM and return result.

    :param param: tuple of string params to insert in the query (see
    notes below)
    :param n: number of tuples in result (0 for unbounded)
    :param with_desc: if True, will return a DB API 7-tuple describing
    columns in query.
    :param with_dict: if True, will return a list of dictionaries
    composed of column-value pairs
    :param connection: if provided, uses the given connection.
    :return: If SELECT, SHOW, DESCRIBE statements, return tuples of data,
    followed by description if parameter with_desc is
    provided.
    If SELECT and with_dict=True, return a list of dictionaries
    composed of column-value pairs, followed by description
    if parameter with_desc is provided.
    If INSERT, return last row id.
    Otherwise return SQL result as provided by database.

    @note: When the site is closed for maintenance (as governed by the
    config variable CFG_ACCESS_CONTROL_LEVEL_SITE), do not attempt
    to run any SQL queries but return empty list immediately.
    Useful to be able to have the website up while MySQL database
    is down for maintenance, hot copies, table repairs, etc.
    @note: In case of problems, exceptions are returned according to
    the Python DB API 2.0.  The client code can import them from
    this file and catch them.
    """
    if cfg['CFG_ACCESS_CONTROL_LEVEL_SITE'] == 3:
        # do not connect to the database as the site is closed for maintenance:
        return []
    elif cfg['CFG_ACCESS_CONTROL_LEVEL_SITE'] > 0:
        # Read only website
        if not sql.upper().startswith("SELECT") and \
                not sql.upper().startswith("SHOW"):
            return

    if param:
        param = tuple(param)

    # FIXME port database slave support
    dbhost = cfg['CFG_DATABASE_HOST']
    if run_on_slave and cfg['CFG_DATABASE_SLAVE']:
        dbhost = cfg['CFG_DATABASE_SLAVE']

    if 'sql-logger' in cfg.get('CFG_DEVEL_TOOLS', []):
        log_sql_query(dbhost, sql, param)

    gc.disable()
    engine = db.engine.execution_options(use_unicode=0)
    sql = sql.replace('`', '"')
    current_app.logger.info(sql)
    if param is None:
        cur = engine.execute(sql.replace('%', '%%'))
    else:
        cur = engine.execute(sql, (param, ))
    gc.enable()

    if string.upper(string.split(sql)[0]) in \
            ("SELECT", "SHOW", "DESC", "DESCRIBE"):
        if n:
            recset = cur.fetchmany(n)
        else:
            recset = cur.fetchall()

        from invenio_base.helpers import utf8ifier
        recset = map(dict if with_dict else tuple, recset)
        recset = utf8ifier(recset)

        if with_desc:
            return recset, cur.description
        else:
            return recset
    else:
        if string.upper(string.split(sql)[0]) == "INSERT":
            return cur.lastrowid
        return cur