Skip to content

Commit 03e5ef0

Browse files
author
Anand
committed
ref issue #10 - Search multiple terms using AND operator
1 parent e9e697f commit 03e5ef0

File tree

1 file changed

+68
-1
lines changed

1 file changed

+68
-1
lines changed

db.go

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,7 @@ func addNewDatabaseEntry(title, userName, url, passwd, notes string, customEntri
229229

230230
err, db = openActiveDatabase()
231231
if err == nil && db != nil {
232-
// result := db.Debug().Create(&entry)
232+
// result := db.Debug().Create(&entry)
233233
result := db.Create(&entry)
234234
if result.Error == nil && result.RowsAffected == 1 {
235235
// Add custom fields if given
@@ -341,6 +341,73 @@ func searchDatabaseEntry(term string) (error, []Entry) {
341341

342342
}
343343

344+
// Union of two entry arrays
345+
func union(entry1 []Entry, entry2 []Entry) []Entry {
346+
347+
m := make(map[int]bool)
348+
349+
for _, item := range entry1 {
350+
m[item.ID] = true
351+
}
352+
353+
for _, item := range entry2 {
354+
if _, ok := m[item.ID]; !ok {
355+
entry1 = append(entry1, item)
356+
}
357+
}
358+
359+
return entry1
360+
}
361+
362+
// Intersection of two entry arrays
363+
func intersection(entry1 []Entry, entry2 []Entry) []Entry {
364+
365+
var common []Entry
366+
367+
m := make(map[int]bool)
368+
369+
for _, item := range entry1 {
370+
m[item.ID] = true
371+
}
372+
373+
for _, item := range entry2 {
374+
if _, ok := m[item.ID]; ok {
375+
common = append(common, item)
376+
}
377+
}
378+
379+
return common
380+
}
381+
382+
// Search database for the given terms and returns matches according to operator
383+
func searchDatabaseEntries(terms []string, operator string) (error, []Entry) {
384+
385+
var err error
386+
var finalEntries []Entry
387+
388+
for idx, term := range terms {
389+
var entries []Entry
390+
391+
err, entries = searchDatabaseEntry(term)
392+
if err != nil {
393+
fmt.Printf("Error searching for term: %s - \"%s\"\n", term, err.Error())
394+
return err, entries
395+
}
396+
397+
if idx == 0 {
398+
finalEntries = entries
399+
} else {
400+
if operator == "AND" {
401+
finalEntries = intersection(finalEntries, entries)
402+
} else if operator == "OR" {
403+
finalEntries = union(finalEntries, entries)
404+
}
405+
}
406+
}
407+
408+
return nil, finalEntries
409+
}
410+
344411
// Remove a given database entry
345412
func removeDatabaseEntry(entry *Entry) error {
346413

0 commit comments

Comments
 (0)