Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

collection.gno

// Package collection provides a generic collection implementation with support for
// multiple indexes, including unique indexes and case-insensitive indexes.
// It is designed to be used with any type and allows efficient lookups using
// different fields or computed values.
//
// Example usage:
//
//	// Define a data type
//	type User struct {
//	    Name     string
//	    Email    string
//	    Age      int
//	    Username string
//	    Tags     []string
//	}
//
//	// Create a new collection
//	c := collection.New()
//
//	// Add indexes with different options
//	c.AddIndex("name", func(v any) string {
//	    return v.(*User).Name
//	}, UniqueIndex)
//
//	c.AddIndex("email", func(v any) string {
//	    return v.(*User).Email
//	}, UniqueIndex|CaseInsensitiveIndex)
//
//	c.AddIndex("age", func(v any) string {
//	    return strconv.Itoa(v.(*User).Age)
//	}, DefaultIndex)  // Non-unique index
//
//	c.AddIndex("username", func(v any) string {
//	    return v.(*User).Username
//	}, UniqueIndex|SparseIndex)  // Allow empty usernames
//
//	// For tags, we index all tags for the user
//	c.AddIndex("tag", func(v any) []string {
//	    return v.(*User).Tags
//	}, DefaultIndex)  // Non-unique to allow multiple users with same tag
//
//	// Store an object
//	id := c.Set(&User{
//	    Name:  "Alice",
//	    Email: "[email protected]",
//	    Age:   30,
//	    Tags:  []string{"admin", "moderator"},  // User can have multiple tags
//	})
//
//	// Retrieve by any index
//	entry := c.GetFirst("email", "[email protected]")
//	adminUsers := c.GetAll("tag", "admin")      // Find all users with admin tag
//	modUsers := c.GetAll("tag", "moderator")    // Find all users with moderator tag
//
// Index options can be combined using the bitwise OR operator.
// Available options:
//   - DefaultIndex: Regular index with no special behavior
//   - UniqueIndex: Ensures values are unique within the index
//   - CaseInsensitiveIndex: Makes string comparisons case-insensitive
//   - SparseIndex: Skips indexing empty values (nil or empty string)
//
// Example: UniqueIndex|CaseInsensitiveIndex for a case-insensitive unique index
//
// # Versioning
//
// This is the B+ tree successor to [gno.land/p/nym-moultest123/collection/v0] (which is
// backed by an AVL tree): a bump to v3 because the backing data structure — and
// thus the on-chain storage layout — changed. The exported API is unchanged from
// v2; only the persisted representation differs, so it is a compatibility (not a
// source) change. A B+ tree packs many entries per persisted node, so each index
// entry costs materially less storage and gas than the AVL backing; prefer v3
// when the collection is part of persisted realm state.
//
// Two operational caveats inherited from the in-place-mutating B+ tree backing:
//
//   - do NOT mutate the collection (Set/Update/Delete) from inside an index
//     iteration callback — the AVL backing's copy-on-write tolerated it, this one
//     does not;
//   - do NOT copy a non-zero Collection by value — the copies would share live
//     tree nodes while their state diverges.
package collection

import (
	"errors"
	"strings"

	"gno.land/p/nt/bptree/v0"
	"gno.land/p/nt/seqid/v0"
)

// New creates a new Collection instance with an initialized ID index.
// The ID index is a special unique index that is always present and
// serves as the primary key for all objects in the collection.
func New() *Collection {
	c := &Collection{
		indexes: make(map[string]*Index),
		idGen:   seqid.ID(0),
	}
	// Initialize _id index
	c.indexes[IDIndex] = &Index{
		options: UniqueIndex,
		tree:    bptree.NewBPTree32(),
	}
	return c
}

// Collection represents a collection of objects with multiple indexes
type Collection struct {
	indexes map[string]*Index
	idGen   seqid.ID
}

const (
	// IDIndex is the reserved name for the primary key index
	IDIndex = "_id"
)

// IndexOption represents configuration options for an index using bit flags
type IndexOption uint64

const (
	// DefaultIndex is a basic index with no special options
	DefaultIndex IndexOption = 0

	// UniqueIndex ensures no duplicate values are allowed
	UniqueIndex IndexOption = 1 << iota

	// CaseInsensitiveIndex automatically converts string values to lowercase
	CaseInsensitiveIndex

	// SparseIndex only indexes non-empty values
	SparseIndex
)

// Index represents an index with its configuration and data.
// The index function can return either:
//   - string: for single-value indexes
//   - []string: for multi-value indexes where one object can be indexed under multiple keys
//
// The backing tree stores either a single ID or []string for multiple IDs per key.
type Index struct {
	fn      any
	options IndexOption
	tree    bptree.ITree
}

// AddIndex adds a new index to the collection with the specified options
//
// Parameters:
//   - name: the unique name of the index (e.g., "tags")
//   - indexFn: a function that extracts either a string or []string from an object
//   - options: bit flags for index configuration (e.g., UniqueIndex)
func (c *Collection) AddIndex(name string, indexFn any, options IndexOption) {
	if name == IDIndex {
		panic("_id is a reserved index name")
	}
	c.indexes[name] = &Index{
		fn:      indexFn,
		options: options,
		tree:    bptree.NewBPTree32(),
	}
}

// storeIndex handles how we store an ID in the index tree
func (idx *Index) store(key string, idStr string) {
	stored := idx.tree.Get(key)
	if stored == nil {
		// First entry for this key
		idx.tree.Set(key, idStr)
		return
	}

	// Handle existing entries
	switch existing := stored.(type) {
	case string:
		if existing == idStr {
			return // Already stored
		}
		// Convert to array
		idx.tree.Set(key, []string{existing, idStr})
	case []string:
		// Check if ID already exists
		for _, id := range existing {
			if id == idStr {
				return
			}
		}
		// Append new ID
		idx.tree.Set(key, append(existing, idStr))
	}
}

// removeIndex handles how we remove an ID from the index tree
func (idx *Index) remove(key string, idStr string) {
	stored := idx.tree.Get(key)
	if stored == nil {
		return
	}

	switch existing := stored.(type) {
	case string:
		if existing == idStr {
			idx.tree.Remove(key)
		}
	case []string:
		newIds := make([]string, 0, len(existing))
		for _, id := range existing {
			if id != idStr {
				newIds = append(newIds, id)
			}
		}
		if len(newIds) == 0 {
			idx.tree.Remove(key)
		} else if len(newIds) == 1 {
			idx.tree.Set(key, newIds[0])
		} else {
			idx.tree.Set(key, newIds)
		}
	}
}

// generateKeys extracts one or more keys from an object for a given index.
func generateKeys(idx *Index, obj any) ([]string, bool) {
	if obj == nil {
		return nil, false
	}

	switch fnTyped := idx.fn.(type) {
	case func(any) string:
		// Single-value index
		key := fnTyped(obj)
		return []string{key}, true
	case func(any) []string:
		// Multi-value index
		keys := fnTyped(obj)
		return keys, true
	default:
		panic("invalid index function type")
	}
}

// Set adds or updates an object in the collection.
// Returns a positive ID if successful.
// Returns 0 if:
//   - The object is nil
//   - A uniqueness constraint would be violated
//   - Index generation fails for any index
func (c *Collection) Set(obj any) uint64 {
	if obj == nil {
		return 0
	}

	// Generate new ID
	id := c.idGen.Next()
	idStr := id.String()

	// Check uniqueness constraints first
	for name, idx := range c.indexes {
		if name == IDIndex {
			continue
		}
		keys, ok := generateKeys(idx, obj)
		if !ok {
			return 0
		}

		for _, key := range keys {
			// Skip empty values for sparse indexes
			if idx.options&SparseIndex != 0 && key == "" {
				continue
			}
			if idx.options&CaseInsensitiveIndex != 0 {
				key = strings.ToLower(key)
			}
			// Only check uniqueness for unique + single-value indexes
			// (UniqueIndex is ambiguous; skipping that scenario)
			if idx.options&UniqueIndex != 0 {
				if existing := idx.tree.Get(key); existing != nil {
					return 0
				}
			}
		}
	}

	// Store in _id index first (the actual object)
	c.indexes[IDIndex].tree.Set(idStr, obj)

	// Store in all other indexes
	for name, idx := range c.indexes {
		if name == IDIndex {
			continue
		}
		keys, ok := generateKeys(idx, obj)
		if !ok {
			// Rollback: remove from _id index
			c.indexes[IDIndex].tree.Remove(idStr)
			return 0
		}

		for _, key := range keys {
			if idx.options&SparseIndex != 0 && key == "" {
				continue
			}
			if idx.options&CaseInsensitiveIndex != 0 {
				key = strings.ToLower(key)
			}
			idx.store(key, idStr)
		}
	}

	return uint64(id)
}

// Get retrieves entries matching the given key in the specified index.
// Returns an iterator over the matching entries.
func (c *Collection) Get(indexName string, key string) EntryIterator {
	idx, exists := c.indexes[indexName]
	if !exists {
		return EntryIterator{err: errors.New("index not found: " + indexName)}
	}

	if idx.options&CaseInsensitiveIndex != 0 {
		key = strings.ToLower(key)
	}

	if indexName == IDIndex {
		// For ID index, validate the ID format first
		_, err := seqid.FromString(key)
		if err != nil {
			return EntryIterator{err: err}
		}
	}

	return EntryIterator{
		collection: c,
		indexName:  indexName,
		key:        key,
	}
}

// GetFirst returns the first matching entry or nil if none found
func (c *Collection) GetFirst(indexName, key string) *Entry {
	iter := c.Get(indexName, key)
	if iter.Next() {
		return iter.Value()
	}
	return nil
}

// Delete removes an object by its ID and returns true if something was deleted
func (c *Collection) Delete(id uint64) bool {
	idStr := seqid.ID(id).String()

	// Get the object first to clean up other indexes
	obj := c.indexes[IDIndex].tree.Get(idStr)
	if obj == nil {
		return false
	}

	// Remove from all indexes
	for name, idx := range c.indexes {
		if name == IDIndex {
			idx.tree.Remove(idStr)
			continue
		}
		keys, ok := generateKeys(idx, obj)
		if !ok {
			continue
		}
		for _, key := range keys {
			if idx.options&CaseInsensitiveIndex != 0 {
				key = strings.ToLower(key)
			}
			idx.remove(key, idStr)
		}
	}
	return true
}

