From bb8357530843ff1a0f23eaec4f623a4bd1ffcc8f Mon Sep 17 00:00:00 2001 From: Katalina Okano Date: Tue, 15 Sep 2020 23:08:29 -0400 Subject: [PATCH] chore: make gazelle run with go generate --- BUILD.bazel | 1 + deps.bzl | 28 +------ go.mod | 3 +- go.sum | 21 ----- hack/generate.go | 7 ++ src/db/cmd/db-tool/BUILD.bazel | 23 ------ src/db/cmd/db-tool/Dockerfile | 59 -------------- src/db/cmd/db-tool/docker-compose.yaml | 14 ---- src/db/cmd/db-tool/import.go | 104 ------------------------- src/db/cmd/db-tool/migrate.go | 58 -------------- src/db/ent/challenge/challenge.go | 10 +++ src/db/ent/challenge_create.go | 61 ++++++++++----- src/db/ent/challenge_query.go | 46 +++++++---- src/db/ent/challenge_update.go | 40 ++++++---- src/db/ent/client.go | 12 +-- src/db/ent/ent.go | 54 +++++++++---- src/db/ent/guild/guild.go | 10 +++ src/db/ent/guild_create.go | 52 ++++++++----- src/db/ent/guild_query.go | 46 +++++++---- src/db/ent/guild_update.go | 40 ++++++---- src/db/ent/hook/hook.go | 2 +- src/db/ent/migrate/migrate.go | 2 +- src/db/ent/runtime/runtime.go | 4 +- src/db/ent/session/session.go | 10 +++ src/db/ent/session_create.go | 59 +++++++++----- src/db/ent/session_query.go | 46 +++++++---- src/db/ent/session_update.go | 40 ++++++---- 27 files changed, 370 insertions(+), 482 deletions(-) create mode 100644 hack/generate.go delete mode 100644 src/db/cmd/db-tool/BUILD.bazel delete mode 100644 src/db/cmd/db-tool/Dockerfile delete mode 100644 src/db/cmd/db-tool/docker-compose.yaml delete mode 100644 src/db/cmd/db-tool/import.go delete mode 100644 src/db/cmd/db-tool/migrate.go diff --git a/BUILD.bazel b/BUILD.bazel index 4f37211..2ec9d09 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -2,6 +2,7 @@ load("@bazel_gazelle//:def.bzl", "gazelle") load("@build_bazel_rules_nodejs//:index.bzl", "nodejs_binary") # gazelle:prefix github.com/roleypoly/roleypoly +# gazelle:exclude hack/** gazelle(name = "gazelle") exports_files( diff --git a/deps.bzl b/deps.bzl index acc60a9..20fd4f2 100644 --- a/deps.bzl +++ b/deps.bzl @@ -19,12 +19,7 @@ def go_repositories(): sum = "h1:qet1QNfXsQxTZqLG4oE62mJzwPIB8+Tee4RNCL9ulrY=", version = "v0.0.0-20151022065526-2efee857e7cf", ) - go_repository( - name = "com_github_andybalholm_cascadia", - importpath = "github.com/andybalholm/cascadia", - sum = "h1:BuuO6sSfQNFRu1LppgbD25Hr2vLYW25JvxHs5zzsLTo=", - version = "v1.1.0", - ) + go_repository( name = "com_github_armon_consul_api", importpath = "github.com/armon/consul-api", @@ -157,12 +152,7 @@ def go_repositories(): sum = "h1:ds9HENceKzpGBgCRlkZNq6TqBIegwKcF3e5reuV9Z0M=", version = "v0.4.3", ) - go_repository( - name = "com_github_facebookincubator_ent", - importpath = "github.com/facebookincubator/ent", - sum = "h1:Jht3vZio7eshMo7yaEZJ6LHk4oM8xUCxKNNDj/Kb4fE=", - version = "v0.3.0", - ) + go_repository( name = "com_github_fsnotify_fsnotify", importpath = "github.com/fsnotify/fsnotify", @@ -523,24 +513,14 @@ def go_repositories(): sum = "h1:YZcsG11NqnK4czYLrWd9mpEuAJIHVQLwdrleYfszMAA=", version = "v0.7.1", ) - go_repository( - name = "com_github_puerkitobio_goquery", - importpath = "github.com/PuerkitoBio/goquery", - sum = "h1:PSPBGne8NIUWw+/7vFBV+kG2J/5MOjbzc7154OaKCSE=", - version = "v1.5.1", - ) + go_repository( name = "com_github_rogpeppe_fastuuid", importpath = "github.com/rogpeppe/fastuuid", sum = "h1:gu+uRPtBe88sKxUCEXRoeCvVG90TJmwhiqRpvdhQFng=", version = "v0.0.0-20150106093220-6724a57986af", ) - go_repository( - name = "com_github_roleypoly_db", - importpath = "github.com/roleypoly/db", - sum = "h1:6As+Zl6a+YeIvpJXWOyDtxHTIP/kZdcYvSDrVkeJRLs=", - version = "v0.0.0-20200815123444-57c7f8a08f84", - ) + go_repository( name = "com_github_rs_cors", importpath = "github.com/rs/cors", diff --git a/go.mod b/go.mod index e72a556..8fff80f 100644 --- a/go.mod +++ b/go.mod @@ -10,9 +10,8 @@ require ( github.com/improbable-eng/grpc-web v0.13.0 github.com/joho/godotenv v1.3.0 github.com/lampjaw/discordclient v0.0.0-20200914142129-e3b4f5747970 - github.com/lib/pq v1.8.0 github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f // indirect - github.com/roleypoly/db v0.0.0-20200815123444-57c7f8a08f84 + github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect github.com/rs/cors v1.7.0 // indirect golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a // indirect golang.org/x/net v0.0.0-20200904194848-62affa334b73 // indirect diff --git a/go.sum b/go.sum index 4d57fe5..bcafc99 100644 --- a/go.sum +++ b/go.sum @@ -1,13 +1,10 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/DATA-DOG/go-sqlmock v1.4.1/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60= github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= -github.com/PuerkitoBio/goquery v1.5.1/go.mod h1:GsLWisAFVj4WgDibEWF4pvYnkVQBpKBKeU+7zCJoLcc= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/andybalholm/cascadia v1.1.0/go.mod h1:GsXiBklL0woXo1j/WYWtSYYC4ouU9PqHO0sqidkEA4Y= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= @@ -37,8 +34,6 @@ github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1m github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/facebook/ent v0.4.3 h1:ds9HENceKzpGBgCRlkZNq6TqBIegwKcF3e5reuV9Z0M= github.com/facebook/ent v0.4.3/go.mod h1:4e/LKv3FFjj/867jPJYCxycZg0aGeEIgkiQ8jv2j6iQ= -github.com/facebookincubator/ent v0.3.0 h1:Jht3vZio7eshMo7yaEZJ6LHk4oM8xUCxKNNDj/Kb4fE= -github.com/facebookincubator/ent v0.3.0/go.mod h1:0PIsj0mNbnwufO/bqBiQmA1WEdxcYkU+ONxf7PRM9q4= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/go-bindata/go-bindata v1.0.1-0.20190711162640-ee3c2418e368/go.mod h1:7xCgX1lzlrXPHkfvn3EhumqHkmSlzt8at9q7v0ax19c= @@ -78,8 +73,6 @@ github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w= github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY= -github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.2 h1:EVhdT+1Kseyi1/pUmXKaFxYsDNy9RQYkMWRH68J/W7Y= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q= @@ -116,7 +109,6 @@ github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czP github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= -github.com/mattn/go-sqlite3 v1.14.0/go.mod h1:JIl7NbARA7phWnGvh0LKTyg7S9BA+6gx71ShQilpsus= github.com/mattn/go-sqlite3 v1.14.3/go.mod h1:WVKg1VTActs4Qso6iwGbiFih2UIHo0ENGwNd0Lj+XmI= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= @@ -150,8 +142,6 @@ github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= -github.com/roleypoly/db v0.0.0-20200815123444-57c7f8a08f84 h1:6As+Zl6a+YeIvpJXWOyDtxHTIP/kZdcYvSDrVkeJRLs= -github.com/roleypoly/db v0.0.0-20200815123444-57c7f8a08f84/go.mod h1:dq8nCSix491Pvgq84GcbSgrLNKU8AwTNz3wCSHvTvss= github.com/rs/cors v1.7.0 h1:+88SsELBHx5r+hZ8TCkggzSstaWNbDvThkVK8H6f9ik= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= @@ -180,7 +170,6 @@ github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1 github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= -github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= @@ -202,10 +191,8 @@ golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvx golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190409202823-959b441ac422 h1:QzoH/1pFpZguR8NrRHLcO6jKqfv2zpuSqZLgdm7ZmjI= golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -216,9 +203,6 @@ golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200904194848-62affa334b73 h1:MXfv8rhZWmFeqX3GNZRsd6vOLoaCHjYEX3qkRo3YBUA= golang.org/x/net v0.0.0-20200904194848-62affa334b73/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= @@ -228,8 +212,6 @@ golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -256,8 +238,6 @@ golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3 golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20200615222825-6aa8f57aacd9 h1:cwgUY+1ja2qxWb2dyaCoixaA66WGWmrijSlxaM+JM/g= -golang.org/x/tools v0.0.0-20200615222825-6aa8f57aacd9/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200904185747-39188db58858 h1:xLt+iB5ksWcZVxqc+g9K41ZHy+6MKWfXCDsjSThnsPA= golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -299,7 +279,6 @@ gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLks gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b h1:QRR6H1YWRnHb4Y/HeNFCTJLFVxaq6wH4YuVdsUOr75U= gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= diff --git a/hack/generate.go b/hack/generate.go new file mode 100644 index 0000000..9532db2 --- /dev/null +++ b/hack/generate.go @@ -0,0 +1,7 @@ +package hacknotused + +//go:generate sh gazelle.sh + +func noop() { + +} \ No newline at end of file diff --git a/src/db/cmd/db-tool/BUILD.bazel b/src/db/cmd/db-tool/BUILD.bazel deleted file mode 100644 index 0b9a01e..0000000 --- a/src/db/cmd/db-tool/BUILD.bazel +++ /dev/null @@ -1,23 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library") - -go_library( - name = "db-tool_lib", - srcs = [ - "import.go", - "migrate.go", - ], - importpath = "github.com/roleypoly/roleypoly/src/db/cmd/db-tool", - visibility = ["//visibility:private"], - deps = [ - "@com_github_lib_pq//:pq", - "@com_github_roleypoly_db//ent", - "@com_github_roleypoly_db//ent/migrate", - "@com_github_roleypoly_db//ent/schema", - ], -) - -go_binary( - name = "db-tool", - embed = [":db-tool_lib"], - visibility = ["//visibility:public"], -) diff --git a/src/db/cmd/db-tool/Dockerfile b/src/db/cmd/db-tool/Dockerfile deleted file mode 100644 index 1a89d34..0000000 --- a/src/db/cmd/db-tool/Dockerfile +++ /dev/null @@ -1,59 +0,0 @@ -# Accept the Go version for the image to be set as a build argument. -# Default to Go 1.12 -ARG GO_VERSION=1.13 - -# First stage: build the executable. -FROM --platform=$BUILDPLATFORM golang:${GO_VERSION}-alpine AS builder - -ARG GOPROXY -ARG BUILDPLATFORM -ARG TARGETARCH -ARG TARGETOS -ENV GOPROXY ${GOPROXY} -ENV GOOS ${TARGETOS} -ENV GOARCH ${TARGETARCH} - -# Create the user and group files that will be used in the running container to -# run the process as an unprivileged user. -RUN mkdir /user && \ - echo 'nobody:x:65534:65534:nobody:/:' > /user/passwd && \ - echo 'nobody:x:65534:' > /user/group - -# Install the Certificate-Authority certificates for the app to be able to make -# calls to HTTPS endpoints. -# Git is required for fetching the dependencies. -RUN apk add --no-cache ca-certificates git - -# Set the working directory outside $GOPATH to enable the support for modules. -WORKDIR /src - -# Fetch dependencies first; they are less susceptible to change on every build -# and will therefore be cached for speeding up the next build -COPY ./go.mod ./go.sum ./ -RUN go mod download - -# Import the code from the context. -COPY ./ ./ - -# Build the executable to `/app`. Mark the build as statically linked. -RUN CGO_ENABLED=0 go build \ - -installsuffix 'static' \ - -o /app ./cmd/db-tool - -# Final stage: the running container. -FROM scratch AS final - -# Import the user and group files from the first stage. -COPY --from=builder /user/group /user/passwd /etc/ - -# Import the Certificate-Authority certificates for enabling HTTPS. -COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ - -# Import the compiled executable from the first stage. -COPY --from=builder /app /app - -# Perform any further action as an unprivileged user. -USER nobody:nobody - -# Run the compiled binary. -ENTRYPOINT ["/app"] \ No newline at end of file diff --git a/src/db/cmd/db-tool/docker-compose.yaml b/src/db/cmd/db-tool/docker-compose.yaml deleted file mode 100644 index 7a7edcd..0000000 --- a/src/db/cmd/db-tool/docker-compose.yaml +++ /dev/null @@ -1,14 +0,0 @@ -version: '2' - -services: - pg: - image: postgres:11-alpine - ports: - - 5432 - volumes: - - './.data/pg:/var/lib/postgresql/data' - environment: - POSTGRES_PASSWORD: 19216801 - POSTGRES_DB: roleypoly - POSTGRES_USER: roleypoly - POSTGRES_INITDB_ARGS: -A trust \ No newline at end of file diff --git a/src/db/cmd/db-tool/import.go b/src/db/cmd/db-tool/import.go deleted file mode 100644 index ab8e1c0..0000000 --- a/src/db/cmd/db-tool/import.go +++ /dev/null @@ -1,104 +0,0 @@ -package main - -import ( - "context" - "database/sql" - "log" - "os" - "time" - - ent "github.com/roleypoly/db/ent" - "github.com/roleypoly/db/ent/schema" -) - -type v1Category struct { - ID string `json:"id"` - Name string `json:"name"` - Roles []string `json:"roles"` - Hidden bool `json:"hidden"` - Type string `json:"type"` - Position int `json:"position"` -} - -type v1Server struct { - ID string `json:"id"` - Categories []v1Category `json:"categories"` - Message string `json:"message"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` -} - -func fromCategories(cats []v1Category) []schema.Category { - out := make([]schema.Category, len(cats)) - for i, cat := range cats { - out[i] = schema.Category{ - ID: cat.ID, - Name: cat.Name, - Hidden: cat.Hidden, - Type: cat.Type, - Position: cat.Position, - Roles: cat.Roles, - } - } - - return out -} - -func runImport(newDB *ent.Client, oldDB *sql.DB) { - ctx := ent.NewContext(context.Background(), newDB) - tx, err := newDB.Tx(ctx) - - oldServers, err := oldDB.Query(`SELECT * FROM servers`) - if err != nil { - tx.Rollback() - log.Fatalln("query error", err) - } - - defer oldServers.Close() - - for oldServers.Next() == true { - var data v1Server - - log.Printf("importing %s\n", data.ID) - - err = oldServers.Scan(&data) - if err != nil { - tx.Rollback() - log.Fatalln("data scan error", err) - } - - guild := tx.Guild.Create() - - guild.SetMessage(data.Message). - SetSnowflake(data.ID). - SetCategories(fromCategories(data.Categories)). - SetCreateTime(data.CreatedAt) - - ctx := ent.NewContext(context.Background(), newDB) - guild.SaveX(ctx) - } - - err = tx.Commit() - if err != nil { - log.Fatalln("tx commit error", err) - } -} - -func importFromV1() { - log.Println("Import from V1 starting.") - - client, err := ent.Open("postgres", os.Getenv("DB_URL")) - if err != nil { - log.Fatalln(err) - } - defer client.Close() - - oldClient, err := sql.Open("postgres", os.Getenv("OLD_DB_URL")) - if err != nil { - log.Fatalln(err) - } - defer oldClient.Close() - - runImport(client, oldClient) - log.Println("Import from V1 finished.") -} diff --git a/src/db/cmd/db-tool/migrate.go b/src/db/cmd/db-tool/migrate.go deleted file mode 100644 index 736943a..0000000 --- a/src/db/cmd/db-tool/migrate.go +++ /dev/null @@ -1,58 +0,0 @@ -package main - -import ( - "context" - "log" - "os" - "time" - - _ "github.com/lib/pq" - ent "github.com/roleypoly/db/ent" - "github.com/roleypoly/db/ent/migrate" -) - -func retryMigrate(client *ent.Client) { - for i := 0; i < 10; i++ { - err := client.Schema.Create(context.Background(), migrate.WithGlobalUniqueID(true)) - if err == nil { - return - } - - log.Println("Migration failed --", err) - time.Sleep(2 * time.Second) - } - - log.Fatalln("Migration failed after 20 seconds.") - return -} - -func doMigrate() { - log.Println("Migrations starting.") - - client, err := ent.Open("postgres", os.Getenv("DB_URL")) - if err != nil { - log.Fatalln(err) - } - - defer client.Close() - - retryMigrate(client) - log.Println("Migrations finished.") -} - -func main() { - tool := os.Args[1] - if tool == "" { - tool = "migrate" - } - - switch tool { - case "migrate": - doMigrate() - case "import": - importFromV1() - default: - log.Fatalln("supported tools: migrate, import") - } - -} diff --git a/src/db/ent/challenge/challenge.go b/src/db/ent/challenge/challenge.go index dc9c444..8d533fe 100644 --- a/src/db/ent/challenge/challenge.go +++ b/src/db/ent/challenge/challenge.go @@ -42,6 +42,16 @@ var Columns = []string{ FieldExpiresAt, } +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + var ( // DefaultCreateTime holds the default value on creation for the create_time field. DefaultCreateTime func() time.Time diff --git a/src/db/ent/challenge_create.go b/src/db/ent/challenge_create.go index fc83d95..da56910 100644 --- a/src/db/ent/challenge_create.go +++ b/src/db/ent/challenge_create.go @@ -93,14 +93,15 @@ func (cc *ChallengeCreate) Mutation() *ChallengeMutation { // Save creates the Challenge in the database. func (cc *ChallengeCreate) Save(ctx context.Context) (*Challenge, error) { - if err := cc.preSave(); err != nil { - return nil, err - } var ( err error node *Challenge ) + cc.defaults() if len(cc.hooks) == 0 { + if err = cc.check(); err != nil { + return nil, err + } node, err = cc.sqlSave(ctx) } else { var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { @@ -108,6 +109,9 @@ func (cc *ChallengeCreate) Save(ctx context.Context) (*Challenge, error) { if !ok { return nil, fmt.Errorf("unexpected mutation type %T", m) } + if err = cc.check(); err != nil { + return nil, err + } cc.mutation = mutation node, err = cc.sqlSave(ctx) mutation.done = true @@ -132,7 +136,8 @@ func (cc *ChallengeCreate) SaveX(ctx context.Context) *Challenge { return v } -func (cc *ChallengeCreate) preSave() error { +// defaults sets the default values of the builder before save. +func (cc *ChallengeCreate) defaults() { if _, ok := cc.mutation.CreateTime(); !ok { v := challenge.DefaultCreateTime() cc.mutation.SetCreateTime(v) @@ -141,6 +146,20 @@ func (cc *ChallengeCreate) preSave() error { v := challenge.DefaultUpdateTime() cc.mutation.SetUpdateTime(v) } + if _, ok := cc.mutation.ExpiresAt(); !ok { + v := challenge.DefaultExpiresAt() + cc.mutation.SetExpiresAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (cc *ChallengeCreate) check() error { + if _, ok := cc.mutation.CreateTime(); !ok { + return &ValidationError{Name: "create_time", err: errors.New("ent: missing required field \"create_time\"")} + } + if _, ok := cc.mutation.UpdateTime(); !ok { + return &ValidationError{Name: "update_time", err: errors.New("ent: missing required field \"update_time\"")} + } if _, ok := cc.mutation.ChallengeID(); !ok { return &ValidationError{Name: "challenge_id", err: errors.New("ent: missing required field \"challenge_id\"")} } @@ -154,14 +173,13 @@ func (cc *ChallengeCreate) preSave() error { return &ValidationError{Name: "magic", err: errors.New("ent: missing required field \"magic\"")} } if _, ok := cc.mutation.ExpiresAt(); !ok { - v := challenge.DefaultExpiresAt() - cc.mutation.SetExpiresAt(v) + return &ValidationError{Name: "expires_at", err: errors.New("ent: missing required field \"expires_at\"")} } return nil } func (cc *ChallengeCreate) sqlSave(ctx context.Context) (*Challenge, error) { - c, _spec := cc.createSpec() + _node, _spec := cc.createSpec() if err := sqlgraph.CreateNode(ctx, cc.driver, _spec); err != nil { if cerr, ok := isSQLConstraintError(err); ok { err = cerr @@ -169,13 +187,13 @@ func (cc *ChallengeCreate) sqlSave(ctx context.Context) (*Challenge, error) { return nil, err } id := _spec.ID.Value.(int64) - c.ID = int(id) - return c, nil + _node.ID = int(id) + return _node, nil } func (cc *ChallengeCreate) createSpec() (*Challenge, *sqlgraph.CreateSpec) { var ( - c = &Challenge{config: cc.config} + _node = &Challenge{config: cc.config} _spec = &sqlgraph.CreateSpec{ Table: challenge.Table, ID: &sqlgraph.FieldSpec{ @@ -190,7 +208,7 @@ func (cc *ChallengeCreate) createSpec() (*Challenge, *sqlgraph.CreateSpec) { Value: value, Column: challenge.FieldCreateTime, }) - c.CreateTime = value + _node.CreateTime = value } if value, ok := cc.mutation.UpdateTime(); ok { _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ @@ -198,7 +216,7 @@ func (cc *ChallengeCreate) createSpec() (*Challenge, *sqlgraph.CreateSpec) { Value: value, Column: challenge.FieldUpdateTime, }) - c.UpdateTime = value + _node.UpdateTime = value } if value, ok := cc.mutation.ChallengeID(); ok { _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ @@ -206,7 +224,7 @@ func (cc *ChallengeCreate) createSpec() (*Challenge, *sqlgraph.CreateSpec) { Value: value, Column: challenge.FieldChallengeID, }) - c.ChallengeID = value + _node.ChallengeID = value } if value, ok := cc.mutation.UserID(); ok { _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ @@ -214,7 +232,7 @@ func (cc *ChallengeCreate) createSpec() (*Challenge, *sqlgraph.CreateSpec) { Value: value, Column: challenge.FieldUserID, }) - c.UserID = value + _node.UserID = value } if value, ok := cc.mutation.Human(); ok { _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ @@ -222,7 +240,7 @@ func (cc *ChallengeCreate) createSpec() (*Challenge, *sqlgraph.CreateSpec) { Value: value, Column: challenge.FieldHuman, }) - c.Human = value + _node.Human = value } if value, ok := cc.mutation.Magic(); ok { _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ @@ -230,7 +248,7 @@ func (cc *ChallengeCreate) createSpec() (*Challenge, *sqlgraph.CreateSpec) { Value: value, Column: challenge.FieldMagic, }) - c.Magic = value + _node.Magic = value } if value, ok := cc.mutation.ExpiresAt(); ok { _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ @@ -238,9 +256,9 @@ func (cc *ChallengeCreate) createSpec() (*Challenge, *sqlgraph.CreateSpec) { Value: value, Column: challenge.FieldExpiresAt, }) - c.ExpiresAt = value + _node.ExpiresAt = value } - return c, _spec + return _node, _spec } // ChallengeCreateBulk is the builder for creating a bulk of Challenge entities. @@ -257,14 +275,15 @@ func (ccb *ChallengeCreateBulk) Save(ctx context.Context) ([]*Challenge, error) for i := range ccb.builders { func(i int, root context.Context) { builder := ccb.builders[i] + builder.defaults() var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - if err := builder.preSave(); err != nil { - return nil, err - } mutation, ok := m.(*ChallengeMutation) if !ok { return nil, fmt.Errorf("unexpected mutation type %T", m) } + if err := builder.check(); err != nil { + return nil, err + } builder.mutation = mutation nodes[i], specs[i] = builder.createSpec() var err error diff --git a/src/db/ent/challenge_query.go b/src/db/ent/challenge_query.go index a00df7b..9de6aaf 100644 --- a/src/db/ent/challenge_query.go +++ b/src/db/ent/challenge_query.go @@ -54,23 +54,23 @@ func (cq *ChallengeQuery) Order(o ...OrderFunc) *ChallengeQuery { // First returns the first Challenge entity in the query. Returns *NotFoundError when no challenge was found. func (cq *ChallengeQuery) First(ctx context.Context) (*Challenge, error) { - cs, err := cq.Limit(1).All(ctx) + nodes, err := cq.Limit(1).All(ctx) if err != nil { return nil, err } - if len(cs) == 0 { + if len(nodes) == 0 { return nil, &NotFoundError{challenge.Label} } - return cs[0], nil + return nodes[0], nil } // FirstX is like First, but panics if an error occurs. func (cq *ChallengeQuery) FirstX(ctx context.Context) *Challenge { - c, err := cq.First(ctx) + node, err := cq.First(ctx) if err != nil && !IsNotFound(err) { panic(err) } - return c + return node } // FirstID returns the first Challenge id in the query. Returns *NotFoundError when no id was found. @@ -97,13 +97,13 @@ func (cq *ChallengeQuery) FirstXID(ctx context.Context) int { // Only returns the only Challenge entity in the query, returns an error if not exactly one entity was returned. func (cq *ChallengeQuery) Only(ctx context.Context) (*Challenge, error) { - cs, err := cq.Limit(2).All(ctx) + nodes, err := cq.Limit(2).All(ctx) if err != nil { return nil, err } - switch len(cs) { + switch len(nodes) { case 1: - return cs[0], nil + return nodes[0], nil case 0: return nil, &NotFoundError{challenge.Label} default: @@ -113,11 +113,11 @@ func (cq *ChallengeQuery) Only(ctx context.Context) (*Challenge, error) { // OnlyX is like Only, but panics if an error occurs. func (cq *ChallengeQuery) OnlyX(ctx context.Context) *Challenge { - c, err := cq.Only(ctx) + node, err := cq.Only(ctx) if err != nil { panic(err) } - return c + return node } // OnlyID returns the only Challenge id in the query, returns an error if not exactly one id was returned. @@ -156,11 +156,11 @@ func (cq *ChallengeQuery) All(ctx context.Context) ([]*Challenge, error) { // AllX is like All, but panics if an error occurs. func (cq *ChallengeQuery) AllX(ctx context.Context) []*Challenge { - cs, err := cq.All(ctx) + nodes, err := cq.All(ctx) if err != nil { panic(err) } - return cs + return nodes } // IDs executes the query and returns a list of Challenge ids. @@ -362,7 +362,7 @@ func (cq *ChallengeQuery) querySpec() *sqlgraph.QuerySpec { if ps := cq.order; len(ps) > 0 { _spec.Order = func(selector *sql.Selector) { for i := range ps { - ps[i](selector) + ps[i](selector, challenge.ValidColumn) } } } @@ -381,7 +381,7 @@ func (cq *ChallengeQuery) sqlQuery() *sql.Selector { p(selector) } for _, p := range cq.order { - p(selector) + p(selector, challenge.ValidColumn) } if offset := cq.offset; offset != nil { // limit is mandatory for offset clause. We start @@ -616,8 +616,17 @@ func (cgb *ChallengeGroupBy) BoolX(ctx context.Context) bool { } func (cgb *ChallengeGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range cgb.fields { + if !challenge.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := cgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } rows := &sql.Rows{} - query, args := cgb.sqlQuery().Query() + query, args := selector.Query() if err := cgb.driver.Query(ctx, query, args, rows); err != nil { return err } @@ -630,7 +639,7 @@ func (cgb *ChallengeGroupBy) sqlQuery() *sql.Selector { columns := make([]string, 0, len(cgb.fields)+len(cgb.fns)) columns = append(columns, cgb.fields...) for _, fn := range cgb.fns { - columns = append(columns, fn(selector)) + columns = append(columns, fn(selector, challenge.ValidColumn)) } return selector.Select(columns...).GroupBy(cgb.fields...) } @@ -850,6 +859,11 @@ func (cs *ChallengeSelect) BoolX(ctx context.Context) bool { } func (cs *ChallengeSelect) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range cs.fields { + if !challenge.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for selection", f)} + } + } rows := &sql.Rows{} query, args := cs.sqlQuery().Query() if err := cs.driver.Query(ctx, query, args, rows); err != nil { diff --git a/src/db/ent/challenge_update.go b/src/db/ent/challenge_update.go index a7e5e11..91fdb86 100644 --- a/src/db/ent/challenge_update.go +++ b/src/db/ent/challenge_update.go @@ -34,14 +34,11 @@ func (cu *ChallengeUpdate) Mutation() *ChallengeMutation { // Save executes the query and returns the number of rows/vertices matched by this operation. func (cu *ChallengeUpdate) Save(ctx context.Context) (int, error) { - if _, ok := cu.mutation.UpdateTime(); !ok { - v := challenge.UpdateDefaultUpdateTime() - cu.mutation.SetUpdateTime(v) - } var ( err error affected int ) + cu.defaults() if len(cu.hooks) == 0 { affected, err = cu.sqlSave(ctx) } else { @@ -87,6 +84,14 @@ func (cu *ChallengeUpdate) ExecX(ctx context.Context) { } } +// defaults sets the default values of the builder before save. +func (cu *ChallengeUpdate) defaults() { + if _, ok := cu.mutation.UpdateTime(); !ok { + v := challenge.UpdateDefaultUpdateTime() + cu.mutation.SetUpdateTime(v) + } +} + func (cu *ChallengeUpdate) sqlSave(ctx context.Context) (n int, err error) { _spec := &sqlgraph.UpdateSpec{ Node: &sqlgraph.NodeSpec{ @@ -137,14 +142,11 @@ func (cuo *ChallengeUpdateOne) Mutation() *ChallengeMutation { // Save executes the query and returns the updated entity. func (cuo *ChallengeUpdateOne) Save(ctx context.Context) (*Challenge, error) { - if _, ok := cuo.mutation.UpdateTime(); !ok { - v := challenge.UpdateDefaultUpdateTime() - cuo.mutation.SetUpdateTime(v) - } var ( err error node *Challenge ) + cuo.defaults() if len(cuo.hooks) == 0 { node, err = cuo.sqlSave(ctx) } else { @@ -170,11 +172,11 @@ func (cuo *ChallengeUpdateOne) Save(ctx context.Context) (*Challenge, error) { // SaveX is like Save, but panics if an error occurs. func (cuo *ChallengeUpdateOne) SaveX(ctx context.Context) *Challenge { - c, err := cuo.Save(ctx) + node, err := cuo.Save(ctx) if err != nil { panic(err) } - return c + return node } // Exec executes the query on the entity. @@ -190,7 +192,15 @@ func (cuo *ChallengeUpdateOne) ExecX(ctx context.Context) { } } -func (cuo *ChallengeUpdateOne) sqlSave(ctx context.Context) (c *Challenge, err error) { +// defaults sets the default values of the builder before save. +func (cuo *ChallengeUpdateOne) defaults() { + if _, ok := cuo.mutation.UpdateTime(); !ok { + v := challenge.UpdateDefaultUpdateTime() + cuo.mutation.SetUpdateTime(v) + } +} + +func (cuo *ChallengeUpdateOne) sqlSave(ctx context.Context) (_node *Challenge, err error) { _spec := &sqlgraph.UpdateSpec{ Node: &sqlgraph.NodeSpec{ Table: challenge.Table, @@ -213,9 +223,9 @@ func (cuo *ChallengeUpdateOne) sqlSave(ctx context.Context) (c *Challenge, err e Column: challenge.FieldUpdateTime, }) } - c = &Challenge{config: cuo.config} - _spec.Assign = c.assignValues - _spec.ScanValues = c.scanValues() + _node = &Challenge{config: cuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues() if err = sqlgraph.UpdateNode(ctx, cuo.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{challenge.Label} @@ -224,5 +234,5 @@ func (cuo *ChallengeUpdateOne) sqlSave(ctx context.Context) (c *Challenge, err e } return nil, err } - return c, nil + return _node, nil } diff --git a/src/db/ent/client.go b/src/db/ent/client.go index e4b7964..dcbd744 100644 --- a/src/db/ent/client.go +++ b/src/db/ent/client.go @@ -206,11 +206,11 @@ func (c *ChallengeClient) Get(ctx context.Context, id int) (*Challenge, error) { // GetX is like Get, but panics if an error occurs. func (c *ChallengeClient) GetX(ctx context.Context, id int) *Challenge { - ch, err := c.Get(ctx, id) + obj, err := c.Get(ctx, id) if err != nil { panic(err) } - return ch + return obj } // Hooks returns the client hooks. @@ -294,11 +294,11 @@ func (c *GuildClient) Get(ctx context.Context, id int) (*Guild, error) { // GetX is like Get, but panics if an error occurs. func (c *GuildClient) GetX(ctx context.Context, id int) *Guild { - gu, err := c.Get(ctx, id) + obj, err := c.Get(ctx, id) if err != nil { panic(err) } - return gu + return obj } // Hooks returns the client hooks. @@ -382,11 +382,11 @@ func (c *SessionClient) Get(ctx context.Context, id int) (*Session, error) { // GetX is like Get, but panics if an error occurs. func (c *SessionClient) GetX(ctx context.Context, id int) *Session { - s, err := c.Get(ctx, id) + obj, err := c.Get(ctx, id) if err != nil { panic(err) } - return s + return obj } // Hooks returns the client hooks. diff --git a/src/db/ent/ent.go b/src/db/ent/ent.go index 368fc52..587180b 100644 --- a/src/db/ent/ent.go +++ b/src/db/ent/ent.go @@ -25,29 +25,37 @@ type ( MutateFunc = ent.MutateFunc ) -// OrderFunc applies an ordering on either graph traversal or sql selector. -type OrderFunc func(*sql.Selector) +// OrderFunc applies an ordering on the sql selector. +type OrderFunc func(*sql.Selector, func(string) bool) // Asc applies the given fields in ASC order. func Asc(fields ...string) OrderFunc { - return func(s *sql.Selector) { + return func(s *sql.Selector, check func(string) bool) { for _, f := range fields { - s.OrderBy(sql.Asc(f)) + if check(f) { + s.OrderBy(sql.Asc(f)) + } else { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("invalid field %q for ordering", f)}) + } } } } // Desc applies the given fields in DESC order. func Desc(fields ...string) OrderFunc { - return func(s *sql.Selector) { + return func(s *sql.Selector, check func(string) bool) { for _, f := range fields { - s.OrderBy(sql.Desc(f)) + if check(f) { + s.OrderBy(sql.Desc(f)) + } else { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("invalid field %q for ordering", f)}) + } } } } // AggregateFunc applies an aggregation step on the group-by traversal/selector. -type AggregateFunc func(*sql.Selector) string +type AggregateFunc func(*sql.Selector, func(string) bool) string // As is a pseudo aggregation function for renaming another other functions with custom names. For example: // @@ -56,42 +64,58 @@ type AggregateFunc func(*sql.Selector) string // Scan(ctx, &v) // func As(fn AggregateFunc, end string) AggregateFunc { - return func(s *sql.Selector) string { - return sql.As(fn(s), end) + return func(s *sql.Selector, check func(string) bool) string { + return sql.As(fn(s, check), end) } } // Count applies the "count" aggregation function on each group. func Count() AggregateFunc { - return func(s *sql.Selector) string { + return func(s *sql.Selector, _ func(string) bool) string { return sql.Count("*") } } // Max applies the "max" aggregation function on the given field of each group. func Max(field string) AggregateFunc { - return func(s *sql.Selector) string { + return func(s *sql.Selector, check func(string) bool) string { + if !check(field) { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("invalid field %q for grouping", field)}) + return "" + } return sql.Max(s.C(field)) } } // Mean applies the "mean" aggregation function on the given field of each group. func Mean(field string) AggregateFunc { - return func(s *sql.Selector) string { + return func(s *sql.Selector, check func(string) bool) string { + if !check(field) { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("invalid field %q for grouping", field)}) + return "" + } return sql.Avg(s.C(field)) } } // Min applies the "min" aggregation function on the given field of each group. func Min(field string) AggregateFunc { - return func(s *sql.Selector) string { + return func(s *sql.Selector, check func(string) bool) string { + if !check(field) { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("invalid field %q for grouping", field)}) + return "" + } return sql.Min(s.C(field)) } } // Sum applies the "sum" aggregation function on the given field of each group. func Sum(field string) AggregateFunc { - return func(s *sql.Selector) string { + return func(s *sql.Selector, check func(string) bool) string { + if !check(field) { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("invalid field %q for grouping", field)}) + return "" + } return sql.Sum(s.C(field)) } } @@ -109,7 +133,7 @@ func (e *ValidationError) Error() string { // Unwrap implements the errors.Wrapper interface. func (e *ValidationError) Unwrap() error { - return errors.Unwrap(e.err) + return e.err } // IsValidationError returns a boolean indicating whether the error is a validaton error. diff --git a/src/db/ent/guild/guild.go b/src/db/ent/guild/guild.go index 508250a..3111bb5 100644 --- a/src/db/ent/guild/guild.go +++ b/src/db/ent/guild/guild.go @@ -39,6 +39,16 @@ var Columns = []string{ FieldEntitlements, } +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + var ( // DefaultCreateTime holds the default value on creation for the create_time field. DefaultCreateTime func() time.Time diff --git a/src/db/ent/guild_create.go b/src/db/ent/guild_create.go index 92843ad..80a4796 100644 --- a/src/db/ent/guild_create.go +++ b/src/db/ent/guild_create.go @@ -80,14 +80,15 @@ func (gc *GuildCreate) Mutation() *GuildMutation { // Save creates the Guild in the database. func (gc *GuildCreate) Save(ctx context.Context) (*Guild, error) { - if err := gc.preSave(); err != nil { - return nil, err - } var ( err error node *Guild ) + gc.defaults() if len(gc.hooks) == 0 { + if err = gc.check(); err != nil { + return nil, err + } node, err = gc.sqlSave(ctx) } else { var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { @@ -95,6 +96,9 @@ func (gc *GuildCreate) Save(ctx context.Context) (*Guild, error) { if !ok { return nil, fmt.Errorf("unexpected mutation type %T", m) } + if err = gc.check(); err != nil { + return nil, err + } gc.mutation = mutation node, err = gc.sqlSave(ctx) mutation.done = true @@ -119,7 +123,8 @@ func (gc *GuildCreate) SaveX(ctx context.Context) *Guild { return v } -func (gc *GuildCreate) preSave() error { +// defaults sets the default values of the builder before save. +func (gc *GuildCreate) defaults() { if _, ok := gc.mutation.CreateTime(); !ok { v := guild.DefaultCreateTime() gc.mutation.SetCreateTime(v) @@ -128,6 +133,16 @@ func (gc *GuildCreate) preSave() error { v := guild.DefaultUpdateTime() gc.mutation.SetUpdateTime(v) } +} + +// check runs all checks and user-defined validators on the builder. +func (gc *GuildCreate) check() error { + if _, ok := gc.mutation.CreateTime(); !ok { + return &ValidationError{Name: "create_time", err: errors.New("ent: missing required field \"create_time\"")} + } + if _, ok := gc.mutation.UpdateTime(); !ok { + return &ValidationError{Name: "update_time", err: errors.New("ent: missing required field \"update_time\"")} + } if _, ok := gc.mutation.Snowflake(); !ok { return &ValidationError{Name: "snowflake", err: errors.New("ent: missing required field \"snowflake\"")} } @@ -144,7 +159,7 @@ func (gc *GuildCreate) preSave() error { } func (gc *GuildCreate) sqlSave(ctx context.Context) (*Guild, error) { - gu, _spec := gc.createSpec() + _node, _spec := gc.createSpec() if err := sqlgraph.CreateNode(ctx, gc.driver, _spec); err != nil { if cerr, ok := isSQLConstraintError(err); ok { err = cerr @@ -152,13 +167,13 @@ func (gc *GuildCreate) sqlSave(ctx context.Context) (*Guild, error) { return nil, err } id := _spec.ID.Value.(int64) - gu.ID = int(id) - return gu, nil + _node.ID = int(id) + return _node, nil } func (gc *GuildCreate) createSpec() (*Guild, *sqlgraph.CreateSpec) { var ( - gu = &Guild{config: gc.config} + _node = &Guild{config: gc.config} _spec = &sqlgraph.CreateSpec{ Table: guild.Table, ID: &sqlgraph.FieldSpec{ @@ -173,7 +188,7 @@ func (gc *GuildCreate) createSpec() (*Guild, *sqlgraph.CreateSpec) { Value: value, Column: guild.FieldCreateTime, }) - gu.CreateTime = value + _node.CreateTime = value } if value, ok := gc.mutation.UpdateTime(); ok { _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ @@ -181,7 +196,7 @@ func (gc *GuildCreate) createSpec() (*Guild, *sqlgraph.CreateSpec) { Value: value, Column: guild.FieldUpdateTime, }) - gu.UpdateTime = value + _node.UpdateTime = value } if value, ok := gc.mutation.Snowflake(); ok { _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ @@ -189,7 +204,7 @@ func (gc *GuildCreate) createSpec() (*Guild, *sqlgraph.CreateSpec) { Value: value, Column: guild.FieldSnowflake, }) - gu.Snowflake = value + _node.Snowflake = value } if value, ok := gc.mutation.Message(); ok { _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ @@ -197,7 +212,7 @@ func (gc *GuildCreate) createSpec() (*Guild, *sqlgraph.CreateSpec) { Value: value, Column: guild.FieldMessage, }) - gu.Message = value + _node.Message = value } if value, ok := gc.mutation.Categories(); ok { _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ @@ -205,7 +220,7 @@ func (gc *GuildCreate) createSpec() (*Guild, *sqlgraph.CreateSpec) { Value: value, Column: guild.FieldCategories, }) - gu.Categories = value + _node.Categories = value } if value, ok := gc.mutation.Entitlements(); ok { _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ @@ -213,9 +228,9 @@ func (gc *GuildCreate) createSpec() (*Guild, *sqlgraph.CreateSpec) { Value: value, Column: guild.FieldEntitlements, }) - gu.Entitlements = value + _node.Entitlements = value } - return gu, _spec + return _node, _spec } // GuildCreateBulk is the builder for creating a bulk of Guild entities. @@ -232,14 +247,15 @@ func (gcb *GuildCreateBulk) Save(ctx context.Context) ([]*Guild, error) { for i := range gcb.builders { func(i int, root context.Context) { builder := gcb.builders[i] + builder.defaults() var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - if err := builder.preSave(); err != nil { - return nil, err - } mutation, ok := m.(*GuildMutation) if !ok { return nil, fmt.Errorf("unexpected mutation type %T", m) } + if err := builder.check(); err != nil { + return nil, err + } builder.mutation = mutation nodes[i], specs[i] = builder.createSpec() var err error diff --git a/src/db/ent/guild_query.go b/src/db/ent/guild_query.go index d3b6ed3..ab2d50f 100644 --- a/src/db/ent/guild_query.go +++ b/src/db/ent/guild_query.go @@ -54,23 +54,23 @@ func (gq *GuildQuery) Order(o ...OrderFunc) *GuildQuery { // First returns the first Guild entity in the query. Returns *NotFoundError when no guild was found. func (gq *GuildQuery) First(ctx context.Context) (*Guild, error) { - gus, err := gq.Limit(1).All(ctx) + nodes, err := gq.Limit(1).All(ctx) if err != nil { return nil, err } - if len(gus) == 0 { + if len(nodes) == 0 { return nil, &NotFoundError{guild.Label} } - return gus[0], nil + return nodes[0], nil } // FirstX is like First, but panics if an error occurs. func (gq *GuildQuery) FirstX(ctx context.Context) *Guild { - gu, err := gq.First(ctx) + node, err := gq.First(ctx) if err != nil && !IsNotFound(err) { panic(err) } - return gu + return node } // FirstID returns the first Guild id in the query. Returns *NotFoundError when no id was found. @@ -97,13 +97,13 @@ func (gq *GuildQuery) FirstXID(ctx context.Context) int { // Only returns the only Guild entity in the query, returns an error if not exactly one entity was returned. func (gq *GuildQuery) Only(ctx context.Context) (*Guild, error) { - gus, err := gq.Limit(2).All(ctx) + nodes, err := gq.Limit(2).All(ctx) if err != nil { return nil, err } - switch len(gus) { + switch len(nodes) { case 1: - return gus[0], nil + return nodes[0], nil case 0: return nil, &NotFoundError{guild.Label} default: @@ -113,11 +113,11 @@ func (gq *GuildQuery) Only(ctx context.Context) (*Guild, error) { // OnlyX is like Only, but panics if an error occurs. func (gq *GuildQuery) OnlyX(ctx context.Context) *Guild { - gu, err := gq.Only(ctx) + node, err := gq.Only(ctx) if err != nil { panic(err) } - return gu + return node } // OnlyID returns the only Guild id in the query, returns an error if not exactly one id was returned. @@ -156,11 +156,11 @@ func (gq *GuildQuery) All(ctx context.Context) ([]*Guild, error) { // AllX is like All, but panics if an error occurs. func (gq *GuildQuery) AllX(ctx context.Context) []*Guild { - gus, err := gq.All(ctx) + nodes, err := gq.All(ctx) if err != nil { panic(err) } - return gus + return nodes } // IDs executes the query and returns a list of Guild ids. @@ -362,7 +362,7 @@ func (gq *GuildQuery) querySpec() *sqlgraph.QuerySpec { if ps := gq.order; len(ps) > 0 { _spec.Order = func(selector *sql.Selector) { for i := range ps { - ps[i](selector) + ps[i](selector, guild.ValidColumn) } } } @@ -381,7 +381,7 @@ func (gq *GuildQuery) sqlQuery() *sql.Selector { p(selector) } for _, p := range gq.order { - p(selector) + p(selector, guild.ValidColumn) } if offset := gq.offset; offset != nil { // limit is mandatory for offset clause. We start @@ -616,8 +616,17 @@ func (ggb *GuildGroupBy) BoolX(ctx context.Context) bool { } func (ggb *GuildGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range ggb.fields { + if !guild.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := ggb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } rows := &sql.Rows{} - query, args := ggb.sqlQuery().Query() + query, args := selector.Query() if err := ggb.driver.Query(ctx, query, args, rows); err != nil { return err } @@ -630,7 +639,7 @@ func (ggb *GuildGroupBy) sqlQuery() *sql.Selector { columns := make([]string, 0, len(ggb.fields)+len(ggb.fns)) columns = append(columns, ggb.fields...) for _, fn := range ggb.fns { - columns = append(columns, fn(selector)) + columns = append(columns, fn(selector, guild.ValidColumn)) } return selector.Select(columns...).GroupBy(ggb.fields...) } @@ -850,6 +859,11 @@ func (gs *GuildSelect) BoolX(ctx context.Context) bool { } func (gs *GuildSelect) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range gs.fields { + if !guild.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for selection", f)} + } + } rows := &sql.Rows{} query, args := gs.sqlQuery().Query() if err := gs.driver.Query(ctx, query, args, rows); err != nil { diff --git a/src/db/ent/guild_update.go b/src/db/ent/guild_update.go index 7d15851..b7e0742 100644 --- a/src/db/ent/guild_update.go +++ b/src/db/ent/guild_update.go @@ -53,14 +53,11 @@ func (gu *GuildUpdate) Mutation() *GuildMutation { // Save executes the query and returns the number of rows/vertices matched by this operation. func (gu *GuildUpdate) Save(ctx context.Context) (int, error) { - if _, ok := gu.mutation.UpdateTime(); !ok { - v := guild.UpdateDefaultUpdateTime() - gu.mutation.SetUpdateTime(v) - } var ( err error affected int ) + gu.defaults() if len(gu.hooks) == 0 { affected, err = gu.sqlSave(ctx) } else { @@ -106,6 +103,14 @@ func (gu *GuildUpdate) ExecX(ctx context.Context) { } } +// defaults sets the default values of the builder before save. +func (gu *GuildUpdate) defaults() { + if _, ok := gu.mutation.UpdateTime(); !ok { + v := guild.UpdateDefaultUpdateTime() + gu.mutation.SetUpdateTime(v) + } +} + func (gu *GuildUpdate) sqlSave(ctx context.Context) (n int, err error) { _spec := &sqlgraph.UpdateSpec{ Node: &sqlgraph.NodeSpec{ @@ -195,14 +200,11 @@ func (guo *GuildUpdateOne) Mutation() *GuildMutation { // Save executes the query and returns the updated entity. func (guo *GuildUpdateOne) Save(ctx context.Context) (*Guild, error) { - if _, ok := guo.mutation.UpdateTime(); !ok { - v := guild.UpdateDefaultUpdateTime() - guo.mutation.SetUpdateTime(v) - } var ( err error node *Guild ) + guo.defaults() if len(guo.hooks) == 0 { node, err = guo.sqlSave(ctx) } else { @@ -228,11 +230,11 @@ func (guo *GuildUpdateOne) Save(ctx context.Context) (*Guild, error) { // SaveX is like Save, but panics if an error occurs. func (guo *GuildUpdateOne) SaveX(ctx context.Context) *Guild { - gu, err := guo.Save(ctx) + node, err := guo.Save(ctx) if err != nil { panic(err) } - return gu + return node } // Exec executes the query on the entity. @@ -248,7 +250,15 @@ func (guo *GuildUpdateOne) ExecX(ctx context.Context) { } } -func (guo *GuildUpdateOne) sqlSave(ctx context.Context) (gu *Guild, err error) { +// defaults sets the default values of the builder before save. +func (guo *GuildUpdateOne) defaults() { + if _, ok := guo.mutation.UpdateTime(); !ok { + v := guild.UpdateDefaultUpdateTime() + guo.mutation.SetUpdateTime(v) + } +} + +func (guo *GuildUpdateOne) sqlSave(ctx context.Context) (_node *Guild, err error) { _spec := &sqlgraph.UpdateSpec{ Node: &sqlgraph.NodeSpec{ Table: guild.Table, @@ -292,9 +302,9 @@ func (guo *GuildUpdateOne) sqlSave(ctx context.Context) (gu *Guild, err error) { Column: guild.FieldEntitlements, }) } - gu = &Guild{config: guo.config} - _spec.Assign = gu.assignValues - _spec.ScanValues = gu.scanValues() + _node = &Guild{config: guo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues() if err = sqlgraph.UpdateNode(ctx, guo.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{guild.Label} @@ -303,5 +313,5 @@ func (guo *GuildUpdateOne) sqlSave(ctx context.Context) (gu *Guild, err error) { } return nil, err } - return gu, nil + return _node, nil } diff --git a/src/db/ent/hook/hook.go b/src/db/ent/hook/hook.go index b15002b..bb0843d 100644 --- a/src/db/ent/hook/hook.go +++ b/src/db/ent/hook/hook.go @@ -142,7 +142,7 @@ func HasFields(field string, fields ...string) Condition { // If executes the given hook under condition. // -// Hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) +// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) // func If(hk ent.Hook, cond Condition) ent.Hook { return func(next ent.Mutator) ent.Mutator { diff --git a/src/db/ent/migrate/migrate.go b/src/db/ent/migrate/migrate.go index 27b36b4..7e1d225 100644 --- a/src/db/ent/migrate/migrate.go +++ b/src/db/ent/migrate/migrate.go @@ -29,7 +29,7 @@ var ( // flexibility in the schema changes. WithDropIndex = schema.WithDropIndex // WithFixture sets the foreign-key renaming option to the migration when upgrading - // ent from v0.1.0 (issue-#285). Defaults to true. + // ent from v0.1.0 (issue-#285). Defaults to false. WithFixture = schema.WithFixture ) diff --git a/src/db/ent/runtime/runtime.go b/src/db/ent/runtime/runtime.go index 2624b79..1817fb1 100644 --- a/src/db/ent/runtime/runtime.go +++ b/src/db/ent/runtime/runtime.go @@ -5,6 +5,6 @@ package runtime // The schema-stitching logic is generated in github.com/roleypoly/roleypoly/src/db/ent/runtime.go const ( - Version = "v0.4.2" // Version of ent codegen. - Sum = "h1:JzU5dYJH9XdjfIKgOiPPK3szkqLqcdPWgVder4Ogows=" // Sum of ent codegen. + Version = "v0.4.3" // Version of ent codegen. + Sum = "h1:ds9HENceKzpGBgCRlkZNq6TqBIegwKcF3e5reuV9Z0M=" // Sum of ent codegen. ) diff --git a/src/db/ent/session/session.go b/src/db/ent/session/session.go index 70bc93c..86e5b00 100644 --- a/src/db/ent/session/session.go +++ b/src/db/ent/session/session.go @@ -40,6 +40,16 @@ var Columns = []string{ FieldExpiresAt, } +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + var ( // DefaultCreateTime holds the default value on creation for the create_time field. DefaultCreateTime func() time.Time diff --git a/src/db/ent/session_create.go b/src/db/ent/session_create.go index ad0df69..db263c4 100644 --- a/src/db/ent/session_create.go +++ b/src/db/ent/session_create.go @@ -87,14 +87,15 @@ func (sc *SessionCreate) Mutation() *SessionMutation { // Save creates the Session in the database. func (sc *SessionCreate) Save(ctx context.Context) (*Session, error) { - if err := sc.preSave(); err != nil { - return nil, err - } var ( err error node *Session ) + sc.defaults() if len(sc.hooks) == 0 { + if err = sc.check(); err != nil { + return nil, err + } node, err = sc.sqlSave(ctx) } else { var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { @@ -102,6 +103,9 @@ func (sc *SessionCreate) Save(ctx context.Context) (*Session, error) { if !ok { return nil, fmt.Errorf("unexpected mutation type %T", m) } + if err = sc.check(); err != nil { + return nil, err + } sc.mutation = mutation node, err = sc.sqlSave(ctx) mutation.done = true @@ -126,7 +130,8 @@ func (sc *SessionCreate) SaveX(ctx context.Context) *Session { return v } -func (sc *SessionCreate) preSave() error { +// defaults sets the default values of the builder before save. +func (sc *SessionCreate) defaults() { if _, ok := sc.mutation.CreateTime(); !ok { v := session.DefaultCreateTime() sc.mutation.SetCreateTime(v) @@ -135,6 +140,20 @@ func (sc *SessionCreate) preSave() error { v := session.DefaultUpdateTime() sc.mutation.SetUpdateTime(v) } + if _, ok := sc.mutation.ExpiresAt(); !ok { + v := session.DefaultExpiresAt() + sc.mutation.SetExpiresAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (sc *SessionCreate) check() error { + if _, ok := sc.mutation.CreateTime(); !ok { + return &ValidationError{Name: "create_time", err: errors.New("ent: missing required field \"create_time\"")} + } + if _, ok := sc.mutation.UpdateTime(); !ok { + return &ValidationError{Name: "update_time", err: errors.New("ent: missing required field \"update_time\"")} + } if _, ok := sc.mutation.SessionID(); !ok { return &ValidationError{Name: "session_id", err: errors.New("ent: missing required field \"session_id\"")} } @@ -150,14 +169,13 @@ func (sc *SessionCreate) preSave() error { } } if _, ok := sc.mutation.ExpiresAt(); !ok { - v := session.DefaultExpiresAt() - sc.mutation.SetExpiresAt(v) + return &ValidationError{Name: "expires_at", err: errors.New("ent: missing required field \"expires_at\"")} } return nil } func (sc *SessionCreate) sqlSave(ctx context.Context) (*Session, error) { - s, _spec := sc.createSpec() + _node, _spec := sc.createSpec() if err := sqlgraph.CreateNode(ctx, sc.driver, _spec); err != nil { if cerr, ok := isSQLConstraintError(err); ok { err = cerr @@ -165,13 +183,13 @@ func (sc *SessionCreate) sqlSave(ctx context.Context) (*Session, error) { return nil, err } id := _spec.ID.Value.(int64) - s.ID = int(id) - return s, nil + _node.ID = int(id) + return _node, nil } func (sc *SessionCreate) createSpec() (*Session, *sqlgraph.CreateSpec) { var ( - s = &Session{config: sc.config} + _node = &Session{config: sc.config} _spec = &sqlgraph.CreateSpec{ Table: session.Table, ID: &sqlgraph.FieldSpec{ @@ -186,7 +204,7 @@ func (sc *SessionCreate) createSpec() (*Session, *sqlgraph.CreateSpec) { Value: value, Column: session.FieldCreateTime, }) - s.CreateTime = value + _node.CreateTime = value } if value, ok := sc.mutation.UpdateTime(); ok { _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ @@ -194,7 +212,7 @@ func (sc *SessionCreate) createSpec() (*Session, *sqlgraph.CreateSpec) { Value: value, Column: session.FieldUpdateTime, }) - s.UpdateTime = value + _node.UpdateTime = value } if value, ok := sc.mutation.SessionID(); ok { _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ @@ -202,7 +220,7 @@ func (sc *SessionCreate) createSpec() (*Session, *sqlgraph.CreateSpec) { Value: value, Column: session.FieldSessionID, }) - s.SessionID = value + _node.SessionID = value } if value, ok := sc.mutation.UserID(); ok { _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ @@ -210,7 +228,7 @@ func (sc *SessionCreate) createSpec() (*Session, *sqlgraph.CreateSpec) { Value: value, Column: session.FieldUserID, }) - s.UserID = value + _node.UserID = value } if value, ok := sc.mutation.Source(); ok { _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ @@ -218,7 +236,7 @@ func (sc *SessionCreate) createSpec() (*Session, *sqlgraph.CreateSpec) { Value: value, Column: session.FieldSource, }) - s.Source = value + _node.Source = value } if value, ok := sc.mutation.ExpiresAt(); ok { _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ @@ -226,9 +244,9 @@ func (sc *SessionCreate) createSpec() (*Session, *sqlgraph.CreateSpec) { Value: value, Column: session.FieldExpiresAt, }) - s.ExpiresAt = value + _node.ExpiresAt = value } - return s, _spec + return _node, _spec } // SessionCreateBulk is the builder for creating a bulk of Session entities. @@ -245,14 +263,15 @@ func (scb *SessionCreateBulk) Save(ctx context.Context) ([]*Session, error) { for i := range scb.builders { func(i int, root context.Context) { builder := scb.builders[i] + builder.defaults() var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - if err := builder.preSave(); err != nil { - return nil, err - } mutation, ok := m.(*SessionMutation) if !ok { return nil, fmt.Errorf("unexpected mutation type %T", m) } + if err := builder.check(); err != nil { + return nil, err + } builder.mutation = mutation nodes[i], specs[i] = builder.createSpec() var err error diff --git a/src/db/ent/session_query.go b/src/db/ent/session_query.go index b14e6dc..1a16760 100644 --- a/src/db/ent/session_query.go +++ b/src/db/ent/session_query.go @@ -54,23 +54,23 @@ func (sq *SessionQuery) Order(o ...OrderFunc) *SessionQuery { // First returns the first Session entity in the query. Returns *NotFoundError when no session was found. func (sq *SessionQuery) First(ctx context.Context) (*Session, error) { - sSlice, err := sq.Limit(1).All(ctx) + nodes, err := sq.Limit(1).All(ctx) if err != nil { return nil, err } - if len(sSlice) == 0 { + if len(nodes) == 0 { return nil, &NotFoundError{session.Label} } - return sSlice[0], nil + return nodes[0], nil } // FirstX is like First, but panics if an error occurs. func (sq *SessionQuery) FirstX(ctx context.Context) *Session { - s, err := sq.First(ctx) + node, err := sq.First(ctx) if err != nil && !IsNotFound(err) { panic(err) } - return s + return node } // FirstID returns the first Session id in the query. Returns *NotFoundError when no id was found. @@ -97,13 +97,13 @@ func (sq *SessionQuery) FirstXID(ctx context.Context) int { // Only returns the only Session entity in the query, returns an error if not exactly one entity was returned. func (sq *SessionQuery) Only(ctx context.Context) (*Session, error) { - sSlice, err := sq.Limit(2).All(ctx) + nodes, err := sq.Limit(2).All(ctx) if err != nil { return nil, err } - switch len(sSlice) { + switch len(nodes) { case 1: - return sSlice[0], nil + return nodes[0], nil case 0: return nil, &NotFoundError{session.Label} default: @@ -113,11 +113,11 @@ func (sq *SessionQuery) Only(ctx context.Context) (*Session, error) { // OnlyX is like Only, but panics if an error occurs. func (sq *SessionQuery) OnlyX(ctx context.Context) *Session { - s, err := sq.Only(ctx) + node, err := sq.Only(ctx) if err != nil { panic(err) } - return s + return node } // OnlyID returns the only Session id in the query, returns an error if not exactly one id was returned. @@ -156,11 +156,11 @@ func (sq *SessionQuery) All(ctx context.Context) ([]*Session, error) { // AllX is like All, but panics if an error occurs. func (sq *SessionQuery) AllX(ctx context.Context) []*Session { - sSlice, err := sq.All(ctx) + nodes, err := sq.All(ctx) if err != nil { panic(err) } - return sSlice + return nodes } // IDs executes the query and returns a list of Session ids. @@ -362,7 +362,7 @@ func (sq *SessionQuery) querySpec() *sqlgraph.QuerySpec { if ps := sq.order; len(ps) > 0 { _spec.Order = func(selector *sql.Selector) { for i := range ps { - ps[i](selector) + ps[i](selector, session.ValidColumn) } } } @@ -381,7 +381,7 @@ func (sq *SessionQuery) sqlQuery() *sql.Selector { p(selector) } for _, p := range sq.order { - p(selector) + p(selector, session.ValidColumn) } if offset := sq.offset; offset != nil { // limit is mandatory for offset clause. We start @@ -616,8 +616,17 @@ func (sgb *SessionGroupBy) BoolX(ctx context.Context) bool { } func (sgb *SessionGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range sgb.fields { + if !session.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := sgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } rows := &sql.Rows{} - query, args := sgb.sqlQuery().Query() + query, args := selector.Query() if err := sgb.driver.Query(ctx, query, args, rows); err != nil { return err } @@ -630,7 +639,7 @@ func (sgb *SessionGroupBy) sqlQuery() *sql.Selector { columns := make([]string, 0, len(sgb.fields)+len(sgb.fns)) columns = append(columns, sgb.fields...) for _, fn := range sgb.fns { - columns = append(columns, fn(selector)) + columns = append(columns, fn(selector, session.ValidColumn)) } return selector.Select(columns...).GroupBy(sgb.fields...) } @@ -850,6 +859,11 @@ func (ss *SessionSelect) BoolX(ctx context.Context) bool { } func (ss *SessionSelect) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range ss.fields { + if !session.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for selection", f)} + } + } rows := &sql.Rows{} query, args := ss.sqlQuery().Query() if err := ss.driver.Query(ctx, query, args, rows); err != nil { diff --git a/src/db/ent/session_update.go b/src/db/ent/session_update.go index db38719..5c65706 100644 --- a/src/db/ent/session_update.go +++ b/src/db/ent/session_update.go @@ -34,14 +34,11 @@ func (su *SessionUpdate) Mutation() *SessionMutation { // Save executes the query and returns the number of rows/vertices matched by this operation. func (su *SessionUpdate) Save(ctx context.Context) (int, error) { - if _, ok := su.mutation.UpdateTime(); !ok { - v := session.UpdateDefaultUpdateTime() - su.mutation.SetUpdateTime(v) - } var ( err error affected int ) + su.defaults() if len(su.hooks) == 0 { affected, err = su.sqlSave(ctx) } else { @@ -87,6 +84,14 @@ func (su *SessionUpdate) ExecX(ctx context.Context) { } } +// defaults sets the default values of the builder before save. +func (su *SessionUpdate) defaults() { + if _, ok := su.mutation.UpdateTime(); !ok { + v := session.UpdateDefaultUpdateTime() + su.mutation.SetUpdateTime(v) + } +} + func (su *SessionUpdate) sqlSave(ctx context.Context) (n int, err error) { _spec := &sqlgraph.UpdateSpec{ Node: &sqlgraph.NodeSpec{ @@ -137,14 +142,11 @@ func (suo *SessionUpdateOne) Mutation() *SessionMutation { // Save executes the query and returns the updated entity. func (suo *SessionUpdateOne) Save(ctx context.Context) (*Session, error) { - if _, ok := suo.mutation.UpdateTime(); !ok { - v := session.UpdateDefaultUpdateTime() - suo.mutation.SetUpdateTime(v) - } var ( err error node *Session ) + suo.defaults() if len(suo.hooks) == 0 { node, err = suo.sqlSave(ctx) } else { @@ -170,11 +172,11 @@ func (suo *SessionUpdateOne) Save(ctx context.Context) (*Session, error) { // SaveX is like Save, but panics if an error occurs. func (suo *SessionUpdateOne) SaveX(ctx context.Context) *Session { - s, err := suo.Save(ctx) + node, err := suo.Save(ctx) if err != nil { panic(err) } - return s + return node } // Exec executes the query on the entity. @@ -190,7 +192,15 @@ func (suo *SessionUpdateOne) ExecX(ctx context.Context) { } } -func (suo *SessionUpdateOne) sqlSave(ctx context.Context) (s *Session, err error) { +// defaults sets the default values of the builder before save. +func (suo *SessionUpdateOne) defaults() { + if _, ok := suo.mutation.UpdateTime(); !ok { + v := session.UpdateDefaultUpdateTime() + suo.mutation.SetUpdateTime(v) + } +} + +func (suo *SessionUpdateOne) sqlSave(ctx context.Context) (_node *Session, err error) { _spec := &sqlgraph.UpdateSpec{ Node: &sqlgraph.NodeSpec{ Table: session.Table, @@ -213,9 +223,9 @@ func (suo *SessionUpdateOne) sqlSave(ctx context.Context) (s *Session, err error Column: session.FieldUpdateTime, }) } - s = &Session{config: suo.config} - _spec.Assign = s.assignValues - _spec.ScanValues = s.scanValues() + _node = &Session{config: suo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues() if err = sqlgraph.UpdateNode(ctx, suo.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{session.Label} @@ -224,5 +234,5 @@ func (suo *SessionUpdateOne) sqlSave(ctx context.Context) (s *Session, err error } return nil, err } - return s, nil + return _node, nil }