Schema System Feature
Overview​
The Schema System is the foundation of the forge framework. It provides a declarative way to define models with full Django-like field options, relationships, metadata, and lifecycle hooks.
Location​
forge/schema/
Status​
✅ Complete - Production ready
Core Components​
1. Schema Interface (schema.go)​
The core interface that all models must implement:
type Schema interface {
Fields() []Field
Relations() []Relation
Meta() Meta
Hooks() *ModelHooks
}
2. Field Definitions (field.go)​
Complete field type system with all Django field options:
Field Types:
TypeInt64,TypeInt32- Integer fieldsTypeString,TypeText- String fieldsTypeBool- Boolean fieldsTypeTime,TypeDate,TypeDateTime- Time fieldsTypeFloat32,TypeFloat64,TypeDecimal- Float fieldsTypeEmail,TypeURL- Specialized string fieldsTypeUUID- UUID fieldsTypeJSON- JSON fieldsTypeBytes- Byte array fieldsTypeForeignKey,TypeManyToMany,TypeOneToOne- Relationship fields
Field Options:
Required()- Field is requiredBlank()- Field can be blankDefault(value)- Default valuePrimary()- Primary keyAutoIncrement()- Auto-incrementingUnique()- Unique constraintIndex()- Database indexMaxLength(n)- Maximum lengthMinLength(n)- Minimum lengthChoices([]Choice)- Predefined choicesHelpText(text)- Help textVerboseName(name)- Human-readable nameDBColumn(name)- Custom column nameDBType(type)- Custom database typeDBIndex(bool)- Database indexDBCollation(collation)- Character collationDBComment(comment)- Column commentGenerated(expr)- Generated columnValidators([]Validator)- Custom validatorsValidationTag(tag)- Validation tagEditable(bool)- Editable flagAutoNow()- Auto-update on saveAutoNowAdd()- Auto-set on creation
3. Relationship Definitions (relation.go)​
Django-style relationship definitions:
Relation Types:
ForeignKey- Many-to-one relationshipOneToOne- One-to-one relationshipManyToMany- Many-to-many relationshipOneToMany- One-to-many relationship (reverse)
Relation Options:
Target(model)- Target modelRequired(bool)- Required relationshipOnDelete(action)- Cascade action on deleteOnUpdate(action)- Cascade action on updateRelatedName(name)- Reverse relation nameThrough(model)- Through model for ManyToMany
4. Model Metadata (meta.go)​
Complete Django Meta options:
Meta Options:
TableName- Custom table nameOrderBy- Default orderingVerboseName- Human-readable nameVerboseNamePlural- Plural nameIndexes- Database indexesUniqueTogether- Unique constraintsConstraints- Custom constraintsPermissions- Model permissionsDefaultPermissions- Use default permissions
5. Lifecycle Hooks (hooks.go)​
Model lifecycle hooks for custom logic:
Hooks:
BeforeSave- Before save (create or update)AfterSave- After save (create or update)BeforeCreate- Before createAfterCreate- After createBeforeUpdate- Before updateAfterUpdate- After updateBeforeDelete- Before deleteAfterDelete- After delete
Hook Execution Order:
- Create:
BeforeSave→BeforeCreate→ DB Insert →AfterCreate→AfterSave - Update:
BeforeSave→BeforeUpdate→ DB Update →AfterUpdate→AfterSave - Delete:
BeforeDelete→ DB Delete →AfterDelete
6. Constraint Builder (constraint_builder.go)​
Database constraint builders for advanced schema definitions.
Features​
✅ Complete Features​
- All Django Field Types - Complete field type system
- All Django Field Options - Full field option support
- Relationship Definitions - ForeignKey, OneToOne, ManyToMany
- Model Metadata - Complete Meta options
- Lifecycle Hooks - Before/after save, create, update, delete
- Database Constraints - Indexes, unique constraints, custom constraints
- Validation Integration - Validator support
- Code Generation Ready - Schema designed for code generation
Field Builder Pattern​
Fields use a fluent builder pattern:
fields.String("username").
Required().
MaxLength(150).
Unique().
HelpText("Required. 150 characters or fewer.").
Build()
Usage Examples​
Basic Model​
type User struct {
schema.BaseSchema
}
func (User) Fields() []schema.Field {
return []schema.Field{
fields.Int64("id").Primary().AutoIncrement().Build(),
fields.String("username").Required().Unique().MaxLength(150).Build(),
fields.String("email").Required().Unique().MaxLength(254).Build(),
fields.Bool("is_active").Default(true).Build(),
fields.Time("created_at").AutoNowAdd().Build(),
fields.Time("updated_at").AutoNow().Build(),
}
}
func (User) Meta() schema.Meta {
return schema.Meta{
TableName: "users",
VerboseName: "User",
VerboseNamePlural: "Users",
OrderBy: []string{"-created_at"},
}
}
Model with Relationships​
type Post struct {
schema.BaseSchema
}
func (Post) Fields() []schema.Field {
return []schema.Field{
fields.Int64("id").Primary().AutoIncrement().Build(),
fields.String("title").Required().MaxLength(200).Build(),
fields.Text("content").Required().Build(),
fields.Bool("published").Default(false).Build(),
fields.Time("created_at").AutoNowAdd().Build(),
}
}
func (Post) Relations() []schema.Relation {
return []schema.Relation{
relations.ForeignKey("author", "User").Required().OnDelete(relations.CASCADE).Build(),
relations.ManyToMany("tags", "Tag").Build(),
}
}
Model with Hooks​
func (User) Hooks() *schema.ModelHooks {
return &schema.ModelHooks{
BeforeSave: func(ctx context.Context, instance interface{}) error {
// Custom logic before save
return nil
},
AfterCreate: func(ctx context.Context, instance interface{}) error {
// Custom logic after create
return nil
},
}
}
Integration Points​
Code Generation​
- Schema definitions are parsed by AST parser
- Code generator creates model structs, managers, querysets
ORM System​
- ORM uses schema for query building
- Field expressions generated from schema
- Relationships used for joins
Admin System​
- Admin uses schema for form generation
- Field widgets based on field types
- Relationships used for inlines
Migration System​
- Migrations generated from schema
- Schema changes detected automatically
- Database schema synchronized
Extension Points​
Custom Fields​
- Define custom field types
- Custom field builders
- Custom validation
Custom Relations​
- Custom relationship types
- Custom cascade behaviors
Custom Hooks​
- Additional hook types
- Custom hook execution
Best Practices​
- Use BaseSchema - Embed
schema.BaseSchemafor default implementations - Field Builders - Use field builders for type safety
- Meta Options - Set appropriate Meta options
- Hooks - Use hooks for business logic, not data access
- Validation - Use validators for data validation
- Naming - Follow Django naming conventions
Future Enhancements​
- Custom field types
- Field inheritance
- Schema versioning
- Schema migrations
- Schema validation