From c7c9cfdb665bf83163aa475fe3921651e955297c Mon Sep 17 00:00:00 2001 From: Geapefurit <670884108@qq.com> Date: Wed, 22 Nov 2023 14:41:38 +0800 Subject: [PATCH] support auto increment id --- Makefile | 3 +- cmd/sphinx-proxy/run.go | 5 ++ go.mod | 8 +- go.sum | 7 ++ pkg/db/ent/client.go | 9 +- pkg/db/ent/config.go | 28 +++++++ pkg/db/ent/migrate/schema.go | 10 ++- pkg/db/ent/mutation.go | 68 +++++++++++++-- pkg/db/ent/runtime.go | 49 ++++++----- pkg/db/ent/schema/transaction.go | 11 ++- pkg/db/ent/transaction.go | 21 +++-- pkg/db/ent/transaction/transaction.go | 7 +- pkg/db/ent/transaction/where.go | 89 ++++++++++++++++++-- pkg/db/ent/transaction_create.go | 116 +++++++++++++++++++------- pkg/db/ent/transaction_delete.go | 2 +- pkg/db/ent/transaction_query.go | 78 +++++++++++++---- pkg/db/ent/transaction_update.go | 73 ++++++++++++++-- pkg/db/ent/tx.go | 26 ++++++ 18 files changed, 495 insertions(+), 115 deletions(-) diff --git a/Makefile b/Makefile index ed304b3..12e6a22 100644 --- a/Makefile +++ b/Makefile @@ -54,7 +54,8 @@ verify-spelling: ## Verifies spelling. gen-ent: go get -d entgo.io/ent/cmd/ent@v0.11.2 - go run entgo.io/ent/cmd/ent generate --feature sql/upsert ./pkg/db/ent/schema + go run -mod=mod entgo.io/ent/cmd/ent generate --feature entql,sql/lock,sql/execquery,sql/upsert,privacy,schema/snapshot,sql/modifier ./pkg/db/ent/schema + all: verify-build diff --git a/cmd/sphinx-proxy/run.go b/cmd/sphinx-proxy/run.go index 43904c1..9255733 100644 --- a/cmd/sphinx-proxy/run.go +++ b/cmd/sphinx-proxy/run.go @@ -8,6 +8,8 @@ import ( "github.com/NpoolPlatform/go-service-framework/pkg/logger" "github.com/NpoolPlatform/sphinx-proxy/api" "github.com/NpoolPlatform/sphinx-proxy/pkg/db" + "github.com/NpoolPlatform/sphinx-proxy/pkg/migrator" + "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" cli "github.com/urfave/cli/v2" "google.golang.org/grpc" @@ -29,6 +31,9 @@ var runCmd = &cli.Command{ } func run(ctx context.Context) error { + if err := migrator.Migrate(ctx); err != nil { + return err + } if err := db.Init(); err != nil { return err } diff --git a/go.mod b/go.mod index cc7b101..3934054 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/NpoolPlatform/sphinx-proxy go 1.17 require ( - entgo.io/ent v0.12.0 + entgo.io/ent v0.11.2 github.com/NpoolPlatform/basal-middleware v0.0.0-20231015112137-254853c60eec github.com/NpoolPlatform/chain-middleware v0.0.0-20231020114413-49166aeb1ec8 github.com/NpoolPlatform/go-service-framework v0.0.0-20230930023319-e48074d9472e @@ -78,6 +78,7 @@ require ( github.com/deckarep/golang-set v1.8.0 // indirect github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 // indirect github.com/dfuse-io/logging v0.0.0-20210109005628-b97a57253f70 // indirect + github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/ethereum/go-ethereum v1.10.26 // indirect github.com/fatih/color v1.13.0 // indirect github.com/filecoin-project/go-address v0.0.6 // indirect @@ -115,6 +116,7 @@ require ( github.com/go-logr/stdr v1.2.2 // indirect github.com/go-ole/go-ole v1.2.5 // indirect github.com/go-openapi/inflect v0.19.0 // indirect + github.com/go-redis/redis/v8 v8.11.4 // indirect github.com/go-resty/resty/v2 v2.7.0 // indirect github.com/go-sql-driver/mysql v1.7.0 // indirect github.com/go-stack/stack v1.8.1 // indirect @@ -142,6 +144,7 @@ require ( github.com/hashicorp/hcl/v2 v2.13.0 // indirect github.com/hashicorp/serf v0.9.7 // indirect github.com/icza/backscanner v0.0.0-20210726202459-ac2ffc679f94 // indirect + github.com/inconshreveable/mousetrap v1.0.0 // indirect github.com/ipfs/bbloom v0.0.4 // indirect github.com/ipfs/go-block-format v0.0.3 // indirect github.com/ipfs/go-blockservice v0.2.1 // indirect @@ -217,7 +220,7 @@ require ( github.com/myxtype/filecoin-client v0.3.2 // indirect github.com/nkovacs/streamquote v1.0.0 // indirect github.com/oklog/ulid v1.3.1 // indirect - github.com/onsi/gomega v1.16.0 // indirect + github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/opentracing/opentracing-go v1.2.0 // indirect github.com/pborman/uuid v1.2.1 // indirect github.com/pelletier/go-toml v1.9.5 // indirect @@ -242,6 +245,7 @@ require ( github.com/spaolacci/murmur3 v1.1.0 // indirect github.com/spf13/afero v1.9.2 // indirect github.com/spf13/cast v1.5.0 // indirect + github.com/spf13/cobra v1.5.0 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/spf13/viper v1.12.0 // indirect diff --git a/go.sum b/go.sum index b7486b1..f0da7e4 100644 --- a/go.sum +++ b/go.sum @@ -335,6 +335,7 @@ github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZm github.com/dgryski/go-farm v0.0.0-20190104051053-3adb47b1fb0f/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= github.com/docker/go-units v0.4.0 h1:3uh0PgVws3nIA0Q+MwDC8yjEPf9zjRfZZWXZYDct3Tw= github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= @@ -541,6 +542,7 @@ github.com/go-ole/go-ole v1.2.5/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiU github.com/go-openapi/inflect v0.19.0 h1:9jCH9scKIbHeV9m12SmPilScz6krDxKRasNNSNPXu/4= github.com/go-openapi/inflect v0.19.0/go.mod h1:lHpZVlpIQqLyKwJ4N+YSc9hchQy/i12fJykb83CRBH4= github.com/go-redis/redis/v8 v8.11.4 h1:kHoYkfZP6+pe04aFTnhDH6GDROa5yJdHJVNxV3F46Tg= +github.com/go-redis/redis/v8 v8.11.4/go.mod h1:2Z2wHZXdQpCDXEGzqMockDpNyYvi2l4Pxt6RJr792+w= github.com/go-resty/resty/v2 v2.7.0 h1:me+K9p3uhSmXtrBZ4k9jcEAfJmuC8IivWHwaLZwPrFY= github.com/go-resty/resty/v2 v2.7.0/go.mod h1:9PWDzw47qPphMRFfhsyk0NnSgvluHcljSMVIq3w7q0I= github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= @@ -768,6 +770,7 @@ github.com/icza/backscanner v0.0.0-20210726202459-ac2ffc679f94 h1:9tcYMdi+7Rb1y0 github.com/icza/backscanner v0.0.0-20210726202459-ac2ffc679f94/go.mod h1:GYeBD1CF7AqnKZK+UCytLcY3G+UKo0ByXX/3xfdNyqQ= github.com/icza/mighty v0.0.0-20180919140131-cfd07d671de6 h1:8UsGZ2rr2ksmEru6lToqnXgA8Mz1DP11X4zSJ159C3k= github.com/icza/mighty v0.0.0-20180919140131-cfd07d671de6/go.mod h1:xQig96I1VNBDIWGCdTt54nHt6EeI639SmHycLYL7FkA= +github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= github.com/ipfs/bbloom v0.0.1/go.mod h1:oqo8CVWsJFMOZqTglBG4wydCE4IQA/G2/SEofB0rjUI= @@ -1527,6 +1530,7 @@ github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peK github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.13 h1:lTGmDsbAYt5DmK6OnoV7EuIF1wEIFAcxld6ypU4OSgU= github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y= @@ -1689,6 +1693,7 @@ github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= +github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.8.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= @@ -1914,6 +1919,8 @@ github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155 github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= github.com/spf13/cobra v1.1.1/go.mod h1:WnodtKOvamDL/PwE2M4iKs8aMDBZ5Q5klgD3qfVJQMI= +github.com/spf13/cobra v1.5.0 h1:X+jTBEBqF0bHN+9cSMgmfuvv2VHJ9ezmFNf9Y/XstYU= +github.com/spf13/cobra v1.5.0/go.mod h1:dWXEIy2H428czQCjInthrTRUg7yKbok+2Qi/yBIJoUM= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= diff --git a/pkg/db/ent/client.go b/pkg/db/ent/client.go index 52ef88e..d9d1630 100644 --- a/pkg/db/ent/client.go +++ b/pkg/db/ent/client.go @@ -9,7 +9,6 @@ import ( "log" "github.com/NpoolPlatform/sphinx-proxy/pkg/db/ent/migrate" - "github.com/google/uuid" "github.com/NpoolPlatform/sphinx-proxy/pkg/db/ent/transaction" @@ -163,7 +162,7 @@ func (c *TransactionClient) UpdateOne(t *Transaction) *TransactionUpdateOne { } // UpdateOneID returns an update builder for the given id. -func (c *TransactionClient) UpdateOneID(id uuid.UUID) *TransactionUpdateOne { +func (c *TransactionClient) UpdateOneID(id uint32) *TransactionUpdateOne { mutation := newTransactionMutation(c.config, OpUpdateOne, withTransactionID(id)) return &TransactionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} } @@ -180,7 +179,7 @@ func (c *TransactionClient) DeleteOne(t *Transaction) *TransactionDeleteOne { } // DeleteOne returns a builder for deleting the given entity by its id. -func (c *TransactionClient) DeleteOneID(id uuid.UUID) *TransactionDeleteOne { +func (c *TransactionClient) DeleteOneID(id uint32) *TransactionDeleteOne { builder := c.Delete().Where(transaction.ID(id)) builder.mutation.id = &id builder.mutation.op = OpDeleteOne @@ -195,12 +194,12 @@ func (c *TransactionClient) Query() *TransactionQuery { } // Get returns a Transaction entity by its id. -func (c *TransactionClient) Get(ctx context.Context, id uuid.UUID) (*Transaction, error) { +func (c *TransactionClient) Get(ctx context.Context, id uint32) (*Transaction, error) { return c.Query().Where(transaction.ID(id)).Only(ctx) } // GetX is like Get, but panics if an error occurs. -func (c *TransactionClient) GetX(ctx context.Context, id uuid.UUID) *Transaction { +func (c *TransactionClient) GetX(ctx context.Context, id uint32) *Transaction { obj, err := c.Get(ctx, id) if err != nil { panic(err) diff --git a/pkg/db/ent/config.go b/pkg/db/ent/config.go index eeb4f37..62c3d19 100644 --- a/pkg/db/ent/config.go +++ b/pkg/db/ent/config.go @@ -3,6 +3,10 @@ package ent import ( + "context" + stdsql "database/sql" + "fmt" + "entgo.io/ent" "entgo.io/ent/dialect" ) @@ -57,3 +61,27 @@ func Driver(driver dialect.Driver) Option { c.driver = driver } } + +// ExecContext allows calling the underlying ExecContext method of the driver if it is supported by it. +// See, database/sql#DB.ExecContext for more information. +func (c *config) ExecContext(ctx context.Context, query string, args ...interface{}) (stdsql.Result, error) { + ex, ok := c.driver.(interface { + ExecContext(context.Context, string, ...interface{}) (stdsql.Result, error) + }) + if !ok { + return nil, fmt.Errorf("Driver.ExecContext is not supported") + } + return ex.ExecContext(ctx, query, args...) +} + +// QueryContext allows calling the underlying QueryContext method of the driver if it is supported by it. +// See, database/sql#DB.QueryContext for more information. +func (c *config) QueryContext(ctx context.Context, query string, args ...interface{}) (*stdsql.Rows, error) { + q, ok := c.driver.(interface { + QueryContext(context.Context, string, ...interface{}) (*stdsql.Rows, error) + }) + if !ok { + return nil, fmt.Errorf("Driver.QueryContext is not supported") + } + return q.QueryContext(ctx, query, args...) +} diff --git a/pkg/db/ent/migrate/schema.go b/pkg/db/ent/migrate/schema.go index b3a0133..70e2ebf 100644 --- a/pkg/db/ent/migrate/schema.go +++ b/pkg/db/ent/migrate/schema.go @@ -10,7 +10,8 @@ import ( var ( // TransactionsColumns holds the columns for the "transactions" table. TransactionsColumns = []*schema.Column{ - {Name: "id", Type: field.TypeUUID, Unique: true}, + {Name: "id", Type: field.TypeUint32, Increment: true}, + {Name: "ent_id", Type: field.TypeUUID, Unique: true}, {Name: "coin_type", Type: field.TypeInt32, Nullable: true, Default: 0}, {Name: "nonce", Type: field.TypeUint64, Nullable: true, Default: 0}, {Name: "utxo", Type: field.TypeJSON, Nullable: true}, @@ -38,10 +39,15 @@ var ( Columns: TransactionsColumns, PrimaryKey: []*schema.Column{TransactionsColumns[0]}, Indexes: []*schema.Index{ + { + Name: "transaction_ent_id", + Unique: true, + Columns: []*schema.Column{TransactionsColumns[1]}, + }, { Name: "transaction_state_coin_type_created_at", Unique: false, - Columns: []*schema.Column{TransactionsColumns[17], TransactionsColumns[1], TransactionsColumns[18]}, + Columns: []*schema.Column{TransactionsColumns[18], TransactionsColumns[2], TransactionsColumns[19]}, }, }, } diff --git a/pkg/db/ent/mutation.go b/pkg/db/ent/mutation.go index 009b8b6..a10ad0d 100644 --- a/pkg/db/ent/mutation.go +++ b/pkg/db/ent/mutation.go @@ -33,7 +33,8 @@ type TransactionMutation struct { config op Op typ string - id *uuid.UUID + id *uint32 + ent_id *uuid.UUID coin_type *int32 addcoin_type *int32 nonce *uint64 @@ -89,7 +90,7 @@ func newTransactionMutation(c config, op Op, opts ...transactionOption) *Transac } // withTransactionID sets the ID field of the mutation. -func withTransactionID(id uuid.UUID) transactionOption { +func withTransactionID(id uint32) transactionOption { return func(m *TransactionMutation) { var ( err error @@ -141,13 +142,13 @@ func (m TransactionMutation) Tx() (*Tx, error) { // SetID sets the value of the id field. Note that this // operation is only accepted on creation of Transaction entities. -func (m *TransactionMutation) SetID(id uuid.UUID) { +func (m *TransactionMutation) SetID(id uint32) { m.id = &id } // ID returns the ID value in the mutation. Note that the ID is only available // if it was provided to the builder or after it was returned from the database. -func (m *TransactionMutation) ID() (id uuid.UUID, exists bool) { +func (m *TransactionMutation) ID() (id uint32, exists bool) { if m.id == nil { return } @@ -158,12 +159,12 @@ func (m *TransactionMutation) ID() (id uuid.UUID, exists bool) { // That means, if the mutation is applied within a transaction with an isolation level such // as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated // or updated by the mutation. -func (m *TransactionMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { +func (m *TransactionMutation) IDs(ctx context.Context) ([]uint32, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() if exists { - return []uuid.UUID{id}, nil + return []uint32{id}, nil } fallthrough case m.op.Is(OpUpdate | OpDelete): @@ -173,6 +174,42 @@ func (m *TransactionMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { } } +// SetEntID sets the "ent_id" field. +func (m *TransactionMutation) SetEntID(u uuid.UUID) { + m.ent_id = &u +} + +// EntID returns the value of the "ent_id" field in the mutation. +func (m *TransactionMutation) EntID() (r uuid.UUID, exists bool) { + v := m.ent_id + if v == nil { + return + } + return *v, true +} + +// OldEntID returns the old "ent_id" field's value of the Transaction entity. +// If the Transaction object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *TransactionMutation) OldEntID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEntID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEntID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEntID: %w", err) + } + return oldValue.EntID, nil +} + +// ResetEntID resets all changes to the "ent_id" field. +func (m *TransactionMutation) ResetEntID() { + m.ent_id = nil +} + // SetCoinType sets the "coin_type" field. func (m *TransactionMutation) SetCoinType(i int32) { m.coin_type = &i @@ -1348,7 +1385,10 @@ func (m *TransactionMutation) Type() string { // order to get all numeric fields that were incremented/decremented, call // AddedFields(). func (m *TransactionMutation) Fields() []string { - fields := make([]string, 0, 20) + fields := make([]string, 0, 21) + if m.ent_id != nil { + fields = append(fields, transaction.FieldEntID) + } if m.coin_type != nil { fields = append(fields, transaction.FieldCoinType) } @@ -1417,6 +1457,8 @@ func (m *TransactionMutation) Fields() []string { // schema. func (m *TransactionMutation) Field(name string) (ent.Value, bool) { switch name { + case transaction.FieldEntID: + return m.EntID() case transaction.FieldCoinType: return m.CoinType() case transaction.FieldNonce: @@ -1466,6 +1508,8 @@ func (m *TransactionMutation) Field(name string) (ent.Value, bool) { // database failed. func (m *TransactionMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { + case transaction.FieldEntID: + return m.OldEntID(ctx) case transaction.FieldCoinType: return m.OldCoinType(ctx) case transaction.FieldNonce: @@ -1515,6 +1559,13 @@ func (m *TransactionMutation) OldField(ctx context.Context, name string) (ent.Va // type. func (m *TransactionMutation) SetField(name string, value ent.Value) error { switch name { + case transaction.FieldEntID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEntID(v) + return nil case transaction.FieldCoinType: v, ok := value.(int32) if !ok { @@ -1932,6 +1983,9 @@ func (m *TransactionMutation) ClearField(name string) error { // It returns an error if the field is not defined in the schema. func (m *TransactionMutation) ResetField(name string) error { switch name { + case transaction.FieldEntID: + m.ResetEntID() + return nil case transaction.FieldCoinType: m.ResetCoinType() return nil diff --git a/pkg/db/ent/runtime.go b/pkg/db/ent/runtime.go index 9f0a233..44208d8 100644 --- a/pkg/db/ent/runtime.go +++ b/pkg/db/ent/runtime.go @@ -13,90 +13,93 @@ import ( // (default values, validators, hooks and policies) and stitches it // to their package variables. func init() { + transactionMixin := schema.Transaction{}.Mixin() + transactionMixinFields0 := transactionMixin[0].Fields() + _ = transactionMixinFields0 transactionFields := schema.Transaction{}.Fields() _ = transactionFields + // transactionDescEntID is the schema descriptor for ent_id field. + transactionDescEntID := transactionMixinFields0[1].Descriptor() + // transaction.DefaultEntID holds the default value on creation for the ent_id field. + transaction.DefaultEntID = transactionDescEntID.Default.(func() uuid.UUID) // transactionDescCoinType is the schema descriptor for coin_type field. - transactionDescCoinType := transactionFields[1].Descriptor() + transactionDescCoinType := transactionFields[0].Descriptor() // transaction.DefaultCoinType holds the default value on creation for the coin_type field. transaction.DefaultCoinType = transactionDescCoinType.Default.(int32) // transactionDescNonce is the schema descriptor for nonce field. - transactionDescNonce := transactionFields[2].Descriptor() + transactionDescNonce := transactionFields[1].Descriptor() // transaction.DefaultNonce holds the default value on creation for the nonce field. transaction.DefaultNonce = transactionDescNonce.Default.(uint64) // transactionDescUtxo is the schema descriptor for utxo field. - transactionDescUtxo := transactionFields[3].Descriptor() + transactionDescUtxo := transactionFields[2].Descriptor() // transaction.DefaultUtxo holds the default value on creation for the utxo field. transaction.DefaultUtxo = transactionDescUtxo.Default.([]*sphinxplugin.Unspent) // transactionDescPre is the schema descriptor for pre field. - transactionDescPre := transactionFields[4].Descriptor() + transactionDescPre := transactionFields[3].Descriptor() // transaction.DefaultPre holds the default value on creation for the pre field. transaction.DefaultPre = transactionDescPre.Default.(*sphinxplugin.Unspent) // transactionDescTransactionType is the schema descriptor for transaction_type field. - transactionDescTransactionType := transactionFields[5].Descriptor() + transactionDescTransactionType := transactionFields[4].Descriptor() // transaction.DefaultTransactionType holds the default value on creation for the transaction_type field. transaction.DefaultTransactionType = transactionDescTransactionType.Default.(int8) // transactionDescRecentBhash is the schema descriptor for recent_bhash field. - transactionDescRecentBhash := transactionFields[6].Descriptor() + transactionDescRecentBhash := transactionFields[5].Descriptor() // transaction.DefaultRecentBhash holds the default value on creation for the recent_bhash field. transaction.DefaultRecentBhash = transactionDescRecentBhash.Default.(string) // transactionDescTxData is the schema descriptor for tx_data field. - transactionDescTxData := transactionFields[7].Descriptor() + transactionDescTxData := transactionFields[6].Descriptor() // transaction.DefaultTxData holds the default value on creation for the tx_data field. transaction.DefaultTxData = transactionDescTxData.Default.([]byte) // transactionDescCid is the schema descriptor for cid field. - transactionDescCid := transactionFields[9].Descriptor() + transactionDescCid := transactionFields[8].Descriptor() // transaction.DefaultCid holds the default value on creation for the cid field. transaction.DefaultCid = transactionDescCid.Default.(string) // transactionDescExitCode is the schema descriptor for exit_code field. - transactionDescExitCode := transactionFields[10].Descriptor() + transactionDescExitCode := transactionFields[9].Descriptor() // transaction.DefaultExitCode holds the default value on creation for the exit_code field. transaction.DefaultExitCode = transactionDescExitCode.Default.(int64) // transactionDescName is the schema descriptor for name field. - transactionDescName := transactionFields[11].Descriptor() + transactionDescName := transactionFields[10].Descriptor() // transaction.DefaultName holds the default value on creation for the name field. transaction.DefaultName = transactionDescName.Default.(string) // transactionDescFrom is the schema descriptor for from field. - transactionDescFrom := transactionFields[12].Descriptor() + transactionDescFrom := transactionFields[11].Descriptor() // transaction.DefaultFrom holds the default value on creation for the from field. transaction.DefaultFrom = transactionDescFrom.Default.(string) // transactionDescTo is the schema descriptor for to field. - transactionDescTo := transactionFields[13].Descriptor() + transactionDescTo := transactionFields[12].Descriptor() // transaction.DefaultTo holds the default value on creation for the to field. transaction.DefaultTo = transactionDescTo.Default.(string) // transactionDescMemo is the schema descriptor for memo field. - transactionDescMemo := transactionFields[14].Descriptor() + transactionDescMemo := transactionFields[13].Descriptor() // transaction.DefaultMemo holds the default value on creation for the memo field. transaction.DefaultMemo = transactionDescMemo.Default.(string) // transactionDescAmount is the schema descriptor for amount field. - transactionDescAmount := transactionFields[15].Descriptor() + transactionDescAmount := transactionFields[14].Descriptor() // transaction.DefaultAmount holds the default value on creation for the amount field. transaction.DefaultAmount = transactionDescAmount.Default.(uint64) // transactionDescPayload is the schema descriptor for payload field. - transactionDescPayload := transactionFields[16].Descriptor() + transactionDescPayload := transactionFields[15].Descriptor() // transaction.DefaultPayload holds the default value on creation for the payload field. transaction.DefaultPayload = transactionDescPayload.Default.([]byte) // transaction.PayloadValidator is a validator for the "payload" field. It is called by the builders before save. transaction.PayloadValidator = transactionDescPayload.Validators[0].(func([]byte) error) // transactionDescState is the schema descriptor for state field. - transactionDescState := transactionFields[17].Descriptor() + transactionDescState := transactionFields[16].Descriptor() // transaction.DefaultState holds the default value on creation for the state field. transaction.DefaultState = transactionDescState.Default.(uint8) // transactionDescCreatedAt is the schema descriptor for created_at field. - transactionDescCreatedAt := transactionFields[18].Descriptor() + transactionDescCreatedAt := transactionFields[17].Descriptor() // transaction.DefaultCreatedAt holds the default value on creation for the created_at field. transaction.DefaultCreatedAt = transactionDescCreatedAt.Default.(func() uint32) // transactionDescUpdatedAt is the schema descriptor for updated_at field. - transactionDescUpdatedAt := transactionFields[19].Descriptor() + transactionDescUpdatedAt := transactionFields[18].Descriptor() // transaction.DefaultUpdatedAt holds the default value on creation for the updated_at field. transaction.DefaultUpdatedAt = transactionDescUpdatedAt.Default.(func() uint32) // transaction.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. transaction.UpdateDefaultUpdatedAt = transactionDescUpdatedAt.UpdateDefault.(func() uint32) // transactionDescDeletedAt is the schema descriptor for deleted_at field. - transactionDescDeletedAt := transactionFields[20].Descriptor() + transactionDescDeletedAt := transactionFields[19].Descriptor() // transaction.DefaultDeletedAt holds the default value on creation for the deleted_at field. transaction.DefaultDeletedAt = transactionDescDeletedAt.Default.(func() uint32) - // transactionDescID is the schema descriptor for id field. - transactionDescID := transactionFields[0].Descriptor() - // transaction.DefaultID holds the default value on creation for the id field. - transaction.DefaultID = transactionDescID.Default.(func() uuid.UUID) } diff --git a/pkg/db/ent/schema/transaction.go b/pkg/db/ent/schema/transaction.go index 9504bb6..20acece 100644 --- a/pkg/db/ent/schema/transaction.go +++ b/pkg/db/ent/schema/transaction.go @@ -7,9 +7,9 @@ import ( "entgo.io/ent" "entgo.io/ent/schema/field" "entgo.io/ent/schema/index" + crudermixin "github.com/NpoolPlatform/libent-cruder/pkg/mixin" "github.com/NpoolPlatform/message/npool/sphinxplugin" "github.com/NpoolPlatform/sphinx-proxy/pkg/db/ent/transaction" - "github.com/google/uuid" ) // Transaction holds the schema definition for the Transaction entity. @@ -17,12 +17,15 @@ type Transaction struct { ent.Schema } +func (Transaction) Mixin() []ent.Mixin { + return []ent.Mixin{ + crudermixin.AutoIDMixin{}, + } +} + // Fields of the Transaction. func (Transaction) Fields() []ent.Field { return []ent.Field{ - field.UUID("id", uuid.UUID{}). - Default(uuid.New). - Unique(), field.Int32("coin_type"). Optional(). Default(0), diff --git a/pkg/db/ent/transaction.go b/pkg/db/ent/transaction.go index 34c5760..aa6f603 100644 --- a/pkg/db/ent/transaction.go +++ b/pkg/db/ent/transaction.go @@ -17,7 +17,9 @@ import ( type Transaction struct { config `json:"-"` // ID of the ent. - ID uuid.UUID `json:"id,omitempty"` + ID uint32 `json:"id,omitempty"` + // EntID holds the value of the "ent_id" field. + EntID uuid.UUID `json:"ent_id,omitempty"` // CoinType holds the value of the "coin_type" field. CoinType int32 `json:"coin_type,omitempty"` // --will remove @@ -67,11 +69,11 @@ func (*Transaction) scanValues(columns []string) ([]interface{}, error) { switch columns[i] { case transaction.FieldUtxo, transaction.FieldPre, transaction.FieldTxData, transaction.FieldPayload: values[i] = new([]byte) - case transaction.FieldCoinType, transaction.FieldNonce, transaction.FieldTransactionType, transaction.FieldExitCode, transaction.FieldAmount, transaction.FieldState, transaction.FieldCreatedAt, transaction.FieldUpdatedAt, transaction.FieldDeletedAt: + case transaction.FieldID, transaction.FieldCoinType, transaction.FieldNonce, transaction.FieldTransactionType, transaction.FieldExitCode, transaction.FieldAmount, transaction.FieldState, transaction.FieldCreatedAt, transaction.FieldUpdatedAt, transaction.FieldDeletedAt: values[i] = new(sql.NullInt64) case transaction.FieldRecentBhash, transaction.FieldTransactionID, transaction.FieldCid, transaction.FieldName, transaction.FieldFrom, transaction.FieldTo, transaction.FieldMemo: values[i] = new(sql.NullString) - case transaction.FieldID: + case transaction.FieldEntID: values[i] = new(uuid.UUID) default: return nil, fmt.Errorf("unexpected column %q for type Transaction", columns[i]) @@ -89,10 +91,16 @@ func (t *Transaction) assignValues(columns []string, values []interface{}) error for i := range columns { switch columns[i] { case transaction.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + t.ID = uint32(value.Int64) + case transaction.FieldEntID: if value, ok := values[i].(*uuid.UUID); !ok { - return fmt.Errorf("unexpected type %T for field id", values[i]) + return fmt.Errorf("unexpected type %T for field ent_id", values[i]) } else if value != nil { - t.ID = *value + t.EntID = *value } case transaction.FieldCoinType: if value, ok := values[i].(*sql.NullInt64); !ok { @@ -246,6 +254,9 @@ func (t *Transaction) String() string { var builder strings.Builder builder.WriteString("Transaction(") builder.WriteString(fmt.Sprintf("id=%v, ", t.ID)) + builder.WriteString("ent_id=") + builder.WriteString(fmt.Sprintf("%v", t.EntID)) + builder.WriteString(", ") builder.WriteString("coin_type=") builder.WriteString(fmt.Sprintf("%v", t.CoinType)) builder.WriteString(", ") diff --git a/pkg/db/ent/transaction/transaction.go b/pkg/db/ent/transaction/transaction.go index 0107787..5d1ae9d 100644 --- a/pkg/db/ent/transaction/transaction.go +++ b/pkg/db/ent/transaction/transaction.go @@ -12,6 +12,8 @@ const ( Label = "transaction" // FieldID holds the string denoting the id field in the database. FieldID = "id" + // FieldEntID holds the string denoting the ent_id field in the database. + FieldEntID = "ent_id" // FieldCoinType holds the string denoting the coin_type field in the database. FieldCoinType = "coin_type" // FieldNonce holds the string denoting the nonce field in the database. @@ -59,6 +61,7 @@ const ( // Columns holds all SQL columns for transaction fields. var Columns = []string{ FieldID, + FieldEntID, FieldCoinType, FieldNonce, FieldUtxo, @@ -92,6 +95,8 @@ func ValidColumn(column string) bool { } var ( + // DefaultEntID holds the default value on creation for the "ent_id" field. + DefaultEntID func() uuid.UUID // DefaultCoinType holds the default value on creation for the "coin_type" field. DefaultCoinType int32 // DefaultNonce holds the default value on creation for the "nonce" field. @@ -134,6 +139,4 @@ var ( UpdateDefaultUpdatedAt func() uint32 // DefaultDeletedAt holds the default value on creation for the "deleted_at" field. DefaultDeletedAt func() uint32 - // DefaultID holds the default value on creation for the "id" field. - DefaultID func() uuid.UUID ) diff --git a/pkg/db/ent/transaction/where.go b/pkg/db/ent/transaction/where.go index 85f7be4..20f432c 100644 --- a/pkg/db/ent/transaction/where.go +++ b/pkg/db/ent/transaction/where.go @@ -9,28 +9,28 @@ import ( ) // ID filters vertices based on their ID field. -func ID(id uuid.UUID) predicate.Transaction { +func ID(id uint32) predicate.Transaction { return predicate.Transaction(func(s *sql.Selector) { s.Where(sql.EQ(s.C(FieldID), id)) }) } // IDEQ applies the EQ predicate on the ID field. -func IDEQ(id uuid.UUID) predicate.Transaction { +func IDEQ(id uint32) predicate.Transaction { return predicate.Transaction(func(s *sql.Selector) { s.Where(sql.EQ(s.C(FieldID), id)) }) } // IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id uuid.UUID) predicate.Transaction { +func IDNEQ(id uint32) predicate.Transaction { return predicate.Transaction(func(s *sql.Selector) { s.Where(sql.NEQ(s.C(FieldID), id)) }) } // IDIn applies the In predicate on the ID field. -func IDIn(ids ...uuid.UUID) predicate.Transaction { +func IDIn(ids ...uint32) predicate.Transaction { return predicate.Transaction(func(s *sql.Selector) { v := make([]interface{}, len(ids)) for i := range v { @@ -41,7 +41,7 @@ func IDIn(ids ...uuid.UUID) predicate.Transaction { } // IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...uuid.UUID) predicate.Transaction { +func IDNotIn(ids ...uint32) predicate.Transaction { return predicate.Transaction(func(s *sql.Selector) { v := make([]interface{}, len(ids)) for i := range v { @@ -52,33 +52,40 @@ func IDNotIn(ids ...uuid.UUID) predicate.Transaction { } // IDGT applies the GT predicate on the ID field. -func IDGT(id uuid.UUID) predicate.Transaction { +func IDGT(id uint32) predicate.Transaction { return predicate.Transaction(func(s *sql.Selector) { s.Where(sql.GT(s.C(FieldID), id)) }) } // IDGTE applies the GTE predicate on the ID field. -func IDGTE(id uuid.UUID) predicate.Transaction { +func IDGTE(id uint32) predicate.Transaction { return predicate.Transaction(func(s *sql.Selector) { s.Where(sql.GTE(s.C(FieldID), id)) }) } // IDLT applies the LT predicate on the ID field. -func IDLT(id uuid.UUID) predicate.Transaction { +func IDLT(id uint32) predicate.Transaction { return predicate.Transaction(func(s *sql.Selector) { s.Where(sql.LT(s.C(FieldID), id)) }) } // IDLTE applies the LTE predicate on the ID field. -func IDLTE(id uuid.UUID) predicate.Transaction { +func IDLTE(id uint32) predicate.Transaction { return predicate.Transaction(func(s *sql.Selector) { s.Where(sql.LTE(s.C(FieldID), id)) }) } +// EntID applies equality check predicate on the "ent_id" field. It's identical to EntIDEQ. +func EntID(v uuid.UUID) predicate.Transaction { + return predicate.Transaction(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldEntID), v)) + }) +} + // CoinType applies equality check predicate on the "coin_type" field. It's identical to CoinTypeEQ. func CoinType(v int32) predicate.Transaction { return predicate.Transaction(func(s *sql.Selector) { @@ -205,6 +212,70 @@ func DeletedAt(v uint32) predicate.Transaction { }) } +// EntIDEQ applies the EQ predicate on the "ent_id" field. +func EntIDEQ(v uuid.UUID) predicate.Transaction { + return predicate.Transaction(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldEntID), v)) + }) +} + +// EntIDNEQ applies the NEQ predicate on the "ent_id" field. +func EntIDNEQ(v uuid.UUID) predicate.Transaction { + return predicate.Transaction(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldEntID), v)) + }) +} + +// EntIDIn applies the In predicate on the "ent_id" field. +func EntIDIn(vs ...uuid.UUID) predicate.Transaction { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Transaction(func(s *sql.Selector) { + s.Where(sql.In(s.C(FieldEntID), v...)) + }) +} + +// EntIDNotIn applies the NotIn predicate on the "ent_id" field. +func EntIDNotIn(vs ...uuid.UUID) predicate.Transaction { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Transaction(func(s *sql.Selector) { + s.Where(sql.NotIn(s.C(FieldEntID), v...)) + }) +} + +// EntIDGT applies the GT predicate on the "ent_id" field. +func EntIDGT(v uuid.UUID) predicate.Transaction { + return predicate.Transaction(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldEntID), v)) + }) +} + +// EntIDGTE applies the GTE predicate on the "ent_id" field. +func EntIDGTE(v uuid.UUID) predicate.Transaction { + return predicate.Transaction(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldEntID), v)) + }) +} + +// EntIDLT applies the LT predicate on the "ent_id" field. +func EntIDLT(v uuid.UUID) predicate.Transaction { + return predicate.Transaction(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldEntID), v)) + }) +} + +// EntIDLTE applies the LTE predicate on the "ent_id" field. +func EntIDLTE(v uuid.UUID) predicate.Transaction { + return predicate.Transaction(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldEntID), v)) + }) +} + // CoinTypeEQ applies the EQ predicate on the "coin_type" field. func CoinTypeEQ(v int32) predicate.Transaction { return predicate.Transaction(func(s *sql.Selector) { diff --git a/pkg/db/ent/transaction_create.go b/pkg/db/ent/transaction_create.go index 6f081b7..6230a43 100644 --- a/pkg/db/ent/transaction_create.go +++ b/pkg/db/ent/transaction_create.go @@ -7,7 +7,6 @@ import ( "errors" "fmt" - "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" @@ -24,6 +23,20 @@ type TransactionCreate struct { conflict []sql.ConflictOption } +// SetEntID sets the "ent_id" field. +func (tc *TransactionCreate) SetEntID(u uuid.UUID) *TransactionCreate { + tc.mutation.SetEntID(u) + return tc +} + +// SetNillableEntID sets the "ent_id" field if the given value is not nil. +func (tc *TransactionCreate) SetNillableEntID(u *uuid.UUID) *TransactionCreate { + if u != nil { + tc.SetEntID(*u) + } + return tc +} + // SetCoinType sets the "coin_type" field. func (tc *TransactionCreate) SetCoinType(i int32) *TransactionCreate { tc.mutation.SetCoinType(i) @@ -265,19 +278,11 @@ func (tc *TransactionCreate) SetNillableDeletedAt(u *uint32) *TransactionCreate } // SetID sets the "id" field. -func (tc *TransactionCreate) SetID(u uuid.UUID) *TransactionCreate { +func (tc *TransactionCreate) SetID(u uint32) *TransactionCreate { tc.mutation.SetID(u) return tc } -// SetNillableID sets the "id" field if the given value is not nil. -func (tc *TransactionCreate) SetNillableID(u *uuid.UUID) *TransactionCreate { - if u != nil { - tc.SetID(*u) - } - return tc -} - // Mutation returns the TransactionMutation object of the builder. func (tc *TransactionCreate) Mutation() *TransactionMutation { return tc.mutation @@ -355,6 +360,10 @@ func (tc *TransactionCreate) ExecX(ctx context.Context) { // defaults sets the default values of the builder before save. func (tc *TransactionCreate) defaults() { + if _, ok := tc.mutation.EntID(); !ok { + v := transaction.DefaultEntID() + tc.mutation.SetEntID(v) + } if _, ok := tc.mutation.CoinType(); !ok { v := transaction.DefaultCoinType tc.mutation.SetCoinType(v) @@ -431,14 +440,13 @@ func (tc *TransactionCreate) defaults() { v := transaction.DefaultDeletedAt() tc.mutation.SetDeletedAt(v) } - if _, ok := tc.mutation.ID(); !ok { - v := transaction.DefaultID() - tc.mutation.SetID(v) - } } // check runs all checks and user-defined validators on the builder. func (tc *TransactionCreate) check() error { + if _, ok := tc.mutation.EntID(); !ok { + return &ValidationError{Name: "ent_id", err: errors.New(`ent: missing required field "Transaction.ent_id"`)} + } if _, ok := tc.mutation.TransactionID(); !ok { return &ValidationError{Name: "transaction_id", err: errors.New(`ent: missing required field "Transaction.transaction_id"`)} } @@ -458,12 +466,9 @@ func (tc *TransactionCreate) sqlSave(ctx context.Context) (*Transaction, error) } return nil, err } - if _spec.ID.Value != nil { - if id, ok := _spec.ID.Value.(*uuid.UUID); ok { - _node.ID = *id - } else if err := _node.ID.Scan(_spec.ID.Value); err != nil { - return nil, err - } + if _spec.ID.Value != _node.ID { + id := _spec.ID.Value.(int64) + _node.ID = uint32(id) } return _node, nil } @@ -474,7 +479,7 @@ func (tc *TransactionCreate) createSpec() (*Transaction, *sqlgraph.CreateSpec) { _spec = &sqlgraph.CreateSpec{ Table: transaction.Table, ID: &sqlgraph.FieldSpec{ - Type: field.TypeUUID, + Type: field.TypeUint32, Column: transaction.FieldID, }, } @@ -482,7 +487,15 @@ func (tc *TransactionCreate) createSpec() (*Transaction, *sqlgraph.CreateSpec) { _spec.OnConflict = tc.conflict if id, ok := tc.mutation.ID(); ok { _node.ID = id - _spec.ID.Value = &id + _spec.ID.Value = id + } + if value, ok := tc.mutation.EntID(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Value: value, + Column: transaction.FieldEntID, + }) + _node.EntID = value } if value, ok := tc.mutation.CoinType(); ok { _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ @@ -651,7 +664,7 @@ func (tc *TransactionCreate) createSpec() (*Transaction, *sqlgraph.CreateSpec) { // of the `INSERT` statement. For example: // // client.Transaction.Create(). -// SetCoinType(v). +// SetEntID(v). // OnConflict( // // Update the row with the new values // // the was proposed for insertion. @@ -660,7 +673,7 @@ func (tc *TransactionCreate) createSpec() (*Transaction, *sqlgraph.CreateSpec) { // // Override some of the fields with custom // // update values. // Update(func(u *ent.TransactionUpsert) { -// SetCoinType(v+v). +// SetEntID(v+v). // }). // Exec(ctx) func (tc *TransactionCreate) OnConflict(opts ...sql.ConflictOption) *TransactionUpsertOne { @@ -696,6 +709,18 @@ type ( } ) +// SetEntID sets the "ent_id" field. +func (u *TransactionUpsert) SetEntID(v uuid.UUID) *TransactionUpsert { + u.Set(transaction.FieldEntID, v) + return u +} + +// UpdateEntID sets the "ent_id" field to the value that was provided on create. +func (u *TransactionUpsert) UpdateEntID() *TransactionUpsert { + u.SetExcluded(transaction.FieldEntID) + return u +} + // SetCoinType sets the "coin_type" field. func (u *TransactionUpsert) SetCoinType(v int32) *TransactionUpsert { u.Set(transaction.FieldCoinType, v) @@ -1152,6 +1177,20 @@ func (u *TransactionUpsertOne) Update(set func(*TransactionUpsert)) *Transaction return u } +// SetEntID sets the "ent_id" field. +func (u *TransactionUpsertOne) SetEntID(v uuid.UUID) *TransactionUpsertOne { + return u.Update(func(s *TransactionUpsert) { + s.SetEntID(v) + }) +} + +// UpdateEntID sets the "ent_id" field to the value that was provided on create. +func (u *TransactionUpsertOne) UpdateEntID() *TransactionUpsertOne { + return u.Update(func(s *TransactionUpsert) { + s.UpdateEntID() + }) +} + // SetCoinType sets the "coin_type" field. func (u *TransactionUpsertOne) SetCoinType(v int32) *TransactionUpsertOne { return u.Update(func(s *TransactionUpsert) { @@ -1644,12 +1683,7 @@ func (u *TransactionUpsertOne) ExecX(ctx context.Context) { } // Exec executes the UPSERT query and returns the inserted/updated ID. -func (u *TransactionUpsertOne) ID(ctx context.Context) (id uuid.UUID, err error) { - if u.create.driver.Dialect() == dialect.MySQL { - // In case of "ON CONFLICT", there is no way to get back non-numeric ID - // fields from the database since MySQL does not support the RETURNING clause. - return id, errors.New("ent: TransactionUpsertOne.ID is not supported by MySQL driver. Use TransactionUpsertOne.Exec instead") - } +func (u *TransactionUpsertOne) ID(ctx context.Context) (id uint32, err error) { node, err := u.create.Save(ctx) if err != nil { return id, err @@ -1658,7 +1692,7 @@ func (u *TransactionUpsertOne) ID(ctx context.Context) (id uuid.UUID, err error) } // IDX is like ID, but panics if an error occurs. -func (u *TransactionUpsertOne) IDX(ctx context.Context) uuid.UUID { +func (u *TransactionUpsertOne) IDX(ctx context.Context) uint32 { id, err := u.ID(ctx) if err != nil { panic(err) @@ -1709,6 +1743,10 @@ func (tcb *TransactionCreateBulk) Save(ctx context.Context) ([]*Transaction, err return nil, err } mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil && nodes[i].ID == 0 { + id := specs[i].ID.Value.(int64) + nodes[i].ID = uint32(id) + } mutation.done = true return nodes[i], nil }) @@ -1760,7 +1798,7 @@ func (tcb *TransactionCreateBulk) ExecX(ctx context.Context) { // // Override some of the fields with custom // // update values. // Update(func(u *ent.TransactionUpsert) { -// SetCoinType(v+v). +// SetEntID(v+v). // }). // Exec(ctx) func (tcb *TransactionCreateBulk) OnConflict(opts ...sql.ConflictOption) *TransactionUpsertBulk { @@ -1840,6 +1878,20 @@ func (u *TransactionUpsertBulk) Update(set func(*TransactionUpsert)) *Transactio return u } +// SetEntID sets the "ent_id" field. +func (u *TransactionUpsertBulk) SetEntID(v uuid.UUID) *TransactionUpsertBulk { + return u.Update(func(s *TransactionUpsert) { + s.SetEntID(v) + }) +} + +// UpdateEntID sets the "ent_id" field to the value that was provided on create. +func (u *TransactionUpsertBulk) UpdateEntID() *TransactionUpsertBulk { + return u.Update(func(s *TransactionUpsert) { + s.UpdateEntID() + }) +} + // SetCoinType sets the "coin_type" field. func (u *TransactionUpsertBulk) SetCoinType(v int32) *TransactionUpsertBulk { return u.Update(func(s *TransactionUpsert) { diff --git a/pkg/db/ent/transaction_delete.go b/pkg/db/ent/transaction_delete.go index 210c1d7..42914a3 100644 --- a/pkg/db/ent/transaction_delete.go +++ b/pkg/db/ent/transaction_delete.go @@ -72,7 +72,7 @@ func (td *TransactionDelete) sqlExec(ctx context.Context) (int, error) { Node: &sqlgraph.NodeSpec{ Table: transaction.Table, ID: &sqlgraph.FieldSpec{ - Type: field.TypeUUID, + Type: field.TypeUint32, Column: transaction.FieldID, }, }, diff --git a/pkg/db/ent/transaction_query.go b/pkg/db/ent/transaction_query.go index 694cb2c..b1fbb37 100644 --- a/pkg/db/ent/transaction_query.go +++ b/pkg/db/ent/transaction_query.go @@ -7,12 +7,12 @@ import ( "fmt" "math" + "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" "github.com/NpoolPlatform/sphinx-proxy/pkg/db/ent/predicate" "github.com/NpoolPlatform/sphinx-proxy/pkg/db/ent/transaction" - "github.com/google/uuid" ) // TransactionQuery is the builder for querying Transaction entities. @@ -24,6 +24,7 @@ type TransactionQuery struct { order []OrderFunc fields []string predicates []predicate.Transaction + modifiers []func(*sql.Selector) // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -84,8 +85,8 @@ func (tq *TransactionQuery) FirstX(ctx context.Context) *Transaction { // FirstID returns the first Transaction ID from the query. // Returns a *NotFoundError when no Transaction ID was found. -func (tq *TransactionQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { - var ids []uuid.UUID +func (tq *TransactionQuery) FirstID(ctx context.Context) (id uint32, err error) { + var ids []uint32 if ids, err = tq.Limit(1).IDs(ctx); err != nil { return } @@ -97,7 +98,7 @@ func (tq *TransactionQuery) FirstID(ctx context.Context) (id uuid.UUID, err erro } // FirstIDX is like FirstID, but panics if an error occurs. -func (tq *TransactionQuery) FirstIDX(ctx context.Context) uuid.UUID { +func (tq *TransactionQuery) FirstIDX(ctx context.Context) uint32 { id, err := tq.FirstID(ctx) if err != nil && !IsNotFound(err) { panic(err) @@ -135,8 +136,8 @@ func (tq *TransactionQuery) OnlyX(ctx context.Context) *Transaction { // OnlyID is like Only, but returns the only Transaction ID in the query. // Returns a *NotSingularError when more than one Transaction ID is found. // Returns a *NotFoundError when no entities are found. -func (tq *TransactionQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { - var ids []uuid.UUID +func (tq *TransactionQuery) OnlyID(ctx context.Context) (id uint32, err error) { + var ids []uint32 if ids, err = tq.Limit(2).IDs(ctx); err != nil { return } @@ -152,7 +153,7 @@ func (tq *TransactionQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error } // OnlyIDX is like OnlyID, but panics if an error occurs. -func (tq *TransactionQuery) OnlyIDX(ctx context.Context) uuid.UUID { +func (tq *TransactionQuery) OnlyIDX(ctx context.Context) uint32 { id, err := tq.OnlyID(ctx) if err != nil { panic(err) @@ -178,8 +179,8 @@ func (tq *TransactionQuery) AllX(ctx context.Context) []*Transaction { } // IDs executes the query and returns a list of Transaction IDs. -func (tq *TransactionQuery) IDs(ctx context.Context) ([]uuid.UUID, error) { - var ids []uuid.UUID +func (tq *TransactionQuery) IDs(ctx context.Context) ([]uint32, error) { + var ids []uint32 if err := tq.Select(transaction.FieldID).Scan(ctx, &ids); err != nil { return nil, err } @@ -187,7 +188,7 @@ func (tq *TransactionQuery) IDs(ctx context.Context) ([]uuid.UUID, error) { } // IDsX is like IDs, but panics if an error occurs. -func (tq *TransactionQuery) IDsX(ctx context.Context) []uuid.UUID { +func (tq *TransactionQuery) IDsX(ctx context.Context) []uint32 { ids, err := tq.IDs(ctx) if err != nil { panic(err) @@ -254,12 +255,12 @@ func (tq *TransactionQuery) Clone() *TransactionQuery { // Example: // // var v []struct { -// CoinType int32 `json:"coin_type,omitempty"` +// EntID uuid.UUID `json:"ent_id,omitempty"` // Count int `json:"count,omitempty"` // } // // client.Transaction.Query(). -// GroupBy(transaction.FieldCoinType). +// GroupBy(transaction.FieldEntID). // Aggregate(ent.Count()). // Scan(ctx, &v) func (tq *TransactionQuery) GroupBy(field string, fields ...string) *TransactionGroupBy { @@ -282,11 +283,11 @@ func (tq *TransactionQuery) GroupBy(field string, fields ...string) *Transaction // Example: // // var v []struct { -// CoinType int32 `json:"coin_type,omitempty"` +// EntID uuid.UUID `json:"ent_id,omitempty"` // } // // client.Transaction.Query(). -// Select(transaction.FieldCoinType). +// Select(transaction.FieldEntID). // Scan(ctx, &v) func (tq *TransactionQuery) Select(fields ...string) *TransactionSelect { tq.fields = append(tq.fields, fields...) @@ -325,6 +326,9 @@ func (tq *TransactionQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]* nodes = append(nodes, node) return node.assignValues(columns, values) } + if len(tq.modifiers) > 0 { + _spec.Modifiers = tq.modifiers + } for i := range hooks { hooks[i](ctx, _spec) } @@ -339,6 +343,9 @@ func (tq *TransactionQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]* func (tq *TransactionQuery) sqlCount(ctx context.Context) (int, error) { _spec := tq.querySpec() + if len(tq.modifiers) > 0 { + _spec.Modifiers = tq.modifiers + } _spec.Node.Columns = tq.fields if len(tq.fields) > 0 { _spec.Unique = tq.unique != nil && *tq.unique @@ -360,7 +367,7 @@ func (tq *TransactionQuery) querySpec() *sqlgraph.QuerySpec { Table: transaction.Table, Columns: transaction.Columns, ID: &sqlgraph.FieldSpec{ - Type: field.TypeUUID, + Type: field.TypeUint32, Column: transaction.FieldID, }, }, @@ -417,6 +424,9 @@ func (tq *TransactionQuery) sqlQuery(ctx context.Context) *sql.Selector { if tq.unique != nil && *tq.unique { selector.Distinct() } + for _, m := range tq.modifiers { + m(selector) + } for _, p := range tq.predicates { p(selector) } @@ -434,6 +444,38 @@ func (tq *TransactionQuery) sqlQuery(ctx context.Context) *sql.Selector { return selector } +// ForUpdate locks the selected rows against concurrent updates, and prevent them from being +// updated, deleted or "selected ... for update" by other sessions, until the transaction is +// either committed or rolled-back. +func (tq *TransactionQuery) ForUpdate(opts ...sql.LockOption) *TransactionQuery { + if tq.driver.Dialect() == dialect.Postgres { + tq.Unique(false) + } + tq.modifiers = append(tq.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return tq +} + +// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock +// on any rows that are read. Other sessions can read the rows, but cannot modify them +// until your transaction commits. +func (tq *TransactionQuery) ForShare(opts ...sql.LockOption) *TransactionQuery { + if tq.driver.Dialect() == dialect.Postgres { + tq.Unique(false) + } + tq.modifiers = append(tq.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return tq +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (tq *TransactionQuery) Modify(modifiers ...func(s *sql.Selector)) *TransactionSelect { + tq.modifiers = append(tq.modifiers, modifiers...) + return tq.Select() +} + // TransactionGroupBy is the group-by builder for Transaction entities. type TransactionGroupBy struct { config @@ -525,3 +567,9 @@ func (ts *TransactionSelect) sqlScan(ctx context.Context, v interface{}) error { defer rows.Close() return sql.ScanSlice(rows, v) } + +// Modify adds a query modifier for attaching custom logic to queries. +func (ts *TransactionSelect) Modify(modifiers ...func(s *sql.Selector)) *TransactionSelect { + ts.modifiers = append(ts.modifiers, modifiers...) + return ts +} diff --git a/pkg/db/ent/transaction_update.go b/pkg/db/ent/transaction_update.go index 1b539c1..5a05913 100644 --- a/pkg/db/ent/transaction_update.go +++ b/pkg/db/ent/transaction_update.go @@ -13,13 +13,15 @@ import ( "github.com/NpoolPlatform/message/npool/sphinxplugin" "github.com/NpoolPlatform/sphinx-proxy/pkg/db/ent/predicate" "github.com/NpoolPlatform/sphinx-proxy/pkg/db/ent/transaction" + "github.com/google/uuid" ) // TransactionUpdate is the builder for updating Transaction entities. type TransactionUpdate struct { config - hooks []Hook - mutation *TransactionMutation + hooks []Hook + mutation *TransactionMutation + modifiers []func(*sql.UpdateBuilder) } // Where appends a list predicates to the TransactionUpdate builder. @@ -28,6 +30,20 @@ func (tu *TransactionUpdate) Where(ps ...predicate.Transaction) *TransactionUpda return tu } +// SetEntID sets the "ent_id" field. +func (tu *TransactionUpdate) SetEntID(u uuid.UUID) *TransactionUpdate { + tu.mutation.SetEntID(u) + return tu +} + +// SetNillableEntID sets the "ent_id" field if the given value is not nil. +func (tu *TransactionUpdate) SetNillableEntID(u *uuid.UUID) *TransactionUpdate { + if u != nil { + tu.SetEntID(*u) + } + return tu +} + // SetCoinType sets the "coin_type" field. func (tu *TransactionUpdate) SetCoinType(i int32) *TransactionUpdate { tu.mutation.ResetCoinType() @@ -521,13 +537,19 @@ func (tu *TransactionUpdate) check() error { return nil } +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (tu *TransactionUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *TransactionUpdate { + tu.modifiers = append(tu.modifiers, modifiers...) + return tu +} + func (tu *TransactionUpdate) sqlSave(ctx context.Context) (n int, err error) { _spec := &sqlgraph.UpdateSpec{ Node: &sqlgraph.NodeSpec{ Table: transaction.Table, Columns: transaction.Columns, ID: &sqlgraph.FieldSpec{ - Type: field.TypeUUID, + Type: field.TypeUint32, Column: transaction.FieldID, }, }, @@ -539,6 +561,13 @@ func (tu *TransactionUpdate) sqlSave(ctx context.Context) (n int, err error) { } } } + if value, ok := tu.mutation.EntID(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Value: value, + Column: transaction.FieldEntID, + }) + } if value, ok := tu.mutation.CoinType(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeInt32, @@ -856,6 +885,7 @@ func (tu *TransactionUpdate) sqlSave(ctx context.Context) (n int, err error) { Column: transaction.FieldDeletedAt, }) } + _spec.Modifiers = tu.modifiers if n, err = sqlgraph.UpdateNodes(ctx, tu.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{transaction.Label} @@ -870,9 +900,24 @@ func (tu *TransactionUpdate) sqlSave(ctx context.Context) (n int, err error) { // TransactionUpdateOne is the builder for updating a single Transaction entity. type TransactionUpdateOne struct { config - fields []string - hooks []Hook - mutation *TransactionMutation + fields []string + hooks []Hook + mutation *TransactionMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetEntID sets the "ent_id" field. +func (tuo *TransactionUpdateOne) SetEntID(u uuid.UUID) *TransactionUpdateOne { + tuo.mutation.SetEntID(u) + return tuo +} + +// SetNillableEntID sets the "ent_id" field if the given value is not nil. +func (tuo *TransactionUpdateOne) SetNillableEntID(u *uuid.UUID) *TransactionUpdateOne { + if u != nil { + tuo.SetEntID(*u) + } + return tuo } // SetCoinType sets the "coin_type" field. @@ -1381,13 +1426,19 @@ func (tuo *TransactionUpdateOne) check() error { return nil } +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (tuo *TransactionUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *TransactionUpdateOne { + tuo.modifiers = append(tuo.modifiers, modifiers...) + return tuo +} + func (tuo *TransactionUpdateOne) sqlSave(ctx context.Context) (_node *Transaction, err error) { _spec := &sqlgraph.UpdateSpec{ Node: &sqlgraph.NodeSpec{ Table: transaction.Table, Columns: transaction.Columns, ID: &sqlgraph.FieldSpec{ - Type: field.TypeUUID, + Type: field.TypeUint32, Column: transaction.FieldID, }, }, @@ -1416,6 +1467,13 @@ func (tuo *TransactionUpdateOne) sqlSave(ctx context.Context) (_node *Transactio } } } + if value, ok := tuo.mutation.EntID(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Value: value, + Column: transaction.FieldEntID, + }) + } if value, ok := tuo.mutation.CoinType(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeInt32, @@ -1733,6 +1791,7 @@ func (tuo *TransactionUpdateOne) sqlSave(ctx context.Context) (_node *Transactio Column: transaction.FieldDeletedAt, }) } + _spec.Modifiers = tuo.modifiers _node = &Transaction{config: tuo.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/pkg/db/ent/tx.go b/pkg/db/ent/tx.go index 01b2ea0..14cc58f 100644 --- a/pkg/db/ent/tx.go +++ b/pkg/db/ent/tx.go @@ -4,6 +4,8 @@ package ent import ( "context" + stdsql "database/sql" + "fmt" "sync" "entgo.io/ent/dialect" @@ -208,3 +210,27 @@ func (tx *txDriver) Query(ctx context.Context, query string, args, v interface{} } var _ dialect.Driver = (*txDriver)(nil) + +// ExecContext allows calling the underlying ExecContext method of the transaction if it is supported by it. +// See, database/sql#Tx.ExecContext for more information. +func (tx *txDriver) ExecContext(ctx context.Context, query string, args ...interface{}) (stdsql.Result, error) { + ex, ok := tx.tx.(interface { + ExecContext(context.Context, string, ...interface{}) (stdsql.Result, error) + }) + if !ok { + return nil, fmt.Errorf("Tx.ExecContext is not supported") + } + return ex.ExecContext(ctx, query, args...) +} + +// QueryContext allows calling the underlying QueryContext method of the transaction if it is supported by it. +// See, database/sql#Tx.QueryContext for more information. +func (tx *txDriver) QueryContext(ctx context.Context, query string, args ...interface{}) (*stdsql.Rows, error) { + q, ok := tx.tx.(interface { + QueryContext(context.Context, string, ...interface{}) (*stdsql.Rows, error) + }) + if !ok { + return nil, fmt.Errorf("Tx.QueryContext is not supported") + } + return q.QueryContext(ctx, query, args...) +}