Skip to content

Commit

Permalink
init sub query
Browse files Browse the repository at this point in the history
  • Loading branch information
baxiry committed Jul 8, 2024
1 parent df4d2eb commit 4c5c5c6
Show file tree
Hide file tree
Showing 6 changed files with 114 additions and 35 deletions.
17 changes: 14 additions & 3 deletions engine/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ func match(filter gjson.Result, data string) (result bool, err error) {
//fmt.Println("here with: ", subQueryKey.String())

switch subQueryKey.String() {

// comparition
case "$gt":
if !(dataVal.String() > subQueryVal.String()) {
result = false
Expand Down Expand Up @@ -62,24 +64,25 @@ func match(filter gjson.Result, data string) (result bool, err error) {
}
return result

//
case "$or": // not in

result = false
return result

case "$st": // is start with
case "$st": // is it start with ?
if !strings.HasPrefix(dataVal.String(), subQueryVal.String()) {
result = false
}
return result

case "$en": // is end with
case "$en": // is it end with
if !strings.HasSuffix(dataVal.String(), subQueryVal.String()) {
result = false
}
return result

case "$c": // is contains
case "$c": // is it contains
if !strings.Contains(dataVal.String(), subQueryVal.String()) {
result = false
}
Expand Down Expand Up @@ -130,6 +133,7 @@ func match(filter gjson.Result, data string) (result bool, err error) {
result = false
}
return result

case "$in": // in array
for _, v := range subQueryVal.Array() {
if dataVal.String() == v.String() {
Expand All @@ -148,7 +152,14 @@ func match(filter gjson.Result, data string) (result bool, err error) {
}
return result

//case "$ins": // is it is sub query ?

default:
if subQueryKey.Str == "$ins" {
fmt.Println("queryVal : ", subQueryVal.Raw)
fmt.Println("ids: ", getIds(subQueryVal))
}

// {$and:[{name:{$eq:"adam"}},{name:{$eq:"jawad"}}]}
// {$or: [{name:{$eq:"adam"}}, {name:{$eq:"jawad"}}]}

Expand Down
14 changes: 14 additions & 0 deletions engine/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,20 @@ import (
"github.com/tidwall/gjson"
)

func (db *DB) CreateCollection(collection string) error {
query := fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %s (record json);`, collection)
_, err := db.db.Exec(query)
if err != nil {
return err
}
lid, err := getLastId(db.db, collection)
if err != nil {
return err
}
db.lastid[collection] = lid
return nil
}

func getCollections() string {
table, result := "", `["`
res, err := db.db.Query("SELECT name FROM sqlite_master WHERE type='table'")
Expand Down
71 changes: 68 additions & 3 deletions engine/queries.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,70 @@ func (db *DB) updateById(query gjson.Result) (result string) {
return id + " updated"
}

func getIds(query gjson.Result) string {

coll := query.Get("collection").Str
if coll == "" {
return `{"error":"forgot collection name "}`
}

mtch := query.Get("match")

if mtch.String() == "" {
fmt.Println("match.Str is empty")
}

skip := query.Get("skip").Int()
limit := query.Get("limit").Int()
if limit == 0 {
limit = 100
}

stmt := `select rowid, record from ` + coll

rows, err := db.db.Query(stmt)
if err != nil {
return err.Error()
}
defer rows.Close()

record := ""
rowids := ""
rowid := ""

for rows.Next() {
if limit == 0 {
break
}
if skip != 0 {
skip--
continue
}

record = ""
rowid = ""
err := rows.Scan(&rowid, &record)
if err != nil {
return err.Error() // TODO standaring errors
}

ok, err := match(mtch, record)
if err != nil {
return err.Error()
}

if ok {
rowids += rowid + ","
limit--
}
}

if rowids == "" {
return ""
}
return rowids[:len(rowids)-1]
}

// Find finds any obs match creteria.
func (db *DB) findMany(query gjson.Result) (res string) {

Expand Down Expand Up @@ -255,14 +319,13 @@ func (db *DB) findMany(query gjson.Result) (res string) {
order := query.Get("orderBy").Str
reverse := query.Get("reverse").Int()

fmt.Println("reverse :", reverse)
if order != "" {
listData = orderBy(order, int(reverse), listData)
}

// TODO aggrigate here

// remove|rename some fields
// remove or rename some fields
flds := query.Get("fields")
listData = reFields(listData, flds)

Expand Down Expand Up @@ -394,10 +457,12 @@ func (db *DB) findById(query gjson.Result) (res string) {
// Insert
func (db *DB) insertOne(query gjson.Result) (res string) {
coll := query.Get("collection").Str
data := query.Get("data").Str
data := query.Get("data").String() // .Str not works with json obj
fmt.Println(coll, "\n", data)

err := db.insert(coll, data)
if err != nil {
fmt.Println(err)
return err.Error()
}

Expand Down
18 changes: 3 additions & 15 deletions engine/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,30 +86,18 @@ func (db *DB) insert(collection, obj string) error {

db.lastid[collection]++
data := `{"_id":` + fmt.Sprint(db.lastid[collection]) + ", " + d[1:]
fmt.Println("data: ", data)
fmt.Println("coll: ", collection)
_, err := db.db.Exec(`insert into ` + collection + `(record) values('` + data + `');`) // fast
if err != nil {
//println(err)
fmt.Println(err)
db.lastid[collection]--
return err
}

return nil
}

func (db *DB) CreateCollection(collection string) error {
query := fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %s (record json);`, collection)
_, err := db.db.Exec(query)
if err != nil {
return err
}
lid, err := getLastId(db.db, collection)
if err != nil {
return err
}
db.lastid[collection] = lid
return nil
}

// Close db
func (db *DB) Close() {
db.db.Close()
Expand Down
2 changes: 2 additions & 0 deletions static/reconnect.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

27 changes: 13 additions & 14 deletions static/shell.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ for (let [key, value] of Object.entries(yourobject)) {


// This configuration is suitable for development situation
const configs = {debug: false, reconnectDecay:1 , reconnectInterval: 200, reconnectDecay:1, maxReconnectInterval:200}
//const configs = {debug: false, reconnectDecay:1 , reconnectInterval: 200, reconnectDecay:1, maxReconnectInterval:200}

// WebSocket
var ws = new ReconnectingWebSocket('ws://localhost:1111/ws');


function connection() {

ws.onopen = function(){
Expand Down Expand Up @@ -74,28 +75,28 @@ queryInput.addEventListener('keydown', function(event) {


function prettyJSON(jsonString) {
try {
try {
const jsonObject = JSON.parse(jsonString);
let res = JSON.stringify(jsonObject, null, 3);
return res
} catch (error) {
console.log("invalid json")
} catch (error) {
console.error("invalid json")
return jsonString;
}
}
}
}

// Dealing with Textarea Height
function calcHeight(value) {
let numberOfLineBreaks = (value.match(/\n/g) || []).length;
let numberOfLineBreaks = (value.match(/\n/g) || []).length;
if (numberOfLineBreaks < 3) {
numberOfLineBreaks = 3
}
console.log("lines:",numberOfLineBreaks)
// min-height + lines x line-height + padding + border
let newHeight = 20 + numberOfLineBreaks * 20 + 12 + 2;
//console.log("lines:",numberOfLineBreaks)
// min-height + lines x line-height + padding + border
let newHeight = 20 + numberOfLineBreaks * 20 + 12 + 2;

return newHeight;
return newHeight;
}

let textarea = document.querySelector("textarea");
Expand All @@ -108,12 +109,10 @@ textarea.addEventListener("keyup", () => {
connection()

$(document).on("keypress", function (e) {
console.log("event : ", e)
console.log("input : ", $("#query-input").val())

// console.log("event : ", e)
// console.log("input : ", $("#query-input").val())
// TODO some hilit for js object
});

// var queryShow = ""


0 comments on commit 4c5c5c6

Please sign in to comment.