Merge branch 'gcf' into main

Signed-off-by: Katalina Okano <git@kat.cafe>
This commit is contained in:
41666 2020-12-05 03:11:12 -05:00
commit 156bd8f06e
364 changed files with 5234 additions and 22248 deletions

1
src/backend-worker/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
dist

13
src/backend-worker/bindings.d.ts vendored Normal file
View file

@ -0,0 +1,13 @@
export {};
declare global {
const BOT_CLIENT_ID: string;
const BOT_CLIENT_SECRET: string;
const UI_PUBLIC_URI: string;
const API_PUBLIC_URI: string;
const ROOT_USERS: string;
const KV_SESSIONS: KVNamespace;
const KV_GUILDS: KVNamespace;
const KV_GUILD_DATA: KVNamespace;
}

View file

@ -0,0 +1,35 @@
import { Bounce } from '../utils/bounce';
const validGuildID = /^[0-9]+$/;
type URLParams = {
clientID: string;
permissions: number;
guildID?: string;
};
const buildURL = (params: URLParams) => {
let url = `https://discord.com/api/oauth2/authorize?client_id=${params.clientID}&scope=bot&permissions=${params.permissions}`;
if (params.guildID) {
url += `&guild_id=${params.guildID}&disable_guild_select=true`;
}
return url;
};
export const BotJoin = (request: Request): Response => {
let guildID = new URL(request.url).searchParams.get('guild') || '';
if (guildID && !validGuildID.test(guildID)) {
guildID = '';
}
return Bounce(
buildURL({
clientID: BOT_CLIENT_ID,
permissions: 268435456,
guildID,
})
);
};

View file

@ -0,0 +1,31 @@
import { SessionData } from 'roleypoly/common/types';
import { getSessionID, respond } from '../utils/api-tools';
import { Sessions } from '../utils/kv';
const NotAuthenticated = (extra?: string) =>
respond(
{
err: extra || 'not authenticated',
},
{ status: 403 }
);
export const GetSession = async (request: Request): Promise<Response> => {
const sessionID = getSessionID(request);
if (!sessionID) {
return NotAuthenticated('missing auth header');
}
console.log(sessionID);
const sessionData = await Sessions.get<SessionData>(sessionID.id);
if (!sessionData) {
return NotAuthenticated('session not found');
}
const { tokens, ...withoutTokens } = sessionData;
return respond({
...withoutTokens,
});
};

View file

@ -0,0 +1,24 @@
import KSUID from 'ksuid';
import { Bounce } from '../utils/bounce';
import { apiPublicURI, botClientID } from '../utils/config';
type URLParams = {
clientID: string;
redirectURI: string;
state: string;
};
const buildURL = (params: URLParams) =>
`https://discord.com/api/oauth2/authorize?client_id=${
params.clientID
}&response_type=code&scope=identify%20guilds&redirect_uri=${encodeURIComponent(
params.redirectURI
)}&state=${params.state}`;
export const LoginBounce = async (request: Request): Promise<Response> => {
const state = await KSUID.random();
const redirectURI = `${apiPublicURI}/login-callback`;
const clientID = botClientID;
return Bounce(buildURL({ state: state.string, redirectURI, clientID }));
};

View file

@ -0,0 +1,134 @@
import KSUID from 'ksuid';
import {
DiscordUser,
GuildSlug,
SessionData,
AuthTokenResponse,
} from '../../common/types';
import { formData, resolveFailures, parsePermissions } from '../utils/api-tools';
import { Bounce } from '../utils/bounce';
import { apiPublicURI, botClientID, botClientSecret, uiPublicURI } from '../utils/config';
import { Sessions } from '../utils/kv';
const AuthErrorResponse = (extra?: string) =>
Bounce(
uiPublicURI +
`/machinery/error?error_code=authFailure${extra ? `&extra=${extra}` : ''}`
);
export const LoginCallback = resolveFailures(
AuthErrorResponse(),
async (request: Request): Promise<Response> => {
const query = new URL(request.url).searchParams;
const stateValue = query.get('state');
if (stateValue === null) {
return AuthErrorResponse('state missing');
}
try {
const state = KSUID.parse(stateValue);
const stateExpiry = state.date.getTime() + 1000 * 60 * 5;
const currentTime = Date.now();
if (currentTime > stateExpiry) {
return AuthErrorResponse('state expired');
}
} catch (e) {
return AuthErrorResponse('state invalid');
}
const code = query.get('code');
if (!code) {
return AuthErrorResponse('code missing');
}
const tokenRequest = {
client_id: botClientID,
client_secret: botClientSecret,
grant_type: 'authorization_code',
redirect_uri: apiPublicURI + '/login-callback',
scope: 'identify guilds',
code,
};
const tokenFetch = await fetch('https://discord.com/api/v8/oauth2/token', {
method: 'POST',
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
body: formData(tokenRequest),
});
const tokens = (await tokenFetch.json()) as AuthTokenResponse;
if (!tokens.access_token) {
console.info({ tokens });
return AuthErrorResponse('token response invalid');
}
const [sessionID, user, guilds] = await Promise.all([
KSUID.random(),
getUser(tokens.access_token),
getGuilds(tokens.access_token),
]);
const sessionData: SessionData = {
tokens,
sessionID: sessionID.string,
user,
guilds,
};
await Sessions.put(sessionID.string, sessionData, 60 * 60 * 6);
return Bounce(
uiPublicURI + '/machinery/new-session?session_id=' + sessionID.string
);
}
);
const discordFetch = async <T>(url: string, auth: string): Promise<T> => {
const response = await fetch('https://discord.com/api/v8' + url, {
headers: {
authorization: 'Bearer ' + auth,
},
});
return (await response.json()) as T;
};
const getUser = async (accessToken: string): Promise<DiscordUser> => {
const { id, username, discriminator, bot, avatar } = await discordFetch<DiscordUser>(
'/users/@me',
accessToken
);
return { id, username, discriminator, bot, avatar };
};
type UserGuildsPayload = {
id: string;
name: string;
icon: string;
owner: boolean;
permissions: number;
features: string[];
}[];
const getGuilds = async (accessToken: string) => {
const guilds = await discordFetch<UserGuildsPayload>(
'/users/@me/guilds',
accessToken
);
const guildSlugs = guilds.map<GuildSlug>((guild) => ({
id: guild.id,
name: guild.name,
icon: guild.icon,
permissionLevel: parsePermissions(guild.permissions, guild.owner),
}));
return guildSlugs;
};

View file

@ -0,0 +1,16 @@
import { BotJoin } from './handlers/bot-join';
import { GetSession } from './handlers/get-session';
import { LoginBounce } from './handlers/login-bounce';
import { LoginCallback } from './handlers/login-callback';
import { Router } from './router';
const router = new Router();
router.add('GET', 'bot-join', BotJoin);
router.add('GET', 'login-bounce', LoginBounce);
router.add('GET', 'login-callback', LoginCallback);
router.add('GET', 'get-session', GetSession);
addEventListener('fetch', (event: FetchEvent) => {
event.respondWith(router.handle(event.request));
});

View file

@ -0,0 +1,73 @@
export type Handler = (request: Request) => Promise<Response> | Response;
type RoutingTree = {
[method: string]: {
[path: string]: Handler;
};
};
type Fallbacks = {
root: Handler;
404: Handler;
500: Handler;
};
export class Router {
private routingTree: RoutingTree = {};
private fallbacks: Fallbacks = {
root: this.respondToRoot,
404: this.notFound,
500: this.serverError,
};
addFallback(which: keyof Fallbacks, handler: Handler) {
this.fallbacks[which] = handler;
}
add(method: string, rootPath: string, handler: Handler) {
const lowerMethod = method.toLowerCase();
if (!this.routingTree[lowerMethod]) {
this.routingTree[lowerMethod] = {};
}
this.routingTree[lowerMethod][rootPath] = handler;
}
handle(request: Request): Promise<Response> | Response {
if (request.url === '/') {
return this.fallbacks.root(request);
}
const lowerMethod = request.method.toLowerCase();
const url = new URL(request.url);
const rootPath = url.pathname.split('/')[1];
const handler = this.routingTree[lowerMethod]?.[rootPath];
if (handler) {
try {
return handler(request);
} catch (e) {
console.error(e);
return this.fallbacks[500](request);
}
}
return this.fallbacks[404](request);
}
private respondToRoot(): Response {
return new Response('Hi there!');
}
private notFound(): Response {
return new Response(JSON.stringify({ error: 'not_found' }), {
status: 404,
});
}
private serverError(): Response {
return new Response(JSON.stringify({ error: 'internal_server_error' }), {
status: 500,
});
}
}

View file

@ -0,0 +1,14 @@
{
"compilerOptions": {
"outDir": "./dist",
"lib": ["esnext", "webworker"],
"types": ["@cloudflare/workers-types"]
},
"include": [
"./*.ts",
"./**/*.ts",
"../../node_modules/@cloudflare/workers-types/index.d.ts"
],
"exclude": ["./**/*.spec.ts"],
"extends": "../../tsconfig.json"
}

View file

@ -0,0 +1,55 @@
import { UserGuildPermissions } from '../../common/types';
import {
evaluatePermission,
permissions as Permissions,
} from '../../common/utils/hasPermission';
export const formData = (obj: Record<string, any>): string => {
return Object.keys(obj)
.map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
.join('&');
};
export const respond = (obj: Record<string, any>, init?: ResponseInit) =>
new Response(JSON.stringify(obj), init);
export const resolveFailures = (
handleWith: Response,
handler: (request: Request) => Promise<Response> | Response
) => async (request: Request): Promise<Response> | Response => {
try {
return handler(request);
} catch (e) {
console.error(e);
return handleWith;
}
};
export const parsePermissions = (
permissions: number,
owner: boolean = false
): UserGuildPermissions => {
if (owner || evaluatePermission(permissions, Permissions.ADMINISTRATOR)) {
return UserGuildPermissions.Admin;
}
if (evaluatePermission(permissions, Permissions.MANAGE_ROLES)) {
return UserGuildPermissions.Manager;
}
return UserGuildPermissions.User;
};
export const getSessionID = (request: Request): { type: string; id: string } | null => {
const sessionID = request.headers.get('authorization');
if (!sessionID) {
return null;
}
const [type, id] = sessionID.split(' ');
if (type !== 'Bearer') {
return null;
}
return { type, id };
};

View file

@ -0,0 +1,7 @@
export const Bounce = (url: string): Response =>
new Response(null, {
status: 303,
headers: {
location: url,
},
});

View file

@ -0,0 +1,11 @@
const self = (global as any) as Record<string, string>;
const safeURI = (x: string) => x.replace(/\/$/, '');
const list = (x: string) => x.split(',');
export const botClientID = self.BOT_CLIENT_ID;
export const botClientSecret = self.BOT_CLIENT_SECRET;
export const uiPublicURI = safeURI(self.UI_PUBLIC_URI);
export const apiPublicURI = safeURI(self.API_PUBLIC_URI);
export const rootUsers = list(self.ROOT_USERS);
export const kvPrefix = self.KV_PREFIX;

View file

@ -0,0 +1,26 @@
class WrappedKVNamespace {
constructor(private kvNamespace: KVNamespace) {}
async get<T>(key: string): Promise<T | null> {
const data = await this.kvNamespace.get(key, 'text');
if (!data) {
return null;
}
return JSON.parse(data) as T;
}
async put<T>(key: string, value: T, ttlSeconds?: number) {
await this.kvNamespace.put(key, JSON.stringify(value), {
expirationTtl: ttlSeconds,
});
}
list = this.kvNamespace.list;
getWithMetadata = this.kvNamespace.getWithMetadata;
delete = this.kvNamespace.delete;
}
export const Sessions = new WrappedKVNamespace(KV_SESSIONS);
export const GuildData = new WrappedKVNamespace(KV_GUILD_DATA);
export const Guilds = new WrappedKVNamespace(KV_GUILDS);

View file

@ -0,0 +1,29 @@
const path = require('path');
const mode = process.env.NODE_ENV || 'production';
module.exports = {
target: 'webworker',
entry: path.join(__dirname, 'index.ts'),
output: {
filename: `worker.${mode}.js`,
path: path.join(__dirname, 'dist'),
},
mode,
resolve: {
extensions: ['.ts', '.tsx', '.js'],
plugins: [],
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
options: {
transpileOnly: true,
configFile: path.join(__dirname, 'tsconfig.json'),
},
},
],
},
};

View file

@ -1,21 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
go_library(
name = "common",
srcs = [
"await-exit.go",
"envconfig.go",
"finders.go",
],
importpath = "github.com/roleypoly/roleypoly/src/common",
visibility = ["//visibility:public"],
)
go_test(
name = "common_test",
srcs = [
"envconfig_test.go",
"finders_test.go",
],
embed = [":common"],
)

View file

@ -1,18 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "bot",
srcs = [
"commandmux.go",
"scaffolding.go",
],
importpath = "github.com/roleypoly/roleypoly/src/common/bot",
visibility = ["//visibility:public"],
deps = [
"//src/common",
"@com_github_bwmarrin_discordgo//:discordgo",
"@com_github_dghubble_trie//:trie",
"@com_github_lampjaw_discordclient//:discordclient",
"@io_k8s_klog//:klog",
],
)

View file