// Update updates an existing object and returns true if successful
// Returns true if the update was successful.
// Returns false if:
//   - The object is nil
//   - The ID doesn't exist
//   - A uniqueness constraint would be violated
//   - Index generation fails for any index
//
// If the update fails, the collection remains unchanged.
func (c *Collection) Update(id uint64, obj any) bool {
	if obj == nil {
		return false
	}
	idStr := seqid.ID(id).String()
	oldObj := c.indexes[IDIndex].tree.Get(idStr)
	if oldObj == nil {
		return false
	}

	// Check unique constraints
	for name, idx := range c.indexes {
		if name == IDIndex {
			continue
		}

		if idx.options&UniqueIndex != 0 {
			newKeys, newOk := generateKeys(idx, obj)
			_, oldOk := generateKeys(idx, oldObj)
			if !newOk || !oldOk {
				return false
			}

			for _, newKey := range newKeys {
				if idx.options&CaseInsensitiveIndex != 0 {
					newKey = strings.ToLower(newKey)
				}

				found := idx.tree.Get(newKey)
				if found != nil {
					if storedID, ok := found.(string); !ok || storedID != idStr {
						return false
					}
				}
			}
		}
	}

	// Store old index entries for potential rollback
	oldEntries := make(map[string][]string)
	for name, idx := range c.indexes {
		if name == IDIndex {
			continue
		}
		oldKeys, ok := generateKeys(idx, oldObj)
		if !ok {
			continue
		}
		var adjusted []string
		for _, okey := range oldKeys {
			if idx.options&CaseInsensitiveIndex != 0 {
				okey = strings.ToLower(okey)
			}
			// Remove the oldObj from the index right away
			idx.remove(okey, idStr)
			adjusted = append(adjusted, okey)
		}
		oldEntries[name] = adjusted
	}

	// Update the object in the _id index
	c.indexes[IDIndex].tree.Set(idStr, obj)

	// Add new index entries
	for name, idx := range c.indexes {
		if name == IDIndex {
			continue
		}
		newKeys, ok := generateKeys(idx, obj)
		if !ok {
			// Rollback: restore old object and old index entries
			c.indexes[IDIndex].tree.Set(idStr, oldObj)
			for idxName, keys := range oldEntries {
				for _, oldKey := range keys {
					c.indexes[idxName].store(oldKey, idStr)
				}
			}
			return false
		}
		for _, nkey := range newKeys {
			if idx.options&CaseInsensitiveIndex != 0 {
				nkey = strings.ToLower(nkey)
			}
			idx.store(nkey, idStr)
		}
	}

	return true
}

// GetAll retrieves all entries matching the given key in the specified index.
func (c *Collection) GetAll(indexName string, key string) []Entry {
	idx, exists := c.indexes[indexName]
	if !exists {
		return nil
	}

	if idx.options&CaseInsensitiveIndex != 0 {
		key = strings.ToLower(key)
	}

	if indexName == IDIndex {
		if obj := idx.tree.Get(key); obj != nil {
			return []Entry{{ID: key, Obj: obj}}
		}
		return nil
	}

	idData := idx.tree.Get(key)
	if idData == nil {
		return nil
	}

	// Handle both single and multi-value cases based on the actual data type
	switch stored := idData.(type) {
	case []string:
		result := make([]Entry, 0, len(stored))
		for _, idStr := range stored {
			if obj := c.indexes[IDIndex].tree.Get(idStr); obj != nil {
				result = append(result, Entry{ID: idStr, Obj: obj})
			}
		}
		return result
	case string:
		if obj := c.indexes[IDIndex].tree.Get(stored); obj != nil {
			return []Entry{{ID: stored, Obj: obj}}
		}
	}
	return nil
}

// GetIndex returns the underlying tree for an index
func (c *Collection) GetIndex(name string) bptree.ITree {
	idx, exists := c.indexes[name]
	if !exists {
		return nil
	}
	return idx.tree
}

collection_test.gno

package collection

import (
	"errors"
	"strconv"
	"strings"
	"testing"

	"gno.land/p/nt/seqid/v0"
	"gno.land/p/nt/ufmt/v0"
)

type Person struct {
	Name     string
	Age      int
	Email    string
	Username string
	Tags     []string
}

func (p Person) String() string {
	return ufmt.Sprintf("name=%s age=%d email=%s username=%s tags=%s",
		p.Name, p.Age, p.Email, p.Username, strings.Join(p.Tags, ","))
}

// TestOperation represents a single operation in a test sequence
type TestOperation struct {
	op      string // "set" or "update"
	person  *Person
	id      uint64 // for updates
	wantID  uint64
	wantErr bool
}

// TestCase represents a complete test case with setup and operations
type TestCase struct {
	name       string
	setupIndex func(*Collection)
	operations []TestOperation
}

func TestBasicOperations(t *testing.T) {
	c := New()

	// Add indexes
	c.AddIndex("name", func(v any) string {
		return v.(*Person).Name
	}, UniqueIndex)
	c.AddIndex("age", func(v any) string {
		return strconv.Itoa(v.(*Person).Age)
	}, DefaultIndex)

	// Test basic Set and Get
	p1 := &Person{Name: "Alice", Age: 30, Email: "[email protected]"}
	id1 := c.Set(p1)
	if id1 == 0 {
		t.Error("Failed to set first object")
	}

	// Get by ID
	iter := c.Get(IDIndex, seqid.ID(id1).String())
	if !iter.Next() {
		t.Error("Failed to get object by ID")
	}
	entry := iter.Value()
	if entry.Obj.(*Person).Name != "Alice" {
		t.Error("Got wrong object")
	}
}

