snapshot of https://github.com/ent/ent.git (master, 2026-09-15; blobs > 131072B omitted)
This commit is contained in:
42
examples/migration/ent/migrate/main.go
Normal file
42
examples/migration/ent/migrate/main.go
Normal file
@@ -0,0 +1,42 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
//go:build ignore
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
atlas "ariga.io/atlas/sql/migrate"
|
||||
"entgo.io/ent/dialect"
|
||||
"entgo.io/ent/dialect/sql/schema"
|
||||
"entgo.io/ent/examples/migration/ent/migrate"
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
)
|
||||
|
||||
func main() {
|
||||
ctx := context.Background()
|
||||
dir, err := atlas.NewLocalDir("ent/migrate/migrations")
|
||||
if err != nil {
|
||||
log.Fatalf("failed creating atlas migration directory: %v", err)
|
||||
}
|
||||
// Migrate diff options.
|
||||
opts := []schema.MigrateOption{
|
||||
schema.WithDir(dir), // provide migration directory
|
||||
schema.WithMigrationMode(schema.ModeReplay), // provide migration mode
|
||||
schema.WithDialect(dialect.MySQL), // Ent dialect to use
|
||||
schema.WithFormatter(atlas.DefaultFormatter), // Default Atlas formatter
|
||||
}
|
||||
if len(os.Args) != 2 {
|
||||
log.Fatalln("migration name is required. Use: 'go run -mod=mod ./ent/migrate/main.go <name>'")
|
||||
}
|
||||
// Generate migrations using Atlas support for MySQL (note the Ent dialect option passed above).
|
||||
err = migrate.NamedDiff(ctx, "mysql://root:pass@localhost:3306/test", os.Args[1], opts...)
|
||||
if err != nil {
|
||||
log.Fatalf("failed generating migration file: %v", err)
|
||||
}
|
||||
}
|
||||
100
examples/migration/ent/migrate/migrate.go
Normal file
100
examples/migration/ent/migrate/migrate.go
Normal file
@@ -0,0 +1,100 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package migrate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"entgo.io/ent/dialect"
|
||||
"entgo.io/ent/dialect/sql/schema"
|
||||
)
|
||||
|
||||
var (
|
||||
// WithGlobalUniqueID sets the universal ids options to the migration.
|
||||
// If this option is enabled, ent migration will allocate a 1<<32 range
|
||||
// for the ids of each entity (table).
|
||||
// Note that this option cannot be applied on tables that already exist.
|
||||
WithGlobalUniqueID = schema.WithGlobalUniqueID
|
||||
// WithDropColumn sets the drop column option to the migration.
|
||||
// If this option is enabled, ent migration will drop old columns
|
||||
// that were used for both fields and edges. This defaults to false.
|
||||
WithDropColumn = schema.WithDropColumn
|
||||
// WithDropIndex sets the drop index option to the migration.
|
||||
// If this option is enabled, ent migration will drop old indexes
|
||||
// that were defined in the schema. This defaults to false.
|
||||
// Note that unique constraints are defined using `UNIQUE INDEX`,
|
||||
// and therefore, it's recommended to enable this option to get more
|
||||
// flexibility in the schema changes.
|
||||
WithDropIndex = schema.WithDropIndex
|
||||
// WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true.
|
||||
WithForeignKeys = schema.WithForeignKeys
|
||||
)
|
||||
|
||||
// Schema is the API for creating, migrating and dropping a schema.
|
||||
type Schema struct {
|
||||
drv dialect.Driver
|
||||
}
|
||||
|
||||
// NewSchema creates a new schema client.
|
||||
func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} }
|
||||
|
||||
// Create creates all schema resources.
|
||||
func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error {
|
||||
return Create(ctx, s, Tables, opts...)
|
||||
}
|
||||
|
||||
// Create creates all table resources using the given schema driver.
|
||||
func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error {
|
||||
migrate, err := schema.NewMigrate(s.drv, opts...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ent/migrate: %w", err)
|
||||
}
|
||||
return migrate.Create(ctx, tables...)
|
||||
}
|
||||
|
||||
// Diff compares the state read from a database connection or migration directory with
|
||||
// the state defined by the Ent schema. Changes will be written to new migration files.
|
||||
func Diff(ctx context.Context, url string, opts ...schema.MigrateOption) error {
|
||||
return NamedDiff(ctx, url, "changes", opts...)
|
||||
}
|
||||
|
||||
// NamedDiff compares the state read from a database connection or migration directory with
|
||||
// the state defined by the Ent schema. Changes will be written to new named migration files.
|
||||
func NamedDiff(ctx context.Context, url, name string, opts ...schema.MigrateOption) error {
|
||||
return schema.Diff(ctx, url, name, Tables, opts...)
|
||||
}
|
||||
|
||||
// Diff creates a migration file containing the statements to resolve the diff
|
||||
// between the Ent schema and the connected database.
|
||||
func (s *Schema) Diff(ctx context.Context, opts ...schema.MigrateOption) error {
|
||||
migrate, err := schema.NewMigrate(s.drv, opts...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ent/migrate: %w", err)
|
||||
}
|
||||
return migrate.Diff(ctx, Tables...)
|
||||
}
|
||||
|
||||
// NamedDiff creates a named migration file containing the statements to resolve the diff
|
||||
// between the Ent schema and the connected database.
|
||||
func (s *Schema) NamedDiff(ctx context.Context, name string, opts ...schema.MigrateOption) error {
|
||||
migrate, err := schema.NewMigrate(s.drv, opts...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ent/migrate: %w", err)
|
||||
}
|
||||
return migrate.NamedDiff(ctx, name, Tables...)
|
||||
}
|
||||
|
||||
// WriteTo writes the schema changes to w instead of running them against the database.
|
||||
//
|
||||
// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil {
|
||||
// log.Fatal(err)
|
||||
// }
|
||||
func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error {
|
||||
return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...)
|
||||
}
|
||||
120
examples/migration/ent/migrate/migratedata/migratedata.go
Normal file
120
examples/migration/ent/migrate/migratedata/migratedata.go
Normal file
@@ -0,0 +1,120 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
//go:build migratedata_20221126185750
|
||||
|
||||
// Package migratedata holds the functions for generating data migration files.
|
||||
// It exists here for documentation and reference purpose only and has no runtime
|
||||
// effect on the actual migration files.
|
||||
package migratedata
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"ariga.io/atlas/sql/migrate"
|
||||
"entgo.io/ent/dialect"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/schema"
|
||||
"entgo.io/ent/dialect/sql/sqljson"
|
||||
"entgo.io/ent/examples/migration/ent"
|
||||
"entgo.io/ent/examples/migration/ent/user"
|
||||
)
|
||||
|
||||
// BackfillUserTags was used to generate the migration file '20221126185750_backfill_user_tags.sql'.
|
||||
// It exists here for documentation purpose only, and can be used as a reference for future data migrations.
|
||||
func BackfillUserTags(dir *migrate.LocalDir) error {
|
||||
w := &schema.DirWriter{Dir: dir}
|
||||
client := ent.NewClient(ent.Driver(schema.NewWriteDriver(dialect.MySQL, w)))
|
||||
|
||||
// Add defaults "foo" and "bar" tags for users without any.
|
||||
err := client.User.
|
||||
Update().
|
||||
Where(func(s *sql.Selector) {
|
||||
s.Where(
|
||||
sql.Or(
|
||||
sql.IsNull(user.FieldTags),
|
||||
sqljson.ValueIsNull(user.FieldTags),
|
||||
),
|
||||
)
|
||||
}).
|
||||
SetTags([]string{"foo", "bar"}).
|
||||
Exec(context.Background())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed generating backfill statement: %w", err)
|
||||
}
|
||||
// Document all changes until now with a custom comment.
|
||||
w.Change("Backfill NULL or null tags with a default value.")
|
||||
|
||||
// Append the "org" special tag for users with a specific prefix or suffix.
|
||||
err = client.User.
|
||||
Update().
|
||||
Where(
|
||||
user.Or(
|
||||
user.NameHasPrefix("org-"),
|
||||
user.NameHasSuffix("-org"),
|
||||
),
|
||||
// Append to only those without this tag.
|
||||
func(s *sql.Selector) {
|
||||
s.Where(
|
||||
sql.Not(sqljson.ValueContains(user.FieldTags, "org")),
|
||||
)
|
||||
},
|
||||
).
|
||||
AppendTags([]string{"org"}).
|
||||
Exec(context.Background())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed generating backfill statement: %w", err)
|
||||
}
|
||||
// Document all changes until now with a custom comment.
|
||||
w.Change("Append the 'org' tag for organization accounts in case they don't have it.")
|
||||
|
||||
// Write the content to the migration directory.
|
||||
return w.Flush("backfill_user_tags")
|
||||
}
|
||||
|
||||
// BackfillUnknown back-fills all empty users' names with the default value 'Unknown'.
|
||||
func BackfillUnknown(dir *migrate.LocalDir) error {
|
||||
w := &schema.DirWriter{Dir: dir}
|
||||
client := ent.NewClient(ent.Driver(schema.NewWriteDriver(dialect.MySQL, w)))
|
||||
|
||||
// Change all empty names to 'unknown'.
|
||||
err := client.User.
|
||||
Update().
|
||||
Where(
|
||||
user.NameEQ(""),
|
||||
).
|
||||
SetName("Unknown").
|
||||
Exec(context.Background())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed generating statement: %w", err)
|
||||
}
|
||||
|
||||
// Write the content to the migration directory.
|
||||
return w.FlushChange(
|
||||
"unknown_names",
|
||||
"Backfill all empty user names with default value 'unknown'.",
|
||||
)
|
||||
}
|
||||
|
||||
// SeedUsers add the initial users to the database.
|
||||
func SeedUsers(dir *migrate.LocalDir) error {
|
||||
w := &schema.DirWriter{Dir: dir}
|
||||
client := ent.NewClient(ent.Driver(schema.NewWriteDriver(dialect.MySQL, w)))
|
||||
|
||||
// The statement that generates the INSERT statement.
|
||||
err := client.User.CreateBulk(
|
||||
client.User.Create().SetName("a8m").SetAge(1).SetTags([]string{"foo"}),
|
||||
client.User.Create().SetName("nati").SetAge(1).SetTags([]string{"bar"}),
|
||||
).Exec(context.Background())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed generating statement: %w", err)
|
||||
}
|
||||
|
||||
// Write the content to the migration directory.
|
||||
return w.FlushChange(
|
||||
"seed_users",
|
||||
"Add the initial users to the database.",
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
-- create "users" table
|
||||
CREATE TABLE `users` (`id` bigint NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`)) CHARSET utf8mb4 COLLATE utf8mb4_bin;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- modify "users" table
|
||||
ALTER TABLE `users` ADD CHECK (age > 0), ADD COLUMN `age` double NOT NULL;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- modify "users" table
|
||||
ALTER TABLE `users` ADD CONSTRAINT `name_not_empty` CHECK (name <> ''), ADD COLUMN `name` varchar(255) NOT NULL;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- modify "users" table
|
||||
ALTER TABLE `users` ADD COLUMN `tags` json NULL;
|
||||
@@ -0,0 +1,4 @@
|
||||
-- Backfill NULL or null tags with a default value.
|
||||
UPDATE `users` SET `tags` = '["foo","bar"]' WHERE `tags` IS NULL OR JSON_CONTAINS(`tags`, 'null', '$');
|
||||
-- Append the 'org' tag for organization accounts in case they don't have it.
|
||||
UPDATE `users` SET `tags` = CASE WHEN (JSON_TYPE(JSON_EXTRACT(`tags`, '$')) IS NULL OR JSON_TYPE(JSON_EXTRACT(`tags`, '$')) = 'NULL') THEN JSON_ARRAY('org') ELSE JSON_ARRAY_APPEND(`tags`, '$', 'org') END WHERE (`users`.`name` LIKE 'org-%' OR `users`.`name` LIKE '%-org') AND (NOT (JSON_CONTAINS(`tags`, '"org"', '$') = 1));
|
||||
@@ -0,0 +1,4 @@
|
||||
-- create "cards" table
|
||||
CREATE TABLE `cards` (`id` bigint NOT NULL AUTO_INCREMENT, `owner_id` bigint NOT NULL DEFAULT 0, PRIMARY KEY (`id`), INDEX `cards_users_cards` (`owner_id`), CONSTRAINT `cards_users_cards` FOREIGN KEY (`owner_id`) REFERENCES `users` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION) CHARSET utf8mb4 COLLATE utf8mb4_bin;
|
||||
-- create "pets" table
|
||||
CREATE TABLE `pets` (`id` char(36) NOT NULL, `best_friend_id` char(36) NULL DEFAULT "00000000-0000-0000-0000-000000000000", `owner_id` bigint NOT NULL DEFAULT 0, PRIMARY KEY (`id`), UNIQUE INDEX `best_friend_id` (`best_friend_id`), INDEX `pets_users_owner` (`owner_id`), CONSTRAINT `pets_pets_best_friend` FOREIGN KEY (`best_friend_id`) REFERENCES `pets` (`id`) ON UPDATE NO ACTION ON DELETE SET NULL, CONSTRAINT `pets_users_owner` FOREIGN KEY (`owner_id`) REFERENCES `users` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION) CHARSET utf8mb4 COLLATE utf8mb4_bin;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Modify "cards" table
|
||||
ALTER TABLE `cards` ADD CONSTRAINT `number_length` CHECK (length(`number`) = 16), ADD COLUMN `number` varchar(255) NOT NULL;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Modify "pets" table
|
||||
ALTER TABLE `pets` ADD COLUMN `name` varchar(255) NOT NULL, ADD UNIQUE INDEX `pet_name_owner_id` (`name`, `owner_id`);
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Create "payments" table
|
||||
CREATE TABLE `payments` (`id` bigint NOT NULL AUTO_INCREMENT, `amount` double NOT NULL, `currency` enum('USD','ILS') NOT NULL, `time` timestamp NOT NULL, `description` varchar(255) NOT NULL, `status` enum('pending','completed','failed') NOT NULL, `card_id` bigint NOT NULL, PRIMARY KEY (`id`), INDEX `payment_status_time` (`status`, `time`), INDEX `payments_cards_payments` (`card_id`), CONSTRAINT `payments_cards_payments` FOREIGN KEY (`card_id`) REFERENCES `cards` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION, CONSTRAINT `amount_positive` CHECK (`amount` > 0)) CHARSET utf8mb4 COLLATE utf8mb4_bin;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Modify "payments" table
|
||||
ALTER TABLE `payments` MODIFY COLUMN `currency` enum('USD','EUR','ILS') NOT NULL;
|
||||
@@ -0,0 +1,6 @@
|
||||
-- Modify "users" table
|
||||
ALTER TABLE `users` DROP CONSTRAINT `name_not_empty`, ADD CONSTRAINT `first_last_not_empty` CHECK ((`first_name` <> _utf8mb4'') and (`last_name` <> _utf8mb4'')), DROP COLUMN `name`, ADD COLUMN `first_name` varchar(255) NOT NULL, ADD COLUMN `last_name` varchar(255) NOT NULL;
|
||||
-- Create "session_devices" table
|
||||
CREATE TABLE `session_devices` (`id` char(36) NOT NULL, `ip_address` varchar(50) NOT NULL, `user_agent` varchar(512) NOT NULL, `location` varchar(512) NOT NULL, `created_at` timestamp NOT NULL, `updated_at` timestamp NULL, PRIMARY KEY (`id`), INDEX `sessiondevice_ip_address_user_agent` (`ip_address`, `user_agent`), INDEX `sessiondevice_location_updated_at` (`location`, `updated_at`)) CHARSET utf8mb4 COLLATE utf8mb4_bin;
|
||||
-- Create "sessions" table
|
||||
CREATE TABLE `sessions` (`id` char(36) NOT NULL, `active` bool NOT NULL DEFAULT 0, `issued_at` timestamp NOT NULL, `expires_at` timestamp NULL, `token` varchar(255) NULL, `method` json NULL, `device_id` char(36) NULL, PRIMARY KEY (`id`), INDEX `session_active_expires_at` (`active`, `expires_at`), INDEX `sessions_session_devices_sessions` (`device_id`), CONSTRAINT `sessions_session_devices_sessions` FOREIGN KEY (`device_id`) REFERENCES `session_devices` (`id`) ON UPDATE NO ACTION ON DELETE SET NULL, CONSTRAINT `token_length` CHECK (length(`token`) = 64)) CHARSET utf8mb4 COLLATE utf8mb4_bin;
|
||||
@@ -0,0 +1,4 @@
|
||||
-- Modify "cards" table
|
||||
ALTER TABLE `cards` DROP CONSTRAINT `number_length`, ADD CONSTRAINT `number_hash_length` CHECK (length(`number_hash`) = 16), RENAME COLUMN `number` TO `number_hash`, ADD COLUMN `cvv_hash` varchar(255) NOT NULL, ADD COLUMN `expires_at` timestamp NULL;
|
||||
-- Modify "pets" table
|
||||
ALTER TABLE `pets` ADD COLUMN `age` double NOT NULL AFTER `id`, ADD COLUMN `weight` double NOT NULL AFTER `id`;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Modify "cards" table
|
||||
ALTER TABLE `cards` ADD COLUMN `type` varchar(255) NOT NULL DEFAULT "unknown";
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Modify "payments" table
|
||||
ALTER TABLE `payments` MODIFY COLUMN `currency` enum('USD','EUR','VND','ILS') NOT NULL;
|
||||
15
examples/migration/ent/migrate/migrations/atlas.sum
Normal file
15
examples/migration/ent/migrate/migrations/atlas.sum
Normal file
@@ -0,0 +1,15 @@
|
||||
h1:QMBPKnW6IBUAFXLNorT9V6E3OkehchN72/bgEHavP/0=
|
||||
20221114082343_create_users.sql h1:EeOPKbOeYUHO830P1MCXKUsxT3wLk/hSgcpT9GzlGZQ=
|
||||
20221114090322_add_age.sql h1:weRCTqS5cqKyrvIjGXk7Bn24YUXo0nhLNWD0EZBcaoQ=
|
||||
20221114101516_add_name.sql h1:leQgI2JN3URZyujlNzX3gI53MSiTA02MKI/G9cnMu6I=
|
||||
20221126173531_add_user_tags.sql h1:9yq4x41NnP8gqBg3IUbHKwE7gP/23Mx3ylf5IorLoFs=
|
||||
20221126185750_backfill_user_tags.sql h1:qBPBJD4ry+uwj1eGPmTr5COJwv8Sjo2o+OR7TWFj6qs=
|
||||
20230101214930_default_values.sql h1:W07mGRkz22lrW0dvcChRtRc5b03Kp2CsFAQZvsnb8qs=
|
||||
20231231083716_add_card_number.sql h1:sBxY6RlbqEsE8hx6Q/hSuNXfBGvVmZ0OYiZcP8uDNOc=
|
||||
20231231091550_add_pet_name.sql h1:80NyHhZ/ZC4Um0j0NLzUpf1UBj4GKvMu678EqkJsFuU=
|
||||
20231231101555_add_payment.sql h1:Je16hh6fEWuL5/nbQN5v+MNkC8ruhtTgEcEgkh+Gyyg=
|
||||
20231231102849_add_currency.sql h1:Dzm4fDibgEV841whj7Y1TMeat6Qt5d7kQojBXNIh2nY=
|
||||
20231231120006_add_session.sql h1:n725mYZBuwUU2Nl8XdUFDgn2Dbm2kpVwAASEtWOqQuo=
|
||||
20231231123114_hash_card.sql h1:ZsZUe2+vJ6echLKnQxBhXyVoBJja2IAY7rX/P5UZ0iE=
|
||||
20240229200634_add_card_type.sql h1:y6kam4J45wzdgUh7eU9TTgbs8GwKuqNWyfqaFEtNgbY=
|
||||
20240317101809_add_payment_vnd.sql h1:IuRWMJvwkPoZJ+T9luhjvnaBwGQIvgU5vJbduE4HMok=
|
||||
213
examples/migration/ent/migrate/schema.go
Normal file
213
examples/migration/ent/migrate/schema.go
Normal file
@@ -0,0 +1,213 @@
|
||||
// Copyright 2019-present Facebook Inc. All rights reserved.
|
||||
// This source code is licensed under the Apache 2.0 license found
|
||||
// in the LICENSE file in the root directory of this source tree.
|
||||
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package migrate
|
||||
|
||||
import (
|
||||
"entgo.io/ent/dialect/entsql"
|
||||
"entgo.io/ent/dialect/sql/schema"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
var (
|
||||
// CardsColumns holds the columns for the "cards" table.
|
||||
CardsColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeInt, Increment: true},
|
||||
{Name: "type", Type: field.TypeString, Default: "unknown"},
|
||||
{Name: "number_hash", Type: field.TypeString},
|
||||
{Name: "cvv_hash", Type: field.TypeString},
|
||||
{Name: "expires_at", Type: field.TypeTime, Nullable: true},
|
||||
{Name: "owner_id", Type: field.TypeInt, Default: 0},
|
||||
}
|
||||
// CardsTable holds the schema information for the "cards" table.
|
||||
CardsTable = &schema.Table{
|
||||
Name: "cards",
|
||||
Columns: CardsColumns,
|
||||
PrimaryKey: []*schema.Column{CardsColumns[0]},
|
||||
ForeignKeys: []*schema.ForeignKey{
|
||||
{
|
||||
Symbol: "cards_users_cards",
|
||||
Columns: []*schema.Column{CardsColumns[5]},
|
||||
RefColumns: []*schema.Column{UsersColumns[0]},
|
||||
OnDelete: schema.NoAction,
|
||||
},
|
||||
},
|
||||
}
|
||||
// PaymentsColumns holds the columns for the "payments" table.
|
||||
PaymentsColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeInt, Increment: true},
|
||||
{Name: "amount", Type: field.TypeFloat64},
|
||||
{Name: "currency", Type: field.TypeEnum, Enums: []string{"USD", "EUR", "VND", "ILS"}},
|
||||
{Name: "time", Type: field.TypeTime},
|
||||
{Name: "description", Type: field.TypeString},
|
||||
{Name: "status", Type: field.TypeEnum, Enums: []string{"pending", "completed", "failed"}},
|
||||
{Name: "card_id", Type: field.TypeInt},
|
||||
}
|
||||
// PaymentsTable holds the schema information for the "payments" table.
|
||||
PaymentsTable = &schema.Table{
|
||||
Name: "payments",
|
||||
Columns: PaymentsColumns,
|
||||
PrimaryKey: []*schema.Column{PaymentsColumns[0]},
|
||||
ForeignKeys: []*schema.ForeignKey{
|
||||
{
|
||||
Symbol: "payments_cards_payments",
|
||||
Columns: []*schema.Column{PaymentsColumns[6]},
|
||||
RefColumns: []*schema.Column{CardsColumns[0]},
|
||||
OnDelete: schema.NoAction,
|
||||
},
|
||||
},
|
||||
Indexes: []*schema.Index{
|
||||
{
|
||||
Name: "payment_status_time",
|
||||
Unique: false,
|
||||
Columns: []*schema.Column{PaymentsColumns[5], PaymentsColumns[3]},
|
||||
},
|
||||
},
|
||||
}
|
||||
// PetsColumns holds the columns for the "pets" table.
|
||||
PetsColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeUUID},
|
||||
{Name: "name", Type: field.TypeString},
|
||||
{Name: "age", Type: field.TypeFloat64},
|
||||
{Name: "weight", Type: field.TypeFloat64},
|
||||
{Name: "best_friend_id", Type: field.TypeUUID, Unique: true, Nullable: true, Default: "00000000-0000-0000-0000-000000000000"},
|
||||
{Name: "owner_id", Type: field.TypeInt, Default: 0},
|
||||
}
|
||||
// PetsTable holds the schema information for the "pets" table.
|
||||
PetsTable = &schema.Table{
|
||||
Name: "pets",
|
||||
Columns: PetsColumns,
|
||||
PrimaryKey: []*schema.Column{PetsColumns[0]},
|
||||
ForeignKeys: []*schema.ForeignKey{
|
||||
{
|
||||
Symbol: "pets_pets_best_friend",
|
||||
Columns: []*schema.Column{PetsColumns[4]},
|
||||
RefColumns: []*schema.Column{PetsColumns[0]},
|
||||
OnDelete: schema.SetNull,
|
||||
},
|
||||
{
|
||||
Symbol: "pets_users_owner",
|
||||
Columns: []*schema.Column{PetsColumns[5]},
|
||||
RefColumns: []*schema.Column{UsersColumns[0]},
|
||||
OnDelete: schema.NoAction,
|
||||
},
|
||||
},
|
||||
Indexes: []*schema.Index{
|
||||
{
|
||||
Name: "pet_name_owner_id",
|
||||
Unique: true,
|
||||
Columns: []*schema.Column{PetsColumns[1], PetsColumns[5]},
|
||||
},
|
||||
},
|
||||
}
|
||||
// SessionsColumns holds the columns for the "sessions" table.
|
||||
SessionsColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeUUID},
|
||||
{Name: "active", Type: field.TypeBool, Default: false},
|
||||
{Name: "issued_at", Type: field.TypeTime},
|
||||
{Name: "expires_at", Type: field.TypeTime, Nullable: true},
|
||||
{Name: "token", Type: field.TypeString, Nullable: true},
|
||||
{Name: "method", Type: field.TypeJSON, Nullable: true},
|
||||
{Name: "device_id", Type: field.TypeUUID, Nullable: true},
|
||||
}
|
||||
// SessionsTable holds the schema information for the "sessions" table.
|
||||
SessionsTable = &schema.Table{
|
||||
Name: "sessions",
|
||||
Columns: SessionsColumns,
|
||||
PrimaryKey: []*schema.Column{SessionsColumns[0]},
|
||||
ForeignKeys: []*schema.ForeignKey{
|
||||
{
|
||||
Symbol: "sessions_session_devices_sessions",
|
||||
Columns: []*schema.Column{SessionsColumns[6]},
|
||||
RefColumns: []*schema.Column{SessionDevicesColumns[0]},
|
||||
OnDelete: schema.SetNull,
|
||||
},
|
||||
},
|
||||
Indexes: []*schema.Index{
|
||||
{
|
||||
Name: "session_active_expires_at",
|
||||
Unique: false,
|
||||
Columns: []*schema.Column{SessionsColumns[1], SessionsColumns[3]},
|
||||
},
|
||||
},
|
||||
}
|
||||
// SessionDevicesColumns holds the columns for the "session_devices" table.
|
||||
SessionDevicesColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeUUID},
|
||||
{Name: "ip_address", Type: field.TypeString, Size: 50},
|
||||
{Name: "user_agent", Type: field.TypeString, Size: 512},
|
||||
{Name: "location", Type: field.TypeString, Size: 512},
|
||||
{Name: "created_at", Type: field.TypeTime},
|
||||
{Name: "updated_at", Type: field.TypeTime, Nullable: true},
|
||||
}
|
||||
// SessionDevicesTable holds the schema information for the "session_devices" table.
|
||||
SessionDevicesTable = &schema.Table{
|
||||
Name: "session_devices",
|
||||
Columns: SessionDevicesColumns,
|
||||
PrimaryKey: []*schema.Column{SessionDevicesColumns[0]},
|
||||
Indexes: []*schema.Index{
|
||||
{
|
||||
Name: "sessiondevice_ip_address_user_agent",
|
||||
Unique: false,
|
||||
Columns: []*schema.Column{SessionDevicesColumns[1], SessionDevicesColumns[2]},
|
||||
},
|
||||
{
|
||||
Name: "sessiondevice_location_updated_at",
|
||||
Unique: false,
|
||||
Columns: []*schema.Column{SessionDevicesColumns[3], SessionDevicesColumns[5]},
|
||||
},
|
||||
},
|
||||
}
|
||||
// UsersColumns holds the columns for the "users" table.
|
||||
UsersColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeInt, Increment: true},
|
||||
{Name: "age", Type: field.TypeFloat64},
|
||||
{Name: "first_name", Type: field.TypeString},
|
||||
{Name: "last_name", Type: field.TypeString},
|
||||
{Name: "tags", Type: field.TypeJSON, Nullable: true},
|
||||
}
|
||||
// UsersTable holds the schema information for the "users" table.
|
||||
UsersTable = &schema.Table{
|
||||
Name: "users",
|
||||
Columns: UsersColumns,
|
||||
PrimaryKey: []*schema.Column{UsersColumns[0]},
|
||||
}
|
||||
// Tables holds all the tables in the schema.
|
||||
Tables = []*schema.Table{
|
||||
CardsTable,
|
||||
PaymentsTable,
|
||||
PetsTable,
|
||||
SessionsTable,
|
||||
SessionDevicesTable,
|
||||
UsersTable,
|
||||
}
|
||||
)
|
||||
|
||||
func init() {
|
||||
CardsTable.ForeignKeys[0].RefTable = UsersTable
|
||||
CardsTable.Annotation = &entsql.Annotation{}
|
||||
CardsTable.Annotation.Checks = map[string]string{
|
||||
"number_hash_length": "(LENGTH(`number_hash`) = 16)",
|
||||
}
|
||||
PaymentsTable.ForeignKeys[0].RefTable = CardsTable
|
||||
PaymentsTable.Annotation = &entsql.Annotation{}
|
||||
PaymentsTable.Annotation.Checks = map[string]string{
|
||||
"amount_positive": "(`amount` > 0)",
|
||||
}
|
||||
PetsTable.ForeignKeys[0].RefTable = PetsTable
|
||||
PetsTable.ForeignKeys[1].RefTable = UsersTable
|
||||
SessionsTable.ForeignKeys[0].RefTable = SessionDevicesTable
|
||||
SessionsTable.Annotation = &entsql.Annotation{}
|
||||
SessionsTable.Annotation.Checks = map[string]string{
|
||||
"token_length": "(LENGTH(`token`) = 64)",
|
||||
}
|
||||
UsersTable.Annotation = &entsql.Annotation{
|
||||
Check: "age > 0",
|
||||
}
|
||||
UsersTable.Annotation.Checks = map[string]string{
|
||||
"first_last_not_empty": "(`first_name` <> '' AND `last_name` <> '')",
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user