Retrieving User instances from table rows using SELECT JSON
764803
private static void selectJsonRow(CqlSession session) {

    // Reading the whole row as a JSON object
    Statement stmt =
        selectFrom("examples", "json_jsr353_row")
            .json()
            .all()
            .whereColumn("id")
            .in(literal(1), literal(2))
            .build();

    ResultSet rows = session.execute(stmt);

    for (Row row : rows) {
      // SELECT JSON returns only one column for each row, of type VARCHAR,
      // containing the row as a JSON payload.
      // Note that the codec requires that the type passed to the get() method
      // be always JsonStructure, and not a subclass of it, such as JsonObject,
      // hence the need to downcast to JsonObject manually
      JsonObject user = (JsonObject) row.get(0, JsonStructure.class);
      System.out.printf("Retrieved user: %s%n", user);
    }
  }
223750
@GET
	@Path("/{keyspace}/{columnFamily}/{key}")
	public JSONObject getRow(@PathParam("keyspace") String keyspace, @PathParam("columnFamily") String columnFamily,
			@PathParam("key") String key, @HeaderParam(CONSISTENCY_LEVEL_HEADER) String consistencyLevel)
			throws Exception {
		if (logger.isDebugEnabled())
			logger.debug("Getting row [" + keyspace + "]:[" + columnFamily + "]:[" + key + "]");

		return getCassandraStorage().getSlice(keyspace, columnFamily, key,
				config.getConsistencyLevel(consistencyLevel));
	}
1158913
@Override
    public <E> List<E> getColumnsById(String schemaName, String joinTableName, String joinColumnName,
            String inverseJoinColumnName, Object parentId, Class columnJavaType)
    {
        StringBuffer sqlQuery = new StringBuffer();
        sqlQuery.append("SELECT ").append(inverseJoinColumnName).append(" FROM ")
                .append(getFromClause(schemaName, joinTableName)).append(" WHERE ").append(joinColumnName).append("='")
                .append(parentId).append("'");

        Session s = getSession();

        SQLQuery query = s.createSQLQuery(sqlQuery.toString());

        List<E> foreignKeys = new ArrayList<E>();

        foreignKeys = query.list();

        return foreignKeys;
    }
748584
def fetch(table, cols="*", where=(), group="", order=(), limit=(), **kwargs):
    """"""
    return select(table, cols, where, group, order, limit, **kwargs).fetchall()
880338
private Object[] findIdsByColumn(String tableName, String columnName, Object columnValue)
    {
        Object connection = null;

        try
        {
            connection = getConnection();
            String valueAsStr = PropertyAccessorHelper.getString(columnValue);

            Set<String> results = null;

            if (resource != null && resource.isActive())
            {
                Response response = ((Transaction) connection).zrangeByScore(getHashKey(tableName, columnName),
                        getDouble(valueAsStr), getDouble(valueAsStr));
                // ((Transaction) connection).exec();
                ((RedisTransaction) resource).onExecute(((Transaction) connection));

                results = (Set<String>) response.get();
            }
            else
            {
                results = ((Jedis) connection).zrangeByScore(getHashKey(tableName, columnName), getDouble(valueAsStr),
                        getDouble(valueAsStr));

            }
            if (results != null)
            {
                return results.toArray(new Object[0]);
            }

        }
        finally
        {
            onCleanup(connection);
        }

        return null;
    }
1259283
def _populate(self, json):
        
        Base._populate(self, json)

        mapped_udfs = []
        for udf in self.user_defined_fields:
            t = UserDefinedFieldType.text
            choices = None
            if hasattr(udf, 'oneof'):
                t = UserDefinedFieldType.select_one
                choices = udf.oneof.split(',')
            elif hasattr(udf, 'manyof'):
                t = UserDefinedFieldType.select_many
                choices = udf.manyof.split(',')

            mapped_udfs.append(UserDefinedField(udf.name,
                    udf.label if hasattr(udf, 'label') else None,
                    udf.example if hasattr(udf, 'example') else None,
                    t, choices=choices))

        self._set('user_defined_fields', mapped_udfs)
        ndist = [ Image(self._client, d) for d in self.images ]
        self._set('images', ndist)
167232
def get_database_users(self):
        """"""
        url = "db/{0}/users".format(self._database)

        response = self.request(
            url=url,
            method='GET',
            expected_response_code=200
        )

        return response.json()
713820
def select(query, data=None):
    
    connection = _State.connection()
    _State.new_transaction()
    if data is None:
        data = []

    result = connection.execute('select ' + query, data)

    rows = []
    for row in result:
        rows.append(dict(list(row.items())))

    return rows
209524
synchronized JSONObject fetchEvents(Table table, final int limit) {
        final String tName = table.getName();
        Cursor cursor = null;
        String lastId = null;

        final JSONArray events = new JSONArray();

        //noinspection TryFinallyCanBeTryWithResources
        try {
            final SQLiteDatabase db = dbHelper.getReadableDatabase();
            cursor = db.rawQuery("SELECT * FROM " + tName +
                    " ORDER BY " + KEY_CREATED_AT + " ASC LIMIT " + limit, null);


            while (cursor.moveToNext()) {
                if (cursor.isLast()) {
                    lastId = cursor.getString(cursor.getColumnIndex("_id"));
                }
                try {
                    final JSONObject j = new JSONObject(cursor.getString(cursor.getColumnIndex(KEY_DATA)));
                    events.put(j);
                } catch (final JSONException e) {
                    // Ignore
                }
            }
        } catch (final SQLiteException e) {
            getConfigLogger().verbose("Could not fetch records out of database " + tName + ".", e);
            lastId = null;
        } finally {
            dbHelper.close();
            if (cursor != null) {
                cursor.close();
            }
        }

        if (lastId != null) {
            try {
                final JSONObject ret = new JSONObject();
                ret.put(lastId, events);
                return ret;
            } catch (JSONException e) {
                // ignore
            }
        }

        return null;
    }
1027113
def get_user_by_key(id, key, fields = {})
      data = {
          'id' => id,
          'key' => key,
          'fields' => fields
      }
      api_get(:user, data)
    end
39956
function sendSuccessAnswer(table, res, id, field) {
    if(typeof field === "undefined") {
        if(id === 0) {
            //Just assume that everything went okay. It looks like a non numeric primary key.
            res.send({
                result: 'success',
                table: table
            });
            return;
        } else {
            field = "id";
        }
    }
    lastQry = connection.query('SELECT * FROM ?? WHERE ?? = ?', [table, field, id] , function (err, rows) {
        if (err) {
            sendError(res, err.code)
        } else {
            res.send({
                result: 'success',
                json: rows,
                table: table
            });
        }
    });
}
110441
private T extractKeyAndRow(String timestamp, JSONObject jsonRow) {
        T rowValues = null;
        try {
            rowValues = rowMapper.newInstance();
            rowValues.getClass().getMethod("setTimestamp", String.class).invoke(rowValues, timestamp);
            for (Object key : jsonRow.keySet()) {
                Util.applyKVToBean(rowValues, key.toString(), jsonRow.get(key.toString()));
            }

        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException ex) {
            Logger.getLogger(Mapper4Bean.class.getName()).log(Level.SEVERE, null, ex);
        }
        return rowValues;
    }
1038776
def GetUsers(self, rowlimit=0):
        

        # Build Request
        soap_request = soap('GetListItems')
        soap_request.add_parameter('listName', 'UserInfo')

        # Set Row Limit
        soap_request.add_parameter('rowLimit', str(rowlimit))
        self.last_request = str(soap_request)

        # Send Request
        response = self._session.post(url=self._url('Lists'),
                                      headers=self._headers('GetListItems'),
                                      data=str(soap_request),
                                      verify=self._verify_ssl,
                                      timeout=self.timeout)

        # Parse Response
        if response.status_code != 200:
            raise ConnectionError('GetUsers GetListItems request failed')
        try:
            envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
        except:
            raise ConnectionError("GetUsers GetListItems response failed to parse correctly")
        listitems = envelope[0][0][0][0][0]
        data = []
        for row in listitems:
            # Strip the 'ows_' from the beginning with key[4:]
            data.append({key[4:]: value for (key, value) in row.items() if key[4:]})

            return {'py': {i['ImnName']: i['ID'] + ';#' + i['ImnName'] for i in data},
                    'sp': {i['ID'] + ';#' + i['ImnName']: i['ImnName'] for i in data}}
444362
def _record_from_json(value, field):
    """"""
    if _not_null(value, field):
        record = {}
        record_iter = zip(field.fields, value["f"])
        for subfield, cell in record_iter:
            converter = _CELLDATA_FROM_JSON[subfield.field_type]
            if subfield.mode == "REPEATED":
                value = [converter(item["v"], subfield) for item in cell["v"]]
            else:
                value = converter(cell["v"], subfield)
            record[subfield.name] = value
        return record
458560
function runQuery(query, connection, user) {
  const driver = drivers[connection.driver];

  const queryResult = {
    id: uuid.v4(),
    cacheKey: null,
    startTime: new Date(),
    stopTime: null,
    queryRunTime: null,
    fields: [],
    incomplete: false,
    meta: {},
    rows: []
  };

  return driver.runQuery(query, connection).then(results => {
    const { rows, incomplete } = results;
    if (!Array.isArray(rows)) {
      throw new Error(`${connection.driver}.runQuery() must return rows array`);
    }

    queryResult.incomplete = incomplete || false;
    queryResult.rows = rows;
    queryResult.stopTime = new Date();
    queryResult.queryRunTime = queryResult.stopTime - queryResult.startTime;
    queryResult.meta = getMeta(rows);
    queryResult.fields = Object.keys(queryResult.meta);

    if (debug) {
      const connectionName = connection.name;
      const rowCount = rows.length;
      const { startTime, stopTime, queryRunTime } = queryResult;

      console.log(
        JSON.stringify({
          userId: user && user._id,
          userEmail: user && user.email,
          connectionName,
          startTime,
          stopTime,
          queryRunTime,
          rowCount,
          query
        })
      );
    }

    return queryResult;
  });
}
1326158
function (req, res) {

            req.params.table = escape(req.params.table);

            //Request DB structure
            lastQry = connection.query('SHOW COLUMNS FROM ??', req.params.table, function (err, columns) {

                //Get primary key of table if not specified via query
                var field = findPrim(columns, req.query[settings.paramPrefix + 'field']);

                lastQry = connection.query('SELECT * FROM ?? WHERE ??.?? IN (' + req.params.id + ')', [req.params.table, req.params.table, field], function (err, rows) {
                    if (err) return sendError(res, err.code);
                    res.send({
                        result: 'success',
                        json: rows,
                        table: req.params.table,
                        length: rows.length
                    });
                });
            });

        }
938586
def _rows_from_json(values, schema):
    """"""
    from google.cloud.bigquery import Row

    field_to_index = _field_to_index_mapping(schema)
    return [Row(_row_tuple_from_json(r, schema), field_to_index) for r in values]