func TestUniqueConstraints(t *testing.T) {
	tests := []struct {
		name   string
		setup  func(*Collection) uint64
		wantID bool
	}{
		{
			name: "First person",
			setup: func(c *Collection) uint64 {
				return c.Set(&Person{Name: "Alice"})
			},
			wantID: true,
		},
		{
			name: "Duplicate name",
			setup: func(c *Collection) uint64 {
				c.Set(&Person{Name: "Alice"})
				return c.Set(&Person{Name: "Alice"})
			},
			wantID: false,
		},
		{
			name: "Same age (non-unique index)",
			setup: func(c *Collection) uint64 {
				c.AddIndex("age", func(v any) string {
					return strconv.Itoa(v.(*Person).Age)
				}, DefaultIndex)
				c.Set(&Person{Name: "Alice", Age: 30})
				return c.Set(&Person{Name: "Bob", Age: 30})
			},
			wantID: true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			c := New()
			c.AddIndex("name", func(v any) string {
				return v.(*Person).Name
			}, UniqueIndex)

			id := tt.setup(c)
			if (id != 0) != tt.wantID {
				t.Errorf("Set() got id = %v, want non-zero: %v", id, tt.wantID)
			}
		})
	}
}

func TestUpdates(t *testing.T) {
	c := New()
	c.AddIndex("name", func(v any) string {
		return v.(*Person).Name
	}, UniqueIndex)
	c.AddIndex("username", func(v any) string {
		return strings.ToLower(v.(*Person).Username)
	}, UniqueIndex|CaseInsensitiveIndex)

	// Initial setup
	p1 := &Person{Name: "Alice", Username: "alice123"}
	p2 := &Person{Name: "Bob", Username: "bob456"}

	id1 := c.Set(p1)
	c.Set(p2)

	tests := []struct {
		name      string
		id        uint64
		newPerson *Person
		wantRet   bool
	}{
		{
			name:      "Update to non-conflicting values",
			id:        id1,
			newPerson: &Person{Name: "Alice2", Username: "alice1234"},
			wantRet:   true,
		},
		{
			name:      "Update to conflicting username",
			id:        id1,
			newPerson: &Person{Name: "Alice2", Username: "bob456"},
			wantRet:   false,
		},
		{
			name:      "Update non-existent ID",
			id:        99999,
			newPerson: &Person{Name: "Test", Username: "test"},
			wantRet:   false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			gotID := c.Update(tt.id, tt.newPerson)
			if gotID != tt.wantRet {
				t.Errorf("Update() got = %v, want %v", gotID, tt.wantRet)
			}
		})
	}
}

func TestDelete(t *testing.T) {
	c := New()
	c.AddIndex("name", func(v any) string {
		return v.(*Person).Name
	}, UniqueIndex)

	p1 := &Person{Name: "Alice"}
	id1 := c.Set(p1)

	tests := []struct {
		name    string
		id      uint64
		wantRet bool
	}{
		{
			name:    "Delete existing object",
			id:      id1,
			wantRet: true,
		},
		{
			name:    "Delete non-existent object",
			id:      99999,
			wantRet: false,
		},
		{
			name:    "Delete already deleted object",
			id:      id1,
			wantRet: false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			gotID := c.Delete(tt.id)
			if gotID != tt.wantRet {
				t.Errorf("Delete() got = %v, want %v", gotID, tt.wantRet)
			}
		})
	}
}

func TestEdgeCases(t *testing.T) {
	c := New()
	c.AddIndex("name", func(v any) string {
		return v.(*Person).Name
	}, UniqueIndex)

	tests := []struct {
		name      string
		operation func() bool
		wantPanic bool
	}{
		{
			name: "Set nil object",
			operation: func() bool {
				return c.Set(nil) != 0
			},
			wantPanic: false,
		},
		{
			name: "Set wrong type",
			operation: func() bool {
				return c.Set("not a person") != 0
			},
			wantPanic: true,
		},
		{
			name: "Update with nil",
			operation: func() bool {
				id := c.Set(&Person{Name: "Test"})
				return c.Update(id, nil)
			},
			wantPanic: false,
		},
		{
			name: "Get with invalid index name",
			operation: func() bool {
				iter := c.Get("invalid_index", "key")
				if iter.Empty() {
					return false
				}
				entry := iter.Value()
				if entry == nil {
					return false
				}
				_, err := seqid.FromString(entry.ID)
				if err != nil {
					return false
				}
				return true
			},
			wantPanic: false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			var got bool
			panicked := false

			func() {
				defer func() {
					if r := recover(); r != nil {
						panicked = true
					}
				}()
				got = tt.operation()
			}()

			if panicked != tt.wantPanic {
				t.Errorf("Operation panicked = %v, want panic = %v", panicked, tt.wantPanic)
			}
			if !panicked && got != false {
				t.Errorf("Operation returned %v, want 0", got)
			}
		})
	}
}

