// Package models defines the data models used by the chat application. // All model structs embed Base, which provides database access for // relation-fetching methods directly on model instances. package models import ( "context" "database/sql" ) // DB is the interface that models use to query the database. // This avoids a circular import with the db package. type DB interface { GetDB() *sql.DB } // UserLookup provides user lookup by ID without circular imports. type UserLookup interface { GetUserByID(ctx context.Context, id string) (*User, error) } // ChannelLookup provides channel lookup by ID without circular imports. type ChannelLookup interface { GetChannelByID(ctx context.Context, id string) (*Channel, error) } // Base is embedded in all model structs to provide database access. type Base struct { db DB } // SetDB injects the database reference into a model. func (b *Base) SetDB(d DB) { b.db = d } // GetDB returns the database interface for use in model methods. func (b *Base) GetDB() *sql.DB { return b.db.GetDB() } // LookupUser looks up a user by ID if the database supports it. func (b *Base) LookupUser(ctx context.Context, id string) (*User, error) { ul, ok := b.db.(UserLookup) if !ok { return nil, ErrUserLookupNotAvailable } return ul.GetUserByID(ctx, id) } // LookupChannel looks up a channel by ID if the database supports it. func (b *Base) LookupChannel(ctx context.Context, id string) (*Channel, error) { cl, ok := b.db.(ChannelLookup) if !ok { return nil, ErrChannelLookupNotAvailable } return cl.GetChannelByID(ctx, id) }