Skip to content

Commit

Permalink
Add query api
Browse files Browse the repository at this point in the history
  • Loading branch information
txya900619 committed Jan 8, 2022
1 parent 940a79d commit f495ba9
Show file tree
Hide file tree
Showing 26 changed files with 628 additions and 362 deletions.
5 changes: 5 additions & 0 deletions cmd/grpc/main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package main

import (
"github.com/Pirika-Pirilala-Popolina-Peperuto/database-system/internal/handler"
"github.com/Pirika-Pirilala-Popolina-Peperuto/database-system/pkg"
"github.com/Pirika-Pirilala-Popolina-Peperuto/database-system/pkg/ent"
"github.com/Pirika-Pirilala-Popolina-Peperuto/database-system/pkg/ent/proto/entpb"
pkg_grpc "github.com/Pirika-Pirilala-Popolina-Peperuto/database-system/pkg/grpc"
Expand All @@ -17,6 +19,7 @@ func init() {
func main() {
fx.New(
fx.Provide(
ent.NewSqlDriverWithLC,
ent.NewPostgresClientWithLC,
fx.Annotate(
pkg_grpc.NewServerWithLC,
Expand All @@ -42,13 +45,15 @@ func main() {
entpb.NewUserService,
fx.As(new(entpb.UserServiceServer)),
),
pkg.NewRouter,
),
fx.Invoke(
entpb.RegisterCategoryServiceServer,
entpb.RegisterDiscountServiceServer,
entpb.RegisterOrderServiceServer,
entpb.RegisterProductServiceServer,
entpb.RegisterUserServiceServer,
handler.RegisterApiHandler,
),
).Run()
}
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ go 1.17
require (
entgo.io/contrib v0.2.0
entgo.io/ent v0.9.2-0.20210821141344-368a8f7a2e9a
github.com/go-chi/chi/v5 v5.0.7
github.com/go-chi/cors v1.2.0
github.com/google/uuid v1.3.0
github.com/grpc-ecosystem/go-grpc-middleware v1.3.0
github.com/lib/pq v1.10.4
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,10 @@ github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMo
github.com/fsnotify/fsnotify v1.5.1 h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI=
github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/go-chi/chi/v5 v5.0.7 h1:rDTPXLDHGATaeHvVlLcR4Qe0zftYethFucbjVQ1PxU8=
github.com/go-chi/chi/v5 v5.0.7/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/go-chi/cors v1.2.0 h1:tV1g1XENQ8ku4Bq3K9ub2AtgG+p16SmzeMSGTwrOKdE=
github.com/go-chi/cors v1.2.0/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
Expand Down
110 changes: 110 additions & 0 deletions internal/handler/api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package handler

import (
"database/sql"
"encoding/json"
"net/http"

entsql "entgo.io/ent/dialect/sql"
"github.com/go-chi/chi/v5"
)

type apiHandler struct {
db *sql.DB
}

func RegisterApiHandler(router *chi.Mux, db *entsql.Driver) {
handler := &apiHandler{
db: db.DB(),
}

router.Route("/", func(apiRouter chi.Router) {
apiRouter.Get("/query", handler.query)
})

}

func (handler apiHandler) query(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query().Get("sql")
result, err := handler.db.Query(query)
if err != nil {
w.Write([]byte(err.Error()))
}

columnTypes, err := result.ColumnTypes()
if err != nil {
w.Write([]byte(err.Error()))
}

count := len(columnTypes)
finalRows := []interface{}{}

for result.Next() {

scanArgs := make([]interface{}, count)

for i, v := range columnTypes {

switch v.DatabaseTypeName() {
case "VARCHAR", "TEXT", "UUID", "TIMESTAMP":
scanArgs[i] = new(sql.NullString)
break
case "BOOL":
scanArgs[i] = new(sql.NullBool)
break
case "INT4":
scanArgs[i] = new(sql.NullInt64)
break
default:
scanArgs[i] = new(sql.NullString)
}
}

err := result.Scan(scanArgs...)

if err != nil {
w.Write([]byte(err.Error()))
}

masterData := map[string]interface{}{}

for i, v := range columnTypes {

if z, ok := (scanArgs[i]).(*sql.NullBool); ok {
masterData[v.Name()] = z.Bool
continue
}

if z, ok := (scanArgs[i]).(*sql.NullString); ok {
masterData[v.Name()] = z.String
continue
}

if z, ok := (scanArgs[i]).(*sql.NullInt64); ok {
masterData[v.Name()] = z.Int64
continue
}

if z, ok := (scanArgs[i]).(*sql.NullFloat64); ok {
masterData[v.Name()] = z.Float64
continue
}

if z, ok := (scanArgs[i]).(*sql.NullInt32); ok {
masterData[v.Name()] = z.Int32
continue
}

masterData[v.Name()] = scanArgs[i]
}

finalRows = append(finalRows, masterData)
}

resultJson, err := json.Marshal(finalRows)
if err != nil {
w.Write([]byte(err.Error()))
}

w.Write(resultJson)
}
36 changes: 36 additions & 0 deletions pkg/chi.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package pkg

import (
"context"
"net/http"

"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"go.uber.org/fx"
)

func NewRouter(lifecycle fx.Lifecycle) (*chi.Mux, error) {
r := chi.NewRouter()
r.Use(middleware.Logger, middleware.Recoverer)

server := &http.Server{
Addr: ":80",
Handler: r,
}

lifecycle.Append(fx.Hook{
OnStart: func(context.Context) error {
go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
panic(err)
}
}()
return nil
},
OnStop: func(ctx context.Context) error {
return server.Shutdown(ctx)
},
})

return r, nil
}
4 changes: 2 additions & 2 deletions pkg/ent/client.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 10 additions & 10 deletions pkg/ent/migrate/schema.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit f495ba9

Please sign in to comment.