func TestIndexTypes(t *testing.T) {
	c := New()

	// Test different types of indexes
	c.AddIndex("composite", func(v any) string {
		p := v.(*Person)
		return p.Name + ":" + strconv.Itoa(p.Age)
	}, UniqueIndex)

	c.AddIndex("case_insensitive", func(v any) string {
		return strings.ToLower(v.(*Person).Username)
	}, UniqueIndex|CaseInsensitiveIndex)

	// Test composite index
	p1 := &Person{Name: "Alice", Age: 30, Username: "Alice123"}
	id1 := c.Set(p1)
	if id1 == 0 {
		t.Error("Failed to set object with composite index")
	}

	// Test case-insensitive index
	p2 := &Person{Name: "Bob", Age: 25, Username: "alice123"}
	id2 := c.Set(p2)
	if id2 != 0 {
		t.Error("Case-insensitive index failed to prevent duplicate")
	}
}

func TestIndexOptions(t *testing.T) {
	tests := []struct {
		name    string
		setup   func(*Collection) uint64
		wantID  bool
		wantErr bool
	}{
		{
			name: "Unique case-sensitive index",
			setup: func(c *Collection) uint64 {
				c.AddIndex("username", func(v any) string {
					return v.(*Person).Username
				}, UniqueIndex)

				c.Set(&Person{Username: "Alice"})
				return c.Set(&Person{Username: "Alice"}) // Should fail
			},
			wantID: false,
		},
		{
			name: "Unique case-insensitive index",
			setup: func(c *Collection) uint64 {
				c.AddIndex("email", func(v any) string {
					return v.(*Person).Email
				}, UniqueIndex|CaseInsensitiveIndex)

				c.Set(&Person{Email: "[email protected]"})
				return c.Set(&Person{Email: "[email protected]"}) // Should fail
			},
			wantID: false,
		},
		{
			name: "Default index",
			setup: func(c *Collection) uint64 {
				c.AddIndex("age", func(v any) string {
					return strconv.Itoa(v.(*Person).Age)
				}, DefaultIndex)

				// First person with age 30
				id1 := c.Set(&Person{Age: 30})
				if id1 == 0 {
					t.Error("Failed to set first person")
				}

				// Second person with same age should succeed
				return c.Set(&Person{Age: 30})
			},
			wantID: true,
		},
		{
			name: "Multiple options",
			setup: func(c *Collection) uint64 {
				c.AddIndex("name", func(v any) string {
					return v.(*Person).Name
				}, UniqueIndex|CaseInsensitiveIndex|SparseIndex)

				c.Set(&Person{Name: "Alice"})
				return c.Set(&Person{Name: "ALICE"}) // Should fail
			},
			wantID: false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			c := New() // Create new collection for each test
			id := tt.setup(c)
			if (id != 0) != tt.wantID {
				t.Errorf("got id = %v, want non-zero: %v", id, tt.wantID)
			}
		})
	}
}

func TestConcurrentOperations(t *testing.T) {
	c := New()
	c.AddIndex("name", func(v any) string {
		return v.(*Person).Name
	}, UniqueIndex)

	p1 := &Person{Name: "Alice"}
	id1 := c.Set(p1)
	iter := c.Get("_id", seqid.ID(id1).String())
	success := c.Update(id1, &Person{Name: "Alice2"})

	if iter.Empty() || !success {
		t.Error("Concurrent operations failed")
	}
}

func TestSparseIndexBehavior(t *testing.T) {
	c := New()
	c.AddIndex("optional_field", func(v any) string {
		return v.(*Person).Username
	}, SparseIndex)

	tests := []struct {
		name   string
		person *Person
		wantID bool
	}{
		{
			name:   "Empty optional field",
			person: &Person{Name: "Alice", Email: "[email protected]"},
			wantID: true,
		},
		{
			name:   "Populated optional field",
			person: &Person{Name: "Bob", Email: "[email protected]", Username: "bobby"},
			wantID: true,
		},
		{
			name:   "Multiple empty fields",
			person: &Person{Name: "Charlie"},
			wantID: true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			id := c.Set(tt.person)
			if (id != 0) != tt.wantID {
				t.Errorf("Set() got id = %v, want non-zero: %v", id, tt.wantID)
			}
		})
	}
}

func TestIndexKeyGeneration(t *testing.T) {
	c := New()
	c.AddIndex("composite", func(v any) string {
		p := v.(*Person)
		return p.Name + ":" + strconv.Itoa(p.Age)
	}, UniqueIndex)

	tests := []struct {
		name   string
		person *Person
		wantID bool
	}{
		{
			name:   "Valid composite key",
			person: &Person{Name: "Alice", Age: 30},
			wantID: true,
		},
		{
			name:   "Duplicate composite key",
			person: &Person{Name: "Alice", Age: 30},
			wantID: false,
		},
		{
			name:   "Different composite key",
			person: &Person{Name: "Alice", Age: 31},
			wantID: true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			id := c.Set(tt.person)
			if (id != 0) != tt.wantID {
				t.Errorf("Set() got id = %v, want non-zero: %v", id, tt.wantID)
			}
		})
	}
}

func TestGetIndex(t *testing.T) {
	c := New()
	c.AddIndex("name", func(v any) string {
		return v.(*Person).Name
	}, UniqueIndex)

	tests := []struct {
		name      string
		indexName string
		wantNil   bool
	}{
		{
			name:      "Get existing index",
			indexName: "name",
			wantNil:   false,
		},
		{
			name:      "Get _id index",
			indexName: IDIndex,
			wantNil:   false,
		},
		{
			name:      "Get non-existent index",
			indexName: "invalid",
			wantNil:   true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			tree := c.GetIndex(tt.indexName)
			if (tree == nil) != tt.wantNil {
				t.Errorf("GetIndex() got nil = %v, want nil = %v", tree == nil, tt.wantNil)
			}
		})
	}
}

func TestAddIndexPanic(t *testing.T) {
	c := New()
	defer func() {
		if r := recover(); r == nil {
			t.Error("Expected panic when adding _id index")
		}
	}()

	c.AddIndex(IDIndex, func(v any) string {
		return ""
	}, DefaultIndex)
}

func TestCaseInsensitiveOperations(t *testing.T) {
	c := New()
	c.AddIndex("email", func(v any) string {
		return v.(*Person).Email
	}, UniqueIndex|CaseInsensitiveIndex)

	p := &Person{Email: "[email protected]"}
	id := c.Set(p)

	tests := []struct {
		name      string
		key       string
		wantObj   bool
		operation string // "get" or "getAll"
		wantCount int
	}{
		{"Get exact match", "[email protected]", true, "get", 1},
		{"Get different case", "[email protected]", true, "get", 1},
		{"Get non-existent", "[email protected]", false, "get", 0},
		{"GetAll exact match", "[email protected]", true, "getAll", 1},
		{"GetAll different case", "[email protected]", true, "getAll", 1},
		{"GetAll non-existent", "[email protected]", false, "getAll", 0},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if tt.operation == "get" {
				iter := c.Get("email", tt.key)
				if iter.Empty() {
					if tt.wantObj {
						t.Error("Expected iterator to not be empty")
					}
					return
				}
				hasValue := iter.Next()
				if hasValue != tt.wantObj {
					t.Errorf("Get() got object = %v, want object = %v", hasValue, tt.wantObj)
				}
				if hasValue {
					entry := iter.Value()
					if entry.ID != seqid.ID(id).String() {
						t.Errorf("Get() got id = %v, want id = %v", entry.ID, seqid.ID(id).String())
					}
				}
			} else {
				entries := c.GetAll("email", tt.key)
				if len(entries) != tt.wantCount {
					t.Errorf("GetAll() returned %d entries, want %d", len(entries), tt.wantCount)
				}
				if tt.wantCount > 0 {
					entry := entries[0]
					if entry.ID != seqid.ID(id).String() {
						t.Errorf("GetAll() returned ID %s, want %s", entry.ID, seqid.ID(id).String())
					}
				}
			}
		})
	}
}

func TestGetInvalidID(t *testing.T) {
	c := New()
	iter := c.Get(IDIndex, "not-a-valid-id")
	if !iter.Empty() {
		t.Errorf("Get() with invalid ID format got an entry, want nil")
	}
}

func TestGetAll(t *testing.T) {
	c := New()
	c.AddIndex("tags", func(v any) []string {
		return v.(*Person).Tags
	}, DefaultIndex)
	c.AddIndex("age", func(v any) string {
		return strconv.Itoa(v.(*Person).Age)
	}, DefaultIndex)
	c.AddIndex("name", func(v any) string {
		return v.(*Person).Name
	}, UniqueIndex)

	// Create test data
	people := []*Person{
		{Name: "Alice", Age: 30, Tags: []string{"dev", "go"}},
		{Name: "Bob", Age: 30, Tags: []string{"dev", "python"}},
		{Name: "Charlie", Age: 25, Tags: []string{"dev", "rust"}},
	}

	ids := make([]uint64, len(people))
	for i, p := range people {
		ids[i] = c.Set(p)
		if ids[i] == 0 {
			t.Fatalf("Failed to set person %s", p.Name)
		}
	}

	tests := []struct {
		name      string
		indexName string
		key       string
		wantCount int
	}{
		{
			name:      "Multi-value index with multiple matches",
			indexName: "tags",
			key:       "dev",
			wantCount: 3,
		},
		{
			name:      "Multi-value index with single match",
			indexName: "tags",
			key:       "go",
			wantCount: 1,
		},
		{
			name:      "Multi-value index with no matches",
			indexName: "tags",
			key:       "java",
			wantCount: 0,
		},
		{
			name:      "Single-value non-unique index with multiple matches",
			indexName: "age",
			key:       "30",
			wantCount: 2,
		},
		{
			name:      "Single-value unique index",
			indexName: "name",
			key:       "Alice",
			wantCount: 1,
		},
		{
			name:      "Non-existent index",
			indexName: "invalid",
			key:       "value",
			wantCount: 0,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			iter := c.Get(tt.indexName, tt.key)
			count := 0
			for iter.Next() {
				entry := iter.Value()
				if entry.ID == "" {
					t.Error("Got entry with empty ID")
				}
				if entry.Obj == nil {
					t.Error("Got entry with nil Obj")
				}
				count++
			}
			if count != tt.wantCount {
				t.Errorf("Got %d entries, want %d", count, tt.wantCount)
			}
		})
	}
}

func TestIndexOperations(t *testing.T) {
	tests := []struct {
		name    string
		setup   func(*Collection) (uint64, error)
		verify  func(*Collection, uint64) error
		wantErr bool
	}{
		{
			name: "Basic set and get",
			setup: func(c *Collection) (uint64, error) {
				c.AddIndex("name", func(v any) string {
					return v.(*Person).Name
				}, UniqueIndex)
				return c.Set(&Person{Name: "Alice", Age: 30}), nil
			},
			verify: func(c *Collection, id uint64) error {
				iter := c.Get(IDIndex, seqid.ID(id).String())
				if !iter.Next() {
					return errors.New("failed to get object by ID")
				}
				entry := iter.Value()
				if entry.Obj.(*Person).Name != "Alice" {
					return errors.New("got wrong object")
				}
				return nil
			},
		},
		{
			name: "Composite index",
			setup: func(c *Collection) (uint64, error) {
				c.AddIndex("composite", func(v any) string {
					p := v.(*Person)
					return p.Name + ":" + strconv.Itoa(p.Age)
				}, UniqueIndex)
				return c.Set(&Person{Name: "Alice", Age: 30}), nil
			},
			verify: func(c *Collection, id uint64) error {
				iter := c.Get("composite", "Alice:30")
				if !iter.Next() {
					return errors.New("failed to get object by composite index")
				}
				return nil
			},
		},
		// Add more test cases combining unique scenarios from original tests
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			c := New()
			id, err := tt.setup(c)
			if (err != nil) != tt.wantErr {
				t.Errorf("setup error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if err == nil {
				if err := tt.verify(c, id); err != nil {
					t.Errorf("verification failed: %v", err)
				}
			}
		})
	}
}

func TestMultiValueIndexes(t *testing.T) {
	c := New()
	c.AddIndex("tags", func(v any) []string {
		return v.(*Person).Tags
	}, DefaultIndex)

	tests := []struct {
		name      string
		setup     []*Person
		searchTag string
		wantCount int
	}{
		{
			name: "Multiple tags, multiple matches",
			setup: []*Person{
				{Name: "Alice", Tags: []string{"dev", "go"}},
				{Name: "Bob", Tags: []string{"dev", "python"}},
				{Name: "Charlie", Tags: []string{"dev", "rust"}},
			},
			searchTag: "dev",
			wantCount: 3,
		},
		{
			name: "Single tag match",
			setup: []*Person{
				{Name: "Alice", Tags: []string{"dev", "go"}},
				{Name: "Bob", Tags: []string{"dev", "python"}},
			},
			searchTag: "go",
			wantCount: 1,
		},
		{
			name: "No matches",
			setup: []*Person{
				{Name: "Alice", Tags: []string{"dev", "go"}},
				{Name: "Bob", Tags: []string{"dev", "python"}},
			},
			searchTag: "java",
			wantCount: 0,
		},
		{
			name: "Empty tags",
			setup: []*Person{
				{Name: "Alice", Tags: []string{}},
				{Name: "Bob", Tags: nil},
			},
			searchTag: "dev",
			wantCount: 0,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			c := New()
			c.AddIndex("tags", func(v any) []string {
				return v.(*Person).Tags
			}, DefaultIndex)

			// Setup test data
			for _, p := range tt.setup {
				if id := c.Set(p); id == 0 {
					t.Fatalf("Failed to set person %s", p.Name)
				}
			}

			// Test Get operation
			iter := c.Get("tags", tt.searchTag)
			count := 0
			for iter.Next() {
				count++
			}
			if count != tt.wantCount {
				t.Errorf("Get() got %d matches, want %d", count, tt.wantCount)
			}
		})
	}
}

func TestGetOperations(t *testing.T) {
	c := New()
	c.AddIndex("name", func(v any) string {
		return v.(*Person).Name
	}, UniqueIndex)
	c.AddIndex("age", func(v any) string {
		return strconv.Itoa(v.(*Person).Age)
	}, DefaultIndex)

	// Setup test data
	testPeople := []*Person{
		{Name: "Alice", Age: 30},
		{Name: "Bob", Age: 30},
		{Name: "Charlie", Age: 25},
	}

	ids := make([]uint64, len(testPeople))
	for i, p := range testPeople {
		ids[i] = c.Set(p)
		if ids[i] == 0 {
			t.Fatalf("Failed to set person %s", p.Name)
		}
	}

	tests := []struct {
		name      string
		indexName string
		key       string
		wantCount int
		wantErr   bool
	}{
		{
			name:      "Get by ID",
			indexName: IDIndex,
			key:       seqid.ID(ids[0]).String(),
			wantCount: 1,
			wantErr:   false,
		},
		{
			name:      "Get by unique index",
			indexName: "name",
			key:       "Alice",
			wantCount: 1,
			wantErr:   false,
		},
		{
			name:      "Get by non-unique index",
			indexName: "age",
			key:       "30",
			wantCount: 2,
			wantErr:   false,
		},
		{
			name:      "Get with invalid index",
			indexName: "invalid_index",
			key:       "value",
			wantCount: 0,
			wantErr:   true,
		},
		{
			name:      "Get with invalid ID format",
			indexName: IDIndex,
			key:       "not-a-valid-id",
			wantCount: 0,
			wantErr:   true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			iter := c.Get(tt.indexName, tt.key)
			if iter.Empty() {
				if !tt.wantErr {
					t.Errorf("Get() returned empty iterator, wanted %d results", tt.wantCount)
				}
				return
			}

			count := 0
			for iter.Next() {
				entry := iter.Value()
				if entry.ID == "" {
					t.Error("Got entry with empty ID")
				}
				if entry.Obj == nil {
					t.Error("Got entry with nil Obj")
				}
				count++
			}

			if count != tt.wantCount {
				t.Errorf("Get() returned %d results, want %d", count, tt.wantCount)
			}
		})
	}
}

func TestEntryString(t *testing.T) {
	tests := []struct {
		name     string
		entry    *Entry
		expected string
	}{
		{
			name:     "Nil entry",
			entry:    nil,
			expected: "<nil>",
		},
		{
			name: "Person entry",
			entry: &Entry{
				ID:  "123",
				Obj: &Person{Name: "Alice", Age: 30},
			},
			expected: `Entry{ID: 123, Obj: name=Alice age=30 email= username= tags=}`,
		},
		{
			name: "Entry with nil object",
			entry: &Entry{
				ID:  "456",
				Obj: nil,
			},
			expected: `Entry{ID: 456, Obj: <nil>}`,
		},
		{
			name: "Entry with complete person",
			entry: &Entry{
				ID: "789",
				Obj: &Person{
					Name:     "Bob",
					Age:      25,
					Email:    "[email protected]",
					Username: "bobby",
					Tags:     []string{"dev", "go"},
				},
			},
			expected: `Entry{ID: 789, Obj: name=Bob age=25 [email protected] username=bobby tags=dev,go}`,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := tt.entry.String()
			if got != tt.expected {
				t.Errorf("Entry.String() = %q, want %q", got, tt.expected)
			}
		})
	}
}

entry.gno

package collection

import "gno.land/p/nt/ufmt/v0"

// Entry represents a single object in the collection with its ID
type Entry struct {
	ID  string
	Obj any
}

// String returns a string representation of the Entry
func (e *Entry) String() string {
	if e == nil {
		return "<nil>"
	}
	return ufmt.Sprintf("Entry{ID: %s, Obj: %v}", e.ID, e.Obj)
}

// EntryIterator provides iteration over collection entries
type EntryIterator struct {
	collection *Collection
	indexName  string
	key        string
	currentID  string
	currentObj any
	err        error
	closed     bool

	// For multi-value cases
	ids        []string
	currentIdx int
}

func (ei *EntryIterator) Close() error {
	ei.closed = true
	ei.currentID = ""
	ei.currentObj = nil
	ei.ids = nil
	return nil
}

func (ei *EntryIterator) Next() bool {
	if ei == nil || ei.closed || ei.err != nil {
		return false
	}

	// Handle ID index specially
	if ei.indexName == IDIndex {
		if ei.currentID != "" { // We've already returned the single value
			return false
		}
		obj := ei.collection.indexes[IDIndex].tree.Get(ei.key)
		if obj == nil {
			return false
		}
		ei.currentID = ei.key
		ei.currentObj = obj
		return true
	}

	// Get the index
	idx, exists := ei.collection.indexes[ei.indexName]
	if !exists {
		return false
	}

	// Initialize ids slice if needed
	if ei.ids == nil {
		idData := idx.tree.Get(ei.key)
		if idData == nil {
			return false
		}

		switch stored := idData.(type) {
		case []string:
			ei.ids = stored
			ei.currentIdx = -1
		case string:
			ei.ids = []string{stored}
			ei.currentIdx = -1
		default:
			return false
		}
	}

	// Move to next ID
	ei.currentIdx++
	if ei.currentIdx >= len(ei.ids) {
		return false
	}

	// Fetch the actual object
	ei.currentID = ei.ids[ei.currentIdx]
	obj := ei.collection.indexes[IDIndex].tree.Get(ei.currentID)
	if obj == nil {
		// Skip invalid entries
		return ei.Next()
	}
	ei.currentObj = obj
	return true
}

func (ei *EntryIterator) Error() error {
	return ei.err
}

func (ei *EntryIterator) Value() *Entry {
	if ei == nil || ei.closed || ei.currentID == "" {
		return nil
	}
	return &Entry{
		ID:  ei.currentID,
		Obj: ei.currentObj,
	}
}

func (ei *EntryIterator) Empty() bool {
	if ei == nil || ei.closed || ei.err != nil {
		return true
	}

	// Handle ID index specially
	if ei.indexName == IDIndex {
		return !ei.collection.indexes[IDIndex].tree.Has(ei.key)
	}

	// Get the index
	idx, exists := ei.collection.indexes[ei.indexName]
	if !exists {
		return true
	}

	// Check if key exists in index
	idData := idx.tree.Get(ei.key)
	if idData == nil {
		return true
	}

	// Check if there are any valid IDs
	switch stored := idData.(type) {
	case []string:
		return len(stored) == 0
	case string:
		return stored == ""
	default:
		return true
	}
}

gnomod.toml

module = "gno.land/p/nym-moultest123/collection/v0"
gno = "0.9"

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186404
  max_deposit = "16000000ugnot"