@ -9,6 +9,7 @@ import (
// GetenvValue is a holder type for Getenv to translate any Getenv strings to real types
type GetenvValue struct {
key string
value string
}
@ -25,6 +26,7 @@ func Getenv(key string, defaultValue ...string) GetenvValue {
return GetenvValue{
value: strings.TrimSpace(value),
key: key,
}
}
@ -41,6 +43,15 @@ func (g GetenvValue) StringSlice(optionalDelimiter ...string) []string {
return strings.Split(g.value, delimiter)
}
// SafeURL removes any trailing slash
func (g GetenvValue) SafeURL() string {
if g.value[len(g.value)-1] == '/' {
return g.value[:len(g.value)-1]
}
return g.value
}
func (g GetenvValue) Bool() bool {
lowercaseValue := strings.ToLower(g.value)
if g.value == "1" || lowercaseValue == "true" || lowercaseValue == "yes" {
@ -63,3 +74,11 @@ func (g GetenvValue) Number() int {
func (g GetenvValue) JSON(target interface{}) error {
return json.Unmarshal([]byte(g.value), target)
}
func (g GetenvValue) OrFatal() GetenvValue {
if g.value == "" {
panic("Getenv value was empty and shouldn't be. key: " + g.key)
}
return g
}

View file

@ -2,8 +2,10 @@ package common_test
import (
"os"
"strings"
"testing"
"github.com/onsi/gomega"
"github.com/roleypoly/roleypoly/src/common"
)
@ -13,6 +15,8 @@ var (
"slice": "hello,world",
"slice_no_delim": "hello world",
"slice_set_delim": "hello|world",
"url": "https://google.com",
"url_trailing": "https://google.com/",
"number": "10005",
"number_bad": "abc123",
"bool": "true",
@ -60,6 +64,19 @@ func TestEnvconfigStringSliceSetDelimeter(t *testing.T) {
}
}
func TestEnvconfigSafeURL(t *testing.T) {
testUrl := common.Getenv("test__url").SafeURL()
if strings.HasSuffix(testUrl, "/") {
t.FailNow()
}
}
func TestEnvconfigSafeURLWithTrailing(t *testing.T) {
testUrl := common.Getenv("test__url_trailing").SafeURL()
if strings.HasSuffix(testUrl, "/") {
t.FailNow()
}
}
func TestEnvconfigNumber(t *testing.T) {
testNum := common.Getenv("test__number").Number()
if testNum != 10005 {
@ -121,3 +138,17 @@ func TestEnvconfigJSON(t *testing.T) {
t.FailNow()
}
}
func TestEnvconfigFatal(t *testing.T) {
O := gomega.NewWithT(t)
O.Expect(func() {
_ = common.Getenv("test__thing_that_doesnt_exist").OrFatal().String()
}).Should(gomega.Panic(), "Getenv without a value should panic")
}
func TestEnvconfigNotFatal(t *testing.T) {
O := gomega.NewWithT(t)
O.Expect(func() {
_ = common.Getenv("test__string").OrFatal().String()
}).ShouldNot(gomega.Panic(), "Getenv with a value should not panic")
}

View file

@ -34,3 +34,16 @@ export type PresentableGuild = {
export type GuildEnumeration = {
guildsList: PresentableGuild[];
};
export enum UserGuildPermissions {
User,
Manager,
Admin,
}
export type GuildSlug = {
id: string;
name: string;
icon: string;
permissionLevel: UserGuildPermissions;
};

View file

@ -0,0 +1,18 @@
import { GuildSlug } from './Guild';
import { DiscordUser } from './User';
export type AuthTokenResponse = {
access_token: string;
token_type: 'Bearer';
expires_in: number;
refresh_token: string;
scope: string;
};
export type SessionData = {
/** sessionID is a KSUID */
sessionID: string;
tokens: AuthTokenResponse;
user: DiscordUser;
guilds: GuildSlug[];
};

20
src/common/types/User.go Normal file
View file

@ -0,0 +1,20 @@
package types
type DiscordUser struct {
ID string `json:"id,omitempty"`
Username string `json:"username,omitempty"`
Discriminator string `json:"discriminator,omitempty"`
Avatar string `json:"avatar,omitempty"`
Bot bool `json:"bot,omitempty"`
}
type Member struct {
GuildID string `json:"guildid,omitempty"`
Roles []string `json:"rolesList,omitempty"`
Nick string `json:"nick,omitempty"`
User DiscordUser `json:"user,omitempty"`
}
type RoleypolyUser struct {
DiscordUser DiscordUser `json:"discorduser,omitempty"`
}

View file

@ -2,3 +2,4 @@ export * from './Role';
export * from './Category';
export * from './Guild';
export * from './User';
export * from './Session';

View file

@ -0,0 +1,31 @@
package types
import "time"
// CreateSessionRequest is the payload to /create-session
type CreateSessionRequest struct {
AccessTokenResponse AccessTokenResponse
Fingerprint Fingerprint
}
type Fingerprint struct {
UserAgent string
ClientIP string
ForwardedFor string
}
type CreateSessionResponse struct {
SessionID string
}
type SessionData struct {
SessionID string
Fingerprint Fingerprint
AccessTokens AccessTokenResponse
UserData UserData
}
type UserData struct {
DataExpires time.Time
UserID string
}

View file

@ -0,0 +1,10 @@
package types
// AccessTokenResponse is the response for Discord's OAuth token grant flow
type AccessTokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
Scope string `json:"scope"`
}

View file

@ -1,21 +0,0 @@
load("//hack/bazel/js:react.bzl", "react_library")
load("//hack/bazel/js:jest.bzl", "jest_test")
package(default_visibility = ["//visibility:public"])
react_library(
name = "utils",
deps = [
"chroma-js",
"//src/rpc/shared",
"@types/chroma-js",
],
)
jest_test(
src = ":utils",
deps = [
"//src/design-system/shared-types",
"//src/rpc/shared",
],
)

View file

@ -1,8 +1,8 @@
import { hasPermission, permissions, hasPermissionOrAdmin } from './hasPermission';
import { Role } from 'roleypoly/src/rpc/shared';
import { guildRoles } from 'roleypoly/src/design-system/shared-types/storyData';
import { Role } from 'roleypoly/common/types';
import { guildRoles } from 'roleypoly/common/types/storyData';
const roles: Role.AsObject[] = [
const roles: Role[] = [
{
...guildRoles.rolesList[0],
permissions: permissions.ADMINISTRATOR,

View file

@ -1,14 +1,16 @@
import { Role } from 'roleypoly/src/rpc/shared';
import { Role } from '../types';
export const hasPermission = (roles: Role.AsObject[], permission: number): boolean => {
const aggregateRoles = roles.reduce((acc, role) => acc | role.permissions, 0);
return (aggregateRoles & permission) === permission;
export const evaluatePermission = (haystack: number, needle: number): boolean => {
return (haystack & needle) === needle;
};
export const hasPermissionOrAdmin = (
roles: Role.AsObject[],
permission: number
): boolean => hasPermission(roles, permission | permissions.ADMINISTRATOR);
export const hasPermission = (roles: Role[], permission: number): boolean => {
const aggregateRoles = roles.reduce((acc, role) => acc | role.permissions, 0);
return evaluatePermission(aggregateRoles, permission);
};
export const hasPermissionOrAdmin = (roles: Role[], permission: number): boolean =>
hasPermission(roles, permission | permissions.ADMINISTRATOR);
export const permissions = {
CREATE_INSTANT_INVITE: 0x1,

View file

@ -0,0 +1 @@
export const isBrowser = () => typeof window !== 'undefined';

View file

@ -1,9 +0,0 @@
import { DiscordUser } from 'roleypoly/src/rpc/shared';
import { user } from 'roleypoly/src/design-system/shared-types/storyData';
import { AsObjectToProto } from './protoReflection';
it('converts a RoleypolyUser.AsObject back to protobuf', () => {
const proto = AsObjectToProto(DiscordUser, user);
expect(proto.toObject()).toMatchObject(user);
});

View file

@ -1,47 +0,0 @@
import * as pbjs from 'google-protobuf';
// Protobuf Message itself
type GenericObject<T extends pbjs.Message> = T;
// Message's "setter" call
type ProtoFunction<T extends pbjs.Message, U extends ReturnType<T['toObject']>> = (
value: U[keyof U]
) => void;
/**
* AsObjectToProto does the opposite of ProtoMessage.toObject().
* This function turns regular JS objects back into their source protobuf message type,
* with the help us copious amounts of reflection.
* @param protoClass A protobuf message class
* @param input A JS object that corresponds to the protobuf message class.
*/
export const AsObjectToProto = <T extends pbjs.Message>(
protoClass: { new (): T },
input: ReturnType<T['toObject']>
): GenericObject<T> => {
// First, we create the message itself
const proto = new protoClass();
// We want the keys from the message, this will give us the setter names we need.
const protoKeys = Object.getOwnPropertyNames((proto as any).__proto__);
// Loop over the input data keys
for (let inputKey in input) {
// As we loop, find the setter function for the key
const setCallName = protoKeys.find(
(key) => `set${inputKey.toLowerCase()}` === key.toLowerCase()
) as keyof typeof proto;
// If we encounter a key without a place to go, we silently ignore it.
if (!setCallName) {
continue;
}
// But, if it all succeeds, we call the setter with the JS object's value.
((proto[setCallName] as unknown) as ProtoFunction<T, typeof input>)(
input[inputKey]
);
}
return proto;
};

View file

@ -1,7 +0,0 @@
load("//hack/bazel/js:react.bzl", "react_library")
package(default_visibility = ["//visibility:public"])
react_library(
name = "withContext",
)

View file

@ -1,19 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
go_library(
name = "version",
srcs = ["version.go"],
importpath = "github.com/roleypoly/roleypoly/src/common/version",
visibility = ["//visibility:public"],
x_defs = {
"GitCommit": "{STABLE_GIT_COMMIT}",
"GitBranch": "{STABLE_GIT_BRANCH}",
"BuildDate": "{BUILD_DATE}",
},
)
go_test(
name = "version_test",
srcs = ["version_test.go"],
embed = [":version"],
)

1
src/db/.gitignore vendored
View file

@ -1 +0,0 @@
.env

View file

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2019 roleypoly maintainers
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -1,17 +0,0 @@
# DB
Roleypoly's DB schemas, connectors, and other useful database admin tools.
## Tools
### ent
ent schema and the files it generates.
Edit nothing outside of the `schemas` folder, as all others are generated.
When done editing, do `go generate ./ent` to update generation.
_Failing to generate files will make CI fail._
All schemas must be backwards compatible with previous versions of this library, and be compatible with **CockroachDB**-based Postgres.

View file

@ -1,45 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "ent",
srcs = [
"challenge.go",
"challenge_create.go",
"challenge_delete.go",
"challenge_query.go",
"challenge_update.go",
"client.go",
"config.go",
"context.go",
"ent.go",
"generate.go",
"guild.go",
"guild_create.go",
"guild_delete.go",
"guild_query.go",
"guild_update.go",
"mutation.go",
"runtime.go",
"session.go",
"session_create.go",
"session_delete.go",
"session_query.go",
"session_update.go",
"tx.go",
],
importpath = "github.com/roleypoly/roleypoly/src/db/ent",
visibility = ["//visibility:public"],
deps = [
"//src/db/ent/challenge",
"//src/db/ent/guild",
"//src/db/ent/migrate",
"//src/db/ent/predicate",
"//src/db/ent/schema",
"//src/db/ent/session",
"@com_github_facebook_ent//:ent",
"@com_github_facebook_ent//dialect",
"@com_github_facebook_ent//dialect/sql",
"@com_github_facebook_ent//dialect/sql/sqlgraph",
"@com_github_facebook_ent//schema/field",
],
)

View file

@ -1,147 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"time"
"github.com/facebook/ent/dialect/sql"
"github.com/roleypoly/roleypoly/src/db/ent/challenge"
)
// Challenge is the model entity for the Challenge schema.
type Challenge struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// CreateTime holds the value of the "create_time" field.
CreateTime time.Time `json:"create_time,omitempty"`
// UpdateTime holds the value of the "update_time" field.
UpdateTime time.Time `json:"update_time,omitempty"`
// ChallengeID holds the value of the "challenge_id" field.
ChallengeID string `json:"challenge_id,omitempty"`
// UserID holds the value of the "user_id" field.
UserID string `json:"user_id,omitempty"`
// Human holds the value of the "human" field.
Human string `json:"human,omitempty"`
// Magic holds the value of the "magic" field.
Magic string `json:"magic,omitempty"`
// ExpiresAt holds the value of the "expires_at" field.
ExpiresAt time.Time `json:"expires_at,omitempty"`
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Challenge) scanValues() []interface{} {
return []interface{}{
&sql.NullInt64{}, // id
&sql.NullTime{}, // create_time
&sql.NullTime{}, // update_time
&sql.NullString{}, // challenge_id
&sql.NullString{}, // user_id
&sql.NullString{}, // human
&sql.NullString{}, // magic
&sql.NullTime{}, // expires_at
}
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Challenge fields.
func (c *Challenge) assignValues(values ...interface{}) error {
if m, n := len(values), len(challenge.Columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
value, ok := values[0].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
c.ID = int(value.Int64)
values = values[1:]
if value, ok := values[0].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field create_time", values[0])
} else if value.Valid {
c.CreateTime = value.Time
}
if value, ok := values[1].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field update_time", values[1])
} else if value.Valid {
c.UpdateTime = value.Time
}
if value, ok := values[2].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field challenge_id", values[2])
} else if value.Valid {
c.ChallengeID = value.String
}
if value, ok := values[3].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field user_id", values[3])
} else if value.Valid {
c.UserID = value.String
}
if value, ok := values[4].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field human", values[4])
} else if value.Valid {
c.Human = value.String
}
if value, ok := values[5].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field magic", values[5])
} else if value.Valid {
c.Magic = value.String
}
if value, ok := values[6].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field expires_at", values[6])
} else if value.Valid {
c.ExpiresAt = value.Time
}
return nil
}
// Update returns a builder for updating this Challenge.
// Note that, you need to call Challenge.Unwrap() before calling this method, if this Challenge
// was returned from a transaction, and the transaction was committed or rolled back.
func (c *Challenge) Update() *ChallengeUpdateOne {
return (&ChallengeClient{config: c.config}).UpdateOne(c)
}
// Unwrap unwraps the entity that was returned from a transaction after it was closed,
// so that all next queries will be executed through the driver which created the transaction.
func (c *Challenge) Unwrap() *Challenge {
tx, ok := c.config.driver.(*txDriver)
if !ok {
panic("ent: Challenge is not a transactional entity")
}
c.config.driver = tx.drv
return c
}
// String implements the fmt.Stringer.
func (c *Challenge) String() string {
var builder strings.Builder
builder.WriteString("Challenge(")
builder.WriteString(fmt.Sprintf("id=%v", c.ID))
builder.WriteString(", create_time=")
builder.WriteString(c.CreateTime.Format(time.ANSIC))
builder.WriteString(", update_time=")
builder.WriteString(c.UpdateTime.Format(time.ANSIC))
builder.WriteString(", challenge_id=")
builder.WriteString(c.ChallengeID)
builder.WriteString(", user_id=")
builder.WriteString(c.UserID)
builder.WriteString(", human=")
builder.WriteString(c.Human)
builder.WriteString(", magic=")
builder.WriteString(c.Magic)
builder.WriteString(", expires_at=")
builder.WriteString(c.ExpiresAt.Format(time.ANSIC))
builder.WriteByte(')')
return builder.String()
}
// Challenges is a parsable slice of Challenge.
type Challenges []*Challenge
func (c Challenges) config(cfg config) {
for _i := range c {
c[_i].config = cfg
}
}

View file

@ -1,15 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "challenge",
srcs = [
"challenge.go",
"where.go",
],
importpath = "github.com/roleypoly/roleypoly/src/db/ent/challenge",
visibility = ["//visibility:public"],
deps = [
"//src/db/ent/predicate",
"@com_github_facebook_ent//dialect/sql",
],
)

View file

@ -1,64 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package challenge
import (
"time"
)
const (
// Label holds the string label denoting the challenge type in the database.
Label = "challenge"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldCreateTime holds the string denoting the create_time field in the database.
FieldCreateTime = "create_time"
// FieldUpdateTime holds the string denoting the update_time field in the database.
FieldUpdateTime = "update_time"
// FieldChallengeID holds the string denoting the challenge_id field in the database.
FieldChallengeID = "challenge_id"
// FieldUserID holds the string denoting the user_id field in the database.
FieldUserID = "user_id"
// FieldHuman holds the string denoting the human field in the database.
FieldHuman = "human"
// FieldMagic holds the string denoting the magic field in the database.
FieldMagic = "magic"
// FieldExpiresAt holds the string denoting the expires_at field in the database.
FieldExpiresAt = "expires_at"
// Table holds the table name of the challenge in the database.
Table = "challenges"
)
// Columns holds all SQL columns for challenge fields.
var Columns = []string{
FieldID,
FieldCreateTime,
FieldUpdateTime,
FieldChallengeID,
FieldUserID,
FieldHuman,
FieldMagic,
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
// DefaultUpdateTime holds the default value on creation for the update_time field.
DefaultUpdateTime func() time.Time
// UpdateDefaultUpdateTime holds the default value on update for the update_time field.
UpdateDefaultUpdateTime func() time.Time
// DefaultExpiresAt holds the default value on creation for the expires_at field.
DefaultExpiresAt func() time.Time
)

View file

@ -1,846 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package challenge
import (
"time"
"github.com/facebook/ent/dialect/sql"
"github.com/roleypoly/roleypoly/src/db/ent/predicate"
)
// ID filters vertices based on their identifier.
func ID(id int) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldID), id))
})
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.In(s.C(FieldID), v...))
})
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.NotIn(s.C(FieldID), v...))
})
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldID), id))
})
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldID), id))
})
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldID), id))
})
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldID), id))
})
}
// CreateTime applies equality check predicate on the "create_time" field. It's identical to CreateTimeEQ.
func CreateTime(v time.Time) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldCreateTime), v))
})
}
// UpdateTime applies equality check predicate on the "update_time" field. It's identical to UpdateTimeEQ.
func UpdateTime(v time.Time) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdateTime), v))
})
}
// ChallengeID applies equality check predicate on the "challenge_id" field. It's identical to ChallengeIDEQ.
func ChallengeID(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldChallengeID), v))
})
}
// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
func UserID(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUserID), v))
})
}
// Human applies equality check predicate on the "human" field. It's identical to HumanEQ.
func Human(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldHuman), v))
})
}
// Magic applies equality check predicate on the "magic" field. It's identical to MagicEQ.
func Magic(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldMagic), v))
})
}
// ExpiresAt applies equality check predicate on the "expires_at" field. It's identical to ExpiresAtEQ.
func ExpiresAt(v time.Time) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldExpiresAt), v))
})
}
// CreateTimeEQ applies the EQ predicate on the "create_time" field.
func CreateTimeEQ(v time.Time) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldCreateTime), v))
})
}
// CreateTimeNEQ applies the NEQ predicate on the "create_time" field.
func CreateTimeNEQ(v time.Time) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldCreateTime), v))
})
}
// CreateTimeIn applies the In predicate on the "create_time" field.
func CreateTimeIn(vs ...time.Time) predicate.Challenge {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Challenge(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldCreateTime), v...))
})
}
// CreateTimeNotIn applies the NotIn predicate on the "create_time" field.
func CreateTimeNotIn(vs ...time.Time) predicate.Challenge {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Challenge(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldCreateTime), v...))
})
}
// CreateTimeGT applies the GT predicate on the "create_time" field.
func CreateTimeGT(v time.Time) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldCreateTime), v))
})
}
// CreateTimeGTE applies the GTE predicate on the "create_time" field.
func CreateTimeGTE(v time.Time) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldCreateTime), v))
})
}
// CreateTimeLT applies the LT predicate on the "create_time" field.
func CreateTimeLT(v time.Time) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldCreateTime), v))
})
}
// CreateTimeLTE applies the LTE predicate on the "create_time" field.
func CreateTimeLTE(v time.Time) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldCreateTime), v))
})
}
// UpdateTimeEQ applies the EQ predicate on the "update_time" field.
func UpdateTimeEQ(v time.Time) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdateTime), v))
})
}
// UpdateTimeNEQ applies the NEQ predicate on the "update_time" field.
func UpdateTimeNEQ(v time.Time) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldUpdateTime), v))
})
}
// UpdateTimeIn applies the In predicate on the "update_time" field.
func UpdateTimeIn(vs ...time.Time) predicate.Challenge {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Challenge(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldUpdateTime), v...))
})
}
// UpdateTimeNotIn applies the NotIn predicate on the "update_time" field.
func UpdateTimeNotIn(vs ...time.Time) predicate.Challenge {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Challenge(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldUpdateTime), v...))
})
}
// UpdateTimeGT applies the GT predicate on the "update_time" field.
func UpdateTimeGT(v time.Time) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldUpdateTime), v))
})
}
// UpdateTimeGTE applies the GTE predicate on the "update_time" field.
func UpdateTimeGTE(v time.Time) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldUpdateTime), v))
})
}
// UpdateTimeLT applies the LT predicate on the "update_time" field.
func UpdateTimeLT(v time.Time) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldUpdateTime), v))
})
}
// UpdateTimeLTE applies the LTE predicate on the "update_time" field.
func UpdateTimeLTE(v time.Time) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUpdateTime), v))
})
}
// ChallengeIDEQ applies the EQ predicate on the "challenge_id" field.
func ChallengeIDEQ(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldChallengeID), v))
})
}
// ChallengeIDNEQ applies the NEQ predicate on the "challenge_id" field.
func ChallengeIDNEQ(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldChallengeID), v))
})
}
// ChallengeIDIn applies the In predicate on the "challenge_id" field.
func ChallengeIDIn(vs ...string) predicate.Challenge {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Challenge(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldChallengeID), v...))
})
}
// ChallengeIDNotIn applies the NotIn predicate on the "challenge_id" field.
func ChallengeIDNotIn(vs ...string) predicate.Challenge {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Challenge(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldChallengeID), v...))
})
}
// ChallengeIDGT applies the GT predicate on the "challenge_id" field.
func ChallengeIDGT(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldChallengeID), v))
})
}
// ChallengeIDGTE applies the GTE predicate on the "challenge_id" field.
func ChallengeIDGTE(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldChallengeID), v))
})
}
// ChallengeIDLT applies the LT predicate on the "challenge_id" field.
func ChallengeIDLT(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldChallengeID), v))
})
}
// ChallengeIDLTE applies the LTE predicate on the "challenge_id" field.
func ChallengeIDLTE(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldChallengeID), v))
})
}
// ChallengeIDContains applies the Contains predicate on the "challenge_id" field.
func ChallengeIDContains(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldChallengeID), v))
})
}
// ChallengeIDHasPrefix applies the HasPrefix predicate on the "challenge_id" field.
func ChallengeIDHasPrefix(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldChallengeID), v))
})
}
// ChallengeIDHasSuffix applies the HasSuffix predicate on the "challenge_id" field.
func ChallengeIDHasSuffix(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldChallengeID), v))
})
}
// ChallengeIDEqualFold applies the EqualFold predicate on the "challenge_id" field.
func ChallengeIDEqualFold(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldChallengeID), v))
})
}
// ChallengeIDContainsFold applies the ContainsFold predicate on the "challenge_id" field.
func ChallengeIDContainsFold(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldChallengeID), v))
})
}
// UserIDEQ applies the EQ predicate on the "user_id" field.
func UserIDEQ(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUserID), v))
})
}
// UserIDNEQ applies the NEQ predicate on the "user_id" field.
func UserIDNEQ(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldUserID), v))
})
}
// UserIDIn applies the In predicate on the "user_id" field.
func UserIDIn(vs ...string) predicate.Challenge {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Challenge(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldUserID), v...))
})
}
// UserIDNotIn applies the NotIn predicate on the "user_id" field.
func UserIDNotIn(vs ...string) predicate.Challenge {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Challenge(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldUserID), v...))
})
}
// UserIDGT applies the GT predicate on the "user_id" field.
func UserIDGT(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldUserID), v))
})
}
// UserIDGTE applies the GTE predicate on the "user_id" field.
func UserIDGTE(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldUserID), v))
})
}
// UserIDLT applies the LT predicate on the "user_id" field.
func UserIDLT(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldUserID), v))
})
}
// UserIDLTE applies the LTE predicate on the "user_id" field.
func UserIDLTE(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUserID), v))
})
}
// UserIDContains applies the Contains predicate on the "user_id" field.
func UserIDContains(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldUserID), v))
})
}
// UserIDHasPrefix applies the HasPrefix predicate on the "user_id" field.
func UserIDHasPrefix(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldUserID), v))
})
}
// UserIDHasSuffix applies the HasSuffix predicate on the "user_id" field.
func UserIDHasSuffix(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldUserID), v))
})
}
// UserIDEqualFold applies the EqualFold predicate on the "user_id" field.
func UserIDEqualFold(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldUserID), v))
})
}
// UserIDContainsFold applies the ContainsFold predicate on the "user_id" field.
func UserIDContainsFold(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldUserID), v))
})
}
// HumanEQ applies the EQ predicate on the "human" field.
func HumanEQ(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldHuman), v))
})
}
// HumanNEQ applies the NEQ predicate on the "human" field.
func HumanNEQ(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldHuman), v))
})
}
// HumanIn applies the In predicate on the "human" field.
func HumanIn(vs ...string) predicate.Challenge {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Challenge(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldHuman), v...))
})
}
// HumanNotIn applies the NotIn predicate on the "human" field.
func HumanNotIn(vs ...string) predicate.Challenge {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Challenge(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldHuman), v...))
})
}
// HumanGT applies the GT predicate on the "human" field.
func HumanGT(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldHuman), v))
})
}
// HumanGTE applies the GTE predicate on the "human" field.
func HumanGTE(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldHuman), v))
})
}
// HumanLT applies the LT predicate on the "human" field.
func HumanLT(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldHuman), v))
})
}
// HumanLTE applies the LTE predicate on the "human" field.
func HumanLTE(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldHuman), v))
})
}
// HumanContains applies the Contains predicate on the "human" field.
func HumanContains(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldHuman), v))
})
}
// HumanHasPrefix applies the HasPrefix predicate on the "human" field.
func HumanHasPrefix(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldHuman), v))
})
}
// HumanHasSuffix applies the HasSuffix predicate on the "human" field.
func HumanHasSuffix(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldHuman), v))
})
}
// HumanEqualFold applies the EqualFold predicate on the "human" field.
func HumanEqualFold(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldHuman), v))
})
}
// HumanContainsFold applies the ContainsFold predicate on the "human" field.
func HumanContainsFold(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldHuman), v))
})
}
// MagicEQ applies the EQ predicate on the "magic" field.
func MagicEQ(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldMagic), v))
})
}
// MagicNEQ applies the NEQ predicate on the "magic" field.
func MagicNEQ(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldMagic), v))
})
}
// MagicIn applies the In predicate on the "magic" field.
func MagicIn(vs ...string) predicate.Challenge {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Challenge(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldMagic), v...))
})
}
// MagicNotIn applies the NotIn predicate on the "magic" field.
func MagicNotIn(vs ...string) predicate.Challenge {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Challenge(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldMagic), v...))
})
}
// MagicGT applies the GT predicate on the "magic" field.
func MagicGT(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldMagic), v))
})
}
// MagicGTE applies the GTE predicate on the "magic" field.
func MagicGTE(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldMagic), v))
})
}
// MagicLT applies the LT predicate on the "magic" field.
func MagicLT(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldMagic), v))
})
}
// MagicLTE applies the LTE predicate on the "magic" field.
func MagicLTE(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldMagic), v))
})
}
// MagicContains applies the Contains predicate on the "magic" field.
func MagicContains(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldMagic), v))
})
}
// MagicHasPrefix applies the HasPrefix predicate on the "magic" field.
func MagicHasPrefix(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldMagic), v))
})
}
// MagicHasSuffix applies the HasSuffix predicate on the "magic" field.
func MagicHasSuffix(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldMagic), v))
})
}
// MagicEqualFold applies the EqualFold predicate on the "magic" field.
func MagicEqualFold(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldMagic), v))
})
}
// MagicContainsFold applies the ContainsFold predicate on the "magic" field.
func MagicContainsFold(v string) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldMagic), v))
})
}
// ExpiresAtEQ applies the EQ predicate on the "expires_at" field.
func ExpiresAtEQ(v time.Time) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtNEQ applies the NEQ predicate on the "expires_at" field.
func ExpiresAtNEQ(v time.Time) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtIn applies the In predicate on the "expires_at" field.
func ExpiresAtIn(vs ...time.Time) predicate.Challenge {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Challenge(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldExpiresAt), v...))
})
}
// ExpiresAtNotIn applies the NotIn predicate on the "expires_at" field.
func ExpiresAtNotIn(vs ...time.Time) predicate.Challenge {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Challenge(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldExpiresAt), v...))
})
}
// ExpiresAtGT applies the GT predicate on the "expires_at" field.
func ExpiresAtGT(v time.Time) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtGTE applies the GTE predicate on the "expires_at" field.
func ExpiresAtGTE(v time.Time) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtLT applies the LT predicate on the "expires_at" field.
func ExpiresAtLT(v time.Time) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtLTE applies the LTE predicate on the "expires_at" field.
func ExpiresAtLTE(v time.Time) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldExpiresAt), v))
})
}
// And groups list of predicates with the AND operator between them.
func And(predicates ...predicate.Challenge) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for _, p := range predicates {
p(s1)
}
s.Where(s1.P())
})
}
// Or groups list of predicates with the OR operator between them.
func Or(predicates ...predicate.Challenge) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for i, p := range predicates {
if i > 0 {
s1.Or()
}
p(s1)
}
s.Where(s1.P())
})
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Challenge) predicate.Challenge {
return predicate.Challenge(func(s *sql.Selector) {
p(s.Not())
})
}

View file

@ -1,329 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"github.com/facebook/ent/dialect/sql/sqlgraph"
"github.com/facebook/ent/schema/field"
"github.com/roleypoly/roleypoly/src/db/ent/challenge"
)
// ChallengeCreate is the builder for creating a Challenge entity.
type ChallengeCreate struct {
config
mutation *ChallengeMutation
hooks []Hook
}
// SetCreateTime sets the create_time field.
func (cc *ChallengeCreate) SetCreateTime(t time.Time) *ChallengeCreate {
cc.mutation.SetCreateTime(t)
return cc
}
// SetNillableCreateTime sets the create_time field if the given value is not nil.
func (cc *ChallengeCreate) SetNillableCreateTime(t *time.Time) *ChallengeCreate {
if t != nil {
cc.SetCreateTime(*t)
}
return cc
}
// SetUpdateTime sets the update_time field.
func (cc *ChallengeCreate) SetUpdateTime(t time.Time) *ChallengeCreate {
cc.mutation.SetUpdateTime(t)
return cc
}
// SetNillableUpdateTime sets the update_time field if the given value is not nil.
func (cc *ChallengeCreate) SetNillableUpdateTime(t *time.Time) *ChallengeCreate {
if t != nil {
cc.SetUpdateTime(*t)
}
return cc
}
// SetChallengeID sets the challenge_id field.
func (cc *ChallengeCreate) SetChallengeID(s string) *ChallengeCreate {
cc.mutation.SetChallengeID(s)
return cc
}
// SetUserID sets the user_id field.
func (cc *ChallengeCreate) SetUserID(s string) *ChallengeCreate {
cc.mutation.SetUserID(s)
return cc
}
// SetHuman sets the human field.
func (cc *ChallengeCreate) SetHuman(s string) *ChallengeCreate {
cc.mutation.SetHuman(s)
return cc
}
// SetMagic sets the magic field.
func (cc *ChallengeCreate) SetMagic(s string) *ChallengeCreate {
cc.mutation.SetMagic(s)
return cc
}
// SetExpiresAt sets the expires_at field.
func (cc *ChallengeCreate) SetExpiresAt(t time.Time) *ChallengeCreate {
cc.mutation.SetExpiresAt(t)
return cc
}
// SetNillableExpiresAt sets the expires_at field if the given value is not nil.
func (cc *ChallengeCreate) SetNillableExpiresAt(t *time.Time) *ChallengeCreate {
if t != nil {
cc.SetExpiresAt(*t)
}
return cc
}
// Mutation returns the ChallengeMutation object of the builder.
func (cc *ChallengeCreate) Mutation() *ChallengeMutation {
return cc.mutation
}
// Save creates the Challenge in the database.
func (cc *ChallengeCreate) Save(ctx context.Context) (*Challenge, error) {
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) {
mutation, ok := m.(*ChallengeMutation)
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
return node, err
})
for i := len(cc.hooks) - 1; i >= 0; i-- {
mut = cc.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, cc.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (cc *ChallengeCreate) SaveX(ctx context.Context) *Challenge {
v, err := cc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// 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)
}
if _, ok := cc.mutation.UpdateTime(); !ok {
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\"")}
}
if _, ok := cc.mutation.UserID(); !ok {
return &ValidationError{Name: "user_id", err: errors.New("ent: missing required field \"user_id\"")}
}
if _, ok := cc.mutation.Human(); !ok {
return &ValidationError{Name: "human", err: errors.New("ent: missing required field \"human\"")}
}
if _, ok := cc.mutation.Magic(); !ok {
return &ValidationError{Name: "magic", err: errors.New("ent: missing required field \"magic\"")}
}
if _, ok := cc.mutation.ExpiresAt(); !ok {
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) {
_node, _spec := cc.createSpec()
if err := sqlgraph.CreateNode(ctx, cc.driver, _spec); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
return _node, nil
}
func (cc *ChallengeCreate) createSpec() (*Challenge, *sqlgraph.CreateSpec) {
var (
_node = &Challenge{config: cc.config}
_spec = &sqlgraph.CreateSpec{
Table: challenge.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: challenge.FieldID,
},
}
)
if value, ok := cc.mutation.CreateTime(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: challenge.FieldCreateTime,
})
_node.CreateTime = value
}
if value, ok := cc.mutation.UpdateTime(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: challenge.FieldUpdateTime,
})
_node.UpdateTime = value
}
if value, ok := cc.mutation.ChallengeID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: challenge.FieldChallengeID,
})
_node.ChallengeID = value
}
if value, ok := cc.mutation.UserID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: challenge.FieldUserID,
})
_node.UserID = value
}
if value, ok := cc.mutation.Human(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: challenge.FieldHuman,
})
_node.Human = value
}
if value, ok := cc.mutation.Magic(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: challenge.FieldMagic,
})
_node.Magic = value
}
if value, ok := cc.mutation.ExpiresAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: challenge.FieldExpiresAt,
})
_node.ExpiresAt = value
}
return _node, _spec
}
// ChallengeCreateBulk is the builder for creating a bulk of Challenge entities.
type ChallengeCreateBulk struct {
config
builders []*ChallengeCreate
}
// Save creates the Challenge entities in the database.
func (ccb *ChallengeCreateBulk) Save(ctx context.Context) ([]*Challenge, error) {
specs := make([]*sqlgraph.CreateSpec, len(ccb.builders))
nodes := make([]*Challenge, len(ccb.builders))
mutators := make([]Mutator, len(ccb.builders))
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) {
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
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, ccb.builders[i+1].mutation)
} else {
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, ccb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
}
}
mutation.done = true
if err != nil {
return nil, err
}
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, ccb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX calls Save and panics if Save returns an error.
func (ccb *ChallengeCreateBulk) SaveX(ctx context.Context) []*Challenge {
v, err := ccb.Save(ctx)
if err != nil {
panic(err)
}
return v
}

View file

