client

package module
v1.0.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 10, 2026 License: MIT Imports: 13 Imported by: 0

README

Memory tools client Go Repository

Code example

/* ==========================================================
   File: ./main.go
   ========================================================== */

package main

import (
 "fmt"
 "log"
 "math/rand"
 "time"

 mtclient "github.com/adoboscan21/memory-tools-client-go"
)

func main() {
 fmt.Println("======================================================")
 fmt.Println("🚀 INICIANDO PRUEBAS DE ESTRÉS Y RENDIMIENTO (100K DATOS)")
 fmt.Println("======================================================")

 client := mtclient.NewClient(mtclient.ClientOptions{
  Host:               "localhost",
  Port:               5876,
  Username:           "admin",
  Password:           "adminpass",
  InsecureSkipVerify: true,
 })

 if err := client.Connect(); err != nil {
  log.Fatalf("❌ [FAIL] Error de conexión: %v", err)
 }
 defer client.Close()
 fmt.Println("✅ [OK] Conectado al motor Memory Tools")

 // Nombres de colecciones dinámicos
 colUsers := fmt.Sprintf("test_users_%d", time.Now().UnixNano())
 colDepts := fmt.Sprintf("test_depts_%d", time.Now().UnixNano())

 // ==========================================
 // 1. CREACIÓN DE COLECCIONES E ÍNDICES
 // ==========================================
 fmt.Printf("\n--- Fase 1: Esquema e Índices ---\n")
 client.CollectionCreate(colUsers)
 client.CollectionCreate(colDepts)

 // Crear índices estratégicos para acelerar las consultas masivas
 indexes := []string{"age", "salary", "dept_id", "status"}
 for _, idx := range indexes {
  if resp, err := client.CollectionIndexCreate(colUsers, idx); err != nil || !resp.OK() {
   log.Fatalf("❌ [FAIL] Error creando índice '%s': %v", idx, err)
  }
 }
 fmt.Println("✅ [OK] Colecciones e Índices B-Tree creados correctamente.")

 // ==========================================
 // 2. INSERCIÓN MASIVA (100.000 REGISTROS)
 // ==========================================
 fmt.Printf("\n--- Fase 2: Inserción Masiva (100.000 registros) ---\n")

 // Insertar 10 Departamentos
 depts := make([]any, 10)
 for i := 0; i < 10; i++ {
  depts[i] = map[string]any{
   "_id":   fmt.Sprintf("dept_%d", i),
   "name":  fmt.Sprintf("Department %d", i),
   "level": i,
  }
 }
 client.CollectionItemSetMany(colDepts, depts)
 fmt.Println("✅ [OK] 10 Departamentos base insertados.")

 // Insertar 100.000 Usuarios en lotes de 10.000
 totalUsers := 100000
 batchSize := 10000
 statuses := []string{"active", "inactive", "pending", "banned"}

 fmt.Println("⏳ Generando e insertando 100.000 usuarios por lotes...")
 startInsert := time.Now()

 for i := 0; i < totalUsers; i += batchSize {
  batch := make([]any, 0, batchSize)
  for j := 0; j < batchSize; j++ {
   id := i + j
   batch = append(batch, map[string]any{
    "_id":     fmt.Sprintf("user_%d", id),
    "name":    fmt.Sprintf("User Name %d", id),
    "age":     rand.Intn(50) + 18,                    // Edades entre 18 y 67
    "salary":  float64(rand.Intn(90000) + 30000),     // Salarios entre 30k y 120k
    "dept_id": fmt.Sprintf("dept_%d", rand.Intn(10)), // Asignar a un departamento (0-9)
    "status":  statuses[rand.Intn(len(statuses))],
   })
  }

  if resp, err := client.CollectionItemSetMany(colUsers, batch); err != nil || !resp.OK() {
   log.Fatalf("❌ [FAIL] Error insertando lote %d: %v", i, err)
  }
  fmt.Printf("   -> Insertados %d / %d\n", i+batchSize, totalUsers)
 }
 fmt.Printf("✅ [OK] 100.000 registros insertados en %v\n", time.Since(startInsert))

 // ==========================================
 // 3. CONSULTAS PROFUNDAS (DEEP QUERIES)
 // ==========================================
 fmt.Printf("\n--- Fase 3: Consultas Complejas ---\n")

 limit := 5
 startQuery := time.Now()
 // Buscar usuarios "active", entre 25 y 35 años, ordenados por salario descendente, límite 5
 qDeep := mtclient.Query{
  Filter: map[string]any{
   "and": []any{
    map[string]any{"field": "status", "op": "=", "value": "active"},
    map[string]any{"field": "age", "op": "between", "value": []any{25, 35}},
   },
  },
  OrderBy: []any{
   map[string]any{"field": "salary", "direction": "desc"},
  },
  Limit: &limit,
 }

 deepResp, err := client.CollectionQuery(colUsers, qDeep)
 if err != nil || !deepResp.OK() {
  log.Fatalf("❌ [FAIL] Query profunda falló: %v", err)
 }

 var deepResults []map[string]any
 deepResp.JSON(&deepResults)
 fmt.Printf("✅ [OK] Consulta compleja (Filtros + Sort + Limit) resuelta en %v\n", time.Since(startQuery))
 fmt.Printf("   -> Se encontraron %d resultados de muestra. El salario más alto es: %v\n", len(deepResults), deepResults[0]["salary"])

 // ==========================================
 // 4. LOOKUPS (JOINS) ENTRE 100K REGISTROS
 // ==========================================
 fmt.Printf("\n--- Fase 4: Lookups (Joins en Memoria) ---\n")

 startLookup := time.Now()
 qJoin := mtclient.Query{
  Filter: map[string]any{
   "field": "name", "op": "like", "value": "User Name 999%", // Buscar usuarios específicos
  },
  Lookups: []any{
   map[string]any{
    "from":         colDepts,
    "localField":   "dept_id",
    "foreignField": "_id",
    "as":           "department_info",
   },
  },
  Limit: &limit,
 }

 joinResp, err := client.CollectionQuery(colUsers, qJoin)
 if err != nil || !joinResp.OK() {
  log.Fatalf("❌ [FAIL] Query Lookup falló: %v", err)
 }

 var joinResults []map[string]any
 joinResp.JSON(&joinResults)
 fmt.Printf("✅ [OK] Lookup (Join) resuelto en %v\n", time.Since(startLookup))
 if len(joinResults) > 0 {
  fmt.Printf("   -> Ejemplo de Join: %s pertenece a %v\n", joinResults[0]["name"], joinResults[0]["department_info"])
 }

 // ==========================================
 // 5. AGREGACIONES MATEMÁTICAS Y GROUP BY
 // ==========================================
 fmt.Printf("\n--- Fase 5: Agregaciones (SUM, AVG, MIN, MAX) ---\n")

 startAgg := time.Now()
 qAgg := mtclient.Query{
  GroupBy: []string{"dept_id"}, // Agrupar a los 100k usuarios por departamento
  Aggregations: map[string]any{
   "total_empleados":  map[string]any{"func": "count", "field": "*"},
   "salario_promedio": map[string]any{"func": "avg", "field": "salary"},
   "edad_maxima":      map[string]any{"func": "max", "field": "age"},
  },
 }

 aggResp, err := client.CollectionQuery(colUsers, qAgg)
 if err != nil || !aggResp.OK() {
  log.Fatalf("❌ [FAIL] Query Agregación falló: %v", err)
 }

 var aggResults []map[string]any
 aggResp.JSON(&aggResults)
 fmt.Printf("✅ [OK] Agrupación y métricas calculadas sobre 100.000 registros en %v\n", time.Since(startAgg))
 if len(aggResults) > 0 {
  fmt.Printf("   -> Ejemplo Depto '%v': %v empleados, Salario Promedio: %.2f\n",
   aggResults[0]["dept_id"], aggResults[0]["total_empleados"], aggResults[0]["salario_promedio"])
 }

 // ==========================================
 // 6. OPERACIONES MASIVAS (UPDATE MANY)
 // ==========================================
 fmt.Printf("\n--- Fase 6: Bulk Updates ---\n")

 startUpdate := time.Now()
 // Vamos a darle un aumento a 5 usuarios específicos usando UpdateMany
 updates := []any{
  map[string]any{"_id": "user_10", "patch": map[string]any{"salary": 150000, "status": "promoted"}},
  map[string]any{"_id": "user_20", "patch": map[string]any{"salary": 150000, "status": "promoted"}},
  map[string]any{"_id": "user_30", "patch": map[string]any{"salary": 150000, "status": "promoted"}},
  map[string]any{"_id": "user_40", "patch": map[string]any{"salary": 150000, "status": "promoted"}},
  map[string]any{"_id": "user_50", "patch": map[string]any{"salary": 150000, "status": "promoted"}},
 }

 if resp, err := client.CollectionItemUpdateMany(colUsers, updates); err != nil || !resp.OK() {
  log.Fatalf("❌ [FAIL] UpdateMany falló: %v", err)
 }
 fmt.Printf("✅ [OK] Parches masivos (UpdateMany) aplicados en %v\n", time.Since(startUpdate))

 // ==========================================
 // 7. TRANSACCIONES ACID SOBRE DATOS MASIVOS
 // ==========================================
 fmt.Printf("\n--- Fase 7: Transacciones ACID ---\n")

 client.Begin()
 client.CollectionItemDelete(colUsers, "user_10")
 client.CollectionItemSet(colUsers, "user_999999", map[string]any{"name": "Ghost"}, 0)
 client.Rollback()

 checkRollback, _ := client.CollectionItemGet(colUsers, "user_10")
 if !checkRollback.Found() {
  log.Fatalf("❌ [FAIL] El rollback falló, el usuario fue borrado permanentemente.")
 }
 fmt.Println("✅ [OK] Transacción revertida correctamente (Aislamiento confirmado).")

 // ==========================================
 // 8. LIMPIEZA FINAL
 // ==========================================
 fmt.Printf("\n--- Fase 8: Destrucción del entorno ---\n")
 startClean := time.Now()
 client.CollectionDelete(colUsers)
 client.CollectionDelete(colDepts)
 fmt.Printf("✅ [OK] Entorno de 100.000 datos destruido limpiamente en %v\n", time.Since(startClean))

 fmt.Println("\n======================================================")
 fmt.Println("🏆 ¡ESTRÉS SUPERADO! El motor Memory Tools es una bestia.")
 fmt.Println("======================================================")
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

func NewClient

func NewClient(opts ClientOptions) *Client

func (*Client) Begin

func (c *Client) Begin() (*Tx, error)

Begin inicia una transacción y secuestra la conexión.

func (*Client) Close

func (c *Client) Close() error

func (*Client) CollectionCreate

func (c *Client) CollectionCreate(name string) (*CommandResponse, error)

func (*Client) CollectionDelete

func (c *Client) CollectionDelete(name string) (*CommandResponse, error)

func (*Client) CollectionIndexCreate

func (c *Client) CollectionIndexCreate(collectionName, fieldName string) (*CommandResponse, error)

func (*Client) CollectionIndexDelete

func (c *Client) CollectionIndexDelete(collectionName, fieldName string) (*CommandResponse, error)

func (*Client) CollectionIndexList

func (c *Client) CollectionIndexList(collectionName string) ([]string, error)

func (*Client) CollectionItemDelete

func (c *Client) CollectionItemDelete(collectionName, key string) (*CommandResponse, error)

func (*Client) CollectionItemDeleteMany

func (c *Client) CollectionItemDeleteMany(collectionName string, keys []string) (*CommandResponse, error)

func (*Client) CollectionItemGet

func (c *Client) CollectionItemGet(collectionName, key string) (*GetResult, error)

func (*Client) CollectionItemSet

func (c *Client) CollectionItemSet(collectionName, key string, value any, ttl time.Duration) (*CommandResponse, error)

func (*Client) CollectionItemSetMany

func (c *Client) CollectionItemSetMany(collectionName string, items []any) (*CommandResponse, error)

func (*Client) CollectionItemUpdate

func (c *Client) CollectionItemUpdate(collectionName, key string, patchValue any) (*CommandResponse, error)

func (*Client) CollectionItemUpdateMany

func (c *Client) CollectionItemUpdateMany(collectionName string, items []any) (*CommandResponse, error)

func (*Client) CollectionList

func (c *Client) CollectionList() ([]string, error)

func (*Client) CollectionQuery

func (c *Client) CollectionQuery(collectionName string, query Query) (*CommandResponse, error)

func (*Client) Connect

func (c *Client) Connect() error

func (*Client) IsAuthenticated

func (c *Client) IsAuthenticated() bool

type ClientOptions

type ClientOptions struct {
	Host               string
	Port               int
	Username           string
	Password           string
	ServerCertPath     string
	InsecureSkipVerify bool
	PoolSize           int
}

type CommandResponse

type CommandResponse struct {
	StatusCode byte
	Status     string
	Message    string
	RawData    []byte
}

func (*CommandResponse) BSON added in v1.0.7

func (r *CommandResponse) BSON(v any) error

func (*CommandResponse) OK

func (r *CommandResponse) OK() bool

func (*CommandResponse) UnmarshalResults added in v1.0.7

func (r *CommandResponse) UnmarshalResults(v any) error

type GetResult

type GetResult struct {
	*CommandResponse
}

func (*GetResult) Found

func (r *GetResult) Found() bool

func (*GetResult) Value

func (r *GetResult) Value(v any) error

type Query

type Query struct {
	Filter       map[string]any `bson:"filter,omitempty"`
	OrderBy      []any          `bson:"order_by,omitempty"`
	Limit        *int           `bson:"limit,omitempty"`
	Offset       int            `bson:"offset,omitempty"`
	Count        bool           `bson:"count,omitempty"`
	Aggregations map[string]any `bson:"aggregations,omitempty"`
	GroupBy      []string       `bson:"group_by,omitempty"`
	Having       map[string]any `bson:"having,omitempty"`
	Distinct     string         `bson:"distinct,omitempty"`
	Projection   []string       `bson:"projection,omitempty"`
	Lookups      []any          `bson:"lookups,omitempty"`
}

type Tx added in v1.0.9

type Tx struct {
	// contains filtered or unexported fields
}

Tx representa una transacción activa amarrada a una única conexión de red.

func (*Tx) CollectionItemDelete added in v1.0.9

func (t *Tx) CollectionItemDelete(collectionName, key string) (*CommandResponse, error)

func (*Tx) CollectionItemDeleteMany added in v1.0.9

func (t *Tx) CollectionItemDeleteMany(collectionName string, keys []string) (*CommandResponse, error)

func (*Tx) CollectionItemSet added in v1.0.9

func (t *Tx) CollectionItemSet(collectionName, key string, value any, ttl time.Duration) (*CommandResponse, error)

Métodos de mutación exclusivos de la transacción (Amarrados al Tx)

func (*Tx) CollectionItemSetMany added in v1.0.9

func (t *Tx) CollectionItemSetMany(collectionName string, items []any) (*CommandResponse, error)

func (*Tx) CollectionItemUpdate added in v1.0.9

func (t *Tx) CollectionItemUpdate(collectionName, key string, patchValue any) (*CommandResponse, error)

func (*Tx) CollectionItemUpdateMany added in v1.0.9

func (t *Tx) CollectionItemUpdateMany(collectionName string, items []any) (*CommandResponse, error)

func (*Tx) Commit added in v1.0.9

func (t *Tx) Commit() (*CommandResponse, error)

Commit finaliza la transacción y devuelve la conexión al pool.

func (*Tx) Rollback added in v1.0.9

func (t *Tx) Rollback() (*CommandResponse, error)

Rollback revierte la transacción y devuelve la conexión al pool.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL