### Registry and Engine Setup in Go Source: https://context7.com/latolukasz/fluxaorm/llms.txt Configure FLUXA ORM by registering MySQL, Redis, local caches, entities, and streams with the Registry, then validate to create an Engine for ORM operations. ```go package main import ( "context" "log" fluxaorm "github.com/latolukasz/fluxaorm" ) // Define an entity with ORM tags type User struct { ID uint64 `orm:"localCache;redisCache"` Name string `orm:"max=100;required"` Email string `orm:"max=255;unique=Email"` Age uint64 CreatedAt time.Time } func main() { // Create a new registry registry := fluxaorm.NewRegistry() // Register MySQL connection pool registry.RegisterMySQL( "root:password@tcp(localhost:3306)/mydb", "default", &fluxaorm.MySQLOptions{ MaxOpenConnections: 100, MaxIdleConnections: 10, ConnMaxLifetime: 5 * time.Minute, DefaultEncoding: "utf8mb4", DefaultCollate: "0900_ai_ci", }, ) // Register Redis connection pool registry.RegisterRedis("localhost:6379", 0, "default", nil) // Register local cache (in-memory LRU) registry.RegisterLocalCache("default", 1000) // Register Redis streams for event publishing registry.RegisterRedisStream("user-events", "default") // Register entities registry.RegisterEntity(&User{}) // Validate and create Engine engine, err := registry.Validate() if err != nil { log.Fatal(err) } // Create a context for ORM operations ctx := engine.NewContext(context.Background()) // Use ctx for all ORM operations... } ``` -------------------------------- ### Setup Query Logging in Flux ORM Source: https://context7.com/latolukasz/fluxaorm/llms.txt Registers a custom query logger or enables built-in debug logging for database operations. Supports custom selection of which components to log. ```go func setupLogging(ctx fluxaorm.Context) { logger := &CustomLogger{} // Register for MySQL, Redis, and Local cache ctx.RegisterQueryLogger(logger, true, true, true) // Or enable built-in debug logging ctx.EnableQueryDebug() // Custom selection ctx.EnableQueryDebugCustom( true, // MySQL false, // Redis false, // Local cache ) } ``` -------------------------------- ### Create New Entities Source: https://context7.com/latolukasz/fluxaorm/llms.txt Defines a Product struct and demonstrates creating new instances with auto-generated or specific IDs. ```go type Product struct { ID uint64 `orm:"localCache;redisCache"` Name string `orm:"max=200;required"` Price float64 Stock uint64 CategoryID fluxaorm.Reference[Category] Description *string `orm:"max=1000"` // nullable field } func createProduct(ctx fluxaorm.Context) (*Product, error) { // Create new entity with auto-generated UUID product := fluxaorm.NewEntity[Product](ctx) product.Name = "Gaming Laptop" product.Price = 1299.99 product.Stock = 50 product.CategoryID = fluxaorm.Reference[Category](1) // Reference to Category ID 1 desc := "High-performance gaming laptop" product.Description = &desc // Flush to persist (INSERT) err := ctx.Flush() if err != nil { return nil, err } // product.ID is now set fmt.Printf("Created product with ID: %d\n", product.ID) return product, nil } // Create entity with specific ID func createWithID(ctx fluxaorm.Context) (*Product, error) { product := fluxaorm.NewEntityWithID[Product](ctx, 12345) product.Name = "Specific ID Product" product.Price = 99.99 product.Stock = 100 err := ctx.Flush() return product, err } ``` -------------------------------- ### Build and Test Commands Source: https://github.com/latolukasz/fluxaorm/blob/main/CLAUDE.md Standard Makefile commands for testing, linting, and formatting the project. ```bash make test # Run all tests (go test -race -p 1 ./...) make check # Run linting (revive, gocyclo, format check) make format # Format code with goimports make cover # Run tests with coverage → resources/cover/cover.out make cover-html # Generate and open HTML coverage report make tidy # Run go mod tidy ``` -------------------------------- ### Define and Query Indexes in Go Source: https://context7.com/latolukasz/fluxaorm/llms.txt Shows how to define entity indexes using struct tags and perform optimized lookups using GetByIndex. ```go type Article struct { ID uint64 `orm:"localCache;redisCache"` AuthorID uint64 CategoryID uint64 Title string `orm:"max=255"` Published bool } // Define indexes func (a Article) Indexes() any { return struct { AuthorID fluxaorm.IndexDefinition `index:"AuthorID"` // Non-cached index CategoryID fluxaorm.IndexDefinition `index:"CategoryID;cached"` // Cached in Redis Composite fluxaorm.IndexDefinition `index:"AuthorID,Published;cached"` }{} } func getArticlesByAuthor(ctx fluxaorm.Context, authorID uint64) ([]*Article, error) { // Define the index to use index := fluxaorm.IndexDefinition{Columns: "AuthorID", Cached: true} pager := fluxaorm.NewPager(1, 50) iterator, err := fluxaorm.GetByIndex[Article](ctx, pager, index, authorID) if err != nil { return nil, err } articles := make([]*Article, 0) for iterator.Next() { article, _ := iterator.Entity() articles = append(articles, article) } return articles, nil } // Composite index query func getPublishedByAuthor(ctx fluxaorm.Context, authorID uint64) ([]*Article, error) { index := fluxaorm.IndexDefinition{Columns: "AuthorID,Published", Cached: true} iterator, total, err := fluxaorm.GetByIndexWithCount[Article]( ctx, nil, index, authorID, true, ) if err != nil { return nil, err } fmt.Printf("Total published articles: %d\n", total) var articles []*Article for iterator.Next() { a, _ := iterator.Entity() articles = append(articles, a) } return articles, nil } ``` -------------------------------- ### Search with WHERE Clauses in Go Source: https://context7.com/latolukasz/fluxaorm/llms.txt Demonstrates various search patterns including parameterized queries, pagination, IN clause expansion, single entity retrieval, and soft-delete inclusion. ```go func searchProducts(ctx fluxaorm.Context) ([]*Product, error) { // Simple WHERE clause where := fluxaorm.NewWhere("`Price` > ? AND `Stock` > ?", 100.0, 0) // With pagination pager := fluxaorm.NewPager(1, 20) // Page 1, 20 items per page iterator, err := fluxaorm.Search[Product](ctx, where, pager) if err != nil { return nil, err } products := make([]*Product, 0) for iterator.Next() { product, err := iterator.Entity() if err != nil { return nil, err } products = append(products, product) } return products, nil } // Search with total count for pagination func searchWithCount(ctx fluxaorm.Context, page int) (products []*Product, total int, err error) { where := fluxaorm.NewWhere("`Stock` > 0 ORDER BY `Price` DESC") pager := fluxaorm.NewPager(page, 10) iterator, total, err := fluxaorm.SearchWithCount[Product](ctx, where, pager) if err != nil { return nil, 0, err } for iterator.Next() { product, _ := iterator.Entity() products = append(products, product) } return products, total, nil } // Search with IN clause (auto-expanded) func searchByIDs(ctx fluxaorm.Context, categoryIDs []uint64) ([]*Product, error) { // IN ? is automatically expanded to IN (?,?,?) where := fluxaorm.NewWhere("`CategoryID` IN ?", categoryIDs) iterator, err := fluxaorm.Search[Product](ctx, where, nil) if err != nil { return nil, err } var products []*Product for iterator.Next() { p, _ := iterator.Entity() products = append(products, p) } return products, nil } // Search single entity func findByEmail(ctx fluxaorm.Context, email string) (*User, error) { where := fluxaorm.NewWhere("`Email` = ?", email) user, found, err := fluxaorm.SearchOne[User](ctx, where) if err != nil { return nil, err } if !found { return nil, nil } return user, nil } // Include soft-deleted records func searchWithDeleted(ctx fluxaorm.Context) ([]*Order, error) { where := fluxaorm.NewWhere("`Total` > ?", 100.0) where.WithFakeDeletes() // Include soft-deleted records iterator, err := fluxaorm.Search[Order](ctx, where, nil) if err != nil { return nil, err } var orders []*Order for iterator.Next() { o, _ := iterator.Entity() orders = append(orders, o) } return orders, nil } ``` -------------------------------- ### Execute Redis Pipelines Source: https://context7.com/latolukasz/fluxaorm/llms.txt Batch multiple Redis commands to improve performance by reducing round-trips. ```go func batchRedisOperations(ctx fluxaorm.Context) error { pipeline := ctx.RedisPipeLine("default") // Queue multiple commands getResult := pipeline.Get("key1") pipeline.Set("key2", "value2", time.Hour) pipeline.Incr("counter") lrangeResult := pipeline.LRange("mylist", 0, 10) pipeline.HSet("myhash", "field1", "value1", "field2", "value2") // Execute all commands at once _, err := pipeline.Exec(ctx) if err != nil { return err } // Get results value, err := getResult.Result() if err != nil { return err } fmt.Printf("key1 value: %s\n", value) list, err := lrangeResult.Result() if err != nil { return err } fmt.Printf("list: %v\n", list) return nil } ``` -------------------------------- ### Run Single Test Source: https://github.com/latolukasz/fluxaorm/blob/main/CLAUDE.md Command to execute a specific test case by name. ```bash go test -race -p 1 -run TestName ./... ``` -------------------------------- ### YAML Configuration for FLUXA ORM in Go Source: https://context7.com/latolukasz/fluxaorm/llms.txt Initialize FLUXA ORM using a YAML configuration file for connection pools and streams. Ensure entities are registered after initialization. ```go import ( "os" fluxaorm "github.com/latolukasz/fluxaorm" "gopkg.in/yaml.v2" ) // config.yaml content: // default: // mysql: // uri: root:root@tcp(localhost:3306)/mydb // connMaxLifetime: 30 // maxOpenConnections: 100 // maxIdleConnections: 10 // defaultEncoding: utf8mb4 // defaultCollate: 0900_ai_ci // redis: localhost:6379:0 // local_cache: 1000 // streams: // - user-events // - order-events func setupFromYAML() (fluxaorm.Engine, error) { // Read YAML file data, err := os.ReadFile("config.yaml") if err != nil { return nil, err } var config map[string]any err = yaml.Unmarshal(data, &config) if err != nil { return nil, err } registry := fluxaorm.NewRegistry() // Initialize from YAML err = registry.InitByYaml(config) if err != nil { return nil, err } // Register entities registry.RegisterEntity(&User{}, &Order{}, &Product{}) return registry.Validate() } ``` -------------------------------- ### Implement Distributed Locking with Locker Source: https://context7.com/latolukasz/fluxaorm/llms.txt Use the Locker interface to manage mutual exclusion across application instances. Ensure the lock is released using defer to prevent deadlocks. ```go func processWithLock(ctx fluxaorm.Context, resourceID uint64) error { redis := ctx.Engine().Redis("default") locker := redis.GetLocker() lockKey := fmt.Sprintf("lock:resource:%d", resourceID) ttl := 30 * time.Second waitTimeout := 5 * time.Second // Try to obtain lock lock, obtained, err := locker.Obtain(ctx, lockKey, ttl, waitTimeout) if err != nil { return err } if !obtained { return fmt.Errorf("could not obtain lock for resource %d", resourceID) } // Always release lock when done defer lock.Release(ctx) // Check remaining TTL remaining, err := lock.TTL(ctx) if err != nil { return err } fmt.Printf("Lock TTL remaining: %v\n", remaining) // Refresh lock if operation takes longer if needsMoreTime() { ok, err := lock.Refresh(ctx, 30*time.Second) if err != nil { return err } if !ok { return fmt.Errorf("lost lock") } } // Do exclusive work... return processResource(resourceID) } ``` -------------------------------- ### Define and Load Entity References Source: https://context7.com/latolukasz/fluxaorm/llms.txt Use Reference[T] for foreign key relationships. Supports lazy loading via GetEntity and batch preloading via iterator.LoadReference. ```go type Category struct { ID uint64 `orm:"localCache;redisCache"` Name string `orm:"max=100"` } type Item struct { ID uint64 `orm:"localCache"` Name string `orm:"max=200"` CategoryID fluxaorm.Reference[Category] // Foreign key to Category ParentID *fluxaorm.Reference[Item] // Optional self-reference } func loadItemWithCategory(ctx fluxaorm.Context, itemID uint64) error { item, found, err := fluxaorm.GetByID[Item](ctx, itemID) if err != nil { return err } if !found { return fmt.Errorf("item not found") } // Load referenced category (lazy loading) category, err := item.CategoryID.GetEntity(ctx) if err != nil { return err } if category != nil { fmt.Printf("Item: %s, Category: %s\n", item.Name, category.Name) } // Get just the ID without loading categoryID := item.CategoryID.GetID() fmt.Printf("Category ID: %d\n", categoryID) return nil } // Batch load references using iterator func loadWithReferences(ctx fluxaorm.Context, ids []uint64) error { iterator, err := fluxaorm.GetByIDs[Item](ctx, ids...) if err != nil { return err } // Preload all Category references in batch err = iterator.LoadReference("CategoryID") if err != nil { return err } for iterator.Next() { item, _ := iterator.Entity() category, _ := item.CategoryID.GetEntity(ctx) fmt.Printf("%s -> %s\n", item.Name, category.Name) } return nil } ``` -------------------------------- ### Perform Redis Cache Operations Source: https://context7.com/latolukasz/fluxaorm/llms.txt Direct Redis interface for standard operations and cache-aside patterns using GetSet. ```go func redisCacheOperations(ctx fluxaorm.Context) error { redis := ctx.Engine().Redis("default") // String operations err := redis.Set(ctx, "user:session:123", "token-data", 30*time.Minute) if err != nil { return err } value, found, err := redis.Get(ctx, "user:session:123") if err != nil { return err } if found { fmt.Printf("Session: %s\n", value) } // Hash operations err = redis.HSet(ctx, "user:1:profile", "name", "John", "age", "30") if err != nil { return err } profile, err := redis.HGetAll(ctx, "user:1:profile") if err != nil { return err } fmt.Printf("Profile: %v\n", profile) // List operations _, err = redis.RPush(ctx, "notifications:1", "msg1", "msg2", "msg3") if err != nil { return err } messages, err := redis.LRange(ctx, "notifications:1", 0, -1) if err != nil { return err } fmt.Printf("Messages: %v\n", messages) // Set operations _, err = redis.SAdd(ctx, "tags:popular", "go", "redis", "mysql") if err != nil { return err } isMember, err := redis.SIsMember(ctx, "tags:popular", "go") if err != nil { return err } fmt.Printf("Is member: %v\n", isMember) // Sorted set operations _, err = redis.ZAdd(ctx, "leaderboard", redis.Z{Score: 100, Member: "player1"}, redis.Z{Score: 200, Member: "player2"}, ) if err != nil { return err } // Counter with expiration count, err := redis.IncrWithExpire(ctx, "api:rate:user:1", time.Hour) if err != nil { return err } fmt.Printf("Rate limit count: %d\n", count) return nil } // GetSet pattern for cache-aside func getCachedData(ctx fluxaorm.Context, key string) (any, error) { redis := ctx.Engine().Redis("default") // Automatically fetches from cache or calls provider return redis.GetSet(ctx, key, 5*time.Minute, func() any { // This is called only on cache miss return map[string]string{ "data": "expensive computation result", } }) } ``` -------------------------------- ### Manage Events with Redis Streams Source: https://context7.com/latolukasz/fluxaorm/llms.txt Publish and consume events using the Event Broker. Supports single-event publishing, batch processing, and consumer group patterns. ```go type OrderEvent struct { OrderID uint64 UserID uint64 Action string Amount float64 } func publishEvent(ctx fluxaorm.Context) error { broker := ctx.GetEventBroker() event := OrderEvent{ OrderID: 12345, UserID: 1, Action: "created", Amount: 99.99, } // Publish single event id, err := broker.Publish("order-events", event, "type", "order", "priority", "high") if err != nil { return err } fmt.Printf("Published event: %s\n", id) return nil } // Batch publish multiple events func publishBatch(ctx fluxaorm.Context) error { broker := ctx.GetEventBroker() flusher := broker.NewFlusher() for i := 0; i < 100; i++ { err := flusher.Publish("order-events", OrderEvent{ OrderID: uint64(i), Action: "updated", }) if err != nil { return err } } // Flush all events at once return flusher.Flush() } // Consume events func consumeEvents(ctx fluxaorm.Context) error { broker := ctx.GetEventBroker() // Single consumer (only one instance processes each message) consumer, err := broker.ConsumerSingle(ctx, "order-events") if err != nil { return err } // Process events err = consumer.Consume(100, 5*time.Second, func(events []fluxaorm.Event) error { for _, event := range events { var order OrderEvent err := event.Unserialize(&order) if err != nil { return err } eventType := event.Tag("type") fmt.Printf("Event ID: %s, Type: %s, Order: %d\n", event.ID(), eventType, order.OrderID) // Acknowledge event after processing err = event.Ack() if err != nil { return err } } return nil }) return err } // Multiple consumers (each instance gets unique consumer name) func consumeMany(ctx fluxaorm.Context) error { broker := ctx.GetEventBroker() consumer, err := broker.ConsumerMany(ctx, "order-events") if err != nil { return err } defer consumer.Cleanup() fmt.Printf("Consumer name: %s\n", consumer.Name()) // Process with auto-claim for failed messages return consumer.AutoClaim(100, 5*time.Minute, func(events []fluxaorm.Event) error { for _, event := range events { // Process event... event.Ack() } return nil }) } ``` -------------------------------- ### Retrieve Entities by ID Source: https://context7.com/latolukasz/fluxaorm/llms.txt Retrieves single or multiple entities using the three-tier cache system. ```go func getProduct(ctx fluxaorm.Context, id uint64) (*Product, error) { // Generic type-safe retrieval product, found, err := fluxaorm.GetByID[Product](ctx, id) if err != nil { return nil, err } if !found { return nil, fmt.Errorf("product %d not found", id) } fmt.Printf("Product: %s, Price: %.2f\n", product.Name, product.Price) return product, nil } // Get multiple entities by IDs func getProducts(ctx fluxaorm.Context, ids []uint64) ([]*Product, error) { iterator, err := fluxaorm.GetByIDs[Product](ctx, ids...) if err != nil { return nil, err } products := make([]*Product, 0, iterator.Len()) for iterator.Next() { product, err := iterator.Entity() if err != nil { return nil, err } if product != nil { products = append(products, product) } } return products, nil } ``` -------------------------------- ### Define Flux ORM Entity with Struct Tags Source: https://context7.com/latolukasz/fluxaorm/llms.txt Illustrates defining an entity with various struct tags for ORM configurations like caching, validation, indexing, enums, precision, and nullability. ```go type FullFeaturedEntity struct { // ID field tags control caching and table configuration ID uint64 `orm:"localCache;redisCache;mysql=custom_pool;table=custom_table_name"` // String with max length and required validation Name string `orm:"max=255;required"` // Unique index on single column Email string `orm:"max=255;unique=EmailIndex"` // Enum field with allowed values Status string `orm:"enum=pending,active,suspended;required"` // Set field (stored as comma-separated) Tags []string `orm:"set=tag1,tag2,tag3"` // Float with precision Price float64 `orm:"precision=2"` // Date only (no time component) BirthDate time.Time `orm:"time=date"` // Nullable fields Description *string `orm:"max=1000"` ParentID *uint64 // Reference to another entity CategoryID fluxaorm.Reference[Category] // Optional reference ManagerID *fluxaorm.Reference[User] // Soft delete support FakeDelete uint64 } ``` -------------------------------- ### Inspect Entity Schema in Flux ORM Source: https://context7.com/latolukasz/fluxaorm/llms.txt Retrieves and prints the schema definition for a given entity, including table name, columns, and cache configurations. ```go func inspectSchema(ctx fluxaorm.Context) { schema := fluxaorm.GetEntitySchema[Product](ctx) fmt.Printf("Table: %s\n", schema.GetTableName()) fmt.Printf("Columns: %v\n", schema.GetColumns()) // Check cache configuration if lc, has := schema.GetLocalCache(); has { fmt.Printf("Local cache: %s\n", lc.GetConfig().GetCode()) } if rc, has := schema.GetRedisCache(); has { fmt.Printf("Redis cache: %s\n", rc.GetConfig().GetCode()) } } ``` -------------------------------- ### Edit Entities Source: https://context7.com/latolukasz/fluxaorm/llms.txt Modifies existing entities using tracked copies and checks for pending changes. ```go func updateProduct(ctx fluxaorm.Context, id uint64, newPrice float64) error { // Fetch the original entity original, found, err := fluxaorm.GetByID[Product](ctx, id) if err != nil { return err } if !found { return fmt.Errorf("product not found") } // Create editable copy (changes are tracked) editable := fluxaorm.EditEntity[Product](ctx, original) editable.Price = newPrice editable.Stock = editable.Stock - 1 // Flush to persist (UPDATE only changed fields) return ctx.Flush() } // Check if entity has pending changes func checkDirty(ctx fluxaorm.Context, productID uint64) { oldValues, newValues, hasChanges := fluxaorm.IsDirty[Product](ctx, productID) if hasChanges { fmt.Printf("Old values: %v\n", oldValues) fmt.Printf("New values: %v\n", newValues) } } ``` -------------------------------- ### Perform Async Operations with Flux ORM Source: https://context7.com/latolukasz/fluxaorm/llms.txt Queues multiple entity creations for asynchronous processing using Redis Streams via `FlushAsync`. Operations are processed in the background by a consumer. ```go func asyncOperations(ctx fluxaorm.Context) error { // Create multiple entities for i := 0; i < 1000; i++ { product := fluxaorm.NewEntity[Product](ctx) product.Name = fmt.Sprintf("Product %d", i) product.Price = float64(i) * 10.0 product.Stock = 100 } // Queue for async processing (doesn't block) err := ctx.FlushAsync() if err != nil { return err } // Operations are queued to Redis Stream "lazy_flush" // A background consumer processes them asynchronously return nil } ``` -------------------------------- ### Run Schema Migrations with Flux ORM Source: https://context7.com/latolukasz/fluxaorm/llms.txt Executes SQL ALTER statements to synchronize the database schema with entity definitions. It automatically executes safe alterations. ```go func runMigrations(ctx fluxaorm.Context) error { // Get all required ALTER statements alters, err := fluxaorm.GetAlters(ctx) if err != nil { return err } for _, alter := range alters { fmt.Printf("Pool: %s, Safe: %v\n", alter.Pool, alter.Safe) fmt.Printf("SQL: %s\n\n", alter.SQL) // Execute safe alters automatically if alter.Safe { db := ctx.Engine().DB(alter.Pool) _, err := db.Exec(ctx, alter.SQL) if err != nil { return err } } } return nil } ``` -------------------------------- ### Set Metadata for Logging Context in Flux ORM Source: https://context7.com/latolukasz/fluxaorm/llms.txt Adds key-value metadata to the logging context, which will be included in logs and audit trails. Demonstrates retrieving and printing metadata. ```go func withMetadata(ctx fluxaorm.Context) { ctx.SetMetaData("user_id", "123") ctx.SetMetaData("request_id", "abc-xyz") // Metadata is included in logs and audit trails meta := ctx.GetMetaData() fmt.Printf("Metadata: %v\n", meta) } ``` -------------------------------- ### Implement Custom Query Logger in Flux ORM Source: https://context7.com/latolukasz/fluxaorm/llms.txt Defines a custom logger struct that implements the Handle method to process and display query logs. This is useful for debugging and monitoring. ```go type CustomLogger struct{} func (l *CustomLogger) Handle(log map[string]any) { fmt.Printf("[%s] %s: %s (%.2fms)\n", log["source"], log["operation"], log["query"], log["microseconds"].(int64)/1000.0, ) } ``` -------------------------------- ### Delete Entities Source: https://context7.com/latolukasz/fluxaorm/llms.txt Performs soft or hard deletes on entities. ```go type Order struct { ID uint64 `orm:"localCache"` UserID uint64 Total float64 FakeDelete uint64 // Enables soft delete } func deleteOrder(ctx fluxaorm.Context, id uint64) error { order, found, err := fluxaorm.GetByID[Order](ctx, id) if err != nil { return err } if !found { return fmt.Errorf("order not found") } // Soft delete (sets FakeDelete = ID) fluxaorm.DeleteEntity[Order](ctx, order) return ctx.Flush() } // Force hard delete even with FakeDelete field func forceDeleteOrder(ctx fluxaorm.Context, order *Order) error { ctx.ForceDeleteEntity(order) return ctx.Flush() } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.