How to get "COUNT(*)" in Supabase - supabase

I want to retrieve row count in Supabase.
I am guessing it would be something like this:
const { data, error } = await supabase
.from('cities')
.select('name', 'COUNT(*)')
Is this possible with Supabase?

For future visitors, we are working on this functionality with the PostgREST maintainer:
https://github.com/supabase/postgrest-js/issues/94
(I'm a maintainer)
This is now released:
const { data, count } = supabase
.from('countries')
.select('*', { count: 'exact', head: true })
If you want to return the results simultaneously, remove head:
const { data, count } = supabase
.from('countries')
.select('*', { count: 'exact' })

As a workaround, you could write a standard Postgres stored procedure or function that returns the count then call that via the SB client.
https://supabase.io/docs/client/rpc

It is currently not supported yet, but there is a WIP issue on Github that would bring this feature to Supabase.
The code below has not been implemented in Supabase yet, but it might look something like this:
const { data, error, count } = await supabase
.from('table')
.select('*')
.gt('id', 10)
.count()
Edit 7.19.2021
As kiwicopple has answered, this feature has been added to Supabase with a slightly different form from what I have above. View the accepted answer for more.

Related

How to get query sys_id of current.sys_id Service Portal (ServiceNow)

I have a question regarding a small issue that I'm having. I've created a widget that will live on the Service Portal to allow an admin to Accept or Reject requests.
The data for the widget is pulling from the Approvals (approval_approver) table. Under my GlideRecord, I have a query that checks for the state as requested. (Ex. addQuery('state', 'requested'))
To narrow down the search, I tried entering addQuery('sys_id', current.sys_id). When I use this query, my script breaks and I get an error on the Service Portal end.
Here's a sample of the GlideRecord script I've written to Accept.
[//Accept Request
if(input && input.action=="acceptApproval") {
var inRec1 = new GlideRecord('sysapproval_approver');
inRec1.addQuery('state', 'requested');
//inRec1.get('sys_id', current.sys_id);
inRec1.query();
if(inRec1.next()) {
inRec1.setValue('state', 'Approved');
inRec1.setValue('approver', gs.getUserID());
gs.addInfoMessage("Accept Approval Processed");
inRec1.update();
}
}][1]
I've research the web, tried using $sp.getParameter() as a work-around and no change.
I would really appreciate any help or insight on what I can do different to get script to work and filter the right records.
If I understand your question correctly, you are asking how to get the sysId of the sysapproval_approver record from the client-side in a widget.
Unless you have defined current elsewhere in your server script, current is undefined. Secondly, $sp.getParameter() is used to retrieve URL parameters. So unless you've included the sysId as a URL parameter, that will not get you what you are looking for.
One pattern that I've used is to pass an object to the client after the initial query that gets the list of requests.
When you're ready to send input to the server from the client, you can add relevant information to the input object. See the simplified example below. For the sake of brevity, the code below does not include error handling.
// Client-side function
approveRequest = function(sysId) {
$scope.server.get({
action: "requestApproval",
sysId: sysId
})
.then(function(response) {
console.log("Request approved");
});
};
// Server-side
var requestGr = new GlideRecord();
requestGr.addQuery("SOME_QUERY");
requestGr.query(); // Retrieve initial list of requests to display in the template
data.requests = []; // Add array of requests to data object to be passed to the client via the controller
while(requestsGr.next()) {
data.requests.push({
"number": requestsGr.getValue("number");
"state" : requestsGr.getValue("state");
"sysId" : requestsGr.getValue("sys_id");
});
}
if(input && input.action=="acceptApproval") {
var sysapprovalGr = new GlideRecord('sysapproval_approver');
if(sysapprovalGr.get(input.sysId)) {
sysapprovalGr.setValue('state', 'Approved');
sysapprovalGr.setValue('approver', gs.getUserID());
sysapprovalGr.update();
gs.addInfoMessage("Accept Approval Processed");
}
...

Bring entities on draft mode Strapi

Scenario
I'm trying to get all entities from an endpoint, the ones on draft mode, and the ones on published mode.
I know that if I want to post on draft mode, I have to post published_at on null on the body request.
If I do:
/posts?published_at_null=true
that returns an empty array.
Question
How can I do to return ALL the posts?
It is on the documentation
https://strapi.io/documentation/developer-docs/latest/developer-resources/content-api/content-api.html#publication-state
But quick answer, URL + '?_publicationState=preview'
https://forum.strapi.io/t/draft-and-posted-entities/3576/2
you will have to create a custom control that will fetch all the entries.you cannot fetch draft data using the existing restapi urls.
const { sanitizeEntity } = require('strapi-utils');
module.exports = {
async findUnpublished(ctx) {
//getting all the existing articles, no meter if they have unpublished status
let result = await strapi.query('posts').find();
//sanitize them to hide all private fields
let articles = sanitizeEntity(result, {
model: strapi.models['posts'],
});
//return result to the /findUnpublished API
ctx.send(articles);
}
};

I'm fetching with find and i need to get latest published article in conjunction with limit in Strapi

const { data } = await this.$axios.get(`/articles?_sort=published:ASC&_limit=9`)
Is there a way to actually sort on date or do I need to write my own custom route?
If am to build my custom route, what kind of query should I be using?
const { data } = await this.$axios.get(`/articles?_sort=published:desc&_limit=9`)
You were sorting by asc not desc

request.object.id not returning in afterSave() in Cloud Code

Parse.Cloud.afterSave(function(request) {
var type = request.object.get("type");
switch (type) {
case 'inspiration':
var query = new Parse.Query("Inspiration");
break;
case 'event':
var query = new Parse.Query("Event");
break;
case 'idea':
var query = new Parse.Query("Idea");
break;
case 'comment':
break;
default:
return;
}
if (query) {
query.equalTo("shares", request.object.id);
query.first({
success: function(result) {
result.increment("sharesCount");
result.save();
},
error: function(error) {
throw "Could not save share count: " + error.message;
}
});
}
});
For some reason request.object.id is not returning the object id from the newly created record. I've tested this code out throughly and have isolated it down to the request.object.id variable. I've even successfully ran it with using a pre-existing object ID and it worked fine. Am I using the wrong variable for the object ID?
Thanks in advanced for any help!
Had this exact problem a few weeks ago.
It turned out to be a bug in Parse's newest Javascript SDK. Please have a look at your CloudCode folder - it should contain a global.json file where you can specify the JavaScript SDK version. By default, it states "latest", change it to "1.4.2" and upload your CloudCode folder again.
In case the global.json file is missing in your cloud code folder, please have a look at this thread, where I described how to create it manually.
Thanks for the reply. I found out another work around for this for version 1.6.5. I should probably also mention that my use case for this code is to increment a count column (comments count) when a new relation has been added to a particular record (post).
Instead of implementing an afterSave method on my relation class (comment), I instead implemented a beforeSave method on my class (Post) and used request.object.dirtyKeys() to get my modified columns. From there I check to see if my dirty key was comments and if it is I increment my count column. It works pretty well actually.

How do you delete roles in Parse.com using Cloud Code

How do you delete roles in Parse.com using Cloud Code? I checked: https://parse.com/docs/js/symbols/Parse.Role.html, and it doesn't document any destroy method.
I am creating a role for every group of members, and I'd like to get rid of the role when the group is destroyed. What is the correct way of doing so?
Have you seen:
role.getUsers().remove(user);
This one works for me:
const roles = await new Parse.Query(Parse.Role).find();
await Parse.Object.destroyAll(roles, {useMasterKey: true}};
I played around with this for hours before getting it to work by fluke (no thanks to deficient and incorrect documentation)...
This is architecturally incorrect but the only way I could hack it together was using async function with await + promise... I do not understand Parse's weird mechanics sometimes. It's a love & hate relationship!
// Get user to delete object
let userToDeleteObject = await new Parse.Query(Parse.User)
.equalTo('objectId', userToDelete)
.find({useMasterKey: true});
// Remove user from group role
let roleDeleteQuery = new Parse.Query(Parse.Role);
roleDeleteQuery.contains("name", groupName);
roleDeleteQuery.first({useMasterKey: true})
.then(function(roleObject) {
roleObject.relation("users").remove(userToDeleteObject);
roleObject.save(null, {useMasterKey: true});
});

Resources