Skip to content
This repository was archived by the owner on Sep 2, 2024. It is now read-only.

Commit 3100f49

Browse files
committed
feat: add count function into interface and implement it
1 parent 53e3021 commit 3100f49

File tree

4 files changed

+68
-0
lines changed

4 files changed

+68
-0
lines changed

database/memory/count.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package memory
2+
3+
import (
4+
"github.com/staticbackendhq/core/model"
5+
)
6+
7+
func (m *Memory) Count(auth model.Auth, dbName, col string, filter map[string]interface{}) (int64, error) {
8+
list, err := all[map[string]any](m, dbName, col)
9+
if err != nil {
10+
return -1, err
11+
}
12+
13+
list = secureRead(auth, col, list)
14+
15+
filtered := filterByClauses(list, filter)
16+
17+
return int64(len(filtered)), nil
18+
}

database/mongo/count.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package mongo
2+
3+
import (
4+
"github.com/staticbackendhq/core/model"
5+
)
6+
7+
func (mg *Mongo) Count(auth model.Auth, dbName, col string, filter map[string]interface{}) (count int64, err error) {
8+
db := mg.Client.Database(dbName)
9+
10+
acctID, userID, err := parseObjectID(auth)
11+
if err != nil {
12+
return
13+
}
14+
15+
secureRead(acctID, userID, auth.Role, col, filter)
16+
17+
count, err = db.Collection(model.CleanCollectionName(col)).CountDocuments(mg.Ctx, filter)
18+
if err != nil {
19+
return -1, err
20+
}
21+
22+
return count, nil
23+
}

database/persister.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,4 +142,6 @@ type Persister interface {
142142
DeleteFile(dbName, fileID string) error
143143
// ListAllFiles lists all file
144144
ListAllFiles(dbName, accountID string) ([]model.File, error)
145+
// Count returns the numbers of entries in a collection based on optional filters
146+
Count(auth model.Auth, dbName, col string, filters map[string]interface{}) (int64, error)
145147
}

database/postgresql/count.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package postgresql
2+
3+
import (
4+
"fmt"
5+
6+
"github.com/staticbackendhq/core/model"
7+
)
8+
9+
func (pg *PostgreSQL) Count(auth model.Auth, dbName, col string, filters map[string]interface{}) (count int64, err error) {
10+
where := secureRead(auth, col)
11+
where = applyFilter(where, filters)
12+
13+
query := fmt.Sprintf(`
14+
SELECT COUNT(*)
15+
FROM %s.%s
16+
%s;
17+
`, dbName, model.CleanCollectionName(col), where)
18+
19+
err = pg.DB.QueryRow(query, auth.AccountID, auth.UserID).Scan(&count)
20+
if err != nil {
21+
return -1, err
22+
}
23+
24+
return count, nil
25+
}

0 commit comments

Comments
 (0)