8000 gormschema: support view for standalone mode by luantranminh · Pull Request #48 · ariga/atlas-provider-gorm · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

gormschema: support view for standalone mode #48

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
May 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ go get -u ariga.io/atlas-provider-gorm

#### Standalone

If all of your GORM models exist in a single package, and either embed `gorm.Model` or contain `gorm` struct tags,
If all of your GORM models and [views](#views) exist in a single package, and the models either embed `gorm.Model` or contain `gorm` struct tags,
you can use the provider directly to load your GORM schema into Atlas.

In your project directory, create a new file named `atlas.hcl` with the following contents:
Expand Down
10 changes: 10 additions & 0 deletions internal/testdata/migrations/mysql/20240518091603.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
-- Create "top_pet_owners" view
CREATE VIEW `top_pet_owners` (
`user_id`,
`pet_count`
) AS select `pets`.`user_id` AS `user_id`,count(`pets`.`id`) AS `pet_count` from `pets` group by `pets`.`user_id` order by `pet_count` desc limit 10;
-- Create "working_aged_users" view
CREATE VIEW `working_aged_users` (
`name`,
`age`
) AS select `users`.`name` AS `name`,`users`.`age` AS `age` from `users` where (`users`.`age` between 18 and 65);
3 changes: 2 additions & 1 deletion internal/testdata/migrations/mysql/atlas.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
h1:EyWYG0960slDir9YpK58ESoedcEsH+CKiFHSuErul/s=
h1:lKRYkpC/b7av3+2N9ZwAhoInac+KYoj12ZIPaAINpeI=
20230627123246.sql h1:+bgzC3WJyyIR6Rv/FUvaNXJ1gkbKJlYcEMgp69yORIY=
20240512024238.sql h1:2kQL4tE/tAhvXuozmRAJ3oXTo1KRz11QosVDw+0va14=
20240518091603.sql h1:xNClqqRaOjXwg0julpsiPYsmqUcEL/hJel1iqYzi3DM=
18 changes: 18 additions & 0 deletions internal/testdata/migrations/postgres/20240518091611.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
-- Create "top_pet_owners" view
CREATE VIEW "public"."top_pet_owners" (
"user_id",
"pet_count"
) AS SELECT pets.user_id,
count(pets.id) AS pet_count
FROM pets
GROUP BY pets.user_id
ORDER BY (count(pets.id)) DESC
LIMIT 10;
-- Create "working_aged_users" view
CREATE VIEW "public"."working_aged_users" (
"name",
"age"
) AS SELECT users.name,
users.age
FROM users
WHERE ((users.age >= 18) AND (users.age <= 65));
3 changes: 2 additions & 1 deletion internal/testdata/migrations/postgres/atlas.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
h1:uqmcTXuu1CtyKBXEPvSoc31Grcd1CJSGrp1S1l7aKZA=
h1:LR1ImLA5ZOcbBr9yHMReTtaRiM6dVScC6Xefy3kpxWI=
20230627123049.sql h1:1jYJM2+VCr9152vg6gayCrcEvuT/FE7ufOyZ86VLaOE=
20240512024223.sql h1:RY4w148OJBBr5sXpfBq6B48p/1cFrTEpH4TlwD7mUps=
20240518091611.sql h1:3Kv6mYS8ML72H6HE5qr/a2gdVUrfWuHVufP/1wl70vE=
10 changes: 10 additions & 0 deletions internal/testdata/migrations/sqlite/20240518091437.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
-- Create "top_pet_owners" view
CREATE VIEW `top_pet_owners` (
`user_id`,
`pet_count`
) AS SELECT user_id, COUNT(id) AS pet_count FROM pets GROUP BY user_id ORDER BY pet_count DESC LIMIT 10;
-- Create "working_aged_users" view
CREATE VIEW `working_aged_users` (
`name`,
`age`
) AS SELECT name, age FROM `users` WHERE age BETWEEN 18 AND 65;
3 changes: 2 additions & 1 deletion internal/testdata/migrations/sqlite/atlas.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
h1:PLxrE6aQnCB/DzDmVKw6PWEawC1zPVYEB5fQNJ960C4=
h1:4HTi5BBlSSs2F/Rg17KQCcuEsVY/dDwyF2yzjThRcd0=
20230627123228.sql h1:YfwJdN73sWz1G5/0tU2BtGLyzJCfRQr8blTSquUZ+qo=
20240511123637.sql h1:Kbk3wUzTfBbq8mDdTT08hP93ecNU0y5oTL+O8idEcdQ=
20240518091437.sql h1:svMANRZuZDvgzqO3iyNLUjrUrK8BTMEB2f0NV3d5sJo=
10 changes: 10 additions & 0 deletions internal/testdata/migrations/sqlserver/20240518091510.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
-- Create "top_pet_owners" view
CREATE VIEW [top_pet_owners] (
[user_id],
[pet_count]
) AS SELECT user_id, COUNT(id) AS pet_count FROM pets GROUP BY user_id ORDER BY pet_count DESC OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY;
-- Create "working_aged_users" view
CREATE VIEW [working_aged_users] (
[name],
[age]
) AS SELECT name, age FROM "users" WHERE age BETWEEN 18 AND 65;
3 changes: 2 additions & 1 deletion internal/testdata/migrations/sqlserver/atlas.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
h1:wFBjEJ2HW3DrEa+JbxBrEd/i01JNYWYOFL3R3u9esTs=
h1:24mg+pUG3Z4l321YP5s1fRPPaAg6sJC8VR62qPXClTw=
20240124151658.sql h1:KaWALlql7BBV3oPVRT4rn+dvZaolhDmgbTgUPxIhauU=
20240512024328.sql h1:IBON1V3jlts+AqxRhejN82SE7/BIXSUWM0SQ0pvw4wc=
20240518091510.sql h1:CCFQHjVI+5dLXCgoPSERCHhyGBZl7QistZlrs1I5170=
52 changes: 33 additions & 19 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import (

"github.com/alecthomas/kong"
"golang.org/x/tools/go/packages"

"ariga.io/atlas-provider-gorm/gormschema"
)

var (
Expand Down Expand Up @@ -46,13 +48,27 @@ type LoadCmd struct {
out io.Writer
}

var viewDefiner = reflect.TypeOf((*gormschema.ViewDefiner)(nil)).Elem()

func (c *LoadCmd) Run() error {
cfg := &packages.Config{Mode: packages.NeedName | packages.NeedTypes | packages.NeedTypesInfo | packages.NeedModule | packages.NeedDeps}
pkgs, err := packages.Load(cfg, c.Path)
if err != nil {
return err
cfg := &packages.Config{
Mode: packages.NeedName | packages.NeedTypes | packages.NeedTypesInfo | packages.NeedModule | packages.NeedDeps,
}
var models []model
switch pkgs, err := packages.Load(cfg, c.Path, viewDefiner.PkgPath()); {
case err != nil:
return fmt.Errorf("loading package: %w", err)
case len(pkgs) != 2:
return fmt.Errorf("missing package information for: %s", c.Path)
default:
schemaPkg, modelsPkg := pkgs[0], pkgs[1]
if schemaPkg.PkgPath != viewDefiner.PkgPath() {
schemaPkg, modelsPkg = pkgs[1], pkgs[0]
}
models = gatherModels(modelsPkg, schemaPkg.Types.Scope().
Lookup(viewDefiner.Name()).Type().
Underlying().(*types.Interface))
}
models := gatherModels(pkgs)
p := Payload{
Models: models,
Dialect: c.Dialect,
Expand Down Expand Up @@ -140,21 +156,19 @@ type model struct {
Name string
}

func gatherModels(pkgs []*packages.Package) []model {
func gatherModels(pkg *packages.Package, view *types.Interface) []model {
var models []model
for _, pkg := range pkgs {
for k, v := range pkg.TypesInfo.Defs {
_, ok := v.(*types.TypeName)
if !ok || !k.IsExported() {
continue
}
if isGORMModel(k.Obj.Decl) {
models = append(models, model{
ImportPath: pkg.PkgPath,
Name: k.Name,
PkgName: pkg.Name,
})
}
for k, v := range pkg.TypesInfo.Defs {
typ, ok := v.(*types.TypeName)
if !ok || !k.IsExported() {
continue
}
if isGORMModel(k.Obj.Decl) || types.Implements(typ.Type(), view) {
models = append(models, model{
ImportPath: pkg.PkgPath,
Name: k.Name,
PkgName: pkg.Name,
})
}
}
// Return models in deterministic order.
Expand Down
4 changes: 3 additions & 1 deletion main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ func TestLoad(t *testing.T) {
func TestDeterministicOutput(t *testing.T) {
expected := "CREATE TABLE `users` (`id` integer,`created_at` datetime,`updated_at` datetime,`deleted_at` datetime,`name` text,`age` integer,PRIMARY KEY (`id`));\n" +
"CREATE INDEX `idx_users_deleted_at` ON `users`(`deleted_at`);\n" +
"CREATE TABLE `pets` (`id` integer,`created_at` datetime,`updated_at` datetime,`deleted_at` datetime,`name` text,`user_id` integer,PRIMARY KEY (`id`),CONSTRAINT `fk_users_pets` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`));\nCREATE INDEX `idx_pets_deleted_at` ON `pets`(`deleted_at`);\n\n"
"CREATE TABLE `pets` (`id` integer,`created_at` datetime,`updated_at` datetime,`deleted_at` datetime,`name` text,`user_id` integer,PRIMARY KEY (`id`),CONSTRAINT `fk_users_pets` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`));\nCREATE INDEX `idx_pets_deleted_at` ON `pets`(`deleted_at`);\n" +
"CREATE VIEW top_pet_owners AS SELECT user_id, COUNT(id) AS pet_count FROM pets GROUP BY user_id ORDER BY pet_count DESC LIMIT 10;\n" +
"CREATE VIEW working_aged_users AS SELECT name, age FROM `users` WHERE age BETWEEN 18 AND 65;\n\n"
cmd := &LoadCmd{
Path: "./internal/testdata/models",
Dialect: "sqlite",
Expand Down
Loading
0