Grant SELECT on public schema
357274
def create_user(self, user, table_privileges=['ALL PRIVILEGES'],
                    schema_privileges=['ALL PRIVILEGES'],
                    row_limit=50000):
        con = self.connection or self._connect()
        cur = con.cursor()

        cur.execute('CREATE SCHEMA {0};'.format(user))
        # self._initialize(schema=schema_name)
        password = pwgen(8)
        cur.execute(
            "CREATE USER {user} with PASSWORD '{password}';"
            .format(user=user, password=password))

        
        cur.execute('GRANT USAGE ON SCHEMA public TO {user};'
                    .format(user=user))
        cur.execute(
            'GRANT SELECT ON ALL TABLES IN SCHEMA public TO {user};'
            .format(user=user))
        cur.execute(
            'ALTER ROLE {user} SET search_path TO {user};'
            .format(user=user))

        self.stdout.write(
            'CREATED USER {user} WITH PASSWORD {password}\n'
            .format(user=user, password=password))

        """ initialize user-schema """
        old_schema = self.schema
        self.initialized = False
        self.schema = user
        self._initialize(con)

        """ Privileges on user-schema"""
        cur.execute(
            'GRANT {privileges} ON SCHEMA {user} TO {user};'
            .format(privileges=', '.join(schema_privileges), user=user))
        cur.execute(
            'GRANT {privileges} ON ALL TABLES IN SCHEMA {user} TO {user};'
            .format(privileges=', '.join(table_privileges), user=user))
        cur.execute(
            'GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA {user} TO {user};'
            .format(user=user))
        con.commit()

        if row_limit:
            """ Limit number of rows"""
            for table in ['reaction', 'publication', 'systems',
                          'reaction_system', 'publication_system',
                          'information']:
                table_factor = 1
                if table in ['reaction_system', 'publication_system']:
                    table_factor = 15
                elif table == 'publication':
                    table_factor = 1 / 100
                elif table == 'information':
                    table_factor = 1 / 100

                trigger_function = """
                CREATE OR REPLACE FUNCTION
                check_number_of_rows_{user}_{table}()
                RETURNS TRIGGER AS
                $BODY$
                BEGIN
                    IF (SELECT count(*) FROM {user}.{table}) > {row_limit}
                    THEN
                        RAISE EXCEPTION
                            'INSERT statement exceeding maximum number of rows';
                    END IF;
                    RETURN NEW;
                END;
                $BODY$
                LANGUAGE plpgsql""".format(user=user, table=table,
                                           row_limit=row_limit * table_factor)
                cur.execute(trigger_function)

                trigger = """
                DROP TRIGGER IF EXISTS tr_check_number_of_rows_{user}_{table}
                    on {user}.{table};
                CREATE TRIGGER tr_check_number_of_rows_{user}_{table}
                BEFORE INSERT ON {user}.systems
                FOR EACH ROW EXECUTE PROCEDURE check_number_of_rows_{user}_{table}();
                """.format(user=user, table=table)
                cur.execute(trigger)

        self.schema = old_schema
        set_schema = 'ALTER ROLE {user} SET search_path TO {schema};'\
                     .format(user=self.user, schema=self.schema)
        cur.execute(set_schema)

        if self.connection is None:
            con.commit()
            con.close()

        return password
240932
def grant(self, column=None, value=None, **kwargs):
        
        return self._resolve_call('GIC_GRANT', column, value, **kwargs)
617705
async function createSchema() {
  await knex.schema
    .dropTableIfExists('Person_Movie')
    .dropTableIfExists('Animal')
    .dropTableIfExists('Movie')
    .dropTableIfExists('Person');

  await knex.schema
    .createTable('Person', table => {
      table.increments('id').primary();
      table
        .integer('parentId')
        .unsigned()
        .references('id')
        .inTable('Person');
      table.string('firstName');
      table.string('lastName');
      table.integer('age');
      table.json('address');
    })
    .createTable('Movie', table => {
      table.increments('id').primary();
      table.string('name');
    })
    .createTable('Animal', table => {
      table.increments('id').primary();
      table
        .integer('ownerId')
        .unsigned()
        .references('id')
        .inTable('Person');
      table.string('name');
      table.string('species');
    })
    .createTable('Person_Movie', table => {
      table.increments('id').primary();
      table
        .integer('personId')
        .unsigned()
        .references('id')
        .inTable('Person')
        .onDelete('CASCADE');
      table
        .integer('movieId')
        .unsigned()
        .references('id')
        .inTable('Movie')
        .onDelete('CASCADE');
    });
}
798773
function ( req ) {

    var pk = req.options.id || (req.options.where && req.options.where.id) || req.param('id');

    // TODO: make this smarter...
    // (e.g. look for actual primary key of model and look for it
    //  in the absence of `id`.)
    // See coercePK for reference (although be aware it is not currently in use)

    // exclude criteria on id field
    pk = _.isPlainObject(pk) ? undefined : pk;
    return pk;
  }
1009784
function SchemaBuilder(client) {
  this.client = client;
  this._sequence = [];

  if (client.config) {
    this._debug = client.config.debug;
    saveAsyncStack(this, 4);
  }
}
1024493
function ImmutableCoreModelSelect (args) {
    // create select object to store state of select
    var select = {}
    // model query will be performed on
    select.model = args.model
    // current context of query
    select.context
    // data associated with context
    select.contextData = {}
    // true if next property access should be column name
    select.expectColumn = false
    // all properties
    select.history = []
    // query to be performed
    select.query = {
        session: args.session,
    }
    // create proxy to map property accesses to query builder commands
    select.proxy = new Proxy({}, {
        // proxy handler with get function that passes select object
        // along with the requested property to the actual handler
        get: function (target, property) {
            return getProxy(select, property)
        }
    })
    // return proxy
    return select.proxy
}
393201
def get(self, event):
        """"""
        self.log("Schemarequest for", event.data, "from",
                 event.user, lvl=debug)
        if event.data in schemastore:
            response = {
                'component': 'hfos.events.schemamanager',
                'action': 'get',
                'data': l10n_schemastore[event.client.language][event.data]
            }
            self.fireEvent(send(event.client.uuid, response))
        else:
            self.log("Unavailable schema requested!", lvl=warn)
505256
private void handleRevokedGrants(
      String nodeName, Set<ClusterNode.GrantId> grantsToRevoke) {
    for (ClusterNode.GrantId grantId: grantsToRevoke) {
      String sessionHandle = grantId.getSessionId();

      try {
        sessionManager.revokeResource(sessionHandle,
            Collections.singletonList(grantId.getRequestId()));
      } catch (InvalidSessionHandle e) {
        // ignore
        LOG.warn("Found invalid session: " + sessionHandle +
                 " while timing out node: " + nodeName);
      }
    }
  }
731289
def grant_default_usage_install_privileges(cls, cur, schema_name, roles):
        
        cur.execute('ALTER DEFAULT PRIVILEGES IN SCHEMA {0} '
                    'GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO {1};'
                    'ALTER DEFAULT PRIVILEGES IN SCHEMA {0} GRANT EXECUTE ON FUNCTIONS TO {1};'
                    'ALTER DEFAULT PRIVILEGES IN SCHEMA {0} '
                    'GRANT USAGE, SELECT ON SEQUENCES TO {1};'
                    .format(schema_name, roles))
242237
def resolve_grant_endpoint(doi_grant_code):
    """"""
    # jsonresolver will evaluate current_app on import if outside of function.
    from flask import current_app
    pid_value = '10.13039/{0}'.format(doi_grant_code)
    try:
        _, record = Resolver(pid_type='grant', object_type='rec',
                             getter=Record.get_record).resolve(pid_value)
        return record
    except Exception:
        current_app.logger.error(
            'Grant {0} does not exists.'.format(pid_value), exc_info=True)
        raise
53127
function (ds, opts) {
            opts = opts || {};
            var schema = opts.schema, ret = ds;
            if (schema) {
                ds = ds.filter({"pg_namespace__nspname": schema});
            } else {
                ds = ds.exclude({"pg_namespace__nspname": this.EXCLUDE_SCHEMAS});
            }
            return ds;
        }
21170
function(publicKey, aclRuleId, callback) {
        request.get(
            this.getResourceUrl({
                path: '/keys/' + publicKey + '/access/' + aclRuleId,
                user: null
            }),
            function onAccessControlRulesResponse(err, res, body) {
                callback(err, body, res);
            }
        );
        return this;
    }
703849
public void revoke(OrderedHashSet granteeList, SchemaObject dbObject,
                       Right rights, Grantee grantor, boolean grantOption,
                       boolean cascade) {

        if (!grantor.isFullyAccessibleByRole(dbObject)) {
            throw Error.error(ErrorCode.X_42501, dbObject.getName().name);
        }

        if (grantor.isAdmin()) {
            grantor = dbObject.getOwner();
        }

        for (int i = 0; i < granteeList.size(); i++) {
            String  name = (String) granteeList.get(i);
            Grantee g    = get(name);

            if (g == null) {
                throw Error.error(ErrorCode.X_28501, name);
            }

            if (isImmutable(name)) {
                throw Error.error(ErrorCode.X_28502, name);
            }
        }

        for (int i = 0; i < granteeList.size(); i++) {
            String  name = (String) granteeList.get(i);
            Grantee g    = get(name);

            g.revoke(dbObject, rights, grantor, grantOption);
            g.updateAllRights();

            if (g.isRole) {
                updateAllRights(g);
            }
        }
    }
15530
function getSchema(connection) {
  const schema_sql = connection.schema_sql
    ? connection.schema_sql
    : SCHEMA_SQL_INFORMATION_SCHEMA;
  return runQuery(schema_sql, connection).then(queryResult =>
    formatSchemaQueryResults(queryResult)
  );
}
932767
function select(state) {
  return {
    visibleTodos: selectTodos(state.todos, state.visibilityFilter),
    visibilityFilter: state.visibilityFilter
  };
}
694367
def grant_user_access(self, user, db_names, strict=True):
        
        return self._user_manager.grant_user_access(user, db_names,
                strict=strict)
717559
def user_grants(user,
                host='localhost', **connection_args):
    '''
    
    '''
    if not user_exists(user, host, **connection_args):
        log.info('User \'%s\'@\'%s\' does not exist', user, host)
        return False

    dbc = _connect(**connection_args)
    if dbc is None:
        return False
    cur = dbc.cursor()
    qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
    args = {}
    args['user'] = user
    args['host'] = host
    try:
        _execute(cur, qry, args)
    except MySQLdb.OperationalError as exc:
        err = 'MySQL Error {0}: {1}'.format(*exc.args)
        __context__['mysql.error'] = err
        log.error(err)
        return False

    ret = []
    results = salt.utils.data.decode(cur.fetchall())
    for grant in results:
        tmp = grant[0].split(' IDENTIFIED BY')[0]
        if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
            tmp = '{0} WITH GRANT OPTION'.format(tmp)
        ret.append(tmp)
    log.debug(ret)
    return ret