@ -1,109 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"github.com/facebook/ent/dialect/sql"
"github.com/facebook/ent/dialect/sql/sqlgraph"
"github.com/facebook/ent/schema/field"
"github.com/roleypoly/roleypoly/src/db/ent/challenge"
"github.com/roleypoly/roleypoly/src/db/ent/predicate"
)
// ChallengeDelete is the builder for deleting a Challenge entity.
type ChallengeDelete struct {
config
hooks []Hook
mutation *ChallengeMutation
predicates []predicate.Challenge
}
// Where adds a new predicate to the delete builder.
func (cd *ChallengeDelete) Where(ps ...predicate.Challenge) *ChallengeDelete {
cd.predicates = append(cd.predicates, ps...)
return cd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (cd *ChallengeDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(cd.hooks) == 0 {
affected, err = cd.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ChallengeMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
cd.mutation = mutation
affected, err = cd.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(cd.hooks) - 1; i >= 0; i-- {
mut = cd.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, cd.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (cd *ChallengeDelete) ExecX(ctx context.Context) int {
n, err := cd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (cd *ChallengeDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: challenge.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: challenge.FieldID,
},
},
}
if ps := cd.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return sqlgraph.DeleteNodes(ctx, cd.driver, _spec)
}
// ChallengeDeleteOne is the builder for deleting a single Challenge entity.
type ChallengeDeleteOne struct {
cd *ChallengeDelete
}
// Exec executes the deletion query.
func (cdo *ChallengeDeleteOne) Exec(ctx context.Context) error {
n, err := cdo.cd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{challenge.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (cdo *ChallengeDeleteOne) ExecX(ctx context.Context) {
cdo.cd.ExecX(ctx)
}

View file

@ -1,880 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"math"
"github.com/facebook/ent/dialect/sql"
"github.com/facebook/ent/dialect/sql/sqlgraph"
"github.com/facebook/ent/schema/field"
"github.com/roleypoly/roleypoly/src/db/ent/challenge"
"github.com/roleypoly/roleypoly/src/db/ent/predicate"
)
// ChallengeQuery is the builder for querying Challenge entities.
type ChallengeQuery struct {
config
limit *int
offset *int
order []OrderFunc
unique []string
predicates []predicate.Challenge
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the builder.
func (cq *ChallengeQuery) Where(ps ...predicate.Challenge) *ChallengeQuery {
cq.predicates = append(cq.predicates, ps...)
return cq
}
// Limit adds a limit step to the query.
func (cq *ChallengeQuery) Limit(limit int) *ChallengeQuery {
cq.limit = &limit
return cq
}
// Offset adds an offset step to the query.
func (cq *ChallengeQuery) Offset(offset int) *ChallengeQuery {
cq.offset = &offset
return cq
}
// Order adds an order step to the query.
func (cq *ChallengeQuery) Order(o ...OrderFunc) *ChallengeQuery {
cq.order = append(cq.order, o...)
return cq
}
// 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) {
nodes, err := cq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{challenge.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (cq *ChallengeQuery) FirstX(ctx context.Context) *Challenge {
node, err := cq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Challenge id in the query. Returns *NotFoundError when no id was found.
func (cq *ChallengeQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = cq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{challenge.Label}
return
}
return ids[0], nil
}
// FirstXID is like FirstID, but panics if an error occurs.
func (cq *ChallengeQuery) FirstXID(ctx context.Context) int {
id, err := cq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// 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) {
nodes, err := cq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{challenge.Label}
default:
return nil, &NotSingularError{challenge.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (cq *ChallengeQuery) OnlyX(ctx context.Context) *Challenge {
node, err := cq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID returns the only Challenge id in the query, returns an error if not exactly one id was returned.
func (cq *ChallengeQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = cq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{challenge.Label}
default:
err = &NotSingularError{challenge.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (cq *ChallengeQuery) OnlyIDX(ctx context.Context) int {
id, err := cq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Challenges.
func (cq *ChallengeQuery) All(ctx context.Context) ([]*Challenge, error) {
if err := cq.prepareQuery(ctx); err != nil {
return nil, err
}
return cq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (cq *ChallengeQuery) AllX(ctx context.Context) []*Challenge {
nodes, err := cq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Challenge ids.
func (cq *ChallengeQuery) IDs(ctx context.Context) ([]int, error) {
var ids []int
if err := cq.Select(challenge.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (cq *ChallengeQuery) IDsX(ctx context.Context) []int {
ids, err := cq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (cq *ChallengeQuery) Count(ctx context.Context) (int, error) {
if err := cq.prepareQuery(ctx); err != nil {
return 0, err
}
return cq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (cq *ChallengeQuery) CountX(ctx context.Context) int {
count, err := cq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (cq *ChallengeQuery) Exist(ctx context.Context) (bool, error) {
if err := cq.prepareQuery(ctx); err != nil {
return false, err
}
return cq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (cq *ChallengeQuery) ExistX(ctx context.Context) bool {
exist, err := cq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the query builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (cq *ChallengeQuery) Clone() *ChallengeQuery {
return &ChallengeQuery{
config: cq.config,
limit: cq.limit,
offset: cq.offset,
order: append([]OrderFunc{}, cq.order...),
unique: append([]string{}, cq.unique...),
predicates: append([]predicate.Challenge{}, cq.predicates...),
// clone intermediate query.
sql: cq.sql.Clone(),
path: cq.path,
}
}
// GroupBy used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// CreateTime time.Time `json:"create_time,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Challenge.Query().
// GroupBy(challenge.FieldCreateTime).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
//
func (cq *ChallengeQuery) GroupBy(field string, fields ...string) *ChallengeGroupBy {
group := &ChallengeGroupBy{config: cq.config}
group.fields = append([]string{field}, fields...)
group.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := cq.prepareQuery(ctx); err != nil {
return nil, err
}
return cq.sqlQuery(), nil
}
return group
}
// Select one or more fields from the given query.
//
// Example:
//
// var v []struct {
// CreateTime time.Time `json:"create_time,omitempty"`
// }
//
// client.Challenge.Query().
// Select(challenge.FieldCreateTime).
// Scan(ctx, &v)
//
func (cq *ChallengeQuery) Select(field string, fields ...string) *ChallengeSelect {
selector := &ChallengeSelect{config: cq.config}
selector.fields = append([]string{field}, fields...)
selector.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := cq.prepareQuery(ctx); err != nil {
return nil, err
}
return cq.sqlQuery(), nil
}
return selector
}
func (cq *ChallengeQuery) prepareQuery(ctx context.Context) error {
if cq.path != nil {
prev, err := cq.path(ctx)
if err != nil {
return err
}
cq.sql = prev
}
return nil
}
func (cq *ChallengeQuery) sqlAll(ctx context.Context) ([]*Challenge, error) {
var (
nodes = []*Challenge{}
_spec = cq.querySpec()
)
_spec.ScanValues = func() []interface{} {
node := &Challenge{config: cq.config}
nodes = append(nodes, node)
values := node.scanValues()
return values
}
_spec.Assign = func(values ...interface{}) error {
if len(nodes) == 0 {
return fmt.Errorf("ent: Assign called without calling ScanValues")
}
node := nodes[len(nodes)-1]
return node.assignValues(values...)
}
if err := sqlgraph.QueryNodes(ctx, cq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (cq *ChallengeQuery) sqlCount(ctx context.Context) (int, error) {
_spec := cq.querySpec()
return sqlgraph.CountNodes(ctx, cq.driver, _spec)
}
func (cq *ChallengeQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := cq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("ent: check existence: %v", err)
}
return n > 0, nil
}
func (cq *ChallengeQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: challenge.Table,
Columns: challenge.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: challenge.FieldID,
},
},
From: cq.sql,
Unique: true,
}
if ps := cq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := cq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := cq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := cq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector, challenge.ValidColumn)
}
}
}
return _spec
}
func (cq *ChallengeQuery) sqlQuery() *sql.Selector {
builder := sql.Dialect(cq.driver.Dialect())
t1 := builder.Table(challenge.Table)
selector := builder.Select(t1.Columns(challenge.Columns...)...).From(t1)
if cq.sql != nil {
selector = cq.sql
selector.Select(selector.Columns(challenge.Columns...)...)
}
for _, p := range cq.predicates {
p(selector)
}
for _, p := range cq.order {
p(selector, challenge.ValidColumn)
}
if offset := cq.offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := cq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// ChallengeGroupBy is the builder for group-by Challenge entities.
type ChallengeGroupBy struct {
config
fields []string
fns []AggregateFunc
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Aggregate adds the given aggregation functions to the group-by query.
func (cgb *ChallengeGroupBy) Aggregate(fns ...AggregateFunc) *ChallengeGroupBy {
cgb.fns = append(cgb.fns, fns...)
return cgb
}
// Scan applies the group-by query and scan the result into the given value.
func (cgb *ChallengeGroupBy) Scan(ctx context.Context, v interface{}) error {
query, err := cgb.path(ctx)
if err != nil {
return err
}
cgb.sql = query
return cgb.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (cgb *ChallengeGroupBy) ScanX(ctx context.Context, v interface{}) {
if err := cgb.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from group-by. It is only allowed when querying group-by with one field.
func (cgb *ChallengeGroupBy) Strings(ctx context.Context) ([]string, error) {
if len(cgb.fields) > 1 {
return nil, errors.New("ent: ChallengeGroupBy.Strings is not achievable when grouping more than 1 field")
}
var v []string
if err := cgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (cgb *ChallengeGroupBy) StringsX(ctx context.Context) []string {
v, err := cgb.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from group-by. It is only allowed when querying group-by with one field.
func (cgb *ChallengeGroupBy) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = cgb.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{challenge.Label}
default:
err = fmt.Errorf("ent: ChallengeGroupBy.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (cgb *ChallengeGroupBy) StringX(ctx context.Context) string {
v, err := cgb.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from group-by. It is only allowed when querying group-by with one field.
func (cgb *ChallengeGroupBy) Ints(ctx context.Context) ([]int, error) {
if len(cgb.fields) > 1 {
return nil, errors.New("ent: ChallengeGroupBy.Ints is not achievable when grouping more than 1 field")
}
var v []int
if err := cgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (cgb *ChallengeGroupBy) IntsX(ctx context.Context) []int {
v, err := cgb.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from group-by. It is only allowed when querying group-by with one field.
func (cgb *ChallengeGroupBy) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = cgb.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{challenge.Label}
default:
err = fmt.Errorf("ent: ChallengeGroupBy.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (cgb *ChallengeGroupBy) IntX(ctx context.Context) int {
v, err := cgb.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from group-by. It is only allowed when querying group-by with one field.
func (cgb *ChallengeGroupBy) Float64s(ctx context.Context) ([]float64, error) {
if len(cgb.fields) > 1 {
return nil, errors.New("ent: ChallengeGroupBy.Float64s is not achievable when grouping more than 1 field")
}
var v []float64
if err := cgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (cgb *ChallengeGroupBy) Float64sX(ctx context.Context) []float64 {
v, err := cgb.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from group-by. It is only allowed when querying group-by with one field.
func (cgb *ChallengeGroupBy) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = cgb.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{challenge.Label}
default:
err = fmt.Errorf("ent: ChallengeGroupBy.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (cgb *ChallengeGroupBy) Float64X(ctx context.Context) float64 {
v, err := cgb.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from group-by. It is only allowed when querying group-by with one field.
func (cgb *ChallengeGroupBy) Bools(ctx context.Context) ([]bool, error) {
if len(cgb.fields) > 1 {
return nil, errors.New("ent: ChallengeGroupBy.Bools is not achievable when grouping more than 1 field")
}
var v []bool
if err := cgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (cgb *ChallengeGroupBy) BoolsX(ctx context.Context) []bool {
v, err := cgb.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from group-by. It is only allowed when querying group-by with one field.
func (cgb *ChallengeGroupBy) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = cgb.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{challenge.Label}
default:
err = fmt.Errorf("ent: ChallengeGroupBy.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (cgb *ChallengeGroupBy) BoolX(ctx context.Context) bool {
v, err := cgb.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
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 := selector.Query()
if err := cgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (cgb *ChallengeGroupBy) sqlQuery() *sql.Selector {
selector := cgb.sql
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, challenge.ValidColumn))
}
return selector.Select(columns...).GroupBy(cgb.fields...)
}
// ChallengeSelect is the builder for select fields of Challenge entities.
type ChallengeSelect struct {
config
fields []string
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Scan applies the selector query and scan the result into the given value.
func (cs *ChallengeSelect) Scan(ctx context.Context, v interface{}) error {
query, err := cs.path(ctx)
if err != nil {
return err
}
cs.sql = query
return cs.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (cs *ChallengeSelect) ScanX(ctx context.Context, v interface{}) {
if err := cs.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from selector. It is only allowed when selecting one field.
func (cs *ChallengeSelect) Strings(ctx context.Context) ([]string, error) {
if len(cs.fields) > 1 {
return nil, errors.New("ent: ChallengeSelect.Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := cs.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (cs *ChallengeSelect) StringsX(ctx context.Context) []string {
v, err := cs.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from selector. It is only allowed when selecting one field.
func (cs *ChallengeSelect) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = cs.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{challenge.Label}
default:
err = fmt.Errorf("ent: ChallengeSelect.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (cs *ChallengeSelect) StringX(ctx context.Context) string {
v, err := cs.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from selector. It is only allowed when selecting one field.
func (cs *ChallengeSelect) Ints(ctx context.Context) ([]int, error) {
if len(cs.fields) > 1 {
return nil, errors.New("ent: ChallengeSelect.Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := cs.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (cs *ChallengeSelect) IntsX(ctx context.Context) []int {
v, err := cs.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from selector. It is only allowed when selecting one field.
func (cs *ChallengeSelect) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = cs.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{challenge.Label}
default:
err = fmt.Errorf("ent: ChallengeSelect.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (cs *ChallengeSelect) IntX(ctx context.Context) int {
v, err := cs.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from selector. It is only allowed when selecting one field.
func (cs *ChallengeSelect) Float64s(ctx context.Context) ([]float64, error) {
if len(cs.fields) > 1 {
return nil, errors.New("ent: ChallengeSelect.Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := cs.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (cs *ChallengeSelect) Float64sX(ctx context.Context) []float64 {
v, err := cs.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from selector. It is only allowed when selecting one field.
func (cs *ChallengeSelect) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = cs.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{challenge.Label}
default:
err = fmt.Errorf("ent: ChallengeSelect.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (cs *ChallengeSelect) Float64X(ctx context.Context) float64 {
v, err := cs.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from selector. It is only allowed when selecting one field.
func (cs *ChallengeSelect) Bools(ctx context.Context) ([]bool, error) {
if len(cs.fields) > 1 {
return nil, errors.New("ent: ChallengeSelect.Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := cs.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (cs *ChallengeSelect) BoolsX(ctx context.Context) []bool {
v, err := cs.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from selector. It is only allowed when selecting one field.
func (cs *ChallengeSelect) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = cs.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{challenge.Label}
default:
err = fmt.Errorf("ent: ChallengeSelect.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (cs *ChallengeSelect) BoolX(ctx context.Context) bool {
v, err := cs.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
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 {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (cs *ChallengeSelect) sqlQuery() sql.Querier {
selector := cs.sql
selector.Select(selector.Columns(cs.fields...)...)
return selector
}

View file

@ -1,238 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"github.com/facebook/ent/dialect/sql"
"github.com/facebook/ent/dialect/sql/sqlgraph"
"github.com/facebook/ent/schema/field"
"github.com/roleypoly/roleypoly/src/db/ent/challenge"
"github.com/roleypoly/roleypoly/src/db/ent/predicate"
)
// ChallengeUpdate is the builder for updating Challenge entities.
type ChallengeUpdate struct {
config
hooks []Hook
mutation *ChallengeMutation
predicates []predicate.Challenge
}
// Where adds a new predicate for the builder.
func (cu *ChallengeUpdate) Where(ps ...predicate.Challenge) *ChallengeUpdate {
cu.predicates = append(cu.predicates, ps...)
return cu
}
// Mutation returns the ChallengeMutation object of the builder.
func (cu *ChallengeUpdate) Mutation() *ChallengeMutation {
return cu.mutation
}
// Save executes the query and returns the number of rows/vertices matched by this operation.
func (cu *ChallengeUpdate) Save(ctx context.Context) (int, error) {
var (
err error
affected int
)
cu.defaults()
if len(cu.hooks) == 0 {
affected, err = cu.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ChallengeMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
cu.mutation = mutation
affected, err = cu.sqlSave(ctx)
mutation.done = true
return affected, err
})
for i := len(cu.hooks) - 1; i >= 0; i-- {
mut = cu.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, cu.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// SaveX is like Save, but panics if an error occurs.
func (cu *ChallengeUpdate) SaveX(ctx context.Context) int {
affected, err := cu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (cu *ChallengeUpdate) Exec(ctx context.Context) error {
_, err := cu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (cu *ChallengeUpdate) ExecX(ctx context.Context) {
if err := cu.Exec(ctx); err != nil {
panic(err)
}
}
// 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{
Table: challenge.Table,
Columns: challenge.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: challenge.FieldID,
},
},
}
if ps := cu.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := cu.mutation.UpdateTime(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: challenge.FieldUpdateTime,
})
}
if n, err = sqlgraph.UpdateNodes(ctx, cu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{challenge.Label}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return 0, err
}
return n, nil
}
// ChallengeUpdateOne is the builder for updating a single Challenge entity.
type ChallengeUpdateOne struct {
config
hooks []Hook
mutation *ChallengeMutation
}
// Mutation returns the ChallengeMutation object of the builder.
func (cuo *ChallengeUpdateOne) Mutation() *ChallengeMutation {
return cuo.mutation
}
// Save executes the query and returns the updated entity.
func (cuo *ChallengeUpdateOne) Save(ctx context.Context) (*Challenge, error) {
var (
err error
node *Challenge
)
cuo.defaults()
if len(cuo.hooks) == 0 {
node, err = cuo.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ChallengeMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
cuo.mutation = mutation
node, err = cuo.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(cuo.hooks) - 1; i >= 0; i-- {
mut = cuo.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, cuo.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX is like Save, but panics if an error occurs.
func (cuo *ChallengeUpdateOne) SaveX(ctx context.Context) *Challenge {
node, err := cuo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (cuo *ChallengeUpdateOne) Exec(ctx context.Context) error {
_, err := cuo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (cuo *ChallengeUpdateOne) ExecX(ctx context.Context) {
if err := cuo.Exec(ctx); err != nil {
panic(err)
}
}
// 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,
Columns: challenge.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: challenge.FieldID,
},
},
}
id, ok := cuo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing Challenge.ID for update")}
}
_spec.Node.ID.Value = id
if value, ok := cuo.mutation.UpdateTime(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: challenge.FieldUpdateTime,
})
}
_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}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
return _node, nil
}

View file

@ -1,395 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"log"
"github.com/roleypoly/roleypoly/src/db/ent/migrate"
"github.com/roleypoly/roleypoly/src/db/ent/challenge"
"github.com/roleypoly/roleypoly/src/db/ent/guild"
"github.com/roleypoly/roleypoly/src/db/ent/session"
"github.com/facebook/ent/dialect"
"github.com/facebook/ent/dialect/sql"
)
// Client is the client that holds all ent builders.
type Client struct {
config
// Schema is the client for creating, migrating and dropping schema.
Schema *migrate.Schema
// Challenge is the client for interacting with the Challenge builders.
Challenge *ChallengeClient
// Guild is the client for interacting with the Guild builders.
Guild *GuildClient
// Session is the client for interacting with the Session builders.
Session *SessionClient
}
// NewClient creates a new client configured with the given options.
func NewClient(opts ...Option) *Client {
cfg := config{log: log.Println, hooks: &hooks{}}
cfg.options(opts...)
client := &Client{config: cfg}
client.init()
return client
}
func (c *Client) init() {
c.Schema = migrate.NewSchema(c.driver)
c.Challenge = NewChallengeClient(c.config)
c.Guild = NewGuildClient(c.config)
c.Session = NewSessionClient(c.config)
}
// Open opens a database/sql.DB specified by the driver name and
// the data source name, and returns a new client attached to it.
// Optional parameters can be added for configuring the client.
func Open(driverName, dataSourceName string, options ...Option) (*Client, error) {
switch driverName {
case dialect.MySQL, dialect.Postgres, dialect.SQLite:
drv, err := sql.Open(driverName, dataSourceName)
if err != nil {
return nil, err
}
return NewClient(append(options, Driver(drv))...), nil
default:
return nil, fmt.Errorf("unsupported driver: %q", driverName)
}
}
// Tx returns a new transactional client. The provided context
// is used until the transaction is committed or rolled back.
func (c *Client) Tx(ctx context.Context) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, fmt.Errorf("ent: cannot start a transaction within a transaction")
}
tx, err := newTx(ctx, c.driver)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %v", err)
}
cfg := config{driver: tx, log: c.log, debug: c.debug, hooks: c.hooks}
return &Tx{
ctx: ctx,
config: cfg,
Challenge: NewChallengeClient(cfg),
Guild: NewGuildClient(cfg),
Session: NewSessionClient(cfg),
}, nil
}
// BeginTx returns a transactional client with options.
func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, fmt.Errorf("ent: cannot start a transaction within a transaction")
}
tx, err := c.driver.(*sql.Driver).BeginTx(ctx, opts)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %v", err)
}
cfg := config{driver: &txDriver{tx: tx, drv: c.driver}, log: c.log, debug: c.debug, hooks: c.hooks}
return &Tx{
config: cfg,
Challenge: NewChallengeClient(cfg),
Guild: NewGuildClient(cfg),
Session: NewSessionClient(cfg),
}, nil
}
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
//
// client.Debug().
// Challenge.
// Query().
// Count(ctx)
//
func (c *Client) Debug() *Client {
if c.debug {
return c
}
cfg := config{driver: dialect.Debug(c.driver, c.log), log: c.log, debug: true, hooks: c.hooks}
client := &Client{config: cfg}
client.init()
return client
}
// Close closes the database connection and prevents new queries from starting.
func (c *Client) Close() error {
return c.driver.Close()
}
// Use adds the mutation hooks to all the entity clients.
// In order to add hooks to a specific client, call: `client.Node.Use(...)`.
func (c *Client) Use(hooks ...Hook) {
c.Challenge.Use(hooks...)
c.Guild.Use(hooks...)
c.Session.Use(hooks...)
}
// ChallengeClient is a client for the Challenge schema.
type ChallengeClient struct {
config
}
// NewChallengeClient returns a client for the Challenge from the given config.
func NewChallengeClient(c config) *ChallengeClient {
return &ChallengeClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `challenge.Hooks(f(g(h())))`.
func (c *ChallengeClient) Use(hooks ...Hook) {
c.hooks.Challenge = append(c.hooks.Challenge, hooks...)
}
// Create returns a create builder for Challenge.
func (c *ChallengeClient) Create() *ChallengeCreate {
mutation := newChallengeMutation(c.config, OpCreate)
return &ChallengeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// BulkCreate returns a builder for creating a bulk of Challenge entities.
func (c *ChallengeClient) CreateBulk(builders ...*ChallengeCreate) *ChallengeCreateBulk {
return &ChallengeCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Challenge.
func (c *ChallengeClient) Update() *ChallengeUpdate {
mutation := newChallengeMutation(c.config, OpUpdate)
return &ChallengeUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *ChallengeClient) UpdateOne(ch *Challenge) *ChallengeUpdateOne {
mutation := newChallengeMutation(c.config, OpUpdateOne, withChallenge(ch))
return &ChallengeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *ChallengeClient) UpdateOneID(id int) *ChallengeUpdateOne {
mutation := newChallengeMutation(c.config, OpUpdateOne, withChallengeID(id))
return &ChallengeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Challenge.
func (c *ChallengeClient) Delete() *ChallengeDelete {
mutation := newChallengeMutation(c.config, OpDelete)
return &ChallengeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a delete builder for the given entity.
func (c *ChallengeClient) DeleteOne(ch *Challenge) *ChallengeDeleteOne {
return c.DeleteOneID(ch.ID)
}
// DeleteOneID returns a delete builder for the given id.
func (c *ChallengeClient) DeleteOneID(id int) *ChallengeDeleteOne {
builder := c.Delete().Where(challenge.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &ChallengeDeleteOne{builder}
}
// Query returns a query builder for Challenge.
func (c *ChallengeClient) Query() *ChallengeQuery {
return &ChallengeQuery{config: c.config}
}
// Get returns a Challenge entity by its id.
func (c *ChallengeClient) Get(ctx context.Context, id int) (*Challenge, error) {
return c.Query().Where(challenge.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *ChallengeClient) GetX(ctx context.Context, id int) *Challenge {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// Hooks returns the client hooks.
func (c *ChallengeClient) Hooks() []Hook {
return c.hooks.Challenge
}
// GuildClient is a client for the Guild schema.
type GuildClient struct {
config
}
// NewGuildClient returns a client for the Guild from the given config.
func NewGuildClient(c config) *GuildClient {
return &GuildClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `guild.Hooks(f(g(h())))`.
func (c *GuildClient) Use(hooks ...Hook) {
c.hooks.Guild = append(c.hooks.Guild, hooks...)
}
// Create returns a create builder for Guild.
func (c *GuildClient) Create() *GuildCreate {
mutation := newGuildMutation(c.config, OpCreate)
return &GuildCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// BulkCreate returns a builder for creating a bulk of Guild entities.
func (c *GuildClient) CreateBulk(builders ...*GuildCreate) *GuildCreateBulk {
return &GuildCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Guild.
func (c *GuildClient) Update() *GuildUpdate {
mutation := newGuildMutation(c.config, OpUpdate)
return &GuildUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *GuildClient) UpdateOne(gu *Guild) *GuildUpdateOne {
mutation := newGuildMutation(c.config, OpUpdateOne, withGuild(gu))
return &GuildUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *GuildClient) UpdateOneID(id int) *GuildUpdateOne {
mutation := newGuildMutation(c.config, OpUpdateOne, withGuildID(id))
return &GuildUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Guild.
func (c *GuildClient) Delete() *GuildDelete {
mutation := newGuildMutation(c.config, OpDelete)
return &GuildDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a delete builder for the given entity.
func (c *GuildClient) DeleteOne(gu *Guild) *GuildDeleteOne {
return c.DeleteOneID(gu.ID)
}
// DeleteOneID returns a delete builder for the given id.
func (c *GuildClient) DeleteOneID(id int) *GuildDeleteOne {
builder := c.Delete().Where(guild.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &GuildDeleteOne{builder}
}
// Query returns a query builder for Guild.
func (c *GuildClient) Query() *GuildQuery {
return &GuildQuery{config: c.config}
}
// Get returns a Guild entity by its id.
func (c *GuildClient) Get(ctx context.Context, id int) (*Guild, error) {
return c.Query().Where(guild.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *GuildClient) GetX(ctx context.Context, id int) *Guild {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// Hooks returns the client hooks.
func (c *GuildClient) Hooks() []Hook {
return c.hooks.Guild
}
// SessionClient is a client for the Session schema.
type SessionClient struct {
config
}
// NewSessionClient returns a client for the Session from the given config.
func NewSessionClient(c config) *SessionClient {
return &SessionClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `session.Hooks(f(g(h())))`.
func (c *SessionClient) Use(hooks ...Hook) {
c.hooks.Session = append(c.hooks.Session, hooks...)
}
// Create returns a create builder for Session.
func (c *SessionClient) Create() *SessionCreate {
mutation := newSessionMutation(c.config, OpCreate)
return &SessionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// BulkCreate returns a builder for creating a bulk of Session entities.
func (c *SessionClient) CreateBulk(builders ...*SessionCreate) *SessionCreateBulk {
return &SessionCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Session.
func (c *SessionClient) Update() *SessionUpdate {
mutation := newSessionMutation(c.config, OpUpdate)
return &SessionUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *SessionClient) UpdateOne(s *Session) *SessionUpdateOne {
mutation := newSessionMutation(c.config, OpUpdateOne, withSession(s))
return &SessionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *SessionClient) UpdateOneID(id int) *SessionUpdateOne {
mutation := newSessionMutation(c.config, OpUpdateOne, withSessionID(id))
return &SessionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Session.
func (c *SessionClient) Delete() *SessionDelete {
mutation := newSessionMutation(c.config, OpDelete)
return &SessionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a delete builder for the given entity.
func (c *SessionClient) DeleteOne(s *Session) *SessionDeleteOne {
return c.DeleteOneID(s.ID)
}
// DeleteOneID returns a delete builder for the given id.
func (c *SessionClient) DeleteOneID(id int) *SessionDeleteOne {
builder := c.Delete().Where(session.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &SessionDeleteOne{builder}
}
// Query returns a query builder for Session.
func (c *SessionClient) Query() *SessionQuery {
return &SessionQuery{config: c.config}
}
// Get returns a Session entity by its id.
func (c *SessionClient) Get(ctx context.Context, id int) (*Session, error) {
return c.Query().Where(session.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *SessionClient) GetX(ctx context.Context, id int) *Session {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// Hooks returns the client hooks.
func (c *SessionClient) Hooks() []Hook {
return c.hooks.Session
}

View file

@ -1,61 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"github.com/facebook/ent"
"github.com/facebook/ent/dialect"
)
// Option function to configure the client.
type Option func(*config)
// Config is the configuration for the client and its builder.
type config struct {
// driver used for executing database requests.
driver dialect.Driver
// debug enable a debug logging.
debug bool
// log used for logging on debug mode.
log func(...interface{})
// hooks to execute on mutations.
hooks *hooks
}
// hooks per client, for fast access.
type hooks struct {
Challenge []ent.Hook
Guild []ent.Hook
Session []ent.Hook
}
// Options applies the options on the config object.
func (c *config) options(opts ...Option) {
for _, opt := range opts {
opt(c)
}
if c.debug {
c.driver = dialect.Debug(c.driver, c.log)
}
}
// Debug enables debug logging on the ent.Driver.
func Debug() Option {
return func(c *config) {
c.debug = true
}
}
// Log sets the logging function for debug mode.
func Log(fn func(...interface{})) Option {
return func(c *config) {
c.log = fn
}
}
// Driver configures the client driver.
func Driver(driver dialect.Driver) Option {
return func(c *config) {
c.driver = driver
}
}

View file

@ -1,33 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
)
type clientCtxKey struct{}
// FromContext returns the Client stored in a context, or nil if there isn't one.
func FromContext(ctx context.Context) *Client {
c, _ := ctx.Value(clientCtxKey{}).(*Client)
return c
}
// NewContext returns a new context with the given Client attached.
func NewContext(parent context.Context, c *Client) context.Context {
return context.WithValue(parent, clientCtxKey{}, c)
}
type txCtxKey struct{}
// TxFromContext returns the Tx stored in a context, or nil if there isn't one.
func TxFromContext(ctx context.Context) *Tx {
tx, _ := ctx.Value(txCtxKey{}).(*Tx)
return tx
}
// NewTxContext returns a new context with the given Client attached.
func NewTxContext(parent context.Context, tx *Tx) context.Context {
return context.WithValue(parent, txCtxKey{}, tx)
}

View file

@ -1,270 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"errors"
"fmt"
"strings"
"github.com/facebook/ent"
"github.com/facebook/ent/dialect"
"github.com/facebook/ent/dialect/sql"
"github.com/facebook/ent/dialect/sql/sqlgraph"
)
// ent aliases to avoid import conflict in user's code.
type (
Op = ent.Op
Hook = ent.Hook
Value = ent.Value
Query = ent.Query
Policy = ent.Policy
Mutator = ent.Mutator
Mutation = ent.Mutation
MutateFunc = ent.MutateFunc
)
// 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, check func(string) bool) {
for _, f := range fields {
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, check func(string) bool) {
for _, f := range fields {
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, func(string) bool) string
// As is a pseudo aggregation function for renaming another other functions with custom names. For example:
//
// GroupBy(field1, field2).
// Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")).
// Scan(ctx, &v)
//
func As(fn AggregateFunc, end string) AggregateFunc {
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, _ 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, 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, 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, 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, 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))
}
}
// ValidationError returns when validating a field fails.
type ValidationError struct {
Name string // Field or edge name.
err error
}
// Error implements the error interface.
func (e *ValidationError) Error() string {
return e.err.Error()
}
// Unwrap implements the errors.Wrapper interface.
func (e *ValidationError) Unwrap() error {
return e.err
}
// IsValidationError returns a boolean indicating whether the error is a validaton error.
func IsValidationError(err error) bool {
if err == nil {
return false
}
var e *ValidationError
return errors.As(err, &e)
}
// NotFoundError returns when trying to fetch a specific entity and it was not found in the database.
type NotFoundError struct {
label string
}
// Error implements the error interface.
func (e *NotFoundError) Error() string {
return "ent: " + e.label + " not found"
}
// IsNotFound returns a boolean indicating whether the error is a not found error.
func IsNotFound(err error) bool {
if err == nil {
return false
}
var e *NotFoundError
return errors.As(err, &e)
}
// MaskNotFound masks nor found error.
func MaskNotFound(err error) error {
if IsNotFound(err) {
return nil
}
return err
}
// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database.
type NotSingularError struct {
label string
}
// Error implements the error interface.
func (e *NotSingularError) Error() string {
return "ent: " + e.label + " not singular"
}
// IsNotSingular returns a boolean indicating whether the error is a not singular error.
func IsNotSingular(err error) bool {
if err == nil {
return false
}
var e *NotSingularError
return errors.As(err, &e)
}
// NotLoadedError returns when trying to get a node that was not loaded by the query.
type NotLoadedError struct {
edge string
}
// Error implements the error interface.
func (e *NotLoadedError) Error() string {
return "ent: " + e.edge + " edge was not loaded"
}
// IsNotLoaded returns a boolean indicating whether the error is a not loaded error.
func IsNotLoaded(err error) bool {
if err == nil {
return false
}
var e *NotLoadedError
return errors.As(err, &e)
}
// ConstraintError returns when trying to create/update one or more entities and
// one or more of their constraints failed. For example, violation of edge or
// field uniqueness.
type ConstraintError struct {
msg string
wrap error
}
// Error implements the error interface.
func (e ConstraintError) Error() string {
return "ent: constraint failed: " + e.msg
}
// Unwrap implements the errors.Wrapper interface.
func (e *ConstraintError) Unwrap() error {
return e.wrap
}
// IsConstraintError returns a boolean indicating whether the error is a constraint failure.
func IsConstraintError(err error) bool {
if err == nil {
return false
}
var e *ConstraintError
return errors.As(err, &e)
}
func isSQLConstraintError(err error) (*ConstraintError, bool) {
var (
msg = err.Error()
// error format per dialect.
errors = [...]string{
"Error 1062", // MySQL 1062 error (ER_DUP_ENTRY).
"UNIQUE constraint failed", // SQLite.
"duplicate key value violates unique constraint", // PostgreSQL.
}
)
if _, ok := err.(*sqlgraph.ConstraintError); ok {
return &ConstraintError{msg, err}, true
}
for i := range errors {
if strings.Contains(msg, errors[i]) {
return &ConstraintError{msg, err}, true
}
}
return nil, false
}
// rollback calls to tx.Rollback and wraps the given error with the rollback error if occurred.
func rollback(tx dialect.Tx, err error) error {
if rerr := tx.Rollback(); rerr != nil {
err = fmt.Errorf("%s: %v", err.Error(), rerr)
}
if err, ok := isSQLConstraintError(err); ok {
return err
}
return err
}

View file

@ -1,13 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "enttest",
srcs = ["enttest.go"],
importpath = "github.com/roleypoly/roleypoly/src/db/ent/enttest",
visibility = ["//visibility:public"],
deps = [
"//src/db/ent",
"//src/db/ent/runtime",
"@com_github_facebook_ent//dialect/sql/schema",
],
)

View file

@ -1,78 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package enttest
import (
"context"
"github.com/roleypoly/roleypoly/src/db/ent"
// required by schema hooks.
_ "github.com/roleypoly/roleypoly/src/db/ent/runtime"
"github.com/facebook/ent/dialect/sql/schema"
)
type (
// TestingT is the interface that is shared between
// testing.T and testing.B and used by enttest.
TestingT interface {
FailNow()
Error(...interface{})
}
// Option configures client creation.
Option func(*options)
options struct {
opts []ent.Option
migrateOpts []schema.MigrateOption
}
)
// WithOptions forwards options to client creation.
func WithOptions(opts ...ent.Option) Option {
return func(o *options) {
o.opts = append(o.opts, opts...)
}
}
// WithMigrateOptions forwards options to auto migration.
func WithMigrateOptions(opts ...schema.MigrateOption) Option {
return func(o *options) {
o.migrateOpts = append(o.migrateOpts, opts...)
}
}
func newOptions(opts []Option) *options {
o := &options{}
for _, opt := range opts {
opt(o)
}
return o
}
// Open calls ent.Open and auto-run migration.
func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Client {
o := newOptions(opts)
c, err := ent.Open(driverName, dataSourceName, o.opts...)
if err != nil {
t.Error(err)
t.FailNow()
}
if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil {
t.Error(err)
t.FailNow()
}
return c
}
// NewClient calls ent.NewClient and auto-run migration.
func NewClient(t TestingT, opts ...Option) *ent.Client {
o := newOptions(opts)
c := ent.NewClient(o.opts...)
if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil {
t.Error(err)
t.FailNow()
}
return c
}

View file

@ -1,3 +0,0 @@
package ent
//go:generate go run github.com/facebook/ent/cmd/entc generate ./schema

View file

@ -1,145 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"encoding/json"
"fmt"
"strings"
"time"
"github.com/facebook/ent/dialect/sql"
"github.com/roleypoly/roleypoly/src/db/ent/guild"
"github.com/roleypoly/roleypoly/src/db/ent/schema"
)
// Guild is the model entity for the Guild schema.
type Guild struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// CreateTime holds the value of the "create_time" field.
CreateTime time.Time `json:"create_time,omitempty"`
// UpdateTime holds the value of the "update_time" field.
UpdateTime time.Time `json:"update_time,omitempty"`
// Snowflake holds the value of the "snowflake" field.
Snowflake string `json:"snowflake,omitempty"`
// Message holds the value of the "message" field.
Message string `json:"message,omitempty"`
// Categories holds the value of the "categories" field.
Categories []schema.Category `json:"categories,omitempty"`
// Entitlements holds the value of the "entitlements" field.
Entitlements []string `json:"entitlements,omitempty"`
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Guild) scanValues() []interface{} {
return []interface{}{
&sql.NullInt64{}, // id
&sql.NullTime{}, // create_time
&sql.NullTime{}, // update_time
&sql.NullString{}, // snowflake
&sql.NullString{}, // message
&[]byte{}, // categories
&[]byte{}, // entitlements
}
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Guild fields.
func (gu *Guild) assignValues(values ...interface{}) error {
if m, n := len(values), len(guild.Columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
value, ok := values[0].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
gu.ID = int(value.Int64)
values = values[1:]
if value, ok := values[0].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field create_time", values[0])
} else if value.Valid {
gu.CreateTime = value.Time
}
if value, ok := values[1].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field update_time", values[1])
} else if value.Valid {
gu.UpdateTime = value.Time
}
if value, ok := values[2].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field snowflake", values[2])
} else if value.Valid {
gu.Snowflake = value.String
}
if value, ok := values[3].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field message", values[3])
} else if value.Valid {
gu.Message = value.String
}
if value, ok := values[4].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field categories", values[4])
} else if value != nil && len(*value) > 0 {
if err := json.Unmarshal(*value, &gu.Categories); err != nil {
return fmt.Errorf("unmarshal field categories: %v", err)
}
}
if value, ok := values[5].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field entitlements", values[5])
} else if value != nil && len(*value) > 0 {
if err := json.Unmarshal(*value, &gu.Entitlements); err != nil {
return fmt.Errorf("unmarshal field entitlements: %v", err)
}
}
return nil
}
// Update returns a builder for updating this Guild.
// Note that, you need to call Guild.Unwrap() before calling this method, if this Guild
// was returned from a transaction, and the transaction was committed or rolled back.
func (gu *Guild) Update() *GuildUpdateOne {
return (&GuildClient{config: gu.config}).UpdateOne(gu)
}
// Unwrap unwraps the entity that was returned from a transaction after it was closed,
// so that all next queries will be executed through the driver which created the transaction.
func (gu *Guild) Unwrap() *Guild {
tx, ok := gu.config.driver.(*txDriver)
if !ok {
panic("ent: Guild is not a transactional entity")
}
gu.config.driver = tx.drv
return gu
}
// String implements the fmt.Stringer.
func (gu *Guild) String() string {
var builder strings.Builder
builder.WriteString("Guild(")
builder.WriteString(fmt.Sprintf("id=%v", gu.ID))
builder.WriteString(", create_time=")
builder.WriteString(gu.CreateTime.Format(time.ANSIC))
builder.WriteString(", update_time=")
builder.WriteString(gu.UpdateTime.Format(time.ANSIC))
builder.WriteString(", snowflake=")
builder.WriteString(gu.Snowflake)
builder.WriteString(", message=")
builder.WriteString(gu.Message)
builder.WriteString(", categories=")
builder.WriteString(fmt.Sprintf("%v", gu.Categories))
builder.WriteString(", entitlements=")
builder.WriteString(fmt.Sprintf("%v", gu.Entitlements))
builder.WriteByte(')')
return builder.String()
}
// Guilds is a parsable slice of Guild.
type Guilds []*Guild
func (gu Guilds) config(cfg config) {
for _i := range gu {
gu[_i].config = cfg
}
}

View file

@ -1,15 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "guild",
srcs = [
"guild.go",
"where.go",
],
importpath = "github.com/roleypoly/roleypoly/src/db/ent/guild",
visibility = ["//visibility:public"],
deps = [
"//src/db/ent/predicate",
"@com_github_facebook_ent//dialect/sql",
],
)

View file

@ -1,59 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package guild
import (
"time"
)
const (
// Label holds the string label denoting the guild type in the database.
Label = "guild"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldCreateTime holds the string denoting the create_time field in the database.
FieldCreateTime = "create_time"
// FieldUpdateTime holds the string denoting the update_time field in the database.
FieldUpdateTime = "update_time"
// FieldSnowflake holds the string denoting the snowflake field in the database.
FieldSnowflake = "snowflake"
// FieldMessage holds the string denoting the message field in the database.
FieldMessage = "message"
// FieldCategories holds the string denoting the categories field in the database.
FieldCategories = "categories"
// FieldEntitlements holds the string denoting the entitlements field in the database.
FieldEntitlements = "entitlements"
// Table holds the table name of the guild in the database.
Table = "guilds"
)
// Columns holds all SQL columns for guild fields.
var Columns = []string{
FieldID,
FieldCreateTime,
FieldUpdateTime,
FieldSnowflake,
FieldMessage,
FieldCategories,
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
// DefaultUpdateTime holds the default value on creation for the update_time field.
DefaultUpdateTime func() time.Time
// UpdateDefaultUpdateTime holds the default value on update for the update_time field.
UpdateDefaultUpdateTime func() time.Time
)

View file

@ -1,527 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package guild
import (
"time"
"github.com/facebook/ent/dialect/sql"
"github.com/roleypoly/roleypoly/src/db/ent/predicate"
)
// ID filters vertices based on their identifier.
func ID(id int) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldID), id))
})
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.In(s.C(FieldID), v...))
})
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.NotIn(s.C(FieldID), v...))
})
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldID), id))
})
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldID), id))
})
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldID), id))
})
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldID), id))
})
}
// CreateTime applies equality check predicate on the "create_time" field. It's identical to CreateTimeEQ.
func CreateTime(v time.Time) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldCreateTime), v))
})
}
// UpdateTime applies equality check predicate on the "update_time" field. It's identical to UpdateTimeEQ.
func UpdateTime(v time.Time) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdateTime), v))
})
}
// Snowflake applies equality check predicate on the "snowflake" field. It's identical to SnowflakeEQ.
func Snowflake(v string) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldSnowflake), v))
})
}
// Message applies equality check predicate on the "message" field. It's identical to MessageEQ.
func Message(v string) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldMessage), v))
})
}
// CreateTimeEQ applies the EQ predicate on the "create_time" field.
func CreateTimeEQ(v time.Time) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldCreateTime), v))
})
}
// CreateTimeNEQ applies the NEQ predicate on the "create_time" field.
func CreateTimeNEQ(v time.Time) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldCreateTime), v))
})
}
// CreateTimeIn applies the In predicate on the "create_time" field.
func CreateTimeIn(vs ...time.Time) predicate.Guild {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Guild(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldCreateTime), v...))
})
}
// CreateTimeNotIn applies the NotIn predicate on the "create_time" field.
func CreateTimeNotIn(vs ...time.Time) predicate.Guild {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Guild(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldCreateTime), v...))
})
}
// CreateTimeGT applies the GT predicate on the "create_time" field.
func CreateTimeGT(v time.Time) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldCreateTime), v))
})
}
// CreateTimeGTE applies the GTE predicate on the "create_time" field.
func CreateTimeGTE(v time.Time) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldCreateTime), v))
})
}
// CreateTimeLT applies the LT predicate on the "create_time" field.
func CreateTimeLT(v time.Time) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldCreateTime), v))
})
}
// CreateTimeLTE applies the LTE predicate on the "create_time" field.
func CreateTimeLTE(v time.Time) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldCreateTime), v))
})
}
// UpdateTimeEQ applies the EQ predicate on the "update_time" field.
func UpdateTimeEQ(v time.Time) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdateTime), v))
})
}
// UpdateTimeNEQ applies the NEQ predicate on the "update_time" field.
func UpdateTimeNEQ(v time.Time) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldUpdateTime), v))
})
}
// UpdateTimeIn applies the In predicate on the "update_time" field.
func UpdateTimeIn(vs ...time.Time) predicate.Guild {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Guild(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldUpdateTime), v...))
})
}
// UpdateTimeNotIn applies the NotIn predicate on the "update_time" field.
func UpdateTimeNotIn(vs ...time.Time) predicate.Guild {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Guild(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldUpdateTime), v...))
})
}
// UpdateTimeGT applies the GT predicate on the "update_time" field.
func UpdateTimeGT(v time.Time) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldUpdateTime), v))
})
}
// UpdateTimeGTE applies the GTE predicate on the "update_time" field.
func UpdateTimeGTE(v time.Time) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldUpdateTime), v))
})
}
// UpdateTimeLT applies the LT predicate on the "update_time" field.
func UpdateTimeLT(v time.Time) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldUpdateTime), v))
})
}
// UpdateTimeLTE applies the LTE predicate on the "update_time" field.
func UpdateTimeLTE(v time.Time) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUpdateTime), v))
})
}
// SnowflakeEQ applies the EQ predicate on the "snowflake" field.
func SnowflakeEQ(v string) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldSnowflake), v))
})
}
// SnowflakeNEQ applies the NEQ predicate on the "snowflake" field.
func SnowflakeNEQ(v string) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldSnowflake), v))
})
}
// SnowflakeIn applies the In predicate on the "snowflake" field.
func SnowflakeIn(vs ...string) predicate.Guild {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Guild(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldSnowflake), v...))
})
}
// SnowflakeNotIn applies the NotIn predicate on the "snowflake" field.
func SnowflakeNotIn(vs ...string) predicate.Guild {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Guild(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldSnowflake), v...))
})
}
// SnowflakeGT applies the GT predicate on the "snowflake" field.
func SnowflakeGT(v string) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldSnowflake), v))
})
}
// SnowflakeGTE applies the GTE predicate on the "snowflake" field.
func SnowflakeGTE(v string) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldSnowflake), v))
})
}
// SnowflakeLT applies the LT predicate on the "snowflake" field.
func SnowflakeLT(v string) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldSnowflake), v))
})
}
// SnowflakeLTE applies the LTE predicate on the "snowflake" field.
func SnowflakeLTE(v string) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldSnowflake), v))
})
}
// SnowflakeContains applies the Contains predicate on the "snowflake" field.
func SnowflakeContains(v string) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldSnowflake), v))
})
}
// SnowflakeHasPrefix applies the HasPrefix predicate on the "snowflake" field.
func SnowflakeHasPrefix(v string) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldSnowflake), v))
})
}
// SnowflakeHasSuffix applies the HasSuffix predicate on the "snowflake" field.
func SnowflakeHasSuffix(v string) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldSnowflake), v))
})
}
// SnowflakeEqualFold applies the EqualFold predicate on the "snowflake" field.
func SnowflakeEqualFold(v string) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldSnowflake), v))
})
}
// SnowflakeContainsFold applies the ContainsFold predicate on the "snowflake" field.
func SnowflakeContainsFold(v string) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldSnowflake), v))
})
}
// MessageEQ applies the EQ predicate on the "message" field.
func MessageEQ(v string) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldMessage), v))
})
}
// MessageNEQ applies the NEQ predicate on the "message" field.
func MessageNEQ(v string) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldMessage), v))
})
}
// MessageIn applies the In predicate on the "message" field.
func MessageIn(vs ...string) predicate.Guild {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Guild(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldMessage), v...))
})
}
// MessageNotIn applies the NotIn predicate on the "message" field.
func MessageNotIn(vs ...string) predicate.Guild {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Guild(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldMessage), v...))
})
}
// MessageGT applies the GT predicate on the "message" field.
func MessageGT(v string) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldMessage), v))
})
}
// MessageGTE applies the GTE predicate on the "message" field.
func MessageGTE(v string) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldMessage), v))
})
}
// MessageLT applies the LT predicate on the "message" field.
func MessageLT(v string) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldMessage), v))
})
}
// MessageLTE applies the LTE predicate on the "message" field.
func MessageLTE(v string) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldMessage), v))
})
}
// MessageContains applies the Contains predicate on the "message" field.
func MessageContains(v string) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldMessage), v))
})
}
// MessageHasPrefix applies the HasPrefix predicate on the "message" field.
func MessageHasPrefix(v string) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldMessage), v))
})
}
// MessageHasSuffix applies the HasSuffix predicate on the "message" field.
func MessageHasSuffix(v string) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldMessage), v))
})
}
// MessageEqualFold applies the EqualFold predicate on the "message" field.
func MessageEqualFold(v string) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldMessage), v))
})
}
// MessageContainsFold applies the ContainsFold predicate on the "message" field.
func MessageContainsFold(v string) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldMessage), v))
})
}
// And groups list of predicates with the AND operator between them.
func And(predicates ...predicate.Guild) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for _, p := range predicates {
p(s1)
}
s.Where(s1.P())
})
}
// Or groups list of predicates with the OR operator between them.
func Or(predicates ...predicate.Guild) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for i, p := range predicates {
if i > 0 {
s1.Or()
}
p(s1)
}
s.Where(s1.P())
})
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Guild) predicate.Guild {
return predicate.Guild(func(s *sql.Selector) {
p(s.Not())
})
}

View file

@ -1,301 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"github.com/facebook/ent/dialect/sql/sqlgraph"
"github.com/facebook/ent/schema/field"
"github.com/roleypoly/roleypoly/src/db/ent/guild"
"github.com/roleypoly/roleypoly/src/db/ent/schema"
)
// GuildCreate is the builder for creating a Guild entity.
type GuildCreate struct {
config
mutation *GuildMutation
hooks []Hook
}
// SetCreateTime sets the create_time field.
func (gc *GuildCreate) SetCreateTime(t time.Time) *GuildCreate {
gc.mutation.SetCreateTime(t)
return gc
}
// SetNillableCreateTime sets the create_time field if the given value is not nil.
func (gc *GuildCreate) SetNillableCreateTime(t *time.Time) *GuildCreate {
if t != nil {
gc.SetCreateTime(*t)
}
return gc
}
// SetUpdateTime sets the update_time field.
func (gc *GuildCreate) SetUpdateTime(t time.Time) *GuildCreate {
gc.mutation.SetUpdateTime(t)
return gc
}
// SetNillableUpdateTime sets the update_time field if the given value is not nil.
func (gc *GuildCreate) SetNillableUpdateTime(t *time.Time) *GuildCreate {
if t != nil {
gc.SetUpdateTime(*t)
}
return gc
}
// SetSnowflake sets the snowflake field.
func (gc *GuildCreate) SetSnowflake(s string) *GuildCreate {
gc.mutation.SetSnowflake(s)
return gc
}
// SetMessage sets the message field.
func (gc *GuildCreate) SetMessage(s string) *GuildCreate {
gc.mutation.SetMessage(s)
return gc
}
// SetCategories sets the categories field.
func (gc *GuildCreate) SetCategories(s []schema.Category) *GuildCreate {
gc.mutation.SetCategories(s)
return gc
}
// SetEntitlements sets the entitlements field.
func (gc *GuildCreate) SetEntitlements(s []string) *GuildCreate {
gc.mutation.SetEntitlements(s)
return gc
}
// Mutation returns the GuildMutation object of the builder.
func (gc *GuildCreate) Mutation() *GuildMutation {
return gc.mutation
}
// Save creates the Guild in the database.
func (gc *GuildCreate) Save(ctx context.Context) (*Guild, error) {
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) {
mutation, ok := m.(*GuildMutation)
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
return node, err
})
for i := len(gc.hooks) - 1; i >= 0; i-- {
mut = gc.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, gc.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (gc *GuildCreate) SaveX(ctx context.Context) *Guild {
v, err := gc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// 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)
}
if _, ok := gc.mutation.UpdateTime(); !ok {
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\"")}
}
if _, ok := gc.mutation.Message(); !ok {
return &ValidationError{Name: "message", err: errors.New("ent: missing required field \"message\"")}
}
if _, ok := gc.mutation.Categories(); !ok {
return &ValidationError{Name: "categories", err: errors.New("ent: missing required field \"categories\"")}
}
if _, ok := gc.mutation.Entitlements(); !ok {
return &ValidationError{Name: "entitlements", err: errors.New("ent: missing required field \"entitlements\"")}
}
return nil
}
func (gc *GuildCreate) sqlSave(ctx context.Context) (*Guild, error) {
_node, _spec := gc.createSpec()
if err := sqlgraph.CreateNode(ctx, gc.driver, _spec); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
return _node, nil
}
func (gc *GuildCreate) createSpec() (*Guild, *sqlgraph.CreateSpec) {
var (
_node = &Guild{config: gc.config}
_spec = &sqlgraph.CreateSpec{
Table: guild.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: guild.FieldID,
},
}
)
if value, ok := gc.mutation.CreateTime(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: guild.FieldCreateTime,
})
_node.CreateTime = value
}
if value, ok := gc.mutation.UpdateTime(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: guild.FieldUpdateTime,
})
_node.UpdateTime = value
}
if value, ok := gc.mutation.Snowflake(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: guild.FieldSnowflake,
})
_node.Snowflake = value
}
if value, ok := gc.mutation.Message(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: guild.FieldMessage,
})
_node.Message = value
}
if value, ok := gc.mutation.Categories(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: guild.FieldCategories,
})
_node.Categories = value
}
if value, ok := gc.mutation.Entitlements(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: guild.FieldEntitlements,
})
_node.Entitlements = value
}
return _node, _spec
}
// GuildCreateBulk is the builder for creating a bulk of Guild entities.
type GuildCreateBulk struct {
config
builders []*GuildCreate
}
// Save creates the Guild entities in the database.
func (gcb *GuildCreateBulk) Save(ctx context.Context) ([]*Guild, error) {
specs := make([]*sqlgraph.CreateSpec, len(gcb.builders))
nodes := make([]*Guild, len(gcb.builders))
mutators := make([]Mutator, len(gcb.builders))
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) {
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
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, gcb.builders[i+1].mutation)
} else {
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, gcb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
}
}
mutation.done = true
if err != nil {
return nil, err
}
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, gcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX calls Save and panics if Save returns an error.
func (gcb *GuildCreateBulk) SaveX(ctx context.Context) []*Guild {
v, err := gcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}

View file

@ -1,109 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"github.com/facebook/ent/dialect/sql"
"github.com/facebook/ent/dialect/sql/sqlgraph"
"github.com/facebook/ent/schema/field"
"github.com/roleypoly/roleypoly/src/db/ent/guild"
"github.com/roleypoly/roleypoly/src/db/ent/predicate"
)
// GuildDelete is the builder for deleting a Guild entity.
type GuildDelete struct {
config
hooks []Hook
mutation *GuildMutation
predicates []predicate.Guild
}
// Where adds a new predicate to the delete builder.
func (gd *GuildDelete) Where(ps ...predicate.Guild) *GuildDelete {
gd.predicates = append(gd.predicates, ps...)
return gd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (gd *GuildDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(gd.hooks) == 0 {
affected, err = gd.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*GuildMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
gd.mutation = mutation
affected, err = gd.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(gd.hooks) - 1; i >= 0; i-- {
mut = gd.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, gd.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (gd *GuildDelete) ExecX(ctx context.Context) int {
n, err := gd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (gd *GuildDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: guild.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: guild.FieldID,
},
},
}
if ps := gd.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return sqlgraph.DeleteNodes(ctx, gd.driver, _spec)
}
// GuildDeleteOne is the builder for deleting a single Guild entity.
type GuildDeleteOne struct {
gd *GuildDelete
}
// Exec executes the deletion query.
func (gdo *GuildDeleteOne) Exec(ctx context.Context) error {
n, err := gdo.gd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{guild.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (gdo *GuildDeleteOne) ExecX(ctx context.Context) {
gdo.gd.ExecX(ctx)
}

View file

@ -1,880 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"math"
"github.com/facebook/ent/dialect/sql"
"github.com/facebook/ent/dialect/sql/sqlgraph"
"github.com/facebook/ent/schema/field"
"github.com/roleypoly/roleypoly/src/db/ent/guild"
"github.com/roleypoly/roleypoly/src/db/ent/predicate"
)
// GuildQuery is the builder for querying Guild entities.
type GuildQuery struct {
config
limit *int
offset *int
order []OrderFunc
unique []string
predicates []predicate.Guild
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the builder.
func (gq *GuildQuery) Where(ps ...predicate.Guild) *GuildQuery {
gq.predicates = append(gq.predicates, ps...)
return gq
}
// Limit adds a limit step to the query.
func (gq *GuildQuery) Limit(limit int) *GuildQuery {
gq.limit = &limit
return gq
}
// Offset adds an offset step to the query.
func (gq *GuildQuery) Offset(offset int) *GuildQuery {
gq.offset = &offset
return gq
}
// Order adds an order step to the query.
func (gq *GuildQuery) Order(o ...OrderFunc) *GuildQuery {
gq.order = append(gq.order, o...)
return gq
}
// 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) {
nodes, err := gq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{guild.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (gq *GuildQuery) FirstX(ctx context.Context) *Guild {
node, err := gq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Guild id in the query. Returns *NotFoundError when no id was found.
func (gq *GuildQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = gq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{guild.Label}
return
}
return ids[0], nil
}
// FirstXID is like FirstID, but panics if an error occurs.
func (gq *GuildQuery) FirstXID(ctx context.Context) int {
id, err := gq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// 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) {
nodes, err := gq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{guild.Label}
default:
return nil, &NotSingularError{guild.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (gq *GuildQuery) OnlyX(ctx context.Context) *Guild {
node, err := gq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID returns the only Guild id in the query, returns an error if not exactly one id was returned.
func (gq *GuildQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = gq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{guild.Label}
default:
err = &NotSingularError{guild.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (gq *GuildQuery) OnlyIDX(ctx context.Context) int {
id, err := gq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Guilds.
func (gq *GuildQuery) All(ctx context.Context) ([]*Guild, error) {
if err := gq.prepareQuery(ctx); err != nil {
return nil, err
}
return gq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (gq *GuildQuery) AllX(ctx context.Context) []*Guild {
nodes, err := gq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Guild ids.
func (gq *GuildQuery) IDs(ctx context.Context) ([]int, error) {
var ids []int
if err := gq.Select(guild.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (gq *GuildQuery) IDsX(ctx context.Context) []int {
ids, err := gq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (gq *GuildQuery) Count(ctx context.Context) (int, error) {
if err := gq.prepareQuery(ctx); err != nil {
return 0, err
}
return gq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (gq *GuildQuery) CountX(ctx context.Context) int {
count, err := gq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (gq *GuildQuery) Exist(ctx context.Context) (bool, error) {
if err := gq.prepareQuery(ctx); err != nil {
return false, err
}
return gq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (gq *GuildQuery) ExistX(ctx context.Context) bool {
exist, err := gq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the query builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (gq *GuildQuery) Clone() *GuildQuery {
return &GuildQuery{
config: gq.config,
limit: gq.limit,
offset: gq.offset,
order: append([]OrderFunc{}, gq.order...),
unique: append([]string{}, gq.unique...),
predicates: append([]predicate.Guild{}, gq.predicates...),
// clone intermediate query.
sql: gq.sql.Clone(),
path: gq.path,
}
}
// GroupBy used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// CreateTime time.Time `json:"create_time,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Guild.Query().
// GroupBy(guild.FieldCreateTime).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
//
func (gq *GuildQuery) GroupBy(field string, fields ...string) *GuildGroupBy {
group := &GuildGroupBy{config: gq.config}
group.fields = append([]string{field}, fields...)
group.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := gq.prepareQuery(ctx); err != nil {
return nil, err
}
return gq.sqlQuery(), nil
}
return group
}
// Select one or more fields from the given query.
//
// Example:
//
// var v []struct {
// CreateTime time.Time `json:"create_time,omitempty"`
// }
//
// client.Guild.Query().
// Select(guild.FieldCreateTime).
// Scan(ctx, &v)
//
func (gq *GuildQuery) Select(field string, fields ...string) *GuildSelect {
selector := &GuildSelect{config: gq.config}
selector.fields = append([]string{field}, fields...)
selector.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := gq.prepareQuery(ctx); err != nil {
return nil, err
}
return gq.sqlQuery(), nil
}
return selector
}
func (gq *GuildQuery) prepareQuery(ctx context.Context) error {
if gq.path != nil {
prev, err := gq.path(ctx)
if err != nil {
return err
}
gq.sql = prev
}
return nil
}
func (gq *GuildQuery) sqlAll(ctx context.Context) ([]*Guild, error) {
var (
nodes = []*Guild{}
_spec = gq.querySpec()
)
_spec.ScanValues = func() []interface{} {
node := &Guild{config: gq.config}
nodes = append(nodes, node)
values := node.scanValues()
return values
}
_spec.Assign = func(values ...interface{}) error {
if len(nodes) == 0 {
return fmt.Errorf("ent: Assign called without calling ScanValues")
}
node := nodes[len(nodes)-1]
return node.assignValues(values...)
}
if err := sqlgraph.QueryNodes(ctx, gq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (gq *GuildQuery) sqlCount(ctx context.Context) (int, error) {
_spec := gq.querySpec()
return sqlgraph.CountNodes(ctx, gq.driver, _spec)
}
func (gq *GuildQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := gq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("ent: check existence: %v", err)
}
return n > 0, nil
}
func (gq *GuildQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: guild.Table,
Columns: guild.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: guild.FieldID,
},
},
From: gq.sql,
Unique: true,
}
if ps := gq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := gq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := gq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := gq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector, guild.ValidColumn)
}
}
}
return _spec
}
func (gq *GuildQuery) sqlQuery() *sql.Selector {
builder := sql.Dialect(gq.driver.Dialect())
t1 := builder.Table(guild.Table)
selector := builder.Select(t1.Columns(guild.Columns...)...).From(t1)
if gq.sql != nil {
selector = gq.sql
selector.Select(selector.Columns(guild.Columns...)...)
}
for _, p := range gq.predicates {
p(selector)
}
for _, p := range gq.order {
p(selector, guild.ValidColumn)
}
if offset := gq.offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := gq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// GuildGroupBy is the builder for group-by Guild entities.
type GuildGroupBy struct {
config
fields []string
fns []AggregateFunc
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Aggregate adds the given aggregation functions to the group-by query.
func (ggb *GuildGroupBy) Aggregate(fns ...AggregateFunc) *GuildGroupBy {
ggb.fns = append(ggb.fns, fns...)
return ggb
}
// Scan applies the group-by query and scan the result into the given value.
func (ggb *GuildGroupBy) Scan(ctx context.Context, v interface{}) error {
query, err := ggb.path(ctx)
if err != nil {
return err
}
ggb.sql = query
return ggb.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (ggb *GuildGroupBy) ScanX(ctx context.Context, v interface{}) {
if err := ggb.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from group-by. It is only allowed when querying group-by with one field.
func (ggb *GuildGroupBy) Strings(ctx context.Context) ([]string, error) {
if len(ggb.fields) > 1 {
return nil, errors.New("ent: GuildGroupBy.Strings is not achievable when grouping more than 1 field")
}
var v []string
if err := ggb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (ggb *GuildGroupBy) StringsX(ctx context.Context) []string {
v, err := ggb.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from group-by. It is only allowed when querying group-by with one field.
func (ggb *GuildGroupBy) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = ggb.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{guild.Label}
default:
err = fmt.Errorf("ent: GuildGroupBy.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (ggb *GuildGroupBy) StringX(ctx context.Context) string {
v, err := ggb.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from group-by. It is only allowed when querying group-by with one field.
func (ggb *GuildGroupBy) Ints(ctx context.Context) ([]int, error) {
if len(ggb.fields) > 1 {
return nil, errors.New("ent: GuildGroupBy.Ints is not achievable when grouping more than 1 field")
}
var v []int
if err := ggb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (ggb *GuildGroupBy) IntsX(ctx context.Context) []int {
v, err := ggb.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from group-by. It is only allowed when querying group-by with one field.
func (ggb *GuildGroupBy) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = ggb.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{guild.Label}
default:
err = fmt.Errorf("ent: GuildGroupBy.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (ggb *GuildGroupBy) IntX(ctx context.Context) int {
v, err := ggb.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from group-by. It is only allowed when querying group-by with one field.
func (ggb *GuildGroupBy) Float64s(ctx context.Context) ([]float64, error) {
if len(ggb.fields) > 1 {
return nil, errors.New("ent: GuildGroupBy.Float64s is not achievable when grouping more than 1 field")
}
var v []float64
if err := ggb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (ggb *GuildGroupBy) Float64sX(ctx context.Context) []float64 {
v, err := ggb.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from group-by. It is only allowed when querying group-by with one field.
func (ggb *GuildGroupBy) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = ggb.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{guild.Label}
default:
err = fmt.Errorf("ent: GuildGroupBy.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (ggb *GuildGroupBy) Float64X(ctx context.Context) float64 {
v, err := ggb.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from group-by. It is only allowed when querying group-by with one field.
func (ggb *GuildGroupBy) Bools(ctx context.Context) ([]bool, error) {
if len(ggb.fields) > 1 {
return nil, errors.New("ent: GuildGroupBy.Bools is not achievable when grouping more than 1 field")
}
var v []bool
if err := ggb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (ggb *GuildGroupBy) BoolsX(ctx context.Context) []bool {
v, err := ggb.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from group-by. It is only allowed when querying group-by with one field.
func (ggb *GuildGroupBy) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = ggb.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{guild.Label}
default:
err = fmt.Errorf("ent: GuildGroupBy.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (ggb *GuildGroupBy) BoolX(ctx context.Context) bool {
v, err := ggb.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
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 := selector.Query()
if err := ggb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (ggb *GuildGroupBy) sqlQuery() *sql.Selector {
selector := ggb.sql
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, guild.ValidColumn))
}
return selector.Select(columns...).GroupBy(ggb.fields...)
}
// GuildSelect is the builder for select fields of Guild entities.
type GuildSelect struct {
config
fields []string
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Scan applies the selector query and scan the result into the given value.
func (gs *GuildSelect) Scan(ctx context.Context, v interface{}) error {
query, err := gs.path(ctx)
if err != nil {
return err
}
gs.sql = query
return gs.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (gs *GuildSelect) ScanX(ctx context.Context, v interface{}) {
if err := gs.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from selector. It is only allowed when selecting one field.
func (gs *GuildSelect) Strings(ctx context.Context) ([]string, error) {
if len(gs.fields) > 1 {
return nil, errors.New("ent: GuildSelect.Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := gs.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (gs *GuildSelect) StringsX(ctx context.Context) []string {
v, err := gs.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from selector. It is only allowed when selecting one field.
func (gs *GuildSelect) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = gs.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{guild.Label}
default:
err = fmt.Errorf("ent: GuildSelect.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (gs *GuildSelect) StringX(ctx context.Context) string {
v, err := gs.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from selector. It is only allowed when selecting one field.
func (gs *GuildSelect) Ints(ctx context.Context) ([]int, error) {
if len(gs.fields) > 1 {
return nil, errors.New("ent: GuildSelect.Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := gs.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (gs *GuildSelect) IntsX(ctx context.Context) []int {
v, err := gs.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from selector. It is only allowed when selecting one field.
func (gs *GuildSelect) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = gs.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{guild.Label}
default:
err = fmt.Errorf("ent: GuildSelect.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (gs *GuildSelect) IntX(ctx context.Context) int {
v, err := gs.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from selector. It is only allowed when selecting one field.
func (gs *GuildSelect) Float64s(ctx context.Context) ([]float64, error) {
if len(gs.fields) > 1 {
return nil, errors.New("ent: GuildSelect.Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := gs.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (gs *GuildSelect) Float64sX(ctx context.Context) []float64 {
v, err := gs.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from selector. It is only allowed when selecting one field.
func (gs *GuildSelect) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = gs.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{guild.Label}
default:
err = fmt.Errorf("ent: GuildSelect.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (gs *GuildSelect) Float64X(ctx context.Context) float64 {
v, err := gs.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from selector. It is only allowed when selecting one field.
func (gs *GuildSelect) Bools(ctx context.Context) ([]bool, error) {
if len(gs.fields) > 1 {
return nil, errors.New("ent: GuildSelect.Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := gs.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (gs *GuildSelect) BoolsX(ctx context.Context) []bool {
v, err := gs.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from selector. It is only allowed when selecting one field.
func (gs *GuildSelect) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = gs.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{guild.Label}
default:
err = fmt.Errorf("ent: GuildSelect.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (gs *GuildSelect) BoolX(ctx context.Context) bool {
v, err := gs.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
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 {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (gs *GuildSelect) sqlQuery() sql.Querier {
selector := gs.sql
selector.Select(selector.Columns(gs.fields...)...)
return selector
}

View file

@ -1,317 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"github.com/facebook/ent/dialect/sql"
"github.com/facebook/ent/dialect/sql/sqlgraph"
"github.com/facebook/ent/schema/field"
"github.com/roleypoly/roleypoly/src/db/ent/guild"
"github.com/roleypoly/roleypoly/src/db/ent/predicate"
"github.com/roleypoly/roleypoly/src/db/ent/schema"
)
// GuildUpdate is the builder for updating Guild entities.
type GuildUpdate struct {
config
hooks []Hook
mutation *GuildMutation
predicates []predicate.Guild
}
// Where adds a new predicate for the builder.
func (gu *GuildUpdate) Where(ps ...predicate.Guild) *GuildUpdate {
gu.predicates = append(gu.predicates, ps...)
return gu
}
// SetMessage sets the message field.
func (gu *GuildUpdate) SetMessage(s string) *GuildUpdate {
gu.mutation.SetMessage(s)
return gu
}
// SetCategories sets the categories field.
func (gu *GuildUpdate) SetCategories(s []schema.Category) *GuildUpdate {
gu.mutation.SetCategories(s)
return gu
}
// SetEntitlements sets the entitlements field.
func (gu *GuildUpdate) SetEntitlements(s []string) *GuildUpdate {
gu.mutation.SetEntitlements(s)
return gu
}
// Mutation returns the GuildMutation object of the builder.
func (gu *GuildUpdate) Mutation() *GuildMutation {
return gu.mutation
}
// Save executes the query and returns the number of rows/vertices matched by this operation.
func (gu *GuildUpdate) Save(ctx context.Context) (int, error) {
var (
err error
affected int
)
gu.defaults()
if len(gu.hooks) == 0 {
affected, err = gu.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*GuildMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
gu.mutation = mutation
affected, err = gu.sqlSave(ctx)
mutation.done = true
return affected, err
})
for i := len(gu.hooks) - 1; i >= 0; i-- {
mut = gu.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, gu.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// SaveX is like Save, but panics if an error occurs.
func (gu *GuildUpdate) SaveX(ctx context.Context) int {
affected, err := gu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (gu *GuildUpdate) Exec(ctx context.Context) error {
_, err := gu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (gu *GuildUpdate) ExecX(ctx context.Context) {
if err := gu.Exec(ctx); err != nil {
panic(err)
}
}
// 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{
Table: guild.Table,
Columns: guild.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: guild.FieldID,
},
},
}
if ps := gu.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := gu.mutation.UpdateTime(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: guild.FieldUpdateTime,
})
}
if value, ok := gu.mutation.Message(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: guild.FieldMessage,
})
}
if value, ok := gu.mutation.Categories(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: guild.FieldCategories,
})
}
if value, ok := gu.mutation.Entitlements(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: guild.FieldEntitlements,
})
}
if n, err = sqlgraph.UpdateNodes(ctx, gu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{guild.Label}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return 0, err
}
return n, nil
}
// GuildUpdateOne is the builder for updating a single Guild entity.
type GuildUpdateOne struct {
config
hooks []Hook
mutation *GuildMutation
}
// SetMessage sets the message field.
func (guo *GuildUpdateOne) SetMessage(s string) *GuildUpdateOne {
guo.mutation.SetMessage(s)
return guo
}
// SetCategories sets the categories field.
func (guo *GuildUpdateOne) SetCategories(s []schema.Category) *GuildUpdateOne {
guo.mutation.SetCategories(s)
return guo
}
// SetEntitlements sets the entitlements field.
func (guo *GuildUpdateOne) SetEntitlements(s []string) *GuildUpdateOne {
guo.mutation.SetEntitlements(s)
return guo
}
// Mutation returns the GuildMutation object of the builder.
func (guo *GuildUpdateOne) Mutation() *GuildMutation {
return guo.mutation
}
// Save executes the query and returns the updated entity.
func (guo *GuildUpdateOne) Save(ctx context.Context) (*Guild, error) {
var (
err error
node *Guild
)
guo.defaults()
if len(guo.hooks) == 0 {
node, err = guo.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*GuildMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
guo.mutation = mutation
node, err = guo.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(guo.hooks) - 1; i >= 0; i-- {
mut = guo.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, guo.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX is like Save, but panics if an error occurs.
func (guo *GuildUpdateOne) SaveX(ctx context.Context) *Guild {
node, err := guo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (guo *GuildUpdateOne) Exec(ctx context.Context) error {
_, err := guo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (guo *GuildUpdateOne) ExecX(ctx context.Context) {
if err := guo.Exec(ctx); err != nil {
panic(err)
}
}
// 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,
Columns: guild.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: guild.FieldID,
},
},
}
id, ok := guo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing Guild.ID for update")}
}
_spec.Node.ID.Value = id
if value, ok := guo.mutation.UpdateTime(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: guild.FieldUpdateTime,
})
}
if value, ok := guo.mutation.Message(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: guild.FieldMessage,
})
}
if value, ok := guo.mutation.Categories(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: guild.FieldCategories,
})
}
if value, ok := guo.mutation.Entitlements(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: guild.FieldEntitlements,
})
}
_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}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
return _node, nil
}

View file

@ -1,9 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "hook",
srcs = ["hook.go"],
importpath = "github.com/roleypoly/roleypoly/src/db/ent/hook",
visibility = ["//visibility:public"],
deps = ["//src/db/ent"],
)

View file

@ -1,225 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package hook
import (
"context"
"fmt"
"github.com/roleypoly/roleypoly/src/db/ent"
)
// The ChallengeFunc type is an adapter to allow the use of ordinary
// function as Challenge mutator.
type ChallengeFunc func(context.Context, *ent.ChallengeMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f ChallengeFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
mv, ok := m.(*ent.ChallengeMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ChallengeMutation", m)
}
return f(ctx, mv)
}
// The GuildFunc type is an adapter to allow the use of ordinary
// function as Guild mutator.
type GuildFunc func(context.Context, *ent.GuildMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f GuildFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
mv, ok := m.(*ent.GuildMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GuildMutation", m)
}
return f(ctx, mv)
}
// The SessionFunc type is an adapter to allow the use of ordinary
// function as Session mutator.
type SessionFunc func(context.Context, *ent.SessionMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f SessionFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
mv, ok := m.(*ent.SessionMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.SessionMutation", m)
}
return f(ctx, mv)
}
// Condition is a hook condition function.
type Condition func(context.Context, ent.Mutation) bool
// And groups conditions with the AND operator.
func And(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
if !first(ctx, m) || !second(ctx, m) {
return false
}
for _, cond := range rest {
if !cond(ctx, m) {
return false
}
}
return true
}
}
// Or groups conditions with the OR operator.
func Or(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
if first(ctx, m) || second(ctx, m) {
return true
}
for _, cond := range rest {
if cond(ctx, m) {
return true
}
}
return false
}
}
// Not negates a given condition.
func Not(cond Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
return !cond(ctx, m)
}
}
// HasOp is a condition testing mutation operation.
func HasOp(op ent.Op) Condition {
return func(_ context.Context, m ent.Mutation) bool {
return m.Op().Is(op)
}
}
// HasAddedFields is a condition validating `.AddedField` on fields.
func HasAddedFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if _, exists := m.AddedField(field); !exists {
return false
}
for _, field := range fields {
if _, exists := m.AddedField(field); !exists {
return false
}
}
return true
}
}
// HasClearedFields is a condition validating `.FieldCleared` on fields.
func HasClearedFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if exists := m.FieldCleared(field); !exists {
return false
}
for _, field := range fields {
if exists := m.FieldCleared(field); !exists {
return false
}
}
return true
}
}
// HasFields is a condition validating `.Field` on fields.
func HasFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if _, exists := m.Field(field); !exists {
return false
}
for _, field := range fields {
if _, exists := m.Field(field); !exists {
return false
}
}
return true
}
}
// If executes the given hook under condition.
//
// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...)))
//
func If(hk ent.Hook, cond Condition) ent.Hook {
return func(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if cond(ctx, m) {
return hk(next).Mutate(ctx, m)
}
return next.Mutate(ctx, m)
})
}
}
// On executes the given hook only for the given operation.
//
// hook.On(Log, ent.Delete|ent.Create)
//
func On(hk ent.Hook, op ent.Op) ent.Hook {
return If(hk, HasOp(op))
}
// Unless skips the given hook only for the given operation.
//
// hook.Unless(Log, ent.Update|ent.UpdateOne)
//
func Unless(hk ent.Hook, op ent.Op) ent.Hook {
return If(hk, Not(HasOp(op)))
}
// Reject returns a hook that rejects all operations that match op.
//
// func (T) Hooks() []ent.Hook {
// return []ent.Hook{
// Reject(ent.Delete|ent.Update),
// }
// }
//
func Reject(op ent.Op) ent.Hook {
hk := func(ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(_ context.Context, m ent.Mutation) (ent.Value, error) {
return nil, fmt.Errorf("%s operation is not allowed", m.Op())
})
}
return On(hk, op)
}
// Chain acts as a list of hooks and is effectively immutable.
// Once created, it will always hold the same set of hooks in the same order.
type Chain struct {
hooks []ent.Hook
}
// NewChain creates a new chain of hooks.
func NewChain(hooks ...ent.Hook) Chain {
return Chain{append([]ent.Hook(nil), hooks...)}
}
// Hook chains the list of hooks and returns the final hook.
func (c Chain) Hook() ent.Hook {
return func(mutator ent.Mutator) ent.Mutator {
for i := len(c.hooks) - 1; i >= 0; i-- {
mutator = c.hooks[i](mutator)
}
return mutator
}
}
// Append extends a chain, adding the specified hook
// as the last ones in the mutation flow.
func (c Chain) Append(hooks ...ent.Hook) Chain {
newHooks := make([]ent.Hook, 0, len(c.hooks)+len(hooks))
newHooks = append(newHooks, c.hooks...)
newHooks = append(newHooks, hooks...)
return Chain{newHooks}
}
// Extend extends a chain, adding the specified chain
// as the last ones in the mutation flow.
func (c Chain) Extend(chain Chain) Chain {
return c.Append(chain.hooks...)
}

View file

@ -1,16 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "migrate",
srcs = [
"migrate.go",
"schema.go",
],
importpath = "github.com/roleypoly/roleypoly/src/db/ent/migrate",
visibility = ["//visibility:public"],
deps = [
"@com_github_facebook_ent//dialect",
"@com_github_facebook_ent//dialect/sql/schema",
"@com_github_facebook_ent//schema/field",
],
)

View file

@ -1,70 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package migrate
import (
"context"
"fmt"
"io"
"github.com/facebook/ent/dialect"
"github.com/facebook/ent/dialect/sql/schema"
)
var (
// WithGlobalUniqueID sets the universal ids options to the migration.
// If this option is enabled, ent migration will allocate a 1<<32 range
// for the ids of each entity (table).
// Note that this option cannot be applied on tables that already exist.
WithGlobalUniqueID = schema.WithGlobalUniqueID
// WithDropColumn sets the drop column option to the migration.
// If this option is enabled, ent migration will drop old columns
// that were used for both fields and edges. This defaults to false.
WithDropColumn = schema.WithDropColumn
// WithDropIndex sets the drop index option to the migration.
// If this option is enabled, ent migration will drop old indexes
// that were defined in the schema. This defaults to false.
// Note that unique constraints are defined using `UNIQUE INDEX`,
// and therefore, it's recommended to enable this option to get more
// flexibility in the schema changes.
WithDropIndex = schema.WithDropIndex
// WithFixture sets the foreign-key renaming option to the migration when upgrading
// ent from v0.1.0 (issue-#285). Defaults to false.
WithFixture = schema.WithFixture
)
// Schema is the API for creating, migrating and dropping a schema.
type Schema struct {
drv dialect.Driver
universalID bool
}
// NewSchema creates a new schema client.
func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} }
// Create creates all schema resources.
func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error {
migrate, err := schema.NewMigrate(s.drv, opts...)
if err != nil {
return fmt.Errorf("ent/migrate: %v", err)
}
return migrate.Create(ctx, Tables...)
}
// WriteTo writes the schema changes to w instead of running them against the database.
//
// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil {
// log.Fatal(err)
// }
//
func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error {
drv := &schema.WriteDriver{
Writer: w,
Driver: s.drv,
}
migrate, err := schema.NewMigrate(drv, opts...)
if err != nil {
return fmt.Errorf("ent/migrate: %v", err)
}
return migrate.Create(ctx, Tables...)
}

View file

@ -1,72 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package migrate
import (
"github.com/facebook/ent/dialect/sql/schema"
"github.com/facebook/ent/schema/field"
)
var (
// ChallengesColumns holds the columns for the "challenges" table.
ChallengesColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "create_time", Type: field.TypeTime},
{Name: "update_time", Type: field.TypeTime},
{Name: "challenge_id", Type: field.TypeString, Unique: true, Size: 2147483647},
{Name: "user_id", Type: field.TypeString, Unique: true, Size: 2147483647},
{Name: "human", Type: field.TypeString, Unique: true},
{Name: "magic", Type: field.TypeString, Unique: true},
{Name: "expires_at", Type: field.TypeTime},
}
// ChallengesTable holds the schema information for the "challenges" table.
ChallengesTable = &schema.Table{
Name: "challenges",
Columns: ChallengesColumns,
PrimaryKey: []*schema.Column{ChallengesColumns[0]},
ForeignKeys: []*schema.ForeignKey{},
}
// GuildsColumns holds the columns for the "guilds" table.
GuildsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "create_time", Type: field.TypeTime},
{Name: "update_time", Type: field.TypeTime},
{Name: "snowflake", Type: field.TypeString, Unique: true, Size: 2147483647},
{Name: "message", Type: field.TypeString, Size: 2147483647},
{Name: "categories", Type: field.TypeJSON},
{Name: "entitlements", Type: field.TypeJSON},
}
// GuildsTable holds the schema information for the "guilds" table.
GuildsTable = &schema.Table{
Name: "guilds",
Columns: GuildsColumns,
PrimaryKey: []*schema.Column{GuildsColumns[0]},
ForeignKeys: []*schema.ForeignKey{},
}
// SessionsColumns holds the columns for the "sessions" table.
SessionsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "create_time", Type: field.TypeTime},
{Name: "update_time", Type: field.TypeTime},
{Name: "session_id", Type: field.TypeString, Unique: true, Size: 2147483647},
{Name: "user_id", Type: field.TypeString, Unique: true, Size: 2147483647},
{Name: "source", Type: field.TypeEnum, Enums: []string{"oauth", "dm"}},
{Name: "expires_at", Type: field.TypeTime},
}
// SessionsTable holds the schema information for the "sessions" table.
SessionsTable = &schema.Table{
Name: "sessions",
Columns: SessionsColumns,
PrimaryKey: []*schema.Column{SessionsColumns[0]},
ForeignKeys: []*schema.ForeignKey{},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
ChallengesTable,
GuildsTable,
SessionsTable,
}
)
func init() {
}

File diff suppressed because it is too large Load diff

View file

@ -1,9 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "predicate",
srcs = ["predicate.go"],
importpath = "github.com/roleypoly/roleypoly/src/db/ent/predicate",
visibility = ["//visibility:public"],
deps = ["@com_github_facebook_ent//dialect/sql"],
)

View file

@ -1,16 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package predicate
import (
"github.com/facebook/ent/dialect/sql"
)
// Challenge is the predicate function for challenge builders.
type Challenge func(*sql.Selector)
// Guild is the predicate function for guild builders.
type Guild func(*sql.Selector)
// Session is the predicate function for session builders.
type Session func(*sql.Selector)

View file

@ -1,9 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "privacy",
srcs = ["privacy.go"],
importpath = "github.com/roleypoly/roleypoly/src/db/ent/privacy",
visibility = ["//visibility:public"],
deps = ["//src/db/ent"],
)

View file

@ -1,283 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package privacy
import (
"context"
"errors"
"fmt"
"github.com/roleypoly/roleypoly/src/db/ent"
)
var (
// Allow may be returned by rules to indicate that the policy
// evaluation should terminate with an allow decision.
Allow = errors.New("ent/privacy: allow rule")
// Deny may be returned by rules to indicate that the policy
// evaluation should terminate with an deny decision.
Deny = errors.New("ent/privacy: deny rule")
// Skip may be returned by rules to indicate that the policy
// evaluation should continue to the next rule.
Skip = errors.New("ent/privacy: skip rule")
)
// Allowf returns an formatted wrapped Allow decision.
func Allowf(format string, a ...interface{}) error {
return fmt.Errorf(format+": %w", append(a, Allow)...)
}
// Denyf returns an formatted wrapped Deny decision.
func Denyf(format string, a ...interface{}) error {
return fmt.Errorf(format+": %w", append(a, Deny)...)
}
// Skipf returns an formatted wrapped Skip decision.
func Skipf(format string, a ...interface{}) error {
return fmt.Errorf(format+": %w", append(a, Skip)...)
}
type decisionCtxKey struct{}
// DecisionContext creates a decision context.
func DecisionContext(parent context.Context, decision error) context.Context {
if decision == nil || errors.Is(decision, Skip) {
return parent
}
return context.WithValue(parent, decisionCtxKey{}, decision)
}
func decisionFromContext(ctx context.Context) (error, bool) {
decision, ok := ctx.Value(decisionCtxKey{}).(error)
if ok && errors.Is(decision, Allow) {
decision = nil
}
return decision, ok
}
type (
// QueryPolicy combines multiple query rules into a single policy.
QueryPolicy []QueryRule
// QueryRule defines the interface deciding whether a
// query is allowed and optionally modify it.
QueryRule interface {
EvalQuery(context.Context, ent.Query) error
}
)
// EvalQuery evaluates a query against a query policy.
func (policy QueryPolicy) EvalQuery(ctx context.Context, q ent.Query) error {
if decision, ok := decisionFromContext(ctx); ok {
return decision
}
for _, rule := range policy {
switch decision := rule.EvalQuery(ctx, q); {
case decision == nil || errors.Is(decision, Skip):
case errors.Is(decision, Allow):
return nil
default:
return decision
}
}
return nil
}
// QueryRuleFunc type is an adapter to allow the use of
// ordinary functions as query rules.
type QueryRuleFunc func(context.Context, ent.Query) error
// Eval returns f(ctx, q).
func (f QueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error {
return f(ctx, q)
}
type (
// MutationPolicy combines multiple mutation rules into a single policy.
MutationPolicy []MutationRule
// MutationRule defines the interface deciding whether a
// mutation is allowed and optionally modify it.
MutationRule interface {
EvalMutation(context.Context, ent.Mutation) error
}
)
// EvalMutation evaluates a mutation against a mutation policy.
func (policy MutationPolicy) EvalMutation(ctx context.Context, m ent.Mutation) error {
if decision, ok := decisionFromContext(ctx); ok {
return decision
}
for _, rule := range policy {
switch decision := rule.EvalMutation(ctx, m); {
case decision == nil || errors.Is(decision, Skip):
case errors.Is(decision, Allow):
return nil
default:
return decision
}
}
return nil
}
// MutationRuleFunc type is an adapter to allow the use of
// ordinary functions as mutation rules.
type MutationRuleFunc func(context.Context, ent.Mutation) error
// EvalMutation returns f(ctx, m).
func (f MutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error {
return f(ctx, m)
}
// Policy groups query and mutation policies.
type Policy struct {
Query QueryPolicy
Mutation MutationPolicy
}
// EvalQuery forwards evaluation to query policy.
func (policy Policy) EvalQuery(ctx context.Context, q ent.Query) error {
return policy.Query.EvalQuery(ctx, q)
}
// EvalMutation forwards evaluation to mutation policy.
func (policy Policy) EvalMutation(ctx context.Context, m ent.Mutation) error {
return policy.Mutation.EvalMutation(ctx, m)
}
// QueryMutationRule is the interface that groups query and mutation rules.
type QueryMutationRule interface {
QueryRule
MutationRule
}
// AlwaysAllowRule returns a rule that returns an allow decision.
func AlwaysAllowRule() QueryMutationRule {
return fixedDecision{Allow}
}
// AlwaysDenyRule returns a rule that returns a deny decision.
func AlwaysDenyRule() QueryMutationRule {
return fixedDecision{Deny}
}
type fixedDecision struct {
decision error
}
func (f fixedDecision) EvalQuery(context.Context, ent.Query) error {
return f.decision
}
func (f fixedDecision) EvalMutation(context.Context, ent.Mutation) error {
return f.decision
}
type contextDecision struct {
eval func(context.Context) error
}
// ContextQueryMutationRule creates a query/mutation rule from a context eval func.
func ContextQueryMutationRule(eval func(context.Context) error) QueryMutationRule {
return contextDecision{eval}
}
func (c contextDecision) EvalQuery(ctx context.Context, _ ent.Query) error {
return c.eval(ctx)
}
func (c contextDecision) EvalMutation(ctx context.Context, _ ent.Mutation) error {
return c.eval(ctx)
}
// OnMutationOperation evaluates the given rule only on a given mutation operation.
func OnMutationOperation(rule MutationRule, op ent.Op) MutationRule {
return MutationRuleFunc(func(ctx context.Context, m ent.Mutation) error {
if m.Op().Is(op) {
return rule.EvalMutation(ctx, m)
}
return Skip
})
}
// DenyMutationOperationRule returns a rule denying specified mutation operation.
func DenyMutationOperationRule(op ent.Op) MutationRule {
rule := MutationRuleFunc(func(_ context.Context, m ent.Mutation) error {
return Denyf("ent/privacy: operation %s is not allowed", m.Op())
})
return OnMutationOperation(rule, op)
}
// The ChallengeQueryRuleFunc type is an adapter to allow the use of ordinary
// functions as a query rule.
type ChallengeQueryRuleFunc func(context.Context, *ent.ChallengeQuery) error
// EvalQuery return f(ctx, q).
func (f ChallengeQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.ChallengeQuery); ok {
return f(ctx, q)
}
return Denyf("ent/privacy: unexpected query type %T, expect *ent.ChallengeQuery", q)
}
// The ChallengeMutationRuleFunc type is an adapter to allow the use of ordinary
// functions as a mutation rule.
type ChallengeMutationRuleFunc func(context.Context, *ent.ChallengeMutation) error
// EvalMutation calls f(ctx, m).
func (f ChallengeMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error {
if m, ok := m.(*ent.ChallengeMutation); ok {
return f(ctx, m)
}
return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.ChallengeMutation", m)
}
// The GuildQueryRuleFunc type is an adapter to allow the use of ordinary
// functions as a query rule.
type GuildQueryRuleFunc func(context.Context, *ent.GuildQuery) error
// EvalQuery return f(ctx, q).
func (f GuildQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.GuildQuery); ok {
return f(ctx, q)
}
return Denyf("ent/privacy: unexpected query type %T, expect *ent.GuildQuery", q)
}
// The GuildMutationRuleFunc type is an adapter to allow the use of ordinary
// functions as a mutation rule.
type GuildMutationRuleFunc func(context.Context, *ent.GuildMutation) error
// EvalMutation calls f(ctx, m).
func (f GuildMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error {
if m, ok := m.(*ent.GuildMutation); ok {
return f(ctx, m)
}
return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.GuildMutation", m)
}
// The SessionQueryRuleFunc type is an adapter to allow the use of ordinary
// functions as a query rule.
type SessionQueryRuleFunc func(context.Context, *ent.SessionQuery) error
// EvalQuery return f(ctx, q).
func (f SessionQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.SessionQuery); ok {
return f(ctx, q)
}
return Denyf("ent/privacy: unexpected query type %T, expect *ent.SessionQuery", q)
}
// The SessionMutationRuleFunc type is an adapter to allow the use of ordinary
// functions as a mutation rule.
type SessionMutationRuleFunc func(context.Context, *ent.SessionMutation) error
// EvalMutation calls f(ctx, m).
func (f SessionMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error {
if m, ok := m.(*ent.SessionMutation); ok {
return f(ctx, m)
}
return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.SessionMutation", m)
}

View file

@ -1,68 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"time"
"github.com/roleypoly/roleypoly/src/db/ent/challenge"
"github.com/roleypoly/roleypoly/src/db/ent/guild"
"github.com/roleypoly/roleypoly/src/db/ent/schema"
"github.com/roleypoly/roleypoly/src/db/ent/session"
)
// The init function reads all schema descriptors with runtime
// code (default values, validators or hooks) and stitches it
// to their package variables.
func init() {
challengeMixin := schema.Challenge{}.Mixin()
challengeMixinFields0 := challengeMixin[0].Fields()
challengeFields := schema.Challenge{}.Fields()
_ = challengeFields
// challengeDescCreateTime is the schema descriptor for create_time field.
challengeDescCreateTime := challengeMixinFields0[0].Descriptor()
// challenge.DefaultCreateTime holds the default value on creation for the create_time field.
challenge.DefaultCreateTime = challengeDescCreateTime.Default.(func() time.Time)
// challengeDescUpdateTime is the schema descriptor for update_time field.
challengeDescUpdateTime := challengeMixinFields0[1].Descriptor()
// challenge.DefaultUpdateTime holds the default value on creation for the update_time field.
challenge.DefaultUpdateTime = challengeDescUpdateTime.Default.(func() time.Time)
// challenge.UpdateDefaultUpdateTime holds the default value on update for the update_time field.
challenge.UpdateDefaultUpdateTime = challengeDescUpdateTime.UpdateDefault.(func() time.Time)
// challengeDescExpiresAt is the schema descriptor for expires_at field.
challengeDescExpiresAt := challengeFields[4].Descriptor()
// challenge.DefaultExpiresAt holds the default value on creation for the expires_at field.
challenge.DefaultExpiresAt = challengeDescExpiresAt.Default.(func() time.Time)
guildMixin := schema.Guild{}.Mixin()
guildMixinFields0 := guildMixin[0].Fields()
guildFields := schema.Guild{}.Fields()
_ = guildFields
// guildDescCreateTime is the schema descriptor for create_time field.
guildDescCreateTime := guildMixinFields0[0].Descriptor()
// guild.DefaultCreateTime holds the default value on creation for the create_time field.
guild.DefaultCreateTime = guildDescCreateTime.Default.(func() time.Time)
// guildDescUpdateTime is the schema descriptor for update_time field.
guildDescUpdateTime := guildMixinFields0[1].Descriptor()
// guild.DefaultUpdateTime holds the default value on creation for the update_time field.
guild.DefaultUpdateTime = guildDescUpdateTime.Default.(func() time.Time)
// guild.UpdateDefaultUpdateTime holds the default value on update for the update_time field.
guild.UpdateDefaultUpdateTime = guildDescUpdateTime.UpdateDefault.(func() time.Time)
sessionMixin := schema.Session{}.Mixin()
sessionMixinFields0 := sessionMixin[0].Fields()
sessionFields := schema.Session{}.Fields()
_ = sessionFields
// sessionDescCreateTime is the schema descriptor for create_time field.
sessionDescCreateTime := sessionMixinFields0[0].Descriptor()
// session.DefaultCreateTime holds the default value on creation for the create_time field.
session.DefaultCreateTime = sessionDescCreateTime.Default.(func() time.Time)
// sessionDescUpdateTime is the schema descriptor for update_time field.
sessionDescUpdateTime := sessionMixinFields0[1].Descriptor()
// session.DefaultUpdateTime holds the default value on creation for the update_time field.
session.DefaultUpdateTime = sessionDescUpdateTime.Default.(func() time.Time)
// session.UpdateDefaultUpdateTime holds the default value on update for the update_time field.
session.UpdateDefaultUpdateTime = sessionDescUpdateTime.UpdateDefault.(func() time.Time)
// sessionDescExpiresAt is the schema descriptor for expires_at field.
sessionDescExpiresAt := sessionFields[3].Descriptor()
// session.DefaultExpiresAt holds the default value on creation for the expires_at field.
session.DefaultExpiresAt = sessionDescExpiresAt.Default.(func() time.Time)
}

View file

@ -1,8 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "runtime",
srcs = ["runtime.go"],
importpath = "github.com/roleypoly/roleypoly/src/db/ent/runtime",
visibility = ["//visibility:public"],
)

View file

@ -1,10 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package runtime
// The schema-stitching logic is generated in github.com/roleypoly/roleypoly/src/db/ent/runtime.go
const (
Version = "v0.4.3" // Version of ent codegen.
Sum = "h1:ds9HENceKzpGBgCRlkZNq6TqBIegwKcF3e5reuV9Z0M=" // Sum of ent codegen.
)

View file

@ -1,17 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "schema",
srcs = [
"challenge.go",
"guild.go",
"session.go",
],
importpath = "github.com/roleypoly/roleypoly/src/db/ent/schema",
visibility = ["//visibility:public"],
deps = [
"@com_github_facebook_ent//:ent",
"@com_github_facebook_ent//schema/field",
"@com_github_facebook_ent//schema/mixin",
],
)

View file

@ -1,46 +0,0 @@
package schema
import (
"time"
"github.com/facebook/ent"
"github.com/facebook/ent/schema/field"
"github.com/facebook/ent/schema/mixin"
)
// Challenge holds the schema definition for the Challenge entity.
type Challenge struct {
ent.Schema
}
// Fields of the Challenge.
func (Challenge) Fields() []ent.Field {
return []ent.Field{
field.Text("challenge_id").
Immutable().Unique(),
field.Text("user_id").
Immutable().Unique(),
field.String("human").Immutable().Unique(),
field.String("magic").Immutable().Unique(),
field.Time("expires_at").
Immutable().
Default(func() time.Time {
return time.Now().Add(5 * time.Minute)
}),
}
}
// Edges of the Challenge.
func (Challenge) Edges() []ent.Edge {
return nil
}
// Mixin of the Challenge.
func (Challenge) Mixin() []ent.Mixin {
return []ent.Mixin{
mixin.Time{},
}
}

View file

@ -1,44 +0,0 @@
package schema
import (
"github.com/facebook/ent"
"github.com/facebook/ent/schema/field"
"github.com/facebook/ent/schema/mixin"
)
// Guild holds the schema definition for the Guild entity.
type Guild struct {
ent.Schema
}
type Category struct {
ID string
Name string
Hidden bool
Type string
Position int
Roles []string
}
// Fields of the Guild.
func (Guild) Fields() []ent.Field {
return []ent.Field{
field.Text("snowflake").
Immutable().Unique(),
field.Text("message"),
field.JSON("categories", []Category{}),
field.Strings("entitlements"),
}
}
// Edges of the Guild.
func (Guild) Edges() []ent.Edge {
return nil
}
// Mixin of the Guild.
func (Guild) Mixin() []ent.Mixin {
return []ent.Mixin{
mixin.Time{},
}
}

View file

@ -1,47 +0,0 @@
package schema
import (
"time"
"github.com/facebook/ent"
"github.com/facebook/ent/schema/field"
"github.com/facebook/ent/schema/mixin"
)
// Session holds the schema definition for the Session entity.
type Session struct {
ent.Schema
}
// Fields of the Session.
func (Session) Fields() []ent.Field {
return []ent.Field{
field.Text("session_id").
Immutable().Unique(),
field.Text("user_id").
Immutable().Unique(),
field.Enum("source").
Values("oauth", "dm").
Immutable(),
field.Time("expires_at").
Immutable().
Default(func() time.Time {
return time.Now().Add(6 * time.Hour)
}),
}
}
// Edges of the Session.
func (Session) Edges() []ent.Edge {
return nil
}
// Mixin of the Session.
func (Session) Mixin() []ent.Mixin {
return []ent.Mixin{
mixin.Time{},
}
}

View file

@ -1,137 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"time"
"github.com/facebook/ent/dialect/sql"
"github.com/roleypoly/roleypoly/src/db/ent/session"
)
// Session is the model entity for the Session schema.
type Session struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// CreateTime holds the value of the "create_time" field.
CreateTime time.Time `json:"create_time,omitempty"`
// UpdateTime holds the value of the "update_time" field.
UpdateTime time.Time `json:"update_time,omitempty"`
// SessionID holds the value of the "session_id" field.
SessionID string `json:"session_id,omitempty"`
// UserID holds the value of the "user_id" field.
UserID string `json:"user_id,omitempty"`
// Source holds the value of the "source" field.
Source session.Source `json:"source,omitempty"`
// ExpiresAt holds the value of the "expires_at" field.
ExpiresAt time.Time `json:"expires_at,omitempty"`
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Session) scanValues() []interface{} {
return []interface{}{
&sql.NullInt64{}, // id
&sql.NullTime{}, // create_time
&sql.NullTime{}, // update_time
&sql.NullString{}, // session_id
&sql.NullString{}, // user_id
&sql.NullString{}, // source
&sql.NullTime{}, // expires_at
}
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Session fields.
func (s *Session) assignValues(values ...interface{}) error {
if m, n := len(values), len(session.Columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
value, ok := values[0].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
s.ID = int(value.Int64)
values = values[1:]
if value, ok := values[0].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field create_time", values[0])
} else if value.Valid {
s.CreateTime = value.Time
}
if value, ok := values[1].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field update_time", values[1])
} else if value.Valid {
s.UpdateTime = value.Time
}
if value, ok := values[2].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field session_id", values[2])
} else if value.Valid {
s.SessionID = value.String
}
if value, ok := values[3].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field user_id", values[3])
} else if value.Valid {
s.UserID = value.String
}
if value, ok := values[4].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field source", values[4])
} else if value.Valid {
s.Source = session.Source(value.String)
}
if value, ok := values[5].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field expires_at", values[5])
} else if value.Valid {
s.ExpiresAt = value.Time
}
return nil
}
// Update returns a builder for updating this Session.
// Note that, you need to call Session.Unwrap() before calling this method, if this Session
// was returned from a transaction, and the transaction was committed or rolled back.
func (s *Session) Update() *SessionUpdateOne {
return (&SessionClient{config: s.config}).UpdateOne(s)
}
// Unwrap unwraps the entity that was returned from a transaction after it was closed,
// so that all next queries will be executed through the driver which created the transaction.
func (s *Session) Unwrap() *Session {
tx, ok := s.config.driver.(*txDriver)
if !ok {
panic("ent: Session is not a transactional entity")
}
s.config.driver = tx.drv
return s
}
// String implements the fmt.Stringer.
func (s *Session) String() string {
var builder strings.Builder
builder.WriteString("Session(")
builder.WriteString(fmt.Sprintf("id=%v", s.ID))
builder.WriteString(", create_time=")
builder.WriteString(s.CreateTime.Format(time.ANSIC))
builder.WriteString(", update_time=")
builder.WriteString(s.UpdateTime.Format(time.ANSIC))
builder.WriteString(", session_id=")
builder.WriteString(s.SessionID)
builder.WriteString(", user_id=")
builder.WriteString(s.UserID)
builder.WriteString(", source=")
builder.WriteString(fmt.Sprintf("%v", s.Source))
builder.WriteString(", expires_at=")
builder.WriteString(s.ExpiresAt.Format(time.ANSIC))
builder.WriteByte(')')
return builder.String()
}
// Sessions is a parsable slice of Session.
type Sessions []*Session
func (s Sessions) config(cfg config) {
for _i := range s {
s[_i].config = cfg
}
}

View file

@ -1,15 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "session",
srcs = [
"session.go",
"where.go",
],
importpath = "github.com/roleypoly/roleypoly/src/db/ent/session",
visibility = ["//visibility:public"],
deps = [
"//src/db/ent/predicate",
"@com_github_facebook_ent//dialect/sql",
],
)

View file

@ -1,85 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package session
import (
"fmt"
"time"
)
const (
// Label holds the string label denoting the session type in the database.
Label = "session"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldCreateTime holds the string denoting the create_time field in the database.
FieldCreateTime = "create_time"
// FieldUpdateTime holds the string denoting the update_time field in the database.
FieldUpdateTime = "update_time"
// FieldSessionID holds the string denoting the session_id field in the database.
FieldSessionID = "session_id"
// FieldUserID holds the string denoting the user_id field in the database.
FieldUserID = "user_id"
// FieldSource holds the string denoting the source field in the database.
FieldSource = "source"
// FieldExpiresAt holds the string denoting the expires_at field in the database.
FieldExpiresAt = "expires_at"
// Table holds the table name of the session in the database.
Table = "sessions"
)
// Columns holds all SQL columns for session fields.
var Columns = []string{
FieldID,
FieldCreateTime,
FieldUpdateTime,
FieldSessionID,
FieldUserID,
FieldSource,
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
// DefaultUpdateTime holds the default value on creation for the update_time field.
DefaultUpdateTime func() time.Time
// UpdateDefaultUpdateTime holds the default value on update for the update_time field.
UpdateDefaultUpdateTime func() time.Time
// DefaultExpiresAt holds the default value on creation for the expires_at field.
DefaultExpiresAt func() time.Time
)
// Source defines the type for the source enum field.
type Source string
// Source values.
const (
SourceOauth Source = "oauth"
SourceDm Source = "dm"
)
func (s Source) String() string {
return string(s)
}
// SourceValidator is a validator for the "source" field enum values. It is called by the builders before save.
func SourceValidator(s Source) error {
switch s {
case SourceOauth, SourceDm:
return nil
default:
return fmt.Errorf("session: invalid enum value for source field: %q", s)
}
}

View file

@ -1,658 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package session
import (
"time"
"github.com/facebook/ent/dialect/sql"
"github.com/roleypoly/roleypoly/src/db/ent/predicate"
)
// ID filters vertices based on their identifier.
func ID(id int) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldID), id))
})
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.In(s.C(FieldID), v...))
})
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.NotIn(s.C(FieldID), v...))
})
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldID), id))
})
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldID), id))
})
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldID), id))
})
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldID), id))
})
}
// CreateTime applies equality check predicate on the "create_time" field. It's identical to CreateTimeEQ.
func CreateTime(v time.Time) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldCreateTime), v))
})
}
// UpdateTime applies equality check predicate on the "update_time" field. It's identical to UpdateTimeEQ.
func UpdateTime(v time.Time) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdateTime), v))
})
}
// SessionID applies equality check predicate on the "session_id" field. It's identical to SessionIDEQ.
func SessionID(v string) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldSessionID), v))
})
}
// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
func UserID(v string) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUserID), v))
})
}
// ExpiresAt applies equality check predicate on the "expires_at" field. It's identical to ExpiresAtEQ.
func ExpiresAt(v time.Time) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldExpiresAt), v))
})
}
// CreateTimeEQ applies the EQ predicate on the "create_time" field.
func CreateTimeEQ(v time.Time) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldCreateTime), v))
})
}
// CreateTimeNEQ applies the NEQ predicate on the "create_time" field.
func CreateTimeNEQ(v time.Time) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldCreateTime), v))
})
}
// CreateTimeIn applies the In predicate on the "create_time" field.
func CreateTimeIn(vs ...time.Time) predicate.Session {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Session(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldCreateTime), v...))
})
}
// CreateTimeNotIn applies the NotIn predicate on the "create_time" field.
func CreateTimeNotIn(vs ...time.Time) predicate.Session {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Session(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldCreateTime), v...))
})
}
// CreateTimeGT applies the GT predicate on the "create_time" field.
func CreateTimeGT(v time.Time) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldCreateTime), v))
})
}
// CreateTimeGTE applies the GTE predicate on the "create_time" field.
func CreateTimeGTE(v time.Time) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldCreateTime), v))
})
}
// CreateTimeLT applies the LT predicate on the "create_time" field.
func CreateTimeLT(v time.Time) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldCreateTime), v))
})
}
// CreateTimeLTE applies the LTE predicate on the "create_time" field.
func CreateTimeLTE(v time.Time) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldCreateTime), v))
})
}
// UpdateTimeEQ applies the EQ predicate on the "update_time" field.
func UpdateTimeEQ(v time.Time) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdateTime), v))
})
}
// UpdateTimeNEQ applies the NEQ predicate on the "update_time" field.
func UpdateTimeNEQ(v time.Time) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldUpdateTime), v))
})
}
// UpdateTimeIn applies the In predicate on the "update_time" field.
func UpdateTimeIn(vs ...time.Time) predicate.Session {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Session(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldUpdateTime), v...))
})
}
// UpdateTimeNotIn applies the NotIn predicate on the "update_time" field.
func UpdateTimeNotIn(vs ...time.Time) predicate.Session {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Session(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldUpdateTime), v...))
})
}
// UpdateTimeGT applies the GT predicate on the "update_time" field.
func UpdateTimeGT(v time.Time) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldUpdateTime), v))
})
}
// UpdateTimeGTE applies the GTE predicate on the "update_time" field.
func UpdateTimeGTE(v time.Time) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldUpdateTime), v))
})
}
// UpdateTimeLT applies the LT predicate on the "update_time" field.
func UpdateTimeLT(v time.Time) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldUpdateTime), v))
})
}
// UpdateTimeLTE applies the LTE predicate on the "update_time" field.
func UpdateTimeLTE(v time.Time) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUpdateTime), v))
})
}
// SessionIDEQ applies the EQ predicate on the "session_id" field.
func SessionIDEQ(v string) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldSessionID), v))
})
}
// SessionIDNEQ applies the NEQ predicate on the "session_id" field.
func SessionIDNEQ(v string) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldSessionID), v))
})
}
// SessionIDIn applies the In predicate on the "session_id" field.
func SessionIDIn(vs ...string) predicate.Session {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Session(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldSessionID), v...))
})
}
// SessionIDNotIn applies the NotIn predicate on the "session_id" field.
func SessionIDNotIn(vs ...string) predicate.Session {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Session(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldSessionID), v...))
})
}
// SessionIDGT applies the GT predicate on the "session_id" field.
func SessionIDGT(v string) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldSessionID), v))
})
}
// SessionIDGTE applies the GTE predicate on the "session_id" field.
func SessionIDGTE(v string) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldSessionID), v))
})
}
// SessionIDLT applies the LT predicate on the "session_id" field.
func SessionIDLT(v string) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldSessionID), v))
})
}
// SessionIDLTE applies the LTE predicate on the "session_id" field.
func SessionIDLTE(v string) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldSessionID), v))
})
}
// SessionIDContains applies the Contains predicate on the "session_id" field.
func SessionIDContains(v string) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldSessionID), v))
})
}
// SessionIDHasPrefix applies the HasPrefix predicate on the "session_id" field.
func SessionIDHasPrefix(v string) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldSessionID), v))
})
}
// SessionIDHasSuffix applies the HasSuffix predicate on the "session_id" field.
func SessionIDHasSuffix(v string) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldSessionID), v))
})
}
// SessionIDEqualFold applies the EqualFold predicate on the "session_id" field.
func SessionIDEqualFold(v string) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldSessionID), v))
})
}
// SessionIDContainsFold applies the ContainsFold predicate on the "session_id" field.
func SessionIDContainsFold(v string) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldSessionID), v))
})
}
// UserIDEQ applies the EQ predicate on the "user_id" field.
func UserIDEQ(v string) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUserID), v))
})
}
// UserIDNEQ applies the NEQ predicate on the "user_id" field.
func UserIDNEQ(v string) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldUserID), v))
})
}
// UserIDIn applies the In predicate on the "user_id" field.
func UserIDIn(vs ...string) predicate.Session {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Session(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldUserID), v...))
})
}
// UserIDNotIn applies the NotIn predicate on the "user_id" field.
func UserIDNotIn(vs ...string) predicate.Session {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Session(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldUserID), v...))
})
}
// UserIDGT applies the GT predicate on the "user_id" field.
func UserIDGT(v string) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldUserID), v))
})
}
// UserIDGTE applies the GTE predicate on the "user_id" field.
func UserIDGTE(v string) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldUserID), v))
})
}
// UserIDLT applies the LT predicate on the "user_id" field.
func UserIDLT(v string) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldUserID), v))
})
}
// UserIDLTE applies the LTE predicate on the "user_id" field.
func UserIDLTE(v string) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUserID), v))
})
}
// UserIDContains applies the Contains predicate on the "user_id" field.
func UserIDContains(v string) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldUserID), v))
})
}
// UserIDHasPrefix applies the HasPrefix predicate on the "user_id" field.
func UserIDHasPrefix(v string) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldUserID), v))
})
}
// UserIDHasSuffix applies the HasSuffix predicate on the "user_id" field.
func UserIDHasSuffix(v string) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldUserID), v))
})
}
// UserIDEqualFold applies the EqualFold predicate on the "user_id" field.
func UserIDEqualFold(v string) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldUserID), v))
})
}
// UserIDContainsFold applies the ContainsFold predicate on the "user_id" field.
func UserIDContainsFold(v string) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldUserID), v))
})
}
// SourceEQ applies the EQ predicate on the "source" field.
func SourceEQ(v Source) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldSource), v))
})
}
// SourceNEQ applies the NEQ predicate on the "source" field.
func SourceNEQ(v Source) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldSource), v))
})
}
// SourceIn applies the In predicate on the "source" field.
func SourceIn(vs ...Source) predicate.Session {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Session(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldSource), v...))
})
}
// SourceNotIn applies the NotIn predicate on the "source" field.
func SourceNotIn(vs ...Source) predicate.Session {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Session(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldSource), v...))
})
}
// ExpiresAtEQ applies the EQ predicate on the "expires_at" field.
func ExpiresAtEQ(v time.Time) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtNEQ applies the NEQ predicate on the "expires_at" field.
func ExpiresAtNEQ(v time.Time) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtIn applies the In predicate on the "expires_at" field.
func ExpiresAtIn(vs ...time.Time) predicate.Session {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Session(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldExpiresAt), v...))
})
}
// ExpiresAtNotIn applies the NotIn predicate on the "expires_at" field.
func ExpiresAtNotIn(vs ...time.Time) predicate.Session {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Session(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldExpiresAt), v...))
})
}
// ExpiresAtGT applies the GT predicate on the "expires_at" field.
func ExpiresAtGT(v time.Time) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtGTE applies the GTE predicate on the "expires_at" field.
func ExpiresAtGTE(v time.Time) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtLT applies the LT predicate on the "expires_at" field.
func ExpiresAtLT(v time.Time) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtLTE applies the LTE predicate on the "expires_at" field.
func ExpiresAtLTE(v time.Time) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldExpiresAt), v))
})
}
// And groups list of predicates with the AND operator between them.
func And(predicates ...predicate.Session) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for _, p := range predicates {
p(s1)
}
s.Where(s1.P())
})
}
// Or groups list of predicates with the OR operator between them.
func Or(predicates ...predicate.Session) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for i, p := range predicates {
if i > 0 {
s1.Or()
}
p(s1)
}
s.Where(s1.P())
})
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Session) predicate.Session {
return predicate.Session(func(s *sql.Selector) {
p(s.Not())
})
}

View file

@ -1,317 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"github.com/facebook/ent/dialect/sql/sqlgraph"
"github.com/facebook/ent/schema/field"
"github.com/roleypoly/roleypoly/src/db/ent/session"
)
// SessionCreate is the builder for creating a Session entity.
type SessionCreate struct {
config
mutation *SessionMutation
hooks []Hook
}
// SetCreateTime sets the create_time field.
func (sc *SessionCreate) SetCreateTime(t time.Time) *SessionCreate {
sc.mutation.SetCreateTime(t)
return sc
}
// SetNillableCreateTime sets the create_time field if the given value is not nil.
func (sc *SessionCreate) SetNillableCreateTime(t *time.Time) *SessionCreate {
if t != nil {
sc.SetCreateTime(*t)
}
return sc
}
// SetUpdateTime sets the update_time field.
func (sc *SessionCreate) SetUpdateTime(t time.Time) *SessionCreate {
sc.mutation.SetUpdateTime(t)
return sc
}
// SetNillableUpdateTime sets the update_time field if the given value is not nil.
func (sc *SessionCreate) SetNillableUpdateTime(t *time.Time) *SessionCreate {
if t != nil {
sc.SetUpdateTime(*t)
}
return sc
}
// SetSessionID sets the session_id field.
func (sc *SessionCreate) SetSessionID(s string) *SessionCreate {
sc.mutation.SetSessionID(s)
return sc
}
// SetUserID sets the user_id field.
func (sc *SessionCreate) SetUserID(s string) *SessionCreate {
sc.mutation.SetUserID(s)
return sc
}
// SetSource sets the source field.
func (sc *SessionCreate) SetSource(s session.Source) *SessionCreate {
sc.mutation.SetSource(s)
return sc
}
// SetExpiresAt sets the expires_at field.
func (sc *SessionCreate) SetExpiresAt(t time.Time) *SessionCreate {
sc.mutation.SetExpiresAt(t)
return sc
}
// SetNillableExpiresAt sets the expires_at field if the given value is not nil.
func (sc *SessionCreate) SetNillableExpiresAt(t *time.Time) *SessionCreate {
if t != nil {
sc.SetExpiresAt(*t)
}
return sc
}
// Mutation returns the SessionMutation object of the builder.
func (sc *SessionCreate) Mutation() *SessionMutation {
return sc.mutation
}
// Save creates the Session in the database.
func (sc *SessionCreate) Save(ctx context.Context) (*Session, error) {
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) {
mutation, ok := m.(*SessionMutation)
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
return node, err
})
for i := len(sc.hooks) - 1; i >= 0; i-- {
mut = sc.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, sc.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (sc *SessionCreate) SaveX(ctx context.Context) *Session {
v, err := sc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// 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)
}
if _, ok := sc.mutation.UpdateTime(); !ok {
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\"")}
}
if _, ok := sc.mutation.UserID(); !ok {
return &ValidationError{Name: "user_id", err: errors.New("ent: missing required field \"user_id\"")}
}
if _, ok := sc.mutation.Source(); !ok {
return &ValidationError{Name: "source", err: errors.New("ent: missing required field \"source\"")}
}
if v, ok := sc.mutation.Source(); ok {
if err := session.SourceValidator(v); err != nil {
return &ValidationError{Name: "source", err: fmt.Errorf("ent: validator failed for field \"source\": %w", err)}
}
}
if _, ok := sc.mutation.ExpiresAt(); !ok {
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) {
_node, _spec := sc.createSpec()
if err := sqlgraph.CreateNode(ctx, sc.driver, _spec); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
return _node, nil
}
func (sc *SessionCreate) createSpec() (*Session, *sqlgraph.CreateSpec) {
var (
_node = &Session{config: sc.config}
_spec = &sqlgraph.CreateSpec{
Table: session.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: session.FieldID,
},
}
)
if value, ok := sc.mutation.CreateTime(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: session.FieldCreateTime,
})
_node.CreateTime = value
}
if value, ok := sc.mutation.UpdateTime(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: session.FieldUpdateTime,
})
_node.UpdateTime = value
}
if value, ok := sc.mutation.SessionID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: session.FieldSessionID,
})
_node.SessionID = value
}
if value, ok := sc.mutation.UserID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: session.FieldUserID,
})
_node.UserID = value
}
if value, ok := sc.mutation.Source(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeEnum,
Value: value,
Column: session.FieldSource,
})
_node.Source = value
}
if value, ok := sc.mutation.ExpiresAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: session.FieldExpiresAt,
})
_node.ExpiresAt = value
}
return _node, _spec
}
// SessionCreateBulk is the builder for creating a bulk of Session entities.
type SessionCreateBulk struct {
config
builders []*SessionCreate
}
// Save creates the Session entities in the database.
func (scb *SessionCreateBulk) Save(ctx context.Context) ([]*Session, error) {
specs := make([]*sqlgraph.CreateSpec, len(scb.builders))
nodes := make([]*Session, len(scb.builders))
mutators := make([]Mutator, len(scb.builders))
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) {
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
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, scb.builders[i+1].mutation)
} else {
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, scb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
}
}
mutation.done = true
if err != nil {
return nil, err
}
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, scb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX calls Save and panics if Save returns an error.
func (scb *SessionCreateBulk) SaveX(ctx context.Context) []*Session {
v, err := scb.Save(ctx)
if err != nil {
panic(err)
}
return v
}

View file

@ -1,109 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"github.com/facebook/ent/dialect/sql"
"github.com/facebook/ent/dialect/sql/sqlgraph"
"github.com/facebook/ent/schema/field"
"github.com/roleypoly/roleypoly/src/db/ent/predicate"
"github.com/roleypoly/roleypoly/src/db/ent/session"
)
// SessionDelete is the builder for deleting a Session entity.
type SessionDelete struct {
config
hooks []Hook
mutation *SessionMutation
predicates []predicate.Session
}
// Where adds a new predicate to the delete builder.
func (sd *SessionDelete) Where(ps ...predicate.Session) *SessionDelete {
sd.predicates = append(sd.predicates, ps...)
return sd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (sd *SessionDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(sd.hooks) == 0 {
affected, err = sd.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*SessionMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
sd.mutation = mutation
affected, err = sd.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(sd.hooks) - 1; i >= 0; i-- {
mut = sd.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, sd.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (sd *SessionDelete) ExecX(ctx context.Context) int {
n, err := sd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (sd *SessionDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: session.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: session.FieldID,
},
},
}
if ps := sd.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return sqlgraph.DeleteNodes(ctx, sd.driver, _spec)
}
// SessionDeleteOne is the builder for deleting a single Session entity.
type SessionDeleteOne struct {
sd *SessionDelete
}
// Exec executes the deletion query.
func (sdo *SessionDeleteOne) Exec(ctx context.Context) error {
n, err := sdo.sd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{session.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (sdo *SessionDeleteOne) ExecX(ctx context.Context) {
sdo.sd.ExecX(ctx)
}

View file

@ -1,880 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"math"
"github.com/facebook/ent/dialect/sql"
"github.com/facebook/ent/dialect/sql/sqlgraph"
"github.com/facebook/ent/schema/field"
"github.com/roleypoly/roleypoly/src/db/ent/predicate"
"github.com/roleypoly/roleypoly/src/db/ent/session"
)
// SessionQuery is the builder for querying Session entities.
type SessionQuery struct {
config
limit *int
offset *int
order []OrderFunc
unique []string
predicates []predicate.Session
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the builder.
func (sq *SessionQuery) Where(ps ...predicate.Session) *SessionQuery {
sq.predicates = append(sq.predicates, ps...)
return sq
}
// Limit adds a limit step to the query.
func (sq *SessionQuery) Limit(limit int) *SessionQuery {
sq.limit = &limit
return sq
}
// Offset adds an offset step to the query.
func (sq *SessionQuery) Offset(offset int) *SessionQuery {
sq.offset = &offset
return sq
}
// Order adds an order step to the query.
func (sq *SessionQuery) Order(o ...OrderFunc) *SessionQuery {
sq.order = append(sq.order, o...)
return sq
}
// 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) {
nodes, err := sq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{session.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (sq *SessionQuery) FirstX(ctx context.Context) *Session {
node, err := sq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Session id in the query. Returns *NotFoundError when no id was found.
func (sq *SessionQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = sq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{session.Label}
return
}
return ids[0], nil
}
// FirstXID is like FirstID, but panics if an error occurs.
func (sq *SessionQuery) FirstXID(ctx context.Context) int {
id, err := sq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// 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) {
nodes, err := sq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{session.Label}
default:
return nil, &NotSingularError{session.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (sq *SessionQuery) OnlyX(ctx context.Context) *Session {
node, err := sq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID returns the only Session id in the query, returns an error if not exactly one id was returned.
func (sq *SessionQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = sq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{session.Label}
default:
err = &NotSingularError{session.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (sq *SessionQuery) OnlyIDX(ctx context.Context) int {
id, err := sq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Sessions.
func (sq *SessionQuery) All(ctx context.Context) ([]*Session, error) {
if err := sq.prepareQuery(ctx); err != nil {
return nil, err
}
return sq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (sq *SessionQuery) AllX(ctx context.Context) []*Session {
nodes, err := sq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Session ids.
func (sq *SessionQuery) IDs(ctx context.Context) ([]int, error) {
var ids []int
if err := sq.Select(session.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (sq *SessionQuery) IDsX(ctx context.Context) []int {
ids, err := sq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (sq *SessionQuery) Count(ctx context.Context) (int, error) {
if err := sq.prepareQuery(ctx); err != nil {
return 0, err
}
return sq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (sq *SessionQuery) CountX(ctx context.Context) int {
count, err := sq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (sq *SessionQuery) Exist(ctx context.Context) (bool, error) {
if err := sq.prepareQuery(ctx); err != nil {
return false, err
}
return sq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (sq *SessionQuery) ExistX(ctx context.Context) bool {
exist, err := sq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the query builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (sq *SessionQuery) Clone() *SessionQuery {
return &SessionQuery{
config: sq.config,
limit: sq.limit,
offset: sq.offset,
order: append([]OrderFunc{}, sq.order...),
unique: append([]string{}, sq.unique...),
predicates: append([]predicate.Session{}, sq.predicates...),
// clone intermediate query.
sql: sq.sql.Clone(),
path: sq.path,
}
}
// GroupBy used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// CreateTime time.Time `json:"create_time,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Session.Query().
// GroupBy(session.FieldCreateTime).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
//
func (sq *SessionQuery) GroupBy(field string, fields ...string) *SessionGroupBy {
group := &SessionGroupBy{config: sq.config}
group.fields = append([]string{field}, fields...)
group.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := sq.prepareQuery(ctx); err != nil {
return nil, err
}
return sq.sqlQuery(), nil
}
return group
}
// Select one or more fields from the given query.
//
// Example:
//
// var v []struct {
// CreateTime time.Time `json:"create_time,omitempty"`
// }
//
// client.Session.Query().
// Select(session.FieldCreateTime).
// Scan(ctx, &v)
//
func (sq *SessionQuery) Select(field string, fields ...string) *SessionSelect {
selector := &SessionSelect{config: sq.config}
selector.fields = append([]string{field}, fields...)
selector.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := sq.prepareQuery(ctx); err != nil {
return nil, err
}
return sq.sqlQuery(), nil
}
return selector
}
func (sq *SessionQuery) prepareQuery(ctx context.Context) error {
if sq.path != nil {
prev, err := sq.path(ctx)
if err != nil {
return err
}
sq.sql = prev
}
return nil
}
func (sq *SessionQuery) sqlAll(ctx context.Context) ([]*Session, error) {
var (
nodes = []*Session{}
_spec = sq.querySpec()
)
_spec.ScanValues = func() []interface{} {
node := &Session{config: sq.config}
nodes = append(nodes, node)
values := node.scanValues()
return values
}
_spec.Assign = func(values ...interface{}) error {
if len(nodes) == 0 {
return fmt.Errorf("ent: Assign called without calling ScanValues")
}
node := nodes[len(nodes)-1]
return node.assignValues(values...)
}
if err := sqlgraph.QueryNodes(ctx, sq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (sq *SessionQuery) sqlCount(ctx context.Context) (int, error) {
_spec := sq.querySpec()
return sqlgraph.CountNodes(ctx, sq.driver, _spec)
}
func (sq *SessionQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := sq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("ent: check existence: %v", err)
}
return n > 0, nil
}
func (sq *SessionQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: session.Table,
Columns: session.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: session.FieldID,
},
},
From: sq.sql,
Unique: true,
}
if ps := sq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := sq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := sq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := sq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector, session.ValidColumn)
}
}
}
return _spec
}
func (sq *SessionQuery) sqlQuery() *sql.Selector {
builder := sql.Dialect(sq.driver.Dialect())
t1 := builder.Table(session.Table)
selector := builder.Select(t1.Columns(session.Columns...)...).From(t1)
if sq.sql != nil {
selector = sq.sql
selector.Select(selector.Columns(session.Columns...)...)
}
for _, p := range sq.predicates {
p(selector)
}
for _, p := range sq.order {
p(selector, session.ValidColumn)
}
if offset := sq.offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := sq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// SessionGroupBy is the builder for group-by Session entities.
type SessionGroupBy struct {
config
fields []string
fns []AggregateFunc
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Aggregate adds the given aggregation functions to the group-by query.
func (sgb *SessionGroupBy) Aggregate(fns ...AggregateFunc) *SessionGroupBy {
sgb.fns = append(sgb.fns, fns...)
return sgb
}
// Scan applies the group-by query and scan the result into the given value.
func (sgb *SessionGroupBy) Scan(ctx context.Context, v interface{}) error {
query, err := sgb.path(ctx)
if err != nil {
return err
}
sgb.sql = query
return sgb.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (sgb *SessionGroupBy) ScanX(ctx context.Context, v interface{}) {
if err := sgb.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from group-by. It is only allowed when querying group-by with one field.
func (sgb *SessionGroupBy) Strings(ctx context.Context) ([]string, error) {
if len(sgb.fields) > 1 {
return nil, errors.New("ent: SessionGroupBy.Strings is not achievable when grouping more than 1 field")
}
var v []string
if err := sgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (sgb *SessionGroupBy) StringsX(ctx context.Context) []string {
v, err := sgb.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from group-by. It is only allowed when querying group-by with one field.
func (sgb *SessionGroupBy) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = sgb.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{session.Label}
default:
err = fmt.Errorf("ent: SessionGroupBy.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (sgb *SessionGroupBy) StringX(ctx context.Context) string {
v, err := sgb.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from group-by. It is only allowed when querying group-by with one field.
func (sgb *SessionGroupBy) Ints(ctx context.Context) ([]int, error) {
if len(sgb.fields) > 1 {
return nil, errors.New("ent: SessionGroupBy.Ints is not achievable when grouping more than 1 field")
}
var v []int
if err := sgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (sgb *SessionGroupBy) IntsX(ctx context.Context) []int {
v, err := sgb.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from group-by. It is only allowed when querying group-by with one field.
func (sgb *SessionGroupBy) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = sgb.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{session.Label}
default:
err = fmt.Errorf("ent: SessionGroupBy.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (sgb *SessionGroupBy) IntX(ctx context.Context) int {
v, err := sgb.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from group-by. It is only allowed when querying group-by with one field.
func (sgb *SessionGroupBy) Float64s(ctx context.Context) ([]float64, error) {
if len(sgb.fields) > 1 {
return nil, errors.New("ent: SessionGroupBy.Float64s is not achievable when grouping more than 1 field")
}
var v []float64
if err := sgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (sgb *SessionGroupBy) Float64sX(ctx context.Context) []float64 {
v, err := sgb.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from group-by. It is only allowed when querying group-by with one field.
func (sgb *SessionGroupBy) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = sgb.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{session.Label}
default:
err = fmt.Errorf("ent: SessionGroupBy.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (sgb *SessionGroupBy) Float64X(ctx context.Context) float64 {
v, err := sgb.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from group-by. It is only allowed when querying group-by with one field.
func (sgb *SessionGroupBy) Bools(ctx context.Context) ([]bool, error) {
if len(sgb.fields) > 1 {
return nil, errors.New("ent: SessionGroupBy.Bools is not achievable when grouping more than 1 field")
}
var v []bool
if err := sgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (sgb *SessionGroupBy) BoolsX(ctx context.Context) []bool {
v, err := sgb.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from group-by. It is only allowed when querying group-by with one field.
func (sgb *SessionGroupBy) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = sgb.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{session.Label}
default:
err = fmt.Errorf("ent: SessionGroupBy.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (sgb *SessionGroupBy) BoolX(ctx context.Context) bool {
v, err := sgb.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
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 := selector.Query()
if err := sgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (sgb *SessionGroupBy) sqlQuery() *sql.Selector {
selector := sgb.sql
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, session.ValidColumn))
}
return selector.Select(columns...).GroupBy(sgb.fields...)
}
// SessionSelect is the builder for select fields of Session entities.
type SessionSelect struct {
config
fields []string
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Scan applies the selector query and scan the result into the given value.
func (ss *SessionSelect) Scan(ctx context.Context, v interface{}) error {
query, err := ss.path(ctx)
if err != nil {
return err
}
ss.sql = query
return ss.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (ss *SessionSelect) ScanX(ctx context.Context, v interface{}) {
if err := ss.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from selector. It is only allowed when selecting one field.
func (ss *SessionSelect) Strings(ctx context.Context) ([]string, error) {
if len(ss.fields) > 1 {
return nil, errors.New("ent: SessionSelect.Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := ss.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (ss *SessionSelect) StringsX(ctx context.Context) []string {
v, err := ss.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from selector. It is only allowed when selecting one field.
func (ss *SessionSelect) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = ss.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{session.Label}
default:
err = fmt.Errorf("ent: SessionSelect.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (ss *SessionSelect) StringX(ctx context.Context) string {
v, err := ss.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from selector. It is only allowed when selecting one field.
func (ss *SessionSelect) Ints(ctx context.Context) ([]int, error) {
if len(ss.fields) > 1 {
return nil, errors.New("ent: SessionSelect.Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := ss.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (ss *SessionSelect) IntsX(ctx context.Context) []int {
v, err := ss.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from selector. It is only allowed when selecting one field.
func (ss *SessionSelect) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = ss.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{session.Label}
default:
err = fmt.Errorf("ent: SessionSelect.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (ss *SessionSelect) IntX(ctx context.Context) int {
v, err := ss.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from selector. It is only allowed when selecting one field.
func (ss *SessionSelect) Float64s(ctx context.Context) ([]float64, error) {
if len(ss.fields) > 1 {
return nil, errors.New("ent: SessionSelect.Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := ss.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (ss *SessionSelect) Float64sX(ctx context.Context) []float64 {
v, err := ss.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from selector. It is only allowed when selecting one field.
func (ss *SessionSelect) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = ss.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{session.Label}
default:
err = fmt.Errorf("ent: SessionSelect.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (ss *SessionSelect) Float64X(ctx context.Context) float64 {
v, err := ss.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from selector. It is only allowed when selecting one field.
func (ss *SessionSelect) Bools(ctx context.Context) ([]bool, error) {
if len(ss.fields) > 1 {
return nil, errors.New("ent: SessionSelect.Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := ss.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (ss *SessionSelect) BoolsX(ctx context.Context) []bool {
v, err := ss.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from selector. It is only allowed when selecting one field.
func (ss *SessionSelect) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = ss.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{session.Label}
default:
err = fmt.Errorf("ent: SessionSelect.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (ss *SessionSelect) BoolX(ctx context.Context) bool {
v, err := ss.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
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 {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (ss *SessionSelect) sqlQuery() sql.Querier {
selector := ss.sql
selector.Select(selector.Columns(ss.fields...)...)
return selector
}

View file

@ -1,238 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"github.com/facebook/ent/dialect/sql"
"github.com/facebook/ent/dialect/sql/sqlgraph"
"github.com/facebook/ent/schema/field"
"github.com/roleypoly/roleypoly/src/db/ent/predicate"
"github.com/roleypoly/roleypoly/src/db/ent/session"
)
// SessionUpdate is the builder for updating Session entities.
type SessionUpdate struct {
config
hooks []Hook
mutation *SessionMutation
predicates []predicate.Session
}
// Where adds a new predicate for the builder.
func (su *SessionUpdate) Where(ps ...predicate.Session) *SessionUpdate {
su.predicates = append(su.predicates, ps...)
return su
}
// Mutation returns the SessionMutation object of the builder.
func (su *SessionUpdate) Mutation() *SessionMutation {
return su.mutation
}
// Save executes the query and returns the number of rows/vertices matched by this operation.
func (su *SessionUpdate) Save(ctx context.Context) (int, error) {
var (
err error
affected int
)
su.defaults()
if len(su.hooks) == 0 {
affected, err = su.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*SessionMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
su.mutation = mutation
affected, err = su.sqlSave(ctx)
mutation.done = true
return affected, err
})
for i := len(su.hooks) - 1; i >= 0; i-- {
mut = su.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, su.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// SaveX is like Save, but panics if an error occurs.
func (su *SessionUpdate) SaveX(ctx context.Context) int {
affected, err := su.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (su *SessionUpdate) Exec(ctx context.Context) error {
_, err := su.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (su *SessionUpdate) ExecX(ctx context.Context) {
if err := su.Exec(ctx); err != nil {
panic(err)
}
}
// 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{
Table: session.Table,
Columns: session.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: session.FieldID,
},
},
}
if ps := su.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := su.mutation.UpdateTime(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: session.FieldUpdateTime,
})
}
if n, err = sqlgraph.UpdateNodes(ctx, su.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{session.Label}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return 0, err
}
return n, nil
}
// SessionUpdateOne is the builder for updating a single Session entity.
type SessionUpdateOne struct {
config
hooks []Hook
mutation *SessionMutation
}
// Mutation returns the SessionMutation object of the builder.
func (suo *SessionUpdateOne) Mutation() *SessionMutation {
return suo.mutation
}
// Save executes the query and returns the updated entity.
func (suo *SessionUpdateOne) Save(ctx context.Context) (*Session, error) {
var (
err error
node *Session
)
suo.defaults()
if len(suo.hooks) == 0 {
node, err = suo.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*SessionMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
suo.mutation = mutation
node, err = suo.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(suo.hooks) - 1; i >= 0; i-- {
mut = suo.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, suo.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX is like Save, but panics if an error occurs.
func (suo *SessionUpdateOne) SaveX(ctx context.Context) *Session {
node, err := suo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (suo *SessionUpdateOne) Exec(ctx context.Context) error {
_, err := suo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (suo *SessionUpdateOne) ExecX(ctx context.Context) {
if err := suo.Exec(ctx); err != nil {
panic(err)
}
}
// 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,
Columns: session.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: session.FieldID,
},
},
}
id, ok := suo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing Session.ID for update")}
}
_spec.Node.ID.Value = id
if value, ok := suo.mutation.UpdateTime(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: session.FieldUpdateTime,
})
}
_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}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
return _node, nil
}

View file

@ -1,216 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"sync"
"github.com/facebook/ent/dialect"
)
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
// Challenge is the client for interacting with the Challenge builders.
Challenge *ChallengeClient
// Guild is the client for interacting with the Guild builders.
Guild *GuildClient
// Session is the client for interacting with the Session builders.
Session *SessionClient
// lazily loaded.
client *Client
clientOnce sync.Once
// completion callbacks.
mu sync.Mutex
onCommit []CommitHook
onRollback []RollbackHook
// ctx lives for the life of the transaction. It is
// the same context used by the underlying connection.
ctx context.Context
}
type (
// Committer is the interface that wraps the Committer method.
Committer interface {
Commit(context.Context, *Tx) error
}
// The CommitFunc type is an adapter to allow the use of ordinary
// function as a Committer. If f is a function with the appropriate
// signature, CommitFunc(f) is a Committer that calls f.
CommitFunc func(context.Context, *Tx) error
// CommitHook defines the "commit middleware". A function that gets a Committer
// and returns a Committer. For example:
//
// hook := func(next ent.Committer) ent.Committer {
// return ent.CommitFunc(func(context.Context, tx *ent.Tx) error {
// // Do some stuff before.
// if err := next.Commit(ctx, tx); err != nil {
// return err
// }
// // Do some stuff after.
// return nil
// })
// }
//
CommitHook func(Committer) Committer
)
// Commit calls f(ctx, m).
func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error {
return f(ctx, tx)
}
// Commit commits the transaction.
func (tx *Tx) Commit() error {
txDriver := tx.config.driver.(*txDriver)
var fn Committer = CommitFunc(func(context.Context, *Tx) error {
return txDriver.tx.Commit()
})
tx.mu.Lock()
hooks := append([]CommitHook(nil), tx.onCommit...)
tx.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
return fn.Commit(tx.ctx, tx)
}
// OnCommit adds a hook to call on commit.
func (tx *Tx) OnCommit(f CommitHook) {
tx.mu.Lock()
defer tx.mu.Unlock()
tx.onCommit = append(tx.onCommit, f)
}
type (
// Rollbacker is the interface that wraps the Rollbacker method.
Rollbacker interface {
Rollback(context.Context, *Tx) error
}
// The RollbackFunc type is an adapter to allow the use of ordinary
// function as a Rollbacker. If f is a function with the appropriate
// signature, RollbackFunc(f) is a Rollbacker that calls f.
RollbackFunc func(context.Context, *Tx) error
// RollbackHook defines the "rollback middleware". A function that gets a Rollbacker
// and returns a Rollbacker. For example:
//
// hook := func(next ent.Rollbacker) ent.Rollbacker {
// return ent.RollbackFunc(func(context.Context, tx *ent.Tx) error {
// // Do some stuff before.
// if err := next.Rollback(ctx, tx); err != nil {
// return err
// }
// // Do some stuff after.
// return nil
// })
// }
//
RollbackHook func(Rollbacker) Rollbacker
)
// Rollback calls f(ctx, m).
func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error {
return f(ctx, tx)
}
// Rollback rollbacks the transaction.
func (tx *Tx) Rollback() error {
txDriver := tx.config.driver.(*txDriver)
var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error {
return txDriver.tx.Rollback()
})
tx.mu.Lock()
hooks := append([]RollbackHook(nil), tx.onRollback...)
tx.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
return fn.Rollback(tx.ctx, tx)
}
// OnRollback adds a hook to call on rollback.
func (tx *Tx) OnRollback(f RollbackHook) {
tx.mu.Lock()
defer tx.mu.Unlock()
tx.onRollback = append(tx.onRollback, f)
}
// Client returns a Client that binds to current transaction.
func (tx *Tx) Client() *Client {
tx.clientOnce.Do(func() {
tx.client = &Client{config: tx.config}
tx.client.init()
})
return tx.client
}
func (tx *Tx) init() {
tx.Challenge = NewChallengeClient(tx.config)
tx.Guild = NewGuildClient(tx.config)
tx.Session = NewSessionClient(tx.config)
}
// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation.
// The idea is to support transactions without adding any extra code to the builders.
// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance.
// Commit and Rollback are nop for the internal builders and the user must call one
// of them in order to commit or rollback the transaction.
//
// If a closed transaction is embedded in one of the generated entities, and the entity
// applies a query, for example: Challenge.QueryXXX(), the query will be executed
// through the driver which created this transaction.
//
// Note that txDriver is not goroutine safe.
type txDriver struct {
// the driver we started the transaction from.
drv dialect.Driver
// tx is the underlying transaction.
tx dialect.Tx
}
// newTx creates a new transactional driver.
func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) {
tx, err := drv.Tx(ctx)
if err != nil {
return nil, err
}
return &txDriver{tx: tx, drv: drv}, nil
}
// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls
// from the internal builders. Should be called only by the internal builders.
func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil }
// Dialect returns the dialect of the driver we started the transaction from.
func (tx *txDriver) Dialect() string { return tx.drv.Dialect() }
// Close is a nop close.
func (*txDriver) Close() error { return nil }
// Commit is a nop commit for the internal builders.
// User must call `Tx.Commit` in order to commit the transaction.
func (*txDriver) Commit() error { return nil }
// Rollback is a nop rollback for the internal builders.
// User must call `Tx.Rollback` in order to rollback the transaction.
func (*txDriver) Rollback() error { return nil }
// Exec calls tx.Exec.
func (tx *txDriver) Exec(ctx context.Context, query string, args, v interface{}) error {
return tx.tx.Exec(ctx, query, args, v)
}
// Query calls tx.Query.
func (tx *txDriver) Query(ctx context.Context, query string, args, v interface{}) error {
return tx.tx.Query(ctx, query, args, v)
}
var _ dialect.Driver = (*txDriver)(nil)

View file

@ -1,11 +1,11 @@
import { Meta } from '@storybook/addon-docs/blocks';
import { Logotype } from 'roleypoly/src/design-system/atoms/branding';
import { Space } from 'roleypoly/src/design-system/atoms/space';
import { palette } from 'roleypoly/src/design-system/atoms/colors';
import { Logotype } from 'roleypoly/design-system/atoms/branding';
import { Space } from 'roleypoly/design-system/atoms/space';
import { palette } from 'roleypoly/design-system/atoms/colors';
<Meta title="Roleypoly Design System" />
<Logotype height="4em" circleFill={palette.taupe100} />
<Logotype height="4em" circleFill={palette.taupe100} circleOuterFill={palette.taupe300} />
<Space />
# Rapid UI

View file

@ -1,5 +1,5 @@
import * as React from 'react';
import { Avatar } from './Avatar';
import { Avatar, AvatarProps } from './Avatar';
export default {
title: 'Atoms/Avatar',
@ -12,18 +12,22 @@ export default {
},
};
export const WithInitials = ({ initials, ...rest }) => (
type StoryArgs = {
initials?: string;
} & AvatarProps;
export const WithInitials = ({ initials, ...rest }: StoryArgs) => (
<Avatar src="https://i.imgur.com/epMSRQH.png" size={48} {...rest}>
{initials}
</Avatar>
);
export const WithText = ({ initials, ...rest }) => (
export const WithText = ({ initials, ...rest }: StoryArgs) => (
<Avatar size={48} {...rest}>
{initials}
</Avatar>
);
export const Empty = (args) => <Avatar size={48} {...args}></Avatar>;
export const DeliberatelyEmpty = (args) => (
export const Empty = (args: StoryArgs) => <Avatar size={48} {...args}></Avatar>;
export const DeliberatelyEmpty = (args: StoryArgs) => (
<Avatar size={48} deliberatelyEmpty={true} {...args}></Avatar>
);

View file

@ -1,7 +1,7 @@
import { AvatarProps } from './Avatar';
import styled, { css } from 'styled-components';
import * as _ from 'styled-components'; // eslint-disable-line no-duplicate-imports
import { palette } from 'roleypoly/src/design-system/atoms/colors';
import { palette } from 'roleypoly/design-system/atoms/colors';
type ContainerProps = Pick<AvatarProps, 'size'> & Pick<AvatarProps, 'deliberatelyEmpty'>;
export const Container = styled.div<ContainerProps>`

View file

@ -1,10 +0,0 @@
load("//hack/bazel/js:react.bzl", "react_library")
package(default_visibility = ["//visibility:public"])
react_library(
name = "avatar",
deps = [
"//src/design-system/atoms/colors",
],
)

View file

@ -5,3 +5,6 @@ export const initialsFromName = (name: string) =>
.map((x) => x[0])
.join('')
.toUpperCase();
export const avatarHash = (id: string, hash: string) =>
`https://cdn.discordapp.com/icons/${id}/${hash}.webp?size=256`;

View file

@ -1,10 +0,0 @@
load("//hack/bazel/js:react.bzl", "react_library")
package(default_visibility = ["//visibility:public"])
react_library(
name = "branding",
deps = [
"//src/design-system/atoms/colors",
],
)

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,59 @@
import * as React from 'react';
import ReactTooltip from 'react-tooltip';
import styled from 'styled-components';
import { AllVariants, DynamicLogomark, DynamicLogotype } from './DynamicBranding';
export default {
title: 'Atoms/Branding/Dynamic',
component: DynamicLogotype,
};
const WrapperDiv = styled.div`
background-color: black;
padding: 2em;
`;
const Wrapper = (props: { children: React.ReactNode }) => (
<>
<WrapperDiv>{props.children}</WrapperDiv>
<ReactTooltip />
</>
);
export const DynamicLogotype_ = (args) => {
return (
<Wrapper>
<DynamicLogotype {...args} />
</Wrapper>
);
};
export const DynamicLogomark_ = (args) => {
return (
<Wrapper>
<DynamicLogomark {...args} />
</Wrapper>
);
};
export const AllCustomizedLogotypes = () => {
return (
<Wrapper>
{AllVariants.map((variant, idx) => (
<div key={idx}>
<variant.Logotype height={50} />
</div>
))}
</Wrapper>
);
};
export const AllCustomizedLogomarks = () => {
return (
<Wrapper>
{AllVariants.map((variant, idx) => (
<variant.Logomark key={idx} height={50} />
))}
</Wrapper>
);
};

View file

@ -0,0 +1,658 @@
import * as React from 'react';
import ReactTooltip from 'react-tooltip';
import { palette } from '../colors';
import { SparkleOverlay } from '../sparkle';
import { Logomark, LogoProps, Logotype } from './Branding';
type DynamicLogoProps = Partial<LogoProps> & {
currentDate?: Date;
};
export const DynamicLogomark = (props: DynamicLogoProps) => {
const variant = React.useMemo(() => getRelevantVariant(props.currentDate), [
props.currentDate,
]);
if (!variant) {
return <Logomark {...props} />;
}
let tooltipProps = {};
if (variant.tooltip) {
tooltipProps = {
'data-tip': variant.tooltip,
// 'data-for': 'dynamic-logomark',
};
}
return (
<>
<variant.Logomark {...tooltipProps} {...props} />
<ReactTooltip id="dynamic-logomark" />
</>
);
};
export const DynamicLogotype = (props: DynamicLogoProps) => {
const variant = React.useMemo(() => getRelevantVariant(props.currentDate), [
props.currentDate,
]);
if (!variant) {
return <Logotype {...props} />;
}
let tooltipProps = {};
if (variant.tooltip) {
tooltipProps = {
'data-tip': variant.tooltip,
// 'data-for': 'dynamic-logomark',
};
}
return (
<>
<variant.Logotype {...tooltipProps} {...props} />
<ReactTooltip id="dynamic-logomark" />
</>
);
};
const getRelevantVariant = (currentDate?: Date) => {
for (let variant of AllVariants) {
if (variant.activeIf(currentDate)) return variant;
}
return null;
};
// These should be updated for 2021.
// Please feel free to update with a PR for 2022 or any missing weeks within 2021.
// Rules:
// - common law holidays should have at least 2 extra days before and after
// - pride days should be 1 extra day before and after
// - weeks/months should have no buffer
// - 4/20 is just for 4/20.
const matchDay = (
start: Date,
end: Date,
currentDate: Date = new Date(),
staticDate: boolean = false
) => {
if (!staticDate) {
// pre-fill start/end years to simplify
start.setFullYear(currentDate.getFullYear());
end.setFullYear(currentDate.getFullYear());
}
start.setHours(0, 0, 0, 0);
end.setHours(0, 0, 0, 0);
if (currentDate > start && currentDate < end) {
return true;
}
return false;
};
type Variant = {
activeIf: (currentDate?: Date) => boolean;
sharedProps?: Partial<DynamicLogoProps>;
tooltip?: string;
Logomark: React.FunctionComponent<DynamicLogoProps>;
Logotype: React.FunctionComponent<DynamicLogoProps>;
};
export const Trans: Variant = {
// March 31, Nov 13-20+1
activeIf: (currentDate?: Date) =>
matchDay(new Date('2021-Mar-31'), new Date('2021-Apr-1'), currentDate) ||
matchDay(new Date('2021-Nov-13'), new Date('2021-Nov-22'), currentDate),
sharedProps: {
circleFill: '#F7A8B8',
circleOuterFill: '#55CDFC',
typeFill: palette.grey600,
},
tooltip: 'Roleypoly says trans rights!',
Logomark: (props: DynamicLogoProps) => <Logomark {...props} {...Trans.sharedProps} />,
Logotype: (props: DynamicLogoProps) => <Logotype {...props} {...Trans.sharedProps} />,
};
export const Bi: Variant = {
// Sept 16-23
activeIf: (currentDate?: Date) =>
matchDay(new Date('2021-Sep-16'), new Date('2021-Sep-24'), currentDate),
sharedProps: {
circleFill: '#D60270',
circleOuterFill: '#0038A8',
typeFill: '#9B4F96',
},
tooltip: 'Being bi is a lot like a riding a bicycle since they can go both ways.',
Logomark: (props: DynamicLogoProps) => <Logomark {...props} {...Bi.sharedProps} />,
Logotype: (props: DynamicLogoProps) => <Logotype {...props} {...Bi.sharedProps} />,
};
export const Lesbian: Variant = {
// Apr 26
activeIf: (currentDate?: Date) =>
matchDay(new Date('2021-Apr-25'), new Date('2021-Apt-27'), currentDate),
sharedProps: {
circleFill: '#D362A4',
circleOuterFill: '#A30262',
typeFill: '#FF9A56',
},
tooltip: "I'm a lesbiab... lesbiam... Less Bien... Girls.",
Logomark: (props: DynamicLogoProps) => (
<Logomark {...props} {...Lesbian.sharedProps} />
),
Logotype: (props: DynamicLogoProps) => (
<Logotype {...props} {...Lesbian.sharedProps} />
),
};
export const Ace: Variant = {
// Oct 24-30
activeIf: (currentDate?: Date) =>
matchDay(new Date('2021-Oct-24'), new Date('2021-Oct-31'), currentDate),
sharedProps: {
circleFill: '#333',
circleOuterFill: '#84067C',
typeFill: '#CCC',
},
tooltip: "Sexualn't",
Logomark: (props: DynamicLogoProps) => <Logomark {...props} {...Ace.sharedProps} />,
Logotype: (props: DynamicLogoProps) => <Logotype {...props} {...Ace.sharedProps} />,
};
export const Birthday: Variant = {
// Jan 15
activeIf: (currentDate?: Date) =>
matchDay(new Date('2021-Jan-15'), new Date('2021-Jan-16'), currentDate),
sharedProps: {
circleFill: 'none',
circleOuterFill: palette.taupe300,
typeFill: palette.taupe500,
},
tooltip: '🎉 HAPPY BIRTHDAY ROLEYPOLY 🎉',
Logomark: (props: DynamicLogoProps) => (
<svg
style={props.style}
className={props.className}
width={props.width}
height={props.height}
data-for={props['data-for']}
data-tip={props['data-tip']}
viewBox="30 10 100 100"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<g clipPath="url(#clip0)">
<path
d="M104.737 85.406V86H94.243L75.73 60.953H66.226V86H57.118V21.848H78.007C83.023 21.848 87.247 22.64 90.679 24.224C94.177 25.808 96.784 28.019 98.5 30.857C100.282 33.695 101.173 36.995 101.173 40.757C101.173 43.793 100.579 46.598 99.391 49.172C98.269 51.746 96.553 53.99 94.243 55.904C91.933 57.752 89.062 59.105 85.63 59.963L104.737 85.406ZM66.226 53.429H76.621C81.571 53.429 85.3 52.373 87.808 50.261C90.382 48.083 91.669 45.047 91.669 41.153C91.669 37.391 90.481 34.52 88.105 32.54C85.795 30.56 82.363 29.57 77.809 29.57H66.226V53.429Z"
fill={props.typeFill || Birthday.sharedProps?.typeFill}
/>
<mask
id="mask0"
mask-type="alpha"
maskUnits="userSpaceOnUse"
x="45"
y="25"
width="142"
height="142"
>
<path
d="M115.711 25L186.421 95.7107L115.711 166.421L45 95.7107L115.711 25Z"
fill={
props.circleOuterFill || Birthday.sharedProps?.circleOuterFill
}
/>
</mask>
<g mask="url(#mask0)">
<path
fillRule="evenodd"
clipRule="evenodd"
d="M79.9998 102C103.196 102 122 83.196 122 60C122 36.804 103.196 18 79.9998 18C56.8039 18 37.9998 36.804 37.9998 60C37.9998 83.196 56.8039 102 79.9998 102ZM79.9998 110C107.614 110 130 87.6142 130 60C130 32.3858 107.614 10 79.9998 10C52.3856 10 29.9998 32.3858 29.9998 60C29.9998 87.6142 52.3856 110 79.9998 110Z"
fill={
props.circleOuterFill || Birthday.sharedProps?.circleOuterFill
}
/>
</g>
</g>
<defs>
<clipPath id="clip0">
<rect width="130" height="110" fill="white" />
</clipPath>
</defs>
</svg>
),
Logotype: (props: DynamicLogoProps) => (
<div style={{ display: 'inline-block', maxWidth: props.width }}>
<SparkleOverlay strokeColor={palette.discord400}>
<Logotype {...props} {...Birthday.sharedProps} />
</SparkleOverlay>
</div>
),
};
export const DevilsLettuce: Variant = {
// Apr 20
activeIf: (currentDate?: Date) =>
matchDay(new Date('2021-Apr-20'), new Date('2021-Apr-21'), currentDate),
sharedProps: {
circleFill: palette.green400,
circleOuterFill: palette.green200,
typeFill: palette.green400,
},
tooltip: 'Legalize it.',
Logomark: (props: DynamicLogoProps) => (
<Logomark {...props} {...DevilsLettuce.sharedProps} />
),
Logotype: (props: DynamicLogoProps) => (
<Logotype {...props} {...DevilsLettuce.sharedProps} />
),
};
export const BicycleDay: Variant = {
// Apr 19
// TODO: hexagon is bestagon
activeIf: (currentDate?: Date) =>
matchDay(new Date('2021-Apr-19'), new Date('2021-Apr-20'), currentDate),
sharedProps: {
circleFill: palette.gold400,
circleOuterFill: palette.red200,
typeFill: palette.discord400,
},
tooltip: 'It increases brain complexity.',
Logomark: (props: DynamicLogoProps) => (
<Logomark {...props} {...BicycleDay.sharedProps} />
),
Logotype: (props: DynamicLogoProps) => (
<Logotype {...props} {...BicycleDay.sharedProps} />
),
};
export const Christmas: Variant = {
// Dec 20-27
activeIf: (currentDate?: Date) =>
true || matchDay(new Date('2021-Dec-20'), new Date('2021-Dec-28'), currentDate),
sharedProps: {
circleFill: palette.green200,
circleOuterFill: palette.red200,
typeFill: palette.green400,
},
tooltip: 'Have yourself a merry little Christmas~',
Logomark: (props: DynamicLogoProps) => (
<SparkleOverlay strokeColor={'white'}>
<Logomark {...props} {...Christmas.sharedProps} />
</SparkleOverlay>
),
Logotype: (props: DynamicLogoProps) => (
<SparkleOverlay strokeColor={'white'}>
<Logotype {...props} {...Christmas.sharedProps} />
</SparkleOverlay>
),
};
export const NewYear: Variant = {
// Dec 30 - Jan 2
// TODO: sparkle
activeIf: (currentDate?: Date) =>
matchDay(new Date('2021-Dec-30'), new Date('2021-Jan-3'), currentDate),
sharedProps: {
circleFill: '#222',
circleOuterFill: palette.red400,
typeFill: '#aaa',
},
tooltip: 'Fuck 2020. 🎆🎇🎆🎇',
Logomark: (props: DynamicLogoProps) => (
<Logomark {...props} {...NewYear.sharedProps} />
),
Logotype: (props: DynamicLogoProps) => (
<div style={{ display: 'inline-block', maxWidth: props.width }}>
<SparkleOverlay>
<Logotype {...props} {...NewYear.sharedProps} />
</SparkleOverlay>
</div>
),
};
export const LunarNewYear: Variant = {
// Feb 12, 2021
// Feb 1, 2022
activeIf: (currentDate?: Date) =>
matchDay(new Date('2021-Feb-10'), new Date('2021-Feb-13'), currentDate, true) ||
matchDay(new Date('2022-Jan-30'), new Date('2022-Feb-3'), currentDate, true),
sharedProps: {
circleFill: palette.red200,
circleOuterFill: palette.gold400,
typeFill: palette.taupe300,
},
tooltip: '恭喜发财! 🎊🎆🎇',
Logomark: (props: DynamicLogoProps) => (
<Logomark {...props} {...LunarNewYear.sharedProps} />
),
Logotype: (props: DynamicLogoProps) => (
<div style={{ display: 'inline-block', maxWidth: props.width }}>
<SparkleOverlay>
<Logotype {...props} {...LunarNewYear.sharedProps} />
</SparkleOverlay>
</div>
),
};
export const Pride: Variant = {
// June
activeIf: (currentDate?: Date) =>
matchDay(new Date('2021-Jun-1'), new Date('2021-Jul-1'), currentDate),
sharedProps: {
circleOuterFill: palette.taupe200,
typeFill: palette.grey500,
},
tooltip: 'LOVE WINS. 💖🌈🌟',
Logomark: (props: DynamicLogoProps) => (
<svg
style={props.style}
className={props.className}
width={props.width}
height={props.height}
data-for={props['data-for']}
data-tip={props['data-tip']}
viewBox="30 10 100 100"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<g clipPath="url(#clip0)">
<mask
id="mask0"
mask-type="alpha"
maskUnits="userSpaceOnUse"
x="45"
y="25"
width="142"
height="142"
>
<rect
x="115.711"
y="25"
width="100"
height="100"
transform="rotate(45 115.711 25)"
fill="#C4C4C4"
/>
</mask>
<g mask="url(#mask0)">
<circle
cx="79.9999"
cy="60"
r="46"
fill="#F14343"
stroke="#1D8227"
strokeWidth="8"
/>
<mask
id="mask1"
mask-type="alpha"
maskUnits="userSpaceOnUse"
x="30"
y="10"
width="100"
height="100"
>
<circle
cx="80"
cy="60"
r="46"
fill="#F14343"
stroke="#1D8227"
strokeWidth="8"
/>
</mask>
<g mask="url(#mask1)">
<rect
x="90.8987"
y="6"
width="163.166"
height="15.3994"
transform="rotate(45 90.8987 6)"
fill="#F9238B"
/>
<rect
x="80.0823"
y="16.8164"
width="163.166"
height="15.3994"
transform="rotate(45 80.0823 16.8164)"
fill="#FB7B04"
/>
<rect
x="69.2658"
y="27.6329"
width="163.166"
height="15.3994"
transform="rotate(45 69.2658 27.6329)"
fill="#FFCA66"
/>
<rect
x="58.4493"
y="38.4494"
width="163.166"
height="15.3994"
transform="rotate(45 58.4493 38.4494)"
fill="#00B289"
/>
<rect
x="47.7055"
y="49.1932"
width="163.166"
height="15.3994"
transform="rotate(45 47.7055 49.1932)"
fill="#5A38B5"
/>
<rect
x="36.889"
y="60.0097"
width="163.166"
height="15.3994"
transform="rotate(45 36.889 60.0097)"
fill="#B413F5"
/>
<circle
cx="80"
cy="60"
r="46"
stroke={
props.circleOuterFill ||
Pride.sharedProps?.circleOuterFill
}
strokeWidth="8"
/>
</g>
</g>
</g>
<defs>
<clipPath id="clip0">
<rect width="130" height="110" fill="white" />
</clipPath>
</defs>
</svg>
),
Logotype: (props: DynamicLogoProps) => (
<svg
style={props.style}
className={props.className}
width={props.width}
height={props.height}
data-for={props['data-for']}
data-tip={props['data-tip']}
viewBox="45 25 400 88"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<g clipPath="url(#clip0)">
<path
d="M179.855 95.49V96H170.845L154.95 74.495H146.79V96H138.97V40.92H156.905C161.212 40.92 164.838 41.6 167.785 42.96C170.788 44.32 173.027 46.2183 174.5 48.655C176.03 51.0917 176.795 53.925 176.795 57.155C176.795 59.7617 176.285 62.17 175.265 64.38C174.302 66.59 172.828 68.5167 170.845 70.16C168.862 71.7467 166.397 72.9083 163.45 73.645L179.855 95.49ZM146.79 68.035H155.715C159.965 68.035 163.167 67.1283 165.32 65.315C167.53 63.445 168.635 60.8383 168.635 57.495C168.635 54.265 167.615 51.8 165.575 50.1C163.592 48.4 160.645 47.55 156.735 47.55H146.79V68.035Z"
fill={props.typeFill || Pride.sharedProps?.typeFill}
/>
<path
d="M197.154 97.02C193.188 97.02 189.873 96.17 187.209 94.47C184.546 92.7133 182.563 90.3617 181.259 87.415C179.956 84.4117 179.304 81.04 179.304 77.3C179.304 72.7667 180.154 69.055 181.854 66.165C183.554 63.2183 185.849 61.0933 188.739 59.79C191.629 58.43 194.916 57.75 198.599 57.75C202.566 57.75 205.881 58.6283 208.544 60.385C211.208 62.085 213.191 64.4083 214.494 67.355C215.798 70.3017 216.449 73.645 216.449 77.385C216.449 81.975 215.599 85.7433 213.899 88.69C212.199 91.58 209.904 93.705 207.014 95.065C204.124 96.3683 200.838 97.02 197.154 97.02ZM197.834 91.07C205.144 91.07 208.799 86.48 208.799 77.3C208.799 73.1633 207.893 69.8767 206.079 67.44C204.323 64.9467 201.659 63.7 198.089 63.7C194.123 63.7 191.261 64.9183 189.504 67.355C187.804 69.735 186.954 73.05 186.954 77.3C186.954 81.4933 187.861 84.8367 189.674 87.33C191.488 89.8233 194.208 91.07 197.834 91.07Z"
fill={props.typeFill || Pride.sharedProps?.typeFill}
/>
<path
d="M221.961 96V37.52L229.271 36.67V96H221.961Z"
fill={props.typeFill || Pride.sharedProps?.typeFill}
/>
<path
d="M268.08 78.66H242.155C242.212 82.91 243.232 85.9983 245.215 87.925C247.255 89.8517 249.862 90.815 253.035 90.815C255.302 90.815 257.257 90.5317 258.9 89.965C260.6 89.3983 262.47 88.52 264.51 87.33L267.315 92.515C262.669 95.5183 257.795 97.02 252.695 97.02C247.255 97.02 242.892 95.5183 239.605 92.515C236.375 89.455 234.76 84.6383 234.76 78.065C234.76 74.325 235.44 70.925 236.8 67.865C238.16 64.805 240.172 62.3683 242.835 60.555C245.555 58.685 248.87 57.75 252.78 57.75C256.067 57.75 258.872 58.43 261.195 59.79C263.519 61.0933 265.275 62.9067 266.465 65.23C267.655 67.5533 268.25 70.2167 268.25 73.22L268.08 78.66ZM252.78 63.445C249.834 63.445 247.51 64.3233 245.81 66.08C244.167 67.8367 243.09 70.245 242.58 73.305H261.11V72.965C261.11 69.7917 260.374 67.4117 258.9 65.825C257.484 64.2383 255.444 63.445 252.78 63.445Z"
fill={props.typeFill || Pride.sharedProps?.typeFill}
/>
<path
d="M305.129 58.77V59.28L290.934 98.635C289.687 102.092 288.356 104.84 286.939 106.88C285.522 108.977 283.907 110.478 282.094 111.385C280.337 112.348 278.241 112.83 275.804 112.83C273.311 112.83 270.846 112.405 268.409 111.555L270.364 105.945C272.007 106.455 273.622 106.71 275.209 106.71C276.512 106.71 277.617 106.512 278.524 106.115C279.431 105.718 280.309 104.953 281.159 103.82C282.066 102.687 282.944 100.987 283.794 98.72L284.814 96H282.859L268.579 59.28V58.77H276.314L285.069 82.57L286.004 85.12L287.364 89.115L289.489 82.57L297.649 58.77H305.129Z"
fill={props.typeFill || Pride.sharedProps?.typeFill}
/>
<path
d="M327.505 57.75C331.018 57.75 333.936 58.6 336.26 60.3C338.583 62 340.283 64.2667 341.36 67.1C342.493 69.9333 343.06 73.0217 343.06 76.365C343.06 80.6717 342.21 84.3833 340.51 87.5C338.866 90.6167 336.6 92.9967 333.71 94.64C330.82 96.2267 327.533 97.02 323.85 97.02C321.073 97.02 318.381 96.6517 315.775 95.915V111.81H308.465V58.77L315.775 57.92V61.235C317.815 60.1017 319.826 59.2517 321.81 58.685C323.85 58.0617 325.748 57.75 327.505 57.75ZM323.255 91.24C325.578 91.24 327.618 90.73 329.375 89.71C331.188 88.6333 332.605 86.99 333.625 84.78C334.701 82.57 335.24 79.8217 335.24 76.535C335.24 72.285 334.39 69.14 332.69 67.1C330.99 65.06 328.581 64.04 325.465 64.04C322.178 64.04 318.948 64.975 315.775 66.845V89.965C318.438 90.815 320.931 91.24 323.255 91.24Z"
fill={props.typeFill || Pride.sharedProps?.typeFill}
/>
<path
d="M363.436 97.02C359.469 97.02 356.154 96.17 353.491 94.47C350.827 92.7133 348.844 90.3617 347.541 87.415C346.237 84.4117 345.586 81.04 345.586 77.3C345.586 72.7667 346.436 69.055 348.136 66.165C349.836 63.2183 352.131 61.0933 355.021 59.79C357.911 58.43 361.197 57.75 364.881 57.75C368.847 57.75 372.162 58.6283 374.826 60.385C377.489 62.085 379.472 64.4083 380.776 67.355C382.079 70.3017 382.731 73.645 382.731 77.385C382.731 81.975 381.881 85.7433 380.181 88.69C378.481 91.58 376.186 93.705 373.296 95.065C370.406 96.3683 367.119 97.02 363.436 97.02ZM364.116 91.07C371.426 91.07 375.081 86.48 375.081 77.3C375.081 73.1633 374.174 69.8767 372.361 67.44C370.604 64.9467 367.941 63.7 364.371 63.7C360.404 63.7 357.542 64.9183 355.786 67.355C354.086 69.735 353.236 73.05 353.236 77.3C353.236 81.4933 354.142 84.8367 355.956 87.33C357.769 89.8233 360.489 91.07 364.116 91.07Z"
fill={props.typeFill || Pride.sharedProps?.typeFill}
/>
<path
d="M388.242 96V37.52L395.552 36.67V96H388.242Z"
fill={props.typeFill || Pride.sharedProps?.typeFill}
/>
<path
d="M435.382 58.77V59.28L421.187 98.635C419.94 102.092 418.608 104.84 417.192 106.88C415.775 108.977 414.16 110.478 412.347 111.385C410.59 112.348 408.493 112.83 406.057 112.83C403.563 112.83 401.098 112.405 398.662 111.555L400.617 105.945C402.26 106.455 403.875 106.71 405.462 106.71C406.765 106.71 407.87 106.512 408.777 106.115C409.683 105.718 410.562 104.953 411.412 103.82C412.318 102.687 413.197 100.987 414.047 98.72L415.067 96H413.112L398.832 59.28V58.77H406.567L415.322 82.57L416.257 85.12L417.617 89.115L419.742 82.57L427.902 58.77H435.382Z"
fill={props.typeFill || Pride.sharedProps?.typeFill}
/>
<mask
id="mask0"
mask-type="alpha"
maskUnits="userSpaceOnUse"
x="45"
y="25"
width="142"
height="142"
>
<rect
x="115.711"
y="25"
width="100"
height="100"
transform="rotate(45 115.711 25)"
fill="#C4C4C4"
/>
</mask>
<g mask="url(#mask0)">
<circle
cx="79.9999"
cy="60"
r="46"
fill="#F14343"
stroke="#1D8227"
strokeWidth="8"
/>
<mask
id="mask1"
mask-type="alpha"
maskUnits="userSpaceOnUse"
x="30"
y="10"
width="100"
height="100"
>
<circle
cx="80"
cy="60"
r="46"
fill="#F14343"
stroke="#1D8227"
strokeWidth="8"
/>
</mask>
<g mask="url(#mask1)">
<rect
x="32.8987"
y="-52"
width="163.166"
height="15.3994"
transform="rotate(45 32.8987 -52)"
fill="#F9238B"
/>
<rect
x="22.0823"
y="-41.1836"
width="163.166"
height="15.3994"
transform="rotate(45 22.0823 -41.1836)"
fill="#FB7B04"
/>
<rect
x="11.2658"
y="-30.3671"
width="163.166"
height="15.3994"
transform="rotate(45 11.2658 -30.3671)"
fill="#FFCA66"
/>
<rect
x="0.449356"
y="-19.5506"
width="163.166"
height="15.3994"
transform="rotate(45 0.449356 -19.5506)"
fill="#00B289"
/>
<rect
x="-10.2945"
y="-8.80678"
width="163.166"
height="15.3994"
transform="rotate(45 -10.2945 -8.80678)"
fill="#5A38B5"
/>
<rect
x="-21.111"
y="2.00969"
width="163.166"
height="15.3994"
transform="rotate(45 -21.111 2.00969)"
fill="#B413F5"
/>
<circle
cx="80"
cy="60"
r="46"
stroke={
props.circleOuterFill ||
Pride.sharedProps?.circleOuterFill
}
strokeWidth="8"
/>
</g>
</g>
</g>
<defs>
<clipPath id="clip0">
<rect width="487" height="143" fill="white" />
</clipPath>
</defs>
</svg>
),
};
export const AllVariants: Variant[] = [
Trans,
Pride,
Bi,
Lesbian,
Ace,
Birthday,
DevilsLettuce,
BicycleDay,
Christmas,
NewYear,
LunarNewYear,
];

Some files were not shown because too many files have changed in this diff Show more