🚧 Refactor basic services

This commit is contained in:
2025-12-14 02:19:50 +08:00
parent d16905c0a3
commit cc4c2189dc
126 changed files with 18164 additions and 4247 deletions

View File

@@ -1,28 +0,0 @@
package models
// Git备份相关类型定义
type (
// AuthMethod 定义Git认证方式
AuthMethod string
)
const (
// 认证方式
Token AuthMethod = "token"
SSHKey AuthMethod = "ssh_key"
UserPass AuthMethod = "user_pass"
)
// GitBackupConfig Git备份配置
type GitBackupConfig struct {
Enabled bool `json:"enabled"`
RepoURL string `json:"repo_url"`
AuthMethod AuthMethod `json:"auth_method"`
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
Token string `json:"token,omitempty"`
SSHKeyPath string `json:"ssh_key_path,omitempty"`
SSHKeyPass string `json:"ssh_key_passphrase,omitempty"`
BackupInterval int `json:"backup_interval"` // 分钟
AutoBackup bool `json:"auto_backup"`
}

View File

@@ -126,6 +126,33 @@ type UpdatesConfig struct {
Gitea GiteaConfig `json:"gitea"` // Gitea配置
}
// Git备份相关类型定义
type (
// AuthMethod 定义Git认证方式
AuthMethod string
)
const (
// 认证方式
Token AuthMethod = "token"
SSHKey AuthMethod = "ssh_key"
UserPass AuthMethod = "user_pass"
)
// GitBackupConfig Git备份配置
type GitBackupConfig struct {
Enabled bool `json:"enabled"`
RepoURL string `json:"repo_url"`
AuthMethod AuthMethod `json:"auth_method"`
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
Token string `json:"token,omitempty"`
SSHKeyPath string `json:"ssh_key_path,omitempty"`
SSHKeyPass string `json:"ssh_key_passphrase,omitempty"`
BackupInterval int `json:"backup_interval"` // 分钟
AutoBackup bool `json:"auto_backup"`
}
// AppConfig 应用配置 - 按照前端设置页面分类组织
type AppConfig struct {
General GeneralConfig `json:"general"` // 通用设置

View File

@@ -1,34 +0,0 @@
package models
import (
"time"
)
// Document represents a document in the system
type Document struct {
ID int64 `json:"id" db:"id"`
Title string `json:"title" db:"title"`
Content string `json:"content" db:"content"`
CreatedAt string `json:"createdAt" db:"created_at"`
UpdatedAt string `json:"updatedAt" db:"updated_at"`
IsDeleted bool `json:"is_deleted" db:"is_deleted"`
IsLocked bool `json:"is_locked" db:"is_locked"` // 锁定标志,锁定的文档无法被删除
}
// NewDocument 创建新文档
func NewDocument(title, content string) *Document {
now := time.Now()
return &Document{
Title: title,
Content: content,
CreatedAt: now.String(),
UpdatedAt: now.String(),
IsDeleted: false,
IsLocked: false, // 默认不锁定
}
}
// NewDefaultDocument 创建默认文档
func NewDefaultDocument() *Document {
return NewDocument("default", "\n∞∞∞text-a\n")
}

View File

@@ -0,0 +1,804 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"log"
"reflect"
"voidraft/internal/models/ent/migrate"
"voidraft/internal/models/ent/document"
"voidraft/internal/models/ent/extension"
"voidraft/internal/models/ent/keybinding"
"voidraft/internal/models/ent/theme"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
stdsql "database/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
// Document is the client for interacting with the Document builders.
Document *DocumentClient
// Extension is the client for interacting with the Extension builders.
Extension *ExtensionClient
// KeyBinding is the client for interacting with the KeyBinding builders.
KeyBinding *KeyBindingClient
// Theme is the client for interacting with the Theme builders.
Theme *ThemeClient
}
// NewClient creates a new client configured with the given options.
func NewClient(opts ...Option) *Client {
client := &Client{config: newConfig(opts...)}
client.init()
return client
}
func (c *Client) init() {
c.Schema = migrate.NewSchema(c.driver)
c.Document = NewDocumentClient(c.config)
c.Extension = NewExtensionClient(c.config)
c.KeyBinding = NewKeyBindingClient(c.config)
c.Theme = NewThemeClient(c.config)
}
type (
// config is the configuration for the client and its builder.
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(...any)
// hooks to execute on mutations.
hooks *hooks
// interceptors to execute on queries.
inters *inters
}
// Option function to configure the client.
Option func(*config)
)
// newConfig creates a new config for the client.
func newConfig(opts ...Option) config {
cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}}
cfg.options(opts...)
return cfg
}
// 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(...any)) 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
}
}
// 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)
}
}
// ErrTxStarted is returned when trying to start a new transaction from a transactional client.
var ErrTxStarted = errors.New("ent: cannot start a transaction within a transaction")
// 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, ErrTxStarted
}
tx, err := newTx(ctx, c.driver)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
}
cfg := c.config
cfg.driver = tx
return &Tx{
ctx: ctx,
config: cfg,
Document: NewDocumentClient(cfg),
Extension: NewExtensionClient(cfg),
KeyBinding: NewKeyBindingClient(cfg),
Theme: NewThemeClient(cfg),
}, nil
}
// BeginTx returns a transactional client with specified options.
func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, errors.New("ent: cannot start a transaction within a transaction")
}
tx, err := c.driver.(interface {
BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error)
}).BeginTx(ctx, opts)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
}
cfg := c.config
cfg.driver = &txDriver{tx: tx, drv: c.driver}
return &Tx{
ctx: ctx,
config: cfg,
Document: NewDocumentClient(cfg),
Extension: NewExtensionClient(cfg),
KeyBinding: NewKeyBindingClient(cfg),
Theme: NewThemeClient(cfg),
}, nil
}
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
//
// client.Debug().
// Document.
// Query().
// Count(ctx)
func (c *Client) Debug() *Client {
if c.debug {
return c
}
cfg := c.config
cfg.driver = dialect.Debug(c.driver, c.log)
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.Document.Use(hooks...)
c.Extension.Use(hooks...)
c.KeyBinding.Use(hooks...)
c.Theme.Use(hooks...)
}
// Intercept adds the query interceptors to all the entity clients.
// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`.
func (c *Client) Intercept(interceptors ...Interceptor) {
c.Document.Intercept(interceptors...)
c.Extension.Intercept(interceptors...)
c.KeyBinding.Intercept(interceptors...)
c.Theme.Intercept(interceptors...)
}
// Mutate implements the ent.Mutator interface.
func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
switch m := m.(type) {
case *DocumentMutation:
return c.Document.mutate(ctx, m)
case *ExtensionMutation:
return c.Extension.mutate(ctx, m)
case *KeyBindingMutation:
return c.KeyBinding.mutate(ctx, m)
case *ThemeMutation:
return c.Theme.mutate(ctx, m)
default:
return nil, fmt.Errorf("ent: unknown mutation type %T", m)
}
}
// DocumentClient is a client for the Document schema.
type DocumentClient struct {
config
}
// NewDocumentClient returns a client for the Document from the given config.
func NewDocumentClient(c config) *DocumentClient {
return &DocumentClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `document.Hooks(f(g(h())))`.
func (c *DocumentClient) Use(hooks ...Hook) {
c.hooks.Document = append(c.hooks.Document, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `document.Intercept(f(g(h())))`.
func (c *DocumentClient) Intercept(interceptors ...Interceptor) {
c.inters.Document = append(c.inters.Document, interceptors...)
}
// Create returns a builder for creating a Document entity.
func (c *DocumentClient) Create() *DocumentCreate {
mutation := newDocumentMutation(c.config, OpCreate)
return &DocumentCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Document entities.
func (c *DocumentClient) CreateBulk(builders ...*DocumentCreate) *DocumentCreateBulk {
return &DocumentCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *DocumentClient) MapCreateBulk(slice any, setFunc func(*DocumentCreate, int)) *DocumentCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &DocumentCreateBulk{err: fmt.Errorf("calling to DocumentClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*DocumentCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &DocumentCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Document.
func (c *DocumentClient) Update() *DocumentUpdate {
mutation := newDocumentMutation(c.config, OpUpdate)
return &DocumentUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *DocumentClient) UpdateOne(_m *Document) *DocumentUpdateOne {
mutation := newDocumentMutation(c.config, OpUpdateOne, withDocument(_m))
return &DocumentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *DocumentClient) UpdateOneID(id int) *DocumentUpdateOne {
mutation := newDocumentMutation(c.config, OpUpdateOne, withDocumentID(id))
return &DocumentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Document.
func (c *DocumentClient) Delete() *DocumentDelete {
mutation := newDocumentMutation(c.config, OpDelete)
return &DocumentDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *DocumentClient) DeleteOne(_m *Document) *DocumentDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *DocumentClient) DeleteOneID(id int) *DocumentDeleteOne {
builder := c.Delete().Where(document.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &DocumentDeleteOne{builder}
}
// Query returns a query builder for Document.
func (c *DocumentClient) Query() *DocumentQuery {
return &DocumentQuery{
config: c.config,
ctx: &QueryContext{Type: TypeDocument},
inters: c.Interceptors(),
}
}
// Get returns a Document entity by its id.
func (c *DocumentClient) Get(ctx context.Context, id int) (*Document, error) {
return c.Query().Where(document.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *DocumentClient) GetX(ctx context.Context, id int) *Document {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// Hooks returns the client hooks.
func (c *DocumentClient) Hooks() []Hook {
hooks := c.hooks.Document
return append(hooks[:len(hooks):len(hooks)], document.Hooks[:]...)
}
// Interceptors returns the client interceptors.
func (c *DocumentClient) Interceptors() []Interceptor {
inters := c.inters.Document
return append(inters[:len(inters):len(inters)], document.Interceptors[:]...)
}
func (c *DocumentClient) mutate(ctx context.Context, m *DocumentMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&DocumentCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&DocumentUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&DocumentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&DocumentDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Document mutation op: %q", m.Op())
}
}
// ExtensionClient is a client for the Extension schema.
type ExtensionClient struct {
config
}
// NewExtensionClient returns a client for the Extension from the given config.
func NewExtensionClient(c config) *ExtensionClient {
return &ExtensionClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `extension.Hooks(f(g(h())))`.
func (c *ExtensionClient) Use(hooks ...Hook) {
c.hooks.Extension = append(c.hooks.Extension, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `extension.Intercept(f(g(h())))`.
func (c *ExtensionClient) Intercept(interceptors ...Interceptor) {
c.inters.Extension = append(c.inters.Extension, interceptors...)
}
// Create returns a builder for creating a Extension entity.
func (c *ExtensionClient) Create() *ExtensionCreate {
mutation := newExtensionMutation(c.config, OpCreate)
return &ExtensionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Extension entities.
func (c *ExtensionClient) CreateBulk(builders ...*ExtensionCreate) *ExtensionCreateBulk {
return &ExtensionCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *ExtensionClient) MapCreateBulk(slice any, setFunc func(*ExtensionCreate, int)) *ExtensionCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &ExtensionCreateBulk{err: fmt.Errorf("calling to ExtensionClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*ExtensionCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &ExtensionCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Extension.
func (c *ExtensionClient) Update() *ExtensionUpdate {
mutation := newExtensionMutation(c.config, OpUpdate)
return &ExtensionUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *ExtensionClient) UpdateOne(_m *Extension) *ExtensionUpdateOne {
mutation := newExtensionMutation(c.config, OpUpdateOne, withExtension(_m))
return &ExtensionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *ExtensionClient) UpdateOneID(id int) *ExtensionUpdateOne {
mutation := newExtensionMutation(c.config, OpUpdateOne, withExtensionID(id))
return &ExtensionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Extension.
func (c *ExtensionClient) Delete() *ExtensionDelete {
mutation := newExtensionMutation(c.config, OpDelete)
return &ExtensionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *ExtensionClient) DeleteOne(_m *Extension) *ExtensionDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *ExtensionClient) DeleteOneID(id int) *ExtensionDeleteOne {
builder := c.Delete().Where(extension.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &ExtensionDeleteOne{builder}
}
// Query returns a query builder for Extension.
func (c *ExtensionClient) Query() *ExtensionQuery {
return &ExtensionQuery{
config: c.config,
ctx: &QueryContext{Type: TypeExtension},
inters: c.Interceptors(),
}
}
// Get returns a Extension entity by its id.
func (c *ExtensionClient) Get(ctx context.Context, id int) (*Extension, error) {
return c.Query().Where(extension.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *ExtensionClient) GetX(ctx context.Context, id int) *Extension {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// Hooks returns the client hooks.
func (c *ExtensionClient) Hooks() []Hook {
hooks := c.hooks.Extension
return append(hooks[:len(hooks):len(hooks)], extension.Hooks[:]...)
}
// Interceptors returns the client interceptors.
func (c *ExtensionClient) Interceptors() []Interceptor {
inters := c.inters.Extension
return append(inters[:len(inters):len(inters)], extension.Interceptors[:]...)
}
func (c *ExtensionClient) mutate(ctx context.Context, m *ExtensionMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&ExtensionCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&ExtensionUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&ExtensionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&ExtensionDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Extension mutation op: %q", m.Op())
}
}
// KeyBindingClient is a client for the KeyBinding schema.
type KeyBindingClient struct {
config
}
// NewKeyBindingClient returns a client for the KeyBinding from the given config.
func NewKeyBindingClient(c config) *KeyBindingClient {
return &KeyBindingClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `keybinding.Hooks(f(g(h())))`.
func (c *KeyBindingClient) Use(hooks ...Hook) {
c.hooks.KeyBinding = append(c.hooks.KeyBinding, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `keybinding.Intercept(f(g(h())))`.
func (c *KeyBindingClient) Intercept(interceptors ...Interceptor) {
c.inters.KeyBinding = append(c.inters.KeyBinding, interceptors...)
}
// Create returns a builder for creating a KeyBinding entity.
func (c *KeyBindingClient) Create() *KeyBindingCreate {
mutation := newKeyBindingMutation(c.config, OpCreate)
return &KeyBindingCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of KeyBinding entities.
func (c *KeyBindingClient) CreateBulk(builders ...*KeyBindingCreate) *KeyBindingCreateBulk {
return &KeyBindingCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *KeyBindingClient) MapCreateBulk(slice any, setFunc func(*KeyBindingCreate, int)) *KeyBindingCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &KeyBindingCreateBulk{err: fmt.Errorf("calling to KeyBindingClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*KeyBindingCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &KeyBindingCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for KeyBinding.
func (c *KeyBindingClient) Update() *KeyBindingUpdate {
mutation := newKeyBindingMutation(c.config, OpUpdate)
return &KeyBindingUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *KeyBindingClient) UpdateOne(_m *KeyBinding) *KeyBindingUpdateOne {
mutation := newKeyBindingMutation(c.config, OpUpdateOne, withKeyBinding(_m))
return &KeyBindingUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *KeyBindingClient) UpdateOneID(id int) *KeyBindingUpdateOne {
mutation := newKeyBindingMutation(c.config, OpUpdateOne, withKeyBindingID(id))
return &KeyBindingUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for KeyBinding.
func (c *KeyBindingClient) Delete() *KeyBindingDelete {
mutation := newKeyBindingMutation(c.config, OpDelete)
return &KeyBindingDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *KeyBindingClient) DeleteOne(_m *KeyBinding) *KeyBindingDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *KeyBindingClient) DeleteOneID(id int) *KeyBindingDeleteOne {
builder := c.Delete().Where(keybinding.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &KeyBindingDeleteOne{builder}
}
// Query returns a query builder for KeyBinding.
func (c *KeyBindingClient) Query() *KeyBindingQuery {
return &KeyBindingQuery{
config: c.config,
ctx: &QueryContext{Type: TypeKeyBinding},
inters: c.Interceptors(),
}
}
// Get returns a KeyBinding entity by its id.
func (c *KeyBindingClient) Get(ctx context.Context, id int) (*KeyBinding, error) {
return c.Query().Where(keybinding.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *KeyBindingClient) GetX(ctx context.Context, id int) *KeyBinding {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// Hooks returns the client hooks.
func (c *KeyBindingClient) Hooks() []Hook {
hooks := c.hooks.KeyBinding
return append(hooks[:len(hooks):len(hooks)], keybinding.Hooks[:]...)
}
// Interceptors returns the client interceptors.
func (c *KeyBindingClient) Interceptors() []Interceptor {
inters := c.inters.KeyBinding
return append(inters[:len(inters):len(inters)], keybinding.Interceptors[:]...)
}
func (c *KeyBindingClient) mutate(ctx context.Context, m *KeyBindingMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&KeyBindingCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&KeyBindingUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&KeyBindingUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&KeyBindingDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown KeyBinding mutation op: %q", m.Op())
}
}
// ThemeClient is a client for the Theme schema.
type ThemeClient struct {
config
}
// NewThemeClient returns a client for the Theme from the given config.
func NewThemeClient(c config) *ThemeClient {
return &ThemeClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `theme.Hooks(f(g(h())))`.
func (c *ThemeClient) Use(hooks ...Hook) {
c.hooks.Theme = append(c.hooks.Theme, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `theme.Intercept(f(g(h())))`.
func (c *ThemeClient) Intercept(interceptors ...Interceptor) {
c.inters.Theme = append(c.inters.Theme, interceptors...)
}
// Create returns a builder for creating a Theme entity.
func (c *ThemeClient) Create() *ThemeCreate {
mutation := newThemeMutation(c.config, OpCreate)
return &ThemeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Theme entities.
func (c *ThemeClient) CreateBulk(builders ...*ThemeCreate) *ThemeCreateBulk {
return &ThemeCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *ThemeClient) MapCreateBulk(slice any, setFunc func(*ThemeCreate, int)) *ThemeCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &ThemeCreateBulk{err: fmt.Errorf("calling to ThemeClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*ThemeCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &ThemeCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Theme.
func (c *ThemeClient) Update() *ThemeUpdate {
mutation := newThemeMutation(c.config, OpUpdate)
return &ThemeUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *ThemeClient) UpdateOne(_m *Theme) *ThemeUpdateOne {
mutation := newThemeMutation(c.config, OpUpdateOne, withTheme(_m))
return &ThemeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *ThemeClient) UpdateOneID(id int) *ThemeUpdateOne {
mutation := newThemeMutation(c.config, OpUpdateOne, withThemeID(id))
return &ThemeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Theme.
func (c *ThemeClient) Delete() *ThemeDelete {
mutation := newThemeMutation(c.config, OpDelete)
return &ThemeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *ThemeClient) DeleteOne(_m *Theme) *ThemeDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *ThemeClient) DeleteOneID(id int) *ThemeDeleteOne {
builder := c.Delete().Where(theme.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &ThemeDeleteOne{builder}
}
// Query returns a query builder for Theme.
func (c *ThemeClient) Query() *ThemeQuery {
return &ThemeQuery{
config: c.config,
ctx: &QueryContext{Type: TypeTheme},
inters: c.Interceptors(),
}
}
// Get returns a Theme entity by its id.
func (c *ThemeClient) Get(ctx context.Context, id int) (*Theme, error) {
return c.Query().Where(theme.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *ThemeClient) GetX(ctx context.Context, id int) *Theme {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// Hooks returns the client hooks.
func (c *ThemeClient) Hooks() []Hook {
hooks := c.hooks.Theme
return append(hooks[:len(hooks):len(hooks)], theme.Hooks[:]...)
}
// Interceptors returns the client interceptors.
func (c *ThemeClient) Interceptors() []Interceptor {
inters := c.inters.Theme
return append(inters[:len(inters):len(inters)], theme.Interceptors[:]...)
}
func (c *ThemeClient) mutate(ctx context.Context, m *ThemeMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&ThemeCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&ThemeUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&ThemeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&ThemeDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Theme mutation op: %q", m.Op())
}
}
// hooks and interceptors per client, for fast access.
type (
hooks struct {
Document, Extension, KeyBinding, Theme []ent.Hook
}
inters struct {
Document, Extension, KeyBinding, Theme []ent.Interceptor
}
)
// ExecContext allows calling the underlying ExecContext method of the driver if it is supported by it.
// See, database/sql#DB.ExecContext for more information.
func (c *config) ExecContext(ctx context.Context, query string, args ...any) (stdsql.Result, error) {
ex, ok := c.driver.(interface {
ExecContext(context.Context, string, ...any) (stdsql.Result, error)
})
if !ok {
return nil, fmt.Errorf("Driver.ExecContext is not supported")
}
return ex.ExecContext(ctx, query, args...)
}
// QueryContext allows calling the underlying QueryContext method of the driver if it is supported by it.
// See, database/sql#DB.QueryContext for more information.
func (c *config) QueryContext(ctx context.Context, query string, args ...any) (*stdsql.Rows, error) {
q, ok := c.driver.(interface {
QueryContext(context.Context, string, ...any) (*stdsql.Rows, error)
})
if !ok {
return nil, fmt.Errorf("Driver.QueryContext is not supported")
}
return q.QueryContext(ctx, query, args...)
}

View File

@@ -0,0 +1,163 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"voidraft/internal/models/ent/document"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
)
// Document is the model entity for the Document schema.
type Document struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// 创建时间
CreatedAt string `json:"created_at"`
// 最后更新时间
UpdatedAt string `json:"updated_at"`
// 删除时间NULL表示未删除
DeletedAt *string `json:"deleted_at,omitempty"`
// 文档标题
Title string `json:"title"`
// 文档内容
Content string `json:"content"`
// 是否锁定
Locked bool `json:"locked"`
selectValues sql.SelectValues
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Document) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case document.FieldLocked:
values[i] = new(sql.NullBool)
case document.FieldID:
values[i] = new(sql.NullInt64)
case document.FieldCreatedAt, document.FieldUpdatedAt, document.FieldDeletedAt, document.FieldTitle, document.FieldContent:
values[i] = new(sql.NullString)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Document fields.
func (_m *Document) assignValues(columns []string, values []any) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case document.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
_m.ID = int(value.Int64)
case document.FieldCreatedAt:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
_m.CreatedAt = value.String
}
case document.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
_m.UpdatedAt = value.String
}
case document.FieldDeletedAt:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field deleted_at", values[i])
} else if value.Valid {
_m.DeletedAt = new(string)
*_m.DeletedAt = value.String
}
case document.FieldTitle:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field title", values[i])
} else if value.Valid {
_m.Title = value.String
}
case document.FieldContent:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field content", values[i])
} else if value.Valid {
_m.Content = value.String
}
case document.FieldLocked:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field locked", values[i])
} else if value.Valid {
_m.Locked = value.Bool
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Document.
// This includes values selected through modifiers, order, etc.
func (_m *Document) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// Update returns a builder for updating this Document.
// Note that you need to call Document.Unwrap() before calling this method if this Document
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Document) Update() *DocumentUpdateOne {
return NewDocumentClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Document entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (_m *Document) Unwrap() *Document {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: Document is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Document) String() string {
var builder strings.Builder
builder.WriteString("Document(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("created_at=")
builder.WriteString(_m.CreatedAt)
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(_m.UpdatedAt)
builder.WriteString(", ")
if v := _m.DeletedAt; v != nil {
builder.WriteString("deleted_at=")
builder.WriteString(*v)
}
builder.WriteString(", ")
builder.WriteString("title=")
builder.WriteString(_m.Title)
builder.WriteString(", ")
builder.WriteString("content=")
builder.WriteString(_m.Content)
builder.WriteString(", ")
builder.WriteString("locked=")
builder.WriteString(fmt.Sprintf("%v", _m.Locked))
builder.WriteByte(')')
return builder.String()
}
// Documents is a parsable slice of Document.
type Documents []*Document

View File

@@ -0,0 +1,108 @@
// Code generated by ent, DO NOT EDIT.
package document
import (
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
)
const (
// Label holds the string label denoting the document type in the database.
Label = "document"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
FieldUpdatedAt = "updated_at"
// FieldDeletedAt holds the string denoting the deleted_at field in the database.
FieldDeletedAt = "deleted_at"
// FieldTitle holds the string denoting the title field in the database.
FieldTitle = "title"
// FieldContent holds the string denoting the content field in the database.
FieldContent = "content"
// FieldLocked holds the string denoting the locked field in the database.
FieldLocked = "locked"
// Table holds the table name of the document in the database.
Table = "documents"
)
// Columns holds all SQL columns for document fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldDeletedAt,
FieldTitle,
FieldContent,
FieldLocked,
}
// 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
}
// Note that the variables below are initialized by the runtime
// package on the initialization of the application. Therefore,
// it should be imported in the main as follows:
//
// import _ "voidraft/internal/models/ent/runtime"
var (
Hooks [2]ent.Hook
Interceptors [1]ent.Interceptor
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() string
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() string
// TitleValidator is a validator for the "title" field. It is called by the builders before save.
TitleValidator func(string) error
// DefaultContent holds the default value on creation for the "content" field.
DefaultContent string
// DefaultLocked holds the default value on creation for the "locked" field.
DefaultLocked bool
)
// OrderOption defines the ordering options for the Document queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByCreatedAt orders the results by the created_at field.
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
}
// ByUpdatedAt orders the results by the updated_at field.
func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
}
// ByDeletedAt orders the results by the deleted_at field.
func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDeletedAt, opts...).ToFunc()
}
// ByTitle orders the results by the title field.
func ByTitle(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldTitle, opts...).ToFunc()
}
// ByContent orders the results by the content field.
func ByContent(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldContent, opts...).ToFunc()
}
// ByLocked orders the results by the locked field.
func ByLocked(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldLocked, opts...).ToFunc()
}

View File

@@ -0,0 +1,454 @@
// Code generated by ent, DO NOT EDIT.
package document
import (
"voidraft/internal/models/ent/predicate"
"entgo.io/ent/dialect/sql"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Document {
return predicate.Document(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Document {
return predicate.Document(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Document {
return predicate.Document(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Document {
return predicate.Document(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Document {
return predicate.Document(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Document {
return predicate.Document(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Document {
return predicate.Document(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Document {
return predicate.Document(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Document {
return predicate.Document(sql.FieldLTE(FieldID, id))
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v string) predicate.Document {
return predicate.Document(sql.FieldEQ(FieldCreatedAt, v))
}
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
func UpdatedAt(v string) predicate.Document {
return predicate.Document(sql.FieldEQ(FieldUpdatedAt, v))
}
// DeletedAt applies equality check predicate on the "deleted_at" field. It's identical to DeletedAtEQ.
func DeletedAt(v string) predicate.Document {
return predicate.Document(sql.FieldEQ(FieldDeletedAt, v))
}
// Title applies equality check predicate on the "title" field. It's identical to TitleEQ.
func Title(v string) predicate.Document {
return predicate.Document(sql.FieldEQ(FieldTitle, v))
}
// Content applies equality check predicate on the "content" field. It's identical to ContentEQ.
func Content(v string) predicate.Document {
return predicate.Document(sql.FieldEQ(FieldContent, v))
}
// Locked applies equality check predicate on the "locked" field. It's identical to LockedEQ.
func Locked(v bool) predicate.Document {
return predicate.Document(sql.FieldEQ(FieldLocked, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v string) predicate.Document {
return predicate.Document(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v string) predicate.Document {
return predicate.Document(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...string) predicate.Document {
return predicate.Document(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...string) predicate.Document {
return predicate.Document(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v string) predicate.Document {
return predicate.Document(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v string) predicate.Document {
return predicate.Document(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v string) predicate.Document {
return predicate.Document(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v string) predicate.Document {
return predicate.Document(sql.FieldLTE(FieldCreatedAt, v))
}
// CreatedAtContains applies the Contains predicate on the "created_at" field.
func CreatedAtContains(v string) predicate.Document {
return predicate.Document(sql.FieldContains(FieldCreatedAt, v))
}
// CreatedAtHasPrefix applies the HasPrefix predicate on the "created_at" field.
func CreatedAtHasPrefix(v string) predicate.Document {
return predicate.Document(sql.FieldHasPrefix(FieldCreatedAt, v))
}
// CreatedAtHasSuffix applies the HasSuffix predicate on the "created_at" field.
func CreatedAtHasSuffix(v string) predicate.Document {
return predicate.Document(sql.FieldHasSuffix(FieldCreatedAt, v))
}
// CreatedAtEqualFold applies the EqualFold predicate on the "created_at" field.
func CreatedAtEqualFold(v string) predicate.Document {
return predicate.Document(sql.FieldEqualFold(FieldCreatedAt, v))
}
// CreatedAtContainsFold applies the ContainsFold predicate on the "created_at" field.
func CreatedAtContainsFold(v string) predicate.Document {
return predicate.Document(sql.FieldContainsFold(FieldCreatedAt, v))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v string) predicate.Document {
return predicate.Document(sql.FieldEQ(FieldUpdatedAt, v))
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v string) predicate.Document {
return predicate.Document(sql.FieldNEQ(FieldUpdatedAt, v))
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...string) predicate.Document {
return predicate.Document(sql.FieldIn(FieldUpdatedAt, vs...))
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...string) predicate.Document {
return predicate.Document(sql.FieldNotIn(FieldUpdatedAt, vs...))
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v string) predicate.Document {
return predicate.Document(sql.FieldGT(FieldUpdatedAt, v))
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v string) predicate.Document {
return predicate.Document(sql.FieldGTE(FieldUpdatedAt, v))
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v string) predicate.Document {
return predicate.Document(sql.FieldLT(FieldUpdatedAt, v))
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v string) predicate.Document {
return predicate.Document(sql.FieldLTE(FieldUpdatedAt, v))
}
// UpdatedAtContains applies the Contains predicate on the "updated_at" field.
func UpdatedAtContains(v string) predicate.Document {
return predicate.Document(sql.FieldContains(FieldUpdatedAt, v))
}
// UpdatedAtHasPrefix applies the HasPrefix predicate on the "updated_at" field.
func UpdatedAtHasPrefix(v string) predicate.Document {
return predicate.Document(sql.FieldHasPrefix(FieldUpdatedAt, v))
}
// UpdatedAtHasSuffix applies the HasSuffix predicate on the "updated_at" field.
func UpdatedAtHasSuffix(v string) predicate.Document {
return predicate.Document(sql.FieldHasSuffix(FieldUpdatedAt, v))
}
// UpdatedAtEqualFold applies the EqualFold predicate on the "updated_at" field.
func UpdatedAtEqualFold(v string) predicate.Document {
return predicate.Document(sql.FieldEqualFold(FieldUpdatedAt, v))
}
// UpdatedAtContainsFold applies the ContainsFold predicate on the "updated_at" field.
func UpdatedAtContainsFold(v string) predicate.Document {
return predicate.Document(sql.FieldContainsFold(FieldUpdatedAt, v))
}
// DeletedAtEQ applies the EQ predicate on the "deleted_at" field.
func DeletedAtEQ(v string) predicate.Document {
return predicate.Document(sql.FieldEQ(FieldDeletedAt, v))
}
// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field.
func DeletedAtNEQ(v string) predicate.Document {
return predicate.Document(sql.FieldNEQ(FieldDeletedAt, v))
}
// DeletedAtIn applies the In predicate on the "deleted_at" field.
func DeletedAtIn(vs ...string) predicate.Document {
return predicate.Document(sql.FieldIn(FieldDeletedAt, vs...))
}
// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field.
func DeletedAtNotIn(vs ...string) predicate.Document {
return predicate.Document(sql.FieldNotIn(FieldDeletedAt, vs...))
}
// DeletedAtGT applies the GT predicate on the "deleted_at" field.
func DeletedAtGT(v string) predicate.Document {
return predicate.Document(sql.FieldGT(FieldDeletedAt, v))
}
// DeletedAtGTE applies the GTE predicate on the "deleted_at" field.
func DeletedAtGTE(v string) predicate.Document {
return predicate.Document(sql.FieldGTE(FieldDeletedAt, v))
}
// DeletedAtLT applies the LT predicate on the "deleted_at" field.
func DeletedAtLT(v string) predicate.Document {
return predicate.Document(sql.FieldLT(FieldDeletedAt, v))
}
// DeletedAtLTE applies the LTE predicate on the "deleted_at" field.
func DeletedAtLTE(v string) predicate.Document {
return predicate.Document(sql.FieldLTE(FieldDeletedAt, v))
}
// DeletedAtContains applies the Contains predicate on the "deleted_at" field.
func DeletedAtContains(v string) predicate.Document {
return predicate.Document(sql.FieldContains(FieldDeletedAt, v))
}
// DeletedAtHasPrefix applies the HasPrefix predicate on the "deleted_at" field.
func DeletedAtHasPrefix(v string) predicate.Document {
return predicate.Document(sql.FieldHasPrefix(FieldDeletedAt, v))
}
// DeletedAtHasSuffix applies the HasSuffix predicate on the "deleted_at" field.
func DeletedAtHasSuffix(v string) predicate.Document {
return predicate.Document(sql.FieldHasSuffix(FieldDeletedAt, v))
}
// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field.
func DeletedAtIsNil() predicate.Document {
return predicate.Document(sql.FieldIsNull(FieldDeletedAt))
}
// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field.
func DeletedAtNotNil() predicate.Document {
return predicate.Document(sql.FieldNotNull(FieldDeletedAt))
}
// DeletedAtEqualFold applies the EqualFold predicate on the "deleted_at" field.
func DeletedAtEqualFold(v string) predicate.Document {
return predicate.Document(sql.FieldEqualFold(FieldDeletedAt, v))
}
// DeletedAtContainsFold applies the ContainsFold predicate on the "deleted_at" field.
func DeletedAtContainsFold(v string) predicate.Document {
return predicate.Document(sql.FieldContainsFold(FieldDeletedAt, v))
}
// TitleEQ applies the EQ predicate on the "title" field.
func TitleEQ(v string) predicate.Document {
return predicate.Document(sql.FieldEQ(FieldTitle, v))
}
// TitleNEQ applies the NEQ predicate on the "title" field.
func TitleNEQ(v string) predicate.Document {
return predicate.Document(sql.FieldNEQ(FieldTitle, v))
}
// TitleIn applies the In predicate on the "title" field.
func TitleIn(vs ...string) predicate.Document {
return predicate.Document(sql.FieldIn(FieldTitle, vs...))
}
// TitleNotIn applies the NotIn predicate on the "title" field.
func TitleNotIn(vs ...string) predicate.Document {
return predicate.Document(sql.FieldNotIn(FieldTitle, vs...))
}
// TitleGT applies the GT predicate on the "title" field.
func TitleGT(v string) predicate.Document {
return predicate.Document(sql.FieldGT(FieldTitle, v))
}
// TitleGTE applies the GTE predicate on the "title" field.
func TitleGTE(v string) predicate.Document {
return predicate.Document(sql.FieldGTE(FieldTitle, v))
}
// TitleLT applies the LT predicate on the "title" field.
func TitleLT(v string) predicate.Document {
return predicate.Document(sql.FieldLT(FieldTitle, v))
}
// TitleLTE applies the LTE predicate on the "title" field.
func TitleLTE(v string) predicate.Document {
return predicate.Document(sql.FieldLTE(FieldTitle, v))
}
// TitleContains applies the Contains predicate on the "title" field.
func TitleContains(v string) predicate.Document {
return predicate.Document(sql.FieldContains(FieldTitle, v))
}
// TitleHasPrefix applies the HasPrefix predicate on the "title" field.
func TitleHasPrefix(v string) predicate.Document {
return predicate.Document(sql.FieldHasPrefix(FieldTitle, v))
}
// TitleHasSuffix applies the HasSuffix predicate on the "title" field.
func TitleHasSuffix(v string) predicate.Document {
return predicate.Document(sql.FieldHasSuffix(FieldTitle, v))
}
// TitleEqualFold applies the EqualFold predicate on the "title" field.
func TitleEqualFold(v string) predicate.Document {
return predicate.Document(sql.FieldEqualFold(FieldTitle, v))
}
// TitleContainsFold applies the ContainsFold predicate on the "title" field.
func TitleContainsFold(v string) predicate.Document {
return predicate.Document(sql.FieldContainsFold(FieldTitle, v))
}
// ContentEQ applies the EQ predicate on the "content" field.
func ContentEQ(v string) predicate.Document {
return predicate.Document(sql.FieldEQ(FieldContent, v))
}
// ContentNEQ applies the NEQ predicate on the "content" field.
func ContentNEQ(v string) predicate.Document {
return predicate.Document(sql.FieldNEQ(FieldContent, v))
}
// ContentIn applies the In predicate on the "content" field.
func ContentIn(vs ...string) predicate.Document {
return predicate.Document(sql.FieldIn(FieldContent, vs...))
}
// ContentNotIn applies the NotIn predicate on the "content" field.
func ContentNotIn(vs ...string) predicate.Document {
return predicate.Document(sql.FieldNotIn(FieldContent, vs...))
}
// ContentGT applies the GT predicate on the "content" field.
func ContentGT(v string) predicate.Document {
return predicate.Document(sql.FieldGT(FieldContent, v))
}
// ContentGTE applies the GTE predicate on the "content" field.
func ContentGTE(v string) predicate.Document {
return predicate.Document(sql.FieldGTE(FieldContent, v))
}
// ContentLT applies the LT predicate on the "content" field.
func ContentLT(v string) predicate.Document {
return predicate.Document(sql.FieldLT(FieldContent, v))
}
// ContentLTE applies the LTE predicate on the "content" field.
func ContentLTE(v string) predicate.Document {
return predicate.Document(sql.FieldLTE(FieldContent, v))
}
// ContentContains applies the Contains predicate on the "content" field.
func ContentContains(v string) predicate.Document {
return predicate.Document(sql.FieldContains(FieldContent, v))
}
// ContentHasPrefix applies the HasPrefix predicate on the "content" field.
func ContentHasPrefix(v string) predicate.Document {
return predicate.Document(sql.FieldHasPrefix(FieldContent, v))
}
// ContentHasSuffix applies the HasSuffix predicate on the "content" field.
func ContentHasSuffix(v string) predicate.Document {
return predicate.Document(sql.FieldHasSuffix(FieldContent, v))
}
// ContentIsNil applies the IsNil predicate on the "content" field.
func ContentIsNil() predicate.Document {
return predicate.Document(sql.FieldIsNull(FieldContent))
}
// ContentNotNil applies the NotNil predicate on the "content" field.
func ContentNotNil() predicate.Document {
return predicate.Document(sql.FieldNotNull(FieldContent))
}
// ContentEqualFold applies the EqualFold predicate on the "content" field.
func ContentEqualFold(v string) predicate.Document {
return predicate.Document(sql.FieldEqualFold(FieldContent, v))
}
// ContentContainsFold applies the ContainsFold predicate on the "content" field.
func ContentContainsFold(v string) predicate.Document {
return predicate.Document(sql.FieldContainsFold(FieldContent, v))
}
// LockedEQ applies the EQ predicate on the "locked" field.
func LockedEQ(v bool) predicate.Document {
return predicate.Document(sql.FieldEQ(FieldLocked, v))
}
// LockedNEQ applies the NEQ predicate on the "locked" field.
func LockedNEQ(v bool) predicate.Document {
return predicate.Document(sql.FieldNEQ(FieldLocked, v))
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Document) predicate.Document {
return predicate.Document(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Document) predicate.Document {
return predicate.Document(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Document) predicate.Document {
return predicate.Document(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,318 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"voidraft/internal/models/ent/document"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// DocumentCreate is the builder for creating a Document entity.
type DocumentCreate struct {
config
mutation *DocumentMutation
hooks []Hook
}
// SetCreatedAt sets the "created_at" field.
func (_c *DocumentCreate) SetCreatedAt(v string) *DocumentCreate {
_c.mutation.SetCreatedAt(v)
return _c
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (_c *DocumentCreate) SetNillableCreatedAt(v *string) *DocumentCreate {
if v != nil {
_c.SetCreatedAt(*v)
}
return _c
}
// SetUpdatedAt sets the "updated_at" field.
func (_c *DocumentCreate) SetUpdatedAt(v string) *DocumentCreate {
_c.mutation.SetUpdatedAt(v)
return _c
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (_c *DocumentCreate) SetNillableUpdatedAt(v *string) *DocumentCreate {
if v != nil {
_c.SetUpdatedAt(*v)
}
return _c
}
// SetDeletedAt sets the "deleted_at" field.
func (_c *DocumentCreate) SetDeletedAt(v string) *DocumentCreate {
_c.mutation.SetDeletedAt(v)
return _c
}
// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_c *DocumentCreate) SetNillableDeletedAt(v *string) *DocumentCreate {
if v != nil {
_c.SetDeletedAt(*v)
}
return _c
}
// SetTitle sets the "title" field.
func (_c *DocumentCreate) SetTitle(v string) *DocumentCreate {
_c.mutation.SetTitle(v)
return _c
}
// SetContent sets the "content" field.
func (_c *DocumentCreate) SetContent(v string) *DocumentCreate {
_c.mutation.SetContent(v)
return _c
}
// SetNillableContent sets the "content" field if the given value is not nil.
func (_c *DocumentCreate) SetNillableContent(v *string) *DocumentCreate {
if v != nil {
_c.SetContent(*v)
}
return _c
}
// SetLocked sets the "locked" field.
func (_c *DocumentCreate) SetLocked(v bool) *DocumentCreate {
_c.mutation.SetLocked(v)
return _c
}
// SetNillableLocked sets the "locked" field if the given value is not nil.
func (_c *DocumentCreate) SetNillableLocked(v *bool) *DocumentCreate {
if v != nil {
_c.SetLocked(*v)
}
return _c
}
// Mutation returns the DocumentMutation object of the builder.
func (_c *DocumentCreate) Mutation() *DocumentMutation {
return _c.mutation
}
// Save creates the Document in the database.
func (_c *DocumentCreate) Save(ctx context.Context) (*Document, error) {
if err := _c.defaults(); err != nil {
return nil, err
}
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *DocumentCreate) SaveX(ctx context.Context) *Document {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *DocumentCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *DocumentCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_c *DocumentCreate) defaults() error {
if _, ok := _c.mutation.CreatedAt(); !ok {
if document.DefaultCreatedAt == nil {
return fmt.Errorf("ent: uninitialized document.DefaultCreatedAt (forgotten import ent/runtime?)")
}
v := document.DefaultCreatedAt()
_c.mutation.SetCreatedAt(v)
}
if _, ok := _c.mutation.UpdatedAt(); !ok {
if document.DefaultUpdatedAt == nil {
return fmt.Errorf("ent: uninitialized document.DefaultUpdatedAt (forgotten import ent/runtime?)")
}
v := document.DefaultUpdatedAt()
_c.mutation.SetUpdatedAt(v)
}
if _, ok := _c.mutation.Content(); !ok {
v := document.DefaultContent
_c.mutation.SetContent(v)
}
if _, ok := _c.mutation.Locked(); !ok {
v := document.DefaultLocked
_c.mutation.SetLocked(v)
}
return nil
}
// check runs all checks and user-defined validators on the builder.
func (_c *DocumentCreate) check() error {
if _, ok := _c.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Document.created_at"`)}
}
if _, ok := _c.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Document.updated_at"`)}
}
if _, ok := _c.mutation.Title(); !ok {
return &ValidationError{Name: "title", err: errors.New(`ent: missing required field "Document.title"`)}
}
if v, ok := _c.mutation.Title(); ok {
if err := document.TitleValidator(v); err != nil {
return &ValidationError{Name: "title", err: fmt.Errorf(`ent: validator failed for field "Document.title": %w`, err)}
}
}
if _, ok := _c.mutation.Locked(); !ok {
return &ValidationError{Name: "locked", err: errors.New(`ent: missing required field "Document.locked"`)}
}
return nil
}
func (_c *DocumentCreate) sqlSave(ctx context.Context) (*Document, error) {
if err := _c.check(); err != nil {
return nil, err
}
_node, _spec := _c.createSpec()
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
_c.mutation.id = &_node.ID
_c.mutation.done = true
return _node, nil
}
func (_c *DocumentCreate) createSpec() (*Document, *sqlgraph.CreateSpec) {
var (
_node = &Document{config: _c.config}
_spec = sqlgraph.NewCreateSpec(document.Table, sqlgraph.NewFieldSpec(document.FieldID, field.TypeInt))
)
if value, ok := _c.mutation.CreatedAt(); ok {
_spec.SetField(document.FieldCreatedAt, field.TypeString, value)
_node.CreatedAt = value
}
if value, ok := _c.mutation.UpdatedAt(); ok {
_spec.SetField(document.FieldUpdatedAt, field.TypeString, value)
_node.UpdatedAt = value
}
if value, ok := _c.mutation.DeletedAt(); ok {
_spec.SetField(document.FieldDeletedAt, field.TypeString, value)
_node.DeletedAt = &value
}
if value, ok := _c.mutation.Title(); ok {
_spec.SetField(document.FieldTitle, field.TypeString, value)
_node.Title = value
}
if value, ok := _c.mutation.Content(); ok {
_spec.SetField(document.FieldContent, field.TypeString, value)
_node.Content = value
}
if value, ok := _c.mutation.Locked(); ok {
_spec.SetField(document.FieldLocked, field.TypeBool, value)
_node.Locked = value
}
return _node, _spec
}
// DocumentCreateBulk is the builder for creating many Document entities in bulk.
type DocumentCreateBulk struct {
config
err error
builders []*DocumentCreate
}
// Save creates the Document entities in the database.
func (_c *DocumentCreateBulk) Save(ctx context.Context) ([]*Document, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*Document, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*DocumentMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
mutation.done = true
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, _c.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (_c *DocumentCreateBulk) SaveX(ctx context.Context) []*Document {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *DocumentCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *DocumentCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,88 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"voidraft/internal/models/ent/document"
"voidraft/internal/models/ent/predicate"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// DocumentDelete is the builder for deleting a Document entity.
type DocumentDelete struct {
config
hooks []Hook
mutation *DocumentMutation
}
// Where appends a list predicates to the DocumentDelete builder.
func (_d *DocumentDelete) Where(ps ...predicate.Document) *DocumentDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *DocumentDelete) Exec(ctx context.Context) (int, error) {
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *DocumentDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *DocumentDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(document.Table, sqlgraph.NewFieldSpec(document.FieldID, field.TypeInt))
if ps := _d.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
_d.mutation.done = true
return affected, err
}
// DocumentDeleteOne is the builder for deleting a single Document entity.
type DocumentDeleteOne struct {
_d *DocumentDelete
}
// Where appends a list predicates to the DocumentDelete builder.
func (_d *DocumentDeleteOne) Where(ps ...predicate.Document) *DocumentDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *DocumentDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{document.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *DocumentDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,577 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"voidraft/internal/models/ent/document"
"voidraft/internal/models/ent/predicate"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// DocumentQuery is the builder for querying Document entities.
type DocumentQuery struct {
config
ctx *QueryContext
order []document.OrderOption
inters []Interceptor
predicates []predicate.Document
modifiers []func(*sql.Selector)
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the DocumentQuery builder.
func (_q *DocumentQuery) Where(ps ...predicate.Document) *DocumentQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *DocumentQuery) Limit(limit int) *DocumentQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *DocumentQuery) Offset(offset int) *DocumentQuery {
_q.ctx.Offset = &offset
return _q
}
// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (_q *DocumentQuery) Unique(unique bool) *DocumentQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *DocumentQuery) Order(o ...document.OrderOption) *DocumentQuery {
_q.order = append(_q.order, o...)
return _q
}
// First returns the first Document entity from the query.
// Returns a *NotFoundError when no Document was found.
func (_q *DocumentQuery) First(ctx context.Context) (*Document, error) {
nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{document.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *DocumentQuery) FirstX(ctx context.Context) *Document {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Document ID from the query.
// Returns a *NotFoundError when no Document ID was found.
func (_q *DocumentQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{document.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *DocumentQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Document entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Document entity is found.
// Returns a *NotFoundError when no Document entities are found.
func (_q *DocumentQuery) Only(ctx context.Context) (*Document, error) {
nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{document.Label}
default:
return nil, &NotSingularError{document.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *DocumentQuery) OnlyX(ctx context.Context) *Document {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Document ID in the query.
// Returns a *NotSingularError when more than one Document ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *DocumentQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{document.Label}
default:
err = &NotSingularError{document.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *DocumentQuery) OnlyIDX(ctx context.Context) int {
id, err := _q.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Documents.
func (_q *DocumentQuery) All(ctx context.Context) ([]*Document, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Document, *DocumentQuery]()
return withInterceptors[[]*Document](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *DocumentQuery) AllX(ctx context.Context) []*Document {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Document IDs.
func (_q *DocumentQuery) IDs(ctx context.Context) (ids []int, err error) {
if _q.ctx.Unique == nil && _q.path != nil {
_q.Unique(true)
}
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
if err = _q.Select(document.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *DocumentQuery) IDsX(ctx context.Context) []int {
ids, err := _q.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (_q *DocumentQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)
if err := _q.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, _q, querierCount[*DocumentQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *DocumentQuery) CountX(ctx context.Context) int {
count, err := _q.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (_q *DocumentQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
switch _, err := _q.FirstID(ctx); {
case IsNotFound(err):
return false, nil
case err != nil:
return false, fmt.Errorf("ent: check existence: %w", err)
default:
return true, nil
}
}
// ExistX is like Exist, but panics if an error occurs.
func (_q *DocumentQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the DocumentQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (_q *DocumentQuery) Clone() *DocumentQuery {
if _q == nil {
return nil
}
return &DocumentQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]document.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Document{}, _q.predicates...),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
modifiers: append([]func(*sql.Selector){}, _q.modifiers...),
}
}
// GroupBy is 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 {
// CreatedAt string `json:"created_at"`
// Count int `json:"count,omitempty"`
// }
//
// client.Document.Query().
// GroupBy(document.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *DocumentQuery) GroupBy(field string, fields ...string) *DocumentGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &DocumentGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = document.Label
grbuild.scan = grbuild.Scan
return grbuild
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// CreatedAt string `json:"created_at"`
// }
//
// client.Document.Query().
// Select(document.FieldCreatedAt).
// Scan(ctx, &v)
func (_q *DocumentQuery) Select(fields ...string) *DocumentSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &DocumentSelect{DocumentQuery: _q}
sbuild.label = document.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a DocumentSelect configured with the given aggregations.
func (_q *DocumentQuery) Aggregate(fns ...AggregateFunc) *DocumentSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *DocumentQuery) prepareQuery(ctx context.Context) error {
for _, inter := range _q.inters {
if inter == nil {
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
}
if trv, ok := inter.(Traverser); ok {
if err := trv.Traverse(ctx, _q); err != nil {
return err
}
}
}
for _, f := range _q.ctx.Fields {
if !document.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if _q.path != nil {
prev, err := _q.path(ctx)
if err != nil {
return err
}
_q.sql = prev
}
return nil
}
func (_q *DocumentQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Document, error) {
var (
nodes = []*Document{}
_spec = _q.querySpec()
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Document).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Document{config: _q.config}
nodes = append(nodes, node)
return node.assignValues(columns, values)
}
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (_q *DocumentQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *DocumentQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(document.Table, document.Columns, sqlgraph.NewFieldSpec(document.FieldID, field.TypeInt))
_spec.From = _q.sql
if unique := _q.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if _q.path != nil {
_spec.Unique = true
}
if fields := _q.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, document.FieldID)
for i := range fields {
if fields[i] != document.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := _q.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := _q.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := _q.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := _q.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (_q *DocumentQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(document.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = document.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, m := range _q.modifiers {
m(selector)
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.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 := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
// updated, deleted or "selected ... for update" by other sessions, until the transaction is
// either committed or rolled-back.
func (_q *DocumentQuery) ForUpdate(opts ...sql.LockOption) *DocumentQuery {
if _q.driver.Dialect() == dialect.Postgres {
_q.Unique(false)
}
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
s.ForUpdate(opts...)
})
return _q
}
// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
// on any rows that are read. Other sessions can read the rows, but cannot modify them
// until your transaction commits.
func (_q *DocumentQuery) ForShare(opts ...sql.LockOption) *DocumentQuery {
if _q.driver.Dialect() == dialect.Postgres {
_q.Unique(false)
}
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
s.ForShare(opts...)
})
return _q
}
// Modify adds a query modifier for attaching custom logic to queries.
func (_q *DocumentQuery) Modify(modifiers ...func(s *sql.Selector)) *DocumentSelect {
_q.modifiers = append(_q.modifiers, modifiers...)
return _q.Select()
}
// DocumentGroupBy is the group-by builder for Document entities.
type DocumentGroupBy struct {
selector
build *DocumentQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *DocumentGroupBy) Aggregate(fns ...AggregateFunc) *DocumentGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *DocumentGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)
if err := _g.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*DocumentQuery, *DocumentGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *DocumentGroupBy) sqlScan(ctx context.Context, root *DocumentQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(_g.fns))
for _, fn := range _g.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*_g.flds)+len(_g.fns))
for _, f := range *_g.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*_g.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// DocumentSelect is the builder for selecting fields of Document entities.
type DocumentSelect struct {
*DocumentQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *DocumentSelect) Aggregate(fns ...AggregateFunc) *DocumentSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *DocumentSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)
if err := _s.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*DocumentQuery, *DocumentSelect](ctx, _s.DocumentQuery, _s, _s.inters, v)
}
func (_s *DocumentSelect) sqlScan(ctx context.Context, root *DocumentQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(_s.fns))
for _, fn := range _s.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*_s.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// Modify adds a query modifier for attaching custom logic to queries.
func (_s *DocumentSelect) Modify(modifiers ...func(s *sql.Selector)) *DocumentSelect {
_s.modifiers = append(_s.modifiers, modifiers...)
return _s
}

View File

@@ -0,0 +1,423 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"voidraft/internal/models/ent/document"
"voidraft/internal/models/ent/predicate"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// DocumentUpdate is the builder for updating Document entities.
type DocumentUpdate struct {
config
hooks []Hook
mutation *DocumentMutation
modifiers []func(*sql.UpdateBuilder)
}
// Where appends a list predicates to the DocumentUpdate builder.
func (_u *DocumentUpdate) Where(ps ...predicate.Document) *DocumentUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetUpdatedAt sets the "updated_at" field.
func (_u *DocumentUpdate) SetUpdatedAt(v string) *DocumentUpdate {
_u.mutation.SetUpdatedAt(v)
return _u
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (_u *DocumentUpdate) SetNillableUpdatedAt(v *string) *DocumentUpdate {
if v != nil {
_u.SetUpdatedAt(*v)
}
return _u
}
// SetDeletedAt sets the "deleted_at" field.
func (_u *DocumentUpdate) SetDeletedAt(v string) *DocumentUpdate {
_u.mutation.SetDeletedAt(v)
return _u
}
// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_u *DocumentUpdate) SetNillableDeletedAt(v *string) *DocumentUpdate {
if v != nil {
_u.SetDeletedAt(*v)
}
return _u
}
// ClearDeletedAt clears the value of the "deleted_at" field.
func (_u *DocumentUpdate) ClearDeletedAt() *DocumentUpdate {
_u.mutation.ClearDeletedAt()
return _u
}
// SetTitle sets the "title" field.
func (_u *DocumentUpdate) SetTitle(v string) *DocumentUpdate {
_u.mutation.SetTitle(v)
return _u
}
// SetNillableTitle sets the "title" field if the given value is not nil.
func (_u *DocumentUpdate) SetNillableTitle(v *string) *DocumentUpdate {
if v != nil {
_u.SetTitle(*v)
}
return _u
}
// SetContent sets the "content" field.
func (_u *DocumentUpdate) SetContent(v string) *DocumentUpdate {
_u.mutation.SetContent(v)
return _u
}
// SetNillableContent sets the "content" field if the given value is not nil.
func (_u *DocumentUpdate) SetNillableContent(v *string) *DocumentUpdate {
if v != nil {
_u.SetContent(*v)
}
return _u
}
// ClearContent clears the value of the "content" field.
func (_u *DocumentUpdate) ClearContent() *DocumentUpdate {
_u.mutation.ClearContent()
return _u
}
// SetLocked sets the "locked" field.
func (_u *DocumentUpdate) SetLocked(v bool) *DocumentUpdate {
_u.mutation.SetLocked(v)
return _u
}
// SetNillableLocked sets the "locked" field if the given value is not nil.
func (_u *DocumentUpdate) SetNillableLocked(v *bool) *DocumentUpdate {
if v != nil {
_u.SetLocked(*v)
}
return _u
}
// Mutation returns the DocumentMutation object of the builder.
func (_u *DocumentUpdate) Mutation() *DocumentMutation {
return _u.mutation
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *DocumentUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *DocumentUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *DocumentUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *DocumentUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *DocumentUpdate) check() error {
if v, ok := _u.mutation.Title(); ok {
if err := document.TitleValidator(v); err != nil {
return &ValidationError{Name: "title", err: fmt.Errorf(`ent: validator failed for field "Document.title": %w`, err)}
}
}
return nil
}
// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
func (_u *DocumentUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *DocumentUpdate {
_u.modifiers = append(_u.modifiers, modifiers...)
return _u
}
func (_u *DocumentUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(document.Table, document.Columns, sqlgraph.NewFieldSpec(document.FieldID, field.TypeInt))
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(document.FieldUpdatedAt, field.TypeString, value)
}
if value, ok := _u.mutation.DeletedAt(); ok {
_spec.SetField(document.FieldDeletedAt, field.TypeString, value)
}
if _u.mutation.DeletedAtCleared() {
_spec.ClearField(document.FieldDeletedAt, field.TypeString)
}
if value, ok := _u.mutation.Title(); ok {
_spec.SetField(document.FieldTitle, field.TypeString, value)
}
if value, ok := _u.mutation.Content(); ok {
_spec.SetField(document.FieldContent, field.TypeString, value)
}
if _u.mutation.ContentCleared() {
_spec.ClearField(document.FieldContent, field.TypeString)
}
if value, ok := _u.mutation.Locked(); ok {
_spec.SetField(document.FieldLocked, field.TypeBool, value)
}
_spec.AddModifiers(_u.modifiers...)
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{document.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// DocumentUpdateOne is the builder for updating a single Document entity.
type DocumentUpdateOne struct {
config
fields []string
hooks []Hook
mutation *DocumentMutation
modifiers []func(*sql.UpdateBuilder)
}
// SetUpdatedAt sets the "updated_at" field.
func (_u *DocumentUpdateOne) SetUpdatedAt(v string) *DocumentUpdateOne {
_u.mutation.SetUpdatedAt(v)
return _u
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (_u *DocumentUpdateOne) SetNillableUpdatedAt(v *string) *DocumentUpdateOne {
if v != nil {
_u.SetUpdatedAt(*v)
}
return _u
}
// SetDeletedAt sets the "deleted_at" field.
func (_u *DocumentUpdateOne) SetDeletedAt(v string) *DocumentUpdateOne {
_u.mutation.SetDeletedAt(v)
return _u
}
// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_u *DocumentUpdateOne) SetNillableDeletedAt(v *string) *DocumentUpdateOne {
if v != nil {
_u.SetDeletedAt(*v)
}
return _u
}
// ClearDeletedAt clears the value of the "deleted_at" field.
func (_u *DocumentUpdateOne) ClearDeletedAt() *DocumentUpdateOne {
_u.mutation.ClearDeletedAt()
return _u
}
// SetTitle sets the "title" field.
func (_u *DocumentUpdateOne) SetTitle(v string) *DocumentUpdateOne {
_u.mutation.SetTitle(v)
return _u
}
// SetNillableTitle sets the "title" field if the given value is not nil.
func (_u *DocumentUpdateOne) SetNillableTitle(v *string) *DocumentUpdateOne {
if v != nil {
_u.SetTitle(*v)
}
return _u
}
// SetContent sets the "content" field.
func (_u *DocumentUpdateOne) SetContent(v string) *DocumentUpdateOne {
_u.mutation.SetContent(v)
return _u
}
// SetNillableContent sets the "content" field if the given value is not nil.
func (_u *DocumentUpdateOne) SetNillableContent(v *string) *DocumentUpdateOne {
if v != nil {
_u.SetContent(*v)
}
return _u
}
// ClearContent clears the value of the "content" field.
func (_u *DocumentUpdateOne) ClearContent() *DocumentUpdateOne {
_u.mutation.ClearContent()
return _u
}
// SetLocked sets the "locked" field.
func (_u *DocumentUpdateOne) SetLocked(v bool) *DocumentUpdateOne {
_u.mutation.SetLocked(v)
return _u
}
// SetNillableLocked sets the "locked" field if the given value is not nil.
func (_u *DocumentUpdateOne) SetNillableLocked(v *bool) *DocumentUpdateOne {
if v != nil {
_u.SetLocked(*v)
}
return _u
}
// Mutation returns the DocumentMutation object of the builder.
func (_u *DocumentUpdateOne) Mutation() *DocumentMutation {
return _u.mutation
}
// Where appends a list predicates to the DocumentUpdate builder.
func (_u *DocumentUpdateOne) Where(ps ...predicate.Document) *DocumentUpdateOne {
_u.mutation.Where(ps...)
return _u
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (_u *DocumentUpdateOne) Select(field string, fields ...string) *DocumentUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated Document entity.
func (_u *DocumentUpdateOne) Save(ctx context.Context) (*Document, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *DocumentUpdateOne) SaveX(ctx context.Context) *Document {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *DocumentUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *DocumentUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *DocumentUpdateOne) check() error {
if v, ok := _u.mutation.Title(); ok {
if err := document.TitleValidator(v); err != nil {
return &ValidationError{Name: "title", err: fmt.Errorf(`ent: validator failed for field "Document.title": %w`, err)}
}
}
return nil
}
// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
func (_u *DocumentUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *DocumentUpdateOne {
_u.modifiers = append(_u.modifiers, modifiers...)
return _u
}
func (_u *DocumentUpdateOne) sqlSave(ctx context.Context) (_node *Document, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(document.Table, document.Columns, sqlgraph.NewFieldSpec(document.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Document.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := _u.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, document.FieldID)
for _, f := range fields {
if !document.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != document.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(document.FieldUpdatedAt, field.TypeString, value)
}
if value, ok := _u.mutation.DeletedAt(); ok {
_spec.SetField(document.FieldDeletedAt, field.TypeString, value)
}
if _u.mutation.DeletedAtCleared() {
_spec.ClearField(document.FieldDeletedAt, field.TypeString)
}
if value, ok := _u.mutation.Title(); ok {
_spec.SetField(document.FieldTitle, field.TypeString, value)
}
if value, ok := _u.mutation.Content(); ok {
_spec.SetField(document.FieldContent, field.TypeString, value)
}
if _u.mutation.ContentCleared() {
_spec.ClearField(document.FieldContent, field.TypeString)
}
if value, ok := _u.mutation.Locked(); ok {
_spec.SetField(document.FieldLocked, field.TypeBool, value)
}
_spec.AddModifiers(_u.modifiers...)
_node = &Document{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{document.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

614
internal/models/ent/ent.go Normal file
View File

@@ -0,0 +1,614 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"reflect"
"sync"
"voidraft/internal/models/ent/document"
"voidraft/internal/models/ent/extension"
"voidraft/internal/models/ent/keybinding"
"voidraft/internal/models/ent/theme"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
// ent aliases to avoid import conflicts in user's code.
type (
Op = ent.Op
Hook = ent.Hook
Value = ent.Value
Query = ent.Query
QueryContext = ent.QueryContext
Querier = ent.Querier
QuerierFunc = ent.QuerierFunc
Interceptor = ent.Interceptor
InterceptFunc = ent.InterceptFunc
Traverser = ent.Traverser
TraverseFunc = ent.TraverseFunc
Policy = ent.Policy
Mutator = ent.Mutator
Mutation = ent.Mutation
MutateFunc = ent.MutateFunc
)
type clientCtxKey struct{}
// FromContext returns a Client stored inside 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 a Tx stored inside 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 Tx attached.
func NewTxContext(parent context.Context, tx *Tx) context.Context {
return context.WithValue(parent, txCtxKey{}, tx)
}
// OrderFunc applies an ordering on the sql selector.
// Deprecated: Use Asc/Desc functions or the package builders instead.
type OrderFunc func(*sql.Selector)
var (
initCheck sync.Once
columnCheck sql.ColumnCheck
)
// checkColumn checks if the column exists in the given table.
func checkColumn(t, c string) error {
initCheck.Do(func() {
columnCheck = sql.NewColumnCheck(map[string]func(string) bool{
document.Table: document.ValidColumn,
extension.Table: extension.ValidColumn,
keybinding.Table: keybinding.ValidColumn,
theme.Table: theme.ValidColumn,
})
})
return columnCheck(t, c)
}
// Asc applies the given fields in ASC order.
func Asc(fields ...string) func(*sql.Selector) {
return func(s *sql.Selector) {
for _, f := range fields {
if err := checkColumn(s.TableName(), f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
}
s.OrderBy(sql.Asc(s.C(f)))
}
}
}
// Desc applies the given fields in DESC order.
func Desc(fields ...string) func(*sql.Selector) {
return func(s *sql.Selector) {
for _, f := range fields {
if err := checkColumn(s.TableName(), f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
}
s.OrderBy(sql.Desc(s.C(f)))
}
}
}
// AggregateFunc applies an aggregation step on the group-by traversal/selector.
type AggregateFunc func(*sql.Selector) 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) string {
return sql.As(fn(s), end)
}
}
// Count applies the "count" aggregation function on each group.
func Count() AggregateFunc {
return func(s *sql.Selector) string {
return sql.Count("*")
}
}
// Max applies the "max" aggregation function on the given field of each group.
func Max(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Max(s.C(field))
}
}
// Mean applies the "mean" aggregation function on the given field of each group.
func Mean(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Avg(s.C(field))
}
}
// Min applies the "min" aggregation function on the given field of each group.
func Min(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Min(s.C(field))
}
}
// Sum applies the "sum" aggregation function on the given field of each group.
func Sum(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Sum(s.C(field))
}
}
// ValidationError returns when validating a field or edge 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 validation 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 not 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)
}
// selector embedded by the different Select/GroupBy builders.
type selector struct {
label string
flds *[]string
fns []AggregateFunc
scan func(context.Context, any) error
}
// ScanX is like Scan, but panics if an error occurs.
func (s *selector) ScanX(ctx context.Context, v any) {
if err := s.scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (s *selector) Strings(ctx context.Context) ([]string, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (s *selector) StringsX(ctx context.Context) []string {
v, err := s.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a selector. It is only allowed when selecting one field.
func (s *selector) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = s.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (s *selector) StringX(ctx context.Context) string {
v, err := s.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (s *selector) Ints(ctx context.Context) ([]int, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (s *selector) IntsX(ctx context.Context) []int {
v, err := s.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a selector. It is only allowed when selecting one field.
func (s *selector) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = s.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (s *selector) IntX(ctx context.Context) int {
v, err := s.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (s *selector) Float64s(ctx context.Context) ([]float64, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (s *selector) Float64sX(ctx context.Context) []float64 {
v, err := s.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (s *selector) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = s.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (s *selector) Float64X(ctx context.Context) float64 {
v, err := s.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (s *selector) Bools(ctx context.Context) ([]bool, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (s *selector) BoolsX(ctx context.Context) []bool {
v, err := s.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (s *selector) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = s.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (s *selector) BoolX(ctx context.Context) bool {
v, err := s.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
// withHooks invokes the builder operation with the given hooks, if any.
func withHooks[V Value, M any, PM interface {
*M
Mutation
}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) {
if len(hooks) == 0 {
return exec(ctx)
}
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutationT, ok := any(m).(PM)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
// Set the mutation to the builder.
*mutation = *mutationT
return exec(ctx)
})
for i := len(hooks) - 1; i >= 0; i-- {
if hooks[i] == nil {
return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = hooks[i](mut)
}
v, err := mut.Mutate(ctx, mutation)
if err != nil {
return value, err
}
nv, ok := v.(V)
if !ok {
return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation)
}
return nv, nil
}
// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist.
func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context {
if ent.QueryFromContext(ctx) == nil {
qc.Op = op
ctx = ent.NewQueryContext(ctx, qc)
}
return ctx
}
func querierAll[V Value, Q interface {
sqlAll(context.Context, ...queryHook) (V, error)
}]() Querier {
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
return query.sqlAll(ctx)
})
}
func querierCount[Q interface {
sqlCount(context.Context) (int, error)
}]() Querier {
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
return query.sqlCount(ctx)
})
}
func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) {
for i := len(inters) - 1; i >= 0; i-- {
qr = inters[i].Intercept(qr)
}
rv, err := qr.Query(ctx, q)
if err != nil {
return v, err
}
vt, ok := rv.(V)
if !ok {
return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v)
}
return vt, nil
}
func scanWithInterceptors[Q1 ent.Query, Q2 interface {
sqlScan(context.Context, Q1, any) error
}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error {
rv := reflect.ValueOf(v)
var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q1)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
if err := selectOrGroup.sqlScan(ctx, query, v); err != nil {
return nil, err
}
if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() {
return rv.Elem().Interface(), nil
}
return v, nil
})
for i := len(inters) - 1; i >= 0; i-- {
qr = inters[i].Intercept(qr)
}
vv, err := qr.Query(ctx, rootQuery)
if err != nil {
return err
}
switch rv2 := reflect.ValueOf(vv); {
case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer:
case rv.Type() == rv2.Type():
rv.Elem().Set(rv2.Elem())
case rv.Elem().Type() == rv2.Type():
rv.Elem().Set(rv2)
}
return nil
}
// queryHook describes an internal hook for the different sqlAll methods.
type queryHook func(context.Context, *sqlgraph.QuerySpec)

View File

@@ -0,0 +1,389 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"voidraft/internal/models/ent/document"
"voidraft/internal/models/ent/extension"
"voidraft/internal/models/ent/keybinding"
"voidraft/internal/models/ent/theme"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/entql"
"entgo.io/ent/schema/field"
)
// schemaGraph holds a representation of ent/schema at runtime.
var schemaGraph = func() *sqlgraph.Schema {
graph := &sqlgraph.Schema{Nodes: make([]*sqlgraph.Node, 4)}
graph.Nodes[0] = &sqlgraph.Node{
NodeSpec: sqlgraph.NodeSpec{
Table: document.Table,
Columns: document.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: document.FieldID,
},
},
Type: "Document",
Fields: map[string]*sqlgraph.FieldSpec{
document.FieldCreatedAt: {Type: field.TypeString, Column: document.FieldCreatedAt},
document.FieldUpdatedAt: {Type: field.TypeString, Column: document.FieldUpdatedAt},
document.FieldDeletedAt: {Type: field.TypeString, Column: document.FieldDeletedAt},
document.FieldTitle: {Type: field.TypeString, Column: document.FieldTitle},
document.FieldContent: {Type: field.TypeString, Column: document.FieldContent},
document.FieldLocked: {Type: field.TypeBool, Column: document.FieldLocked},
},
}
graph.Nodes[1] = &sqlgraph.Node{
NodeSpec: sqlgraph.NodeSpec{
Table: extension.Table,
Columns: extension.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: extension.FieldID,
},
},
Type: "Extension",
Fields: map[string]*sqlgraph.FieldSpec{
extension.FieldCreatedAt: {Type: field.TypeString, Column: extension.FieldCreatedAt},
extension.FieldUpdatedAt: {Type: field.TypeString, Column: extension.FieldUpdatedAt},
extension.FieldDeletedAt: {Type: field.TypeString, Column: extension.FieldDeletedAt},
extension.FieldKey: {Type: field.TypeString, Column: extension.FieldKey},
extension.FieldEnabled: {Type: field.TypeBool, Column: extension.FieldEnabled},
extension.FieldConfig: {Type: field.TypeJSON, Column: extension.FieldConfig},
},
}
graph.Nodes[2] = &sqlgraph.Node{
NodeSpec: sqlgraph.NodeSpec{
Table: keybinding.Table,
Columns: keybinding.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: keybinding.FieldID,
},
},
Type: "KeyBinding",
Fields: map[string]*sqlgraph.FieldSpec{
keybinding.FieldCreatedAt: {Type: field.TypeString, Column: keybinding.FieldCreatedAt},
keybinding.FieldUpdatedAt: {Type: field.TypeString, Column: keybinding.FieldUpdatedAt},
keybinding.FieldDeletedAt: {Type: field.TypeString, Column: keybinding.FieldDeletedAt},
keybinding.FieldKey: {Type: field.TypeString, Column: keybinding.FieldKey},
keybinding.FieldCommand: {Type: field.TypeString, Column: keybinding.FieldCommand},
keybinding.FieldExtension: {Type: field.TypeString, Column: keybinding.FieldExtension},
keybinding.FieldEnabled: {Type: field.TypeBool, Column: keybinding.FieldEnabled},
},
}
graph.Nodes[3] = &sqlgraph.Node{
NodeSpec: sqlgraph.NodeSpec{
Table: theme.Table,
Columns: theme.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: theme.FieldID,
},
},
Type: "Theme",
Fields: map[string]*sqlgraph.FieldSpec{
theme.FieldCreatedAt: {Type: field.TypeString, Column: theme.FieldCreatedAt},
theme.FieldUpdatedAt: {Type: field.TypeString, Column: theme.FieldUpdatedAt},
theme.FieldDeletedAt: {Type: field.TypeString, Column: theme.FieldDeletedAt},
theme.FieldKey: {Type: field.TypeString, Column: theme.FieldKey},
theme.FieldType: {Type: field.TypeEnum, Column: theme.FieldType},
theme.FieldColors: {Type: field.TypeJSON, Column: theme.FieldColors},
},
}
return graph
}()
// predicateAdder wraps the addPredicate method.
// All update, update-one and query builders implement this interface.
type predicateAdder interface {
addPredicate(func(s *sql.Selector))
}
// addPredicate implements the predicateAdder interface.
func (_q *DocumentQuery) addPredicate(pred func(s *sql.Selector)) {
_q.predicates = append(_q.predicates, pred)
}
// Filter returns a Filter implementation to apply filters on the DocumentQuery builder.
func (_q *DocumentQuery) Filter() *DocumentFilter {
return &DocumentFilter{config: _q.config, predicateAdder: _q}
}
// addPredicate implements the predicateAdder interface.
func (m *DocumentMutation) addPredicate(pred func(s *sql.Selector)) {
m.predicates = append(m.predicates, pred)
}
// Filter returns an entql.Where implementation to apply filters on the DocumentMutation builder.
func (m *DocumentMutation) Filter() *DocumentFilter {
return &DocumentFilter{config: m.config, predicateAdder: m}
}
// DocumentFilter provides a generic filtering capability at runtime for DocumentQuery.
type DocumentFilter struct {
predicateAdder
config
}
// Where applies the entql predicate on the query filter.
func (f *DocumentFilter) Where(p entql.P) {
f.addPredicate(func(s *sql.Selector) {
if err := schemaGraph.EvalP(schemaGraph.Nodes[0].Type, p, s); err != nil {
s.AddError(err)
}
})
}
// WhereID applies the entql int predicate on the id field.
func (f *DocumentFilter) WhereID(p entql.IntP) {
f.Where(p.Field(document.FieldID))
}
// WhereCreatedAt applies the entql string predicate on the created_at field.
func (f *DocumentFilter) WhereCreatedAt(p entql.StringP) {
f.Where(p.Field(document.FieldCreatedAt))
}
// WhereUpdatedAt applies the entql string predicate on the updated_at field.
func (f *DocumentFilter) WhereUpdatedAt(p entql.StringP) {
f.Where(p.Field(document.FieldUpdatedAt))
}
// WhereDeletedAt applies the entql string predicate on the deleted_at field.
func (f *DocumentFilter) WhereDeletedAt(p entql.StringP) {
f.Where(p.Field(document.FieldDeletedAt))
}
// WhereTitle applies the entql string predicate on the title field.
func (f *DocumentFilter) WhereTitle(p entql.StringP) {
f.Where(p.Field(document.FieldTitle))
}
// WhereContent applies the entql string predicate on the content field.
func (f *DocumentFilter) WhereContent(p entql.StringP) {
f.Where(p.Field(document.FieldContent))
}
// WhereLocked applies the entql bool predicate on the locked field.
func (f *DocumentFilter) WhereLocked(p entql.BoolP) {
f.Where(p.Field(document.FieldLocked))
}
// addPredicate implements the predicateAdder interface.
func (_q *ExtensionQuery) addPredicate(pred func(s *sql.Selector)) {
_q.predicates = append(_q.predicates, pred)
}
// Filter returns a Filter implementation to apply filters on the ExtensionQuery builder.
func (_q *ExtensionQuery) Filter() *ExtensionFilter {
return &ExtensionFilter{config: _q.config, predicateAdder: _q}
}
// addPredicate implements the predicateAdder interface.
func (m *ExtensionMutation) addPredicate(pred func(s *sql.Selector)) {
m.predicates = append(m.predicates, pred)
}
// Filter returns an entql.Where implementation to apply filters on the ExtensionMutation builder.
func (m *ExtensionMutation) Filter() *ExtensionFilter {
return &ExtensionFilter{config: m.config, predicateAdder: m}
}
// ExtensionFilter provides a generic filtering capability at runtime for ExtensionQuery.
type ExtensionFilter struct {
predicateAdder
config
}
// Where applies the entql predicate on the query filter.
func (f *ExtensionFilter) Where(p entql.P) {
f.addPredicate(func(s *sql.Selector) {
if err := schemaGraph.EvalP(schemaGraph.Nodes[1].Type, p, s); err != nil {
s.AddError(err)
}
})
}
// WhereID applies the entql int predicate on the id field.
func (f *ExtensionFilter) WhereID(p entql.IntP) {
f.Where(p.Field(extension.FieldID))
}
// WhereCreatedAt applies the entql string predicate on the created_at field.
func (f *ExtensionFilter) WhereCreatedAt(p entql.StringP) {
f.Where(p.Field(extension.FieldCreatedAt))
}
// WhereUpdatedAt applies the entql string predicate on the updated_at field.
func (f *ExtensionFilter) WhereUpdatedAt(p entql.StringP) {
f.Where(p.Field(extension.FieldUpdatedAt))
}
// WhereDeletedAt applies the entql string predicate on the deleted_at field.
func (f *ExtensionFilter) WhereDeletedAt(p entql.StringP) {
f.Where(p.Field(extension.FieldDeletedAt))
}
// WhereKey applies the entql string predicate on the key field.
func (f *ExtensionFilter) WhereKey(p entql.StringP) {
f.Where(p.Field(extension.FieldKey))
}
// WhereEnabled applies the entql bool predicate on the enabled field.
func (f *ExtensionFilter) WhereEnabled(p entql.BoolP) {
f.Where(p.Field(extension.FieldEnabled))
}
// WhereConfig applies the entql json.RawMessage predicate on the config field.
func (f *ExtensionFilter) WhereConfig(p entql.BytesP) {
f.Where(p.Field(extension.FieldConfig))
}
// addPredicate implements the predicateAdder interface.
func (_q *KeyBindingQuery) addPredicate(pred func(s *sql.Selector)) {
_q.predicates = append(_q.predicates, pred)
}
// Filter returns a Filter implementation to apply filters on the KeyBindingQuery builder.
func (_q *KeyBindingQuery) Filter() *KeyBindingFilter {
return &KeyBindingFilter{config: _q.config, predicateAdder: _q}
}
// addPredicate implements the predicateAdder interface.
func (m *KeyBindingMutation) addPredicate(pred func(s *sql.Selector)) {
m.predicates = append(m.predicates, pred)
}
// Filter returns an entql.Where implementation to apply filters on the KeyBindingMutation builder.
func (m *KeyBindingMutation) Filter() *KeyBindingFilter {
return &KeyBindingFilter{config: m.config, predicateAdder: m}
}
// KeyBindingFilter provides a generic filtering capability at runtime for KeyBindingQuery.
type KeyBindingFilter struct {
predicateAdder
config
}
// Where applies the entql predicate on the query filter.
func (f *KeyBindingFilter) Where(p entql.P) {
f.addPredicate(func(s *sql.Selector) {
if err := schemaGraph.EvalP(schemaGraph.Nodes[2].Type, p, s); err != nil {
s.AddError(err)
}
})
}
// WhereID applies the entql int predicate on the id field.
func (f *KeyBindingFilter) WhereID(p entql.IntP) {
f.Where(p.Field(keybinding.FieldID))
}
// WhereCreatedAt applies the entql string predicate on the created_at field.
func (f *KeyBindingFilter) WhereCreatedAt(p entql.StringP) {
f.Where(p.Field(keybinding.FieldCreatedAt))
}
// WhereUpdatedAt applies the entql string predicate on the updated_at field.
func (f *KeyBindingFilter) WhereUpdatedAt(p entql.StringP) {
f.Where(p.Field(keybinding.FieldUpdatedAt))
}
// WhereDeletedAt applies the entql string predicate on the deleted_at field.
func (f *KeyBindingFilter) WhereDeletedAt(p entql.StringP) {
f.Where(p.Field(keybinding.FieldDeletedAt))
}
// WhereKey applies the entql string predicate on the key field.
func (f *KeyBindingFilter) WhereKey(p entql.StringP) {
f.Where(p.Field(keybinding.FieldKey))
}
// WhereCommand applies the entql string predicate on the command field.
func (f *KeyBindingFilter) WhereCommand(p entql.StringP) {
f.Where(p.Field(keybinding.FieldCommand))
}
// WhereExtension applies the entql string predicate on the extension field.
func (f *KeyBindingFilter) WhereExtension(p entql.StringP) {
f.Where(p.Field(keybinding.FieldExtension))
}
// WhereEnabled applies the entql bool predicate on the enabled field.
func (f *KeyBindingFilter) WhereEnabled(p entql.BoolP) {
f.Where(p.Field(keybinding.FieldEnabled))
}
// addPredicate implements the predicateAdder interface.
func (_q *ThemeQuery) addPredicate(pred func(s *sql.Selector)) {
_q.predicates = append(_q.predicates, pred)
}
// Filter returns a Filter implementation to apply filters on the ThemeQuery builder.
func (_q *ThemeQuery) Filter() *ThemeFilter {
return &ThemeFilter{config: _q.config, predicateAdder: _q}
}
// addPredicate implements the predicateAdder interface.
func (m *ThemeMutation) addPredicate(pred func(s *sql.Selector)) {
m.predicates = append(m.predicates, pred)
}
// Filter returns an entql.Where implementation to apply filters on the ThemeMutation builder.
func (m *ThemeMutation) Filter() *ThemeFilter {
return &ThemeFilter{config: m.config, predicateAdder: m}
}
// ThemeFilter provides a generic filtering capability at runtime for ThemeQuery.
type ThemeFilter struct {
predicateAdder
config
}
// Where applies the entql predicate on the query filter.
func (f *ThemeFilter) Where(p entql.P) {
f.addPredicate(func(s *sql.Selector) {
if err := schemaGraph.EvalP(schemaGraph.Nodes[3].Type, p, s); err != nil {
s.AddError(err)
}
})
}
// WhereID applies the entql int predicate on the id field.
func (f *ThemeFilter) WhereID(p entql.IntP) {
f.Where(p.Field(theme.FieldID))
}
// WhereCreatedAt applies the entql string predicate on the created_at field.
func (f *ThemeFilter) WhereCreatedAt(p entql.StringP) {
f.Where(p.Field(theme.FieldCreatedAt))
}
// WhereUpdatedAt applies the entql string predicate on the updated_at field.
func (f *ThemeFilter) WhereUpdatedAt(p entql.StringP) {
f.Where(p.Field(theme.FieldUpdatedAt))
}
// WhereDeletedAt applies the entql string predicate on the deleted_at field.
func (f *ThemeFilter) WhereDeletedAt(p entql.StringP) {
f.Where(p.Field(theme.FieldDeletedAt))
}
// WhereKey applies the entql string predicate on the key field.
func (f *ThemeFilter) WhereKey(p entql.StringP) {
f.Where(p.Field(theme.FieldKey))
}
// WhereType applies the entql string predicate on the type field.
func (f *ThemeFilter) WhereType(p entql.StringP) {
f.Where(p.Field(theme.FieldType))
}
// WhereColors applies the entql json.RawMessage predicate on the colors field.
func (f *ThemeFilter) WhereColors(p entql.BytesP) {
f.Where(p.Field(theme.FieldColors))
}

View File

@@ -0,0 +1,85 @@
// Code generated by ent, DO NOT EDIT.
package enttest
import (
"context"
"voidraft/internal/models/ent"
// required by schema hooks.
_ "voidraft/internal/models/ent/runtime"
"voidraft/internal/models/ent/migrate"
"entgo.io/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(...any)
}
// 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()
}
migrateSchema(t, c, o)
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...)
migrateSchema(t, c, o)
return c
}
func migrateSchema(t TestingT, c *ent.Client, o *options) {
tables, err := schema.CopyTables(migrate.Tables)
if err != nil {
t.Error(err)
t.FailNow()
}
if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil {
t.Error(err)
t.FailNow()
}
}

View File

@@ -0,0 +1,168 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"encoding/json"
"fmt"
"strings"
"voidraft/internal/models/ent/extension"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
)
// Extension is the model entity for the Extension schema.
type Extension struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// 创建时间
CreatedAt string `json:"created_at"`
// 最后更新时间
UpdatedAt string `json:"updated_at"`
// 删除时间NULL表示未删除
DeletedAt *string `json:"deleted_at,omitempty"`
// 扩展标识符
Key string `json:"key"`
// 是否启用
Enabled bool `json:"enabled"`
// 扩展配置
Config map[string]interface{} `json:"config"`
selectValues sql.SelectValues
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Extension) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case extension.FieldConfig:
values[i] = new([]byte)
case extension.FieldEnabled:
values[i] = new(sql.NullBool)
case extension.FieldID:
values[i] = new(sql.NullInt64)
case extension.FieldCreatedAt, extension.FieldUpdatedAt, extension.FieldDeletedAt, extension.FieldKey:
values[i] = new(sql.NullString)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Extension fields.
func (_m *Extension) assignValues(columns []string, values []any) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case extension.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
_m.ID = int(value.Int64)
case extension.FieldCreatedAt:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
_m.CreatedAt = value.String
}
case extension.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
_m.UpdatedAt = value.String
}
case extension.FieldDeletedAt:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field deleted_at", values[i])
} else if value.Valid {
_m.DeletedAt = new(string)
*_m.DeletedAt = value.String
}
case extension.FieldKey:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field key", values[i])
} else if value.Valid {
_m.Key = value.String
}
case extension.FieldEnabled:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field enabled", values[i])
} else if value.Valid {
_m.Enabled = value.Bool
}
case extension.FieldConfig:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field config", values[i])
} else if value != nil && len(*value) > 0 {
if err := json.Unmarshal(*value, &_m.Config); err != nil {
return fmt.Errorf("unmarshal field config: %w", err)
}
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Extension.
// This includes values selected through modifiers, order, etc.
func (_m *Extension) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// Update returns a builder for updating this Extension.
// Note that you need to call Extension.Unwrap() before calling this method if this Extension
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Extension) Update() *ExtensionUpdateOne {
return NewExtensionClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Extension entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (_m *Extension) Unwrap() *Extension {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: Extension is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Extension) String() string {
var builder strings.Builder
builder.WriteString("Extension(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("created_at=")
builder.WriteString(_m.CreatedAt)
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(_m.UpdatedAt)
builder.WriteString(", ")
if v := _m.DeletedAt; v != nil {
builder.WriteString("deleted_at=")
builder.WriteString(*v)
}
builder.WriteString(", ")
builder.WriteString("key=")
builder.WriteString(_m.Key)
builder.WriteString(", ")
builder.WriteString("enabled=")
builder.WriteString(fmt.Sprintf("%v", _m.Enabled))
builder.WriteString(", ")
builder.WriteString("config=")
builder.WriteString(fmt.Sprintf("%v", _m.Config))
builder.WriteByte(')')
return builder.String()
}
// Extensions is a parsable slice of Extension.
type Extensions []*Extension

View File

@@ -0,0 +1,101 @@
// Code generated by ent, DO NOT EDIT.
package extension
import (
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
)
const (
// Label holds the string label denoting the extension type in the database.
Label = "extension"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
FieldUpdatedAt = "updated_at"
// FieldDeletedAt holds the string denoting the deleted_at field in the database.
FieldDeletedAt = "deleted_at"
// FieldKey holds the string denoting the key field in the database.
FieldKey = "key"
// FieldEnabled holds the string denoting the enabled field in the database.
FieldEnabled = "enabled"
// FieldConfig holds the string denoting the config field in the database.
FieldConfig = "config"
// Table holds the table name of the extension in the database.
Table = "extensions"
)
// Columns holds all SQL columns for extension fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldDeletedAt,
FieldKey,
FieldEnabled,
FieldConfig,
}
// 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
}
// Note that the variables below are initialized by the runtime
// package on the initialization of the application. Therefore,
// it should be imported in the main as follows:
//
// import _ "voidraft/internal/models/ent/runtime"
var (
Hooks [2]ent.Hook
Interceptors [1]ent.Interceptor
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() string
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() string
// KeyValidator is a validator for the "key" field. It is called by the builders before save.
KeyValidator func(string) error
// DefaultEnabled holds the default value on creation for the "enabled" field.
DefaultEnabled bool
)
// OrderOption defines the ordering options for the Extension queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByCreatedAt orders the results by the created_at field.
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
}
// ByUpdatedAt orders the results by the updated_at field.
func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
}
// ByDeletedAt orders the results by the deleted_at field.
func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDeletedAt, opts...).ToFunc()
}
// ByKey orders the results by the key field.
func ByKey(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldKey, opts...).ToFunc()
}
// ByEnabled orders the results by the enabled field.
func ByEnabled(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldEnabled, opts...).ToFunc()
}

View File

@@ -0,0 +1,384 @@
// Code generated by ent, DO NOT EDIT.
package extension
import (
"voidraft/internal/models/ent/predicate"
"entgo.io/ent/dialect/sql"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Extension {
return predicate.Extension(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Extension {
return predicate.Extension(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Extension {
return predicate.Extension(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Extension {
return predicate.Extension(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Extension {
return predicate.Extension(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Extension {
return predicate.Extension(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Extension {
return predicate.Extension(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Extension {
return predicate.Extension(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Extension {
return predicate.Extension(sql.FieldLTE(FieldID, id))
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v string) predicate.Extension {
return predicate.Extension(sql.FieldEQ(FieldCreatedAt, v))
}
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
func UpdatedAt(v string) predicate.Extension {
return predicate.Extension(sql.FieldEQ(FieldUpdatedAt, v))
}
// DeletedAt applies equality check predicate on the "deleted_at" field. It's identical to DeletedAtEQ.
func DeletedAt(v string) predicate.Extension {
return predicate.Extension(sql.FieldEQ(FieldDeletedAt, v))
}
// Key applies equality check predicate on the "key" field. It's identical to KeyEQ.
func Key(v string) predicate.Extension {
return predicate.Extension(sql.FieldEQ(FieldKey, v))
}
// Enabled applies equality check predicate on the "enabled" field. It's identical to EnabledEQ.
func Enabled(v bool) predicate.Extension {
return predicate.Extension(sql.FieldEQ(FieldEnabled, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v string) predicate.Extension {
return predicate.Extension(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v string) predicate.Extension {
return predicate.Extension(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...string) predicate.Extension {
return predicate.Extension(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...string) predicate.Extension {
return predicate.Extension(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v string) predicate.Extension {
return predicate.Extension(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v string) predicate.Extension {
return predicate.Extension(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v string) predicate.Extension {
return predicate.Extension(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v string) predicate.Extension {
return predicate.Extension(sql.FieldLTE(FieldCreatedAt, v))
}
// CreatedAtContains applies the Contains predicate on the "created_at" field.
func CreatedAtContains(v string) predicate.Extension {
return predicate.Extension(sql.FieldContains(FieldCreatedAt, v))
}
// CreatedAtHasPrefix applies the HasPrefix predicate on the "created_at" field.
func CreatedAtHasPrefix(v string) predicate.Extension {
return predicate.Extension(sql.FieldHasPrefix(FieldCreatedAt, v))
}
// CreatedAtHasSuffix applies the HasSuffix predicate on the "created_at" field.
func CreatedAtHasSuffix(v string) predicate.Extension {
return predicate.Extension(sql.FieldHasSuffix(FieldCreatedAt, v))
}
// CreatedAtEqualFold applies the EqualFold predicate on the "created_at" field.
func CreatedAtEqualFold(v string) predicate.Extension {
return predicate.Extension(sql.FieldEqualFold(FieldCreatedAt, v))
}
// CreatedAtContainsFold applies the ContainsFold predicate on the "created_at" field.
func CreatedAtContainsFold(v string) predicate.Extension {
return predicate.Extension(sql.FieldContainsFold(FieldCreatedAt, v))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v string) predicate.Extension {
return predicate.Extension(sql.FieldEQ(FieldUpdatedAt, v))
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v string) predicate.Extension {
return predicate.Extension(sql.FieldNEQ(FieldUpdatedAt, v))
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...string) predicate.Extension {
return predicate.Extension(sql.FieldIn(FieldUpdatedAt, vs...))
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...string) predicate.Extension {
return predicate.Extension(sql.FieldNotIn(FieldUpdatedAt, vs...))
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v string) predicate.Extension {
return predicate.Extension(sql.FieldGT(FieldUpdatedAt, v))
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v string) predicate.Extension {
return predicate.Extension(sql.FieldGTE(FieldUpdatedAt, v))
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v string) predicate.Extension {
return predicate.Extension(sql.FieldLT(FieldUpdatedAt, v))
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v string) predicate.Extension {
return predicate.Extension(sql.FieldLTE(FieldUpdatedAt, v))
}
// UpdatedAtContains applies the Contains predicate on the "updated_at" field.
func UpdatedAtContains(v string) predicate.Extension {
return predicate.Extension(sql.FieldContains(FieldUpdatedAt, v))
}
// UpdatedAtHasPrefix applies the HasPrefix predicate on the "updated_at" field.
func UpdatedAtHasPrefix(v string) predicate.Extension {
return predicate.Extension(sql.FieldHasPrefix(FieldUpdatedAt, v))
}
// UpdatedAtHasSuffix applies the HasSuffix predicate on the "updated_at" field.
func UpdatedAtHasSuffix(v string) predicate.Extension {
return predicate.Extension(sql.FieldHasSuffix(FieldUpdatedAt, v))
}
// UpdatedAtEqualFold applies the EqualFold predicate on the "updated_at" field.
func UpdatedAtEqualFold(v string) predicate.Extension {
return predicate.Extension(sql.FieldEqualFold(FieldUpdatedAt, v))
}
// UpdatedAtContainsFold applies the ContainsFold predicate on the "updated_at" field.
func UpdatedAtContainsFold(v string) predicate.Extension {
return predicate.Extension(sql.FieldContainsFold(FieldUpdatedAt, v))
}
// DeletedAtEQ applies the EQ predicate on the "deleted_at" field.
func DeletedAtEQ(v string) predicate.Extension {
return predicate.Extension(sql.FieldEQ(FieldDeletedAt, v))
}
// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field.
func DeletedAtNEQ(v string) predicate.Extension {
return predicate.Extension(sql.FieldNEQ(FieldDeletedAt, v))
}
// DeletedAtIn applies the In predicate on the "deleted_at" field.
func DeletedAtIn(vs ...string) predicate.Extension {
return predicate.Extension(sql.FieldIn(FieldDeletedAt, vs...))
}
// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field.
func DeletedAtNotIn(vs ...string) predicate.Extension {
return predicate.Extension(sql.FieldNotIn(FieldDeletedAt, vs...))
}
// DeletedAtGT applies the GT predicate on the "deleted_at" field.
func DeletedAtGT(v string) predicate.Extension {
return predicate.Extension(sql.FieldGT(FieldDeletedAt, v))
}
// DeletedAtGTE applies the GTE predicate on the "deleted_at" field.
func DeletedAtGTE(v string) predicate.Extension {
return predicate.Extension(sql.FieldGTE(FieldDeletedAt, v))
}
// DeletedAtLT applies the LT predicate on the "deleted_at" field.
func DeletedAtLT(v string) predicate.Extension {
return predicate.Extension(sql.FieldLT(FieldDeletedAt, v))
}
// DeletedAtLTE applies the LTE predicate on the "deleted_at" field.
func DeletedAtLTE(v string) predicate.Extension {
return predicate.Extension(sql.FieldLTE(FieldDeletedAt, v))
}
// DeletedAtContains applies the Contains predicate on the "deleted_at" field.
func DeletedAtContains(v string) predicate.Extension {
return predicate.Extension(sql.FieldContains(FieldDeletedAt, v))
}
// DeletedAtHasPrefix applies the HasPrefix predicate on the "deleted_at" field.
func DeletedAtHasPrefix(v string) predicate.Extension {
return predicate.Extension(sql.FieldHasPrefix(FieldDeletedAt, v))
}
// DeletedAtHasSuffix applies the HasSuffix predicate on the "deleted_at" field.
func DeletedAtHasSuffix(v string) predicate.Extension {
return predicate.Extension(sql.FieldHasSuffix(FieldDeletedAt, v))
}
// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field.
func DeletedAtIsNil() predicate.Extension {
return predicate.Extension(sql.FieldIsNull(FieldDeletedAt))
}
// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field.
func DeletedAtNotNil() predicate.Extension {
return predicate.Extension(sql.FieldNotNull(FieldDeletedAt))
}
// DeletedAtEqualFold applies the EqualFold predicate on the "deleted_at" field.
func DeletedAtEqualFold(v string) predicate.Extension {
return predicate.Extension(sql.FieldEqualFold(FieldDeletedAt, v))
}
// DeletedAtContainsFold applies the ContainsFold predicate on the "deleted_at" field.
func DeletedAtContainsFold(v string) predicate.Extension {
return predicate.Extension(sql.FieldContainsFold(FieldDeletedAt, v))
}
// KeyEQ applies the EQ predicate on the "key" field.
func KeyEQ(v string) predicate.Extension {
return predicate.Extension(sql.FieldEQ(FieldKey, v))
}
// KeyNEQ applies the NEQ predicate on the "key" field.
func KeyNEQ(v string) predicate.Extension {
return predicate.Extension(sql.FieldNEQ(FieldKey, v))
}
// KeyIn applies the In predicate on the "key" field.
func KeyIn(vs ...string) predicate.Extension {
return predicate.Extension(sql.FieldIn(FieldKey, vs...))
}
// KeyNotIn applies the NotIn predicate on the "key" field.
func KeyNotIn(vs ...string) predicate.Extension {
return predicate.Extension(sql.FieldNotIn(FieldKey, vs...))
}
// KeyGT applies the GT predicate on the "key" field.
func KeyGT(v string) predicate.Extension {
return predicate.Extension(sql.FieldGT(FieldKey, v))
}
// KeyGTE applies the GTE predicate on the "key" field.
func KeyGTE(v string) predicate.Extension {
return predicate.Extension(sql.FieldGTE(FieldKey, v))
}
// KeyLT applies the LT predicate on the "key" field.
func KeyLT(v string) predicate.Extension {
return predicate.Extension(sql.FieldLT(FieldKey, v))
}
// KeyLTE applies the LTE predicate on the "key" field.
func KeyLTE(v string) predicate.Extension {
return predicate.Extension(sql.FieldLTE(FieldKey, v))
}
// KeyContains applies the Contains predicate on the "key" field.
func KeyContains(v string) predicate.Extension {
return predicate.Extension(sql.FieldContains(FieldKey, v))
}
// KeyHasPrefix applies the HasPrefix predicate on the "key" field.
func KeyHasPrefix(v string) predicate.Extension {
return predicate.Extension(sql.FieldHasPrefix(FieldKey, v))
}
// KeyHasSuffix applies the HasSuffix predicate on the "key" field.
func KeyHasSuffix(v string) predicate.Extension {
return predicate.Extension(sql.FieldHasSuffix(FieldKey, v))
}
// KeyEqualFold applies the EqualFold predicate on the "key" field.
func KeyEqualFold(v string) predicate.Extension {
return predicate.Extension(sql.FieldEqualFold(FieldKey, v))
}
// KeyContainsFold applies the ContainsFold predicate on the "key" field.
func KeyContainsFold(v string) predicate.Extension {
return predicate.Extension(sql.FieldContainsFold(FieldKey, v))
}
// EnabledEQ applies the EQ predicate on the "enabled" field.
func EnabledEQ(v bool) predicate.Extension {
return predicate.Extension(sql.FieldEQ(FieldEnabled, v))
}
// EnabledNEQ applies the NEQ predicate on the "enabled" field.
func EnabledNEQ(v bool) predicate.Extension {
return predicate.Extension(sql.FieldNEQ(FieldEnabled, v))
}
// ConfigIsNil applies the IsNil predicate on the "config" field.
func ConfigIsNil() predicate.Extension {
return predicate.Extension(sql.FieldIsNull(FieldConfig))
}
// ConfigNotNil applies the NotNil predicate on the "config" field.
func ConfigNotNil() predicate.Extension {
return predicate.Extension(sql.FieldNotNull(FieldConfig))
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Extension) predicate.Extension {
return predicate.Extension(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Extension) predicate.Extension {
return predicate.Extension(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Extension) predicate.Extension {
return predicate.Extension(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,306 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"voidraft/internal/models/ent/extension"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// ExtensionCreate is the builder for creating a Extension entity.
type ExtensionCreate struct {
config
mutation *ExtensionMutation
hooks []Hook
}
// SetCreatedAt sets the "created_at" field.
func (_c *ExtensionCreate) SetCreatedAt(v string) *ExtensionCreate {
_c.mutation.SetCreatedAt(v)
return _c
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (_c *ExtensionCreate) SetNillableCreatedAt(v *string) *ExtensionCreate {
if v != nil {
_c.SetCreatedAt(*v)
}
return _c
}
// SetUpdatedAt sets the "updated_at" field.
func (_c *ExtensionCreate) SetUpdatedAt(v string) *ExtensionCreate {
_c.mutation.SetUpdatedAt(v)
return _c
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (_c *ExtensionCreate) SetNillableUpdatedAt(v *string) *ExtensionCreate {
if v != nil {
_c.SetUpdatedAt(*v)
}
return _c
}
// SetDeletedAt sets the "deleted_at" field.
func (_c *ExtensionCreate) SetDeletedAt(v string) *ExtensionCreate {
_c.mutation.SetDeletedAt(v)
return _c
}
// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_c *ExtensionCreate) SetNillableDeletedAt(v *string) *ExtensionCreate {
if v != nil {
_c.SetDeletedAt(*v)
}
return _c
}
// SetKey sets the "key" field.
func (_c *ExtensionCreate) SetKey(v string) *ExtensionCreate {
_c.mutation.SetKey(v)
return _c
}
// SetEnabled sets the "enabled" field.
func (_c *ExtensionCreate) SetEnabled(v bool) *ExtensionCreate {
_c.mutation.SetEnabled(v)
return _c
}
// SetNillableEnabled sets the "enabled" field if the given value is not nil.
func (_c *ExtensionCreate) SetNillableEnabled(v *bool) *ExtensionCreate {
if v != nil {
_c.SetEnabled(*v)
}
return _c
}
// SetConfig sets the "config" field.
func (_c *ExtensionCreate) SetConfig(v map[string]interface{}) *ExtensionCreate {
_c.mutation.SetConfig(v)
return _c
}
// Mutation returns the ExtensionMutation object of the builder.
func (_c *ExtensionCreate) Mutation() *ExtensionMutation {
return _c.mutation
}
// Save creates the Extension in the database.
func (_c *ExtensionCreate) Save(ctx context.Context) (*Extension, error) {
if err := _c.defaults(); err != nil {
return nil, err
}
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *ExtensionCreate) SaveX(ctx context.Context) *Extension {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *ExtensionCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *ExtensionCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_c *ExtensionCreate) defaults() error {
if _, ok := _c.mutation.CreatedAt(); !ok {
if extension.DefaultCreatedAt == nil {
return fmt.Errorf("ent: uninitialized extension.DefaultCreatedAt (forgotten import ent/runtime?)")
}
v := extension.DefaultCreatedAt()
_c.mutation.SetCreatedAt(v)
}
if _, ok := _c.mutation.UpdatedAt(); !ok {
if extension.DefaultUpdatedAt == nil {
return fmt.Errorf("ent: uninitialized extension.DefaultUpdatedAt (forgotten import ent/runtime?)")
}
v := extension.DefaultUpdatedAt()
_c.mutation.SetUpdatedAt(v)
}
if _, ok := _c.mutation.Enabled(); !ok {
v := extension.DefaultEnabled
_c.mutation.SetEnabled(v)
}
return nil
}
// check runs all checks and user-defined validators on the builder.
func (_c *ExtensionCreate) check() error {
if _, ok := _c.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Extension.created_at"`)}
}
if _, ok := _c.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Extension.updated_at"`)}
}
if _, ok := _c.mutation.Key(); !ok {
return &ValidationError{Name: "key", err: errors.New(`ent: missing required field "Extension.key"`)}
}
if v, ok := _c.mutation.Key(); ok {
if err := extension.KeyValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "Extension.key": %w`, err)}
}
}
if _, ok := _c.mutation.Enabled(); !ok {
return &ValidationError{Name: "enabled", err: errors.New(`ent: missing required field "Extension.enabled"`)}
}
return nil
}
func (_c *ExtensionCreate) sqlSave(ctx context.Context) (*Extension, error) {
if err := _c.check(); err != nil {
return nil, err
}
_node, _spec := _c.createSpec()
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
_c.mutation.id = &_node.ID
_c.mutation.done = true
return _node, nil
}
func (_c *ExtensionCreate) createSpec() (*Extension, *sqlgraph.CreateSpec) {
var (
_node = &Extension{config: _c.config}
_spec = sqlgraph.NewCreateSpec(extension.Table, sqlgraph.NewFieldSpec(extension.FieldID, field.TypeInt))
)
if value, ok := _c.mutation.CreatedAt(); ok {
_spec.SetField(extension.FieldCreatedAt, field.TypeString, value)
_node.CreatedAt = value
}
if value, ok := _c.mutation.UpdatedAt(); ok {
_spec.SetField(extension.FieldUpdatedAt, field.TypeString, value)
_node.UpdatedAt = value
}
if value, ok := _c.mutation.DeletedAt(); ok {
_spec.SetField(extension.FieldDeletedAt, field.TypeString, value)
_node.DeletedAt = &value
}
if value, ok := _c.mutation.Key(); ok {
_spec.SetField(extension.FieldKey, field.TypeString, value)
_node.Key = value
}
if value, ok := _c.mutation.Enabled(); ok {
_spec.SetField(extension.FieldEnabled, field.TypeBool, value)
_node.Enabled = value
}
if value, ok := _c.mutation.Config(); ok {
_spec.SetField(extension.FieldConfig, field.TypeJSON, value)
_node.Config = value
}
return _node, _spec
}
// ExtensionCreateBulk is the builder for creating many Extension entities in bulk.
type ExtensionCreateBulk struct {
config
err error
builders []*ExtensionCreate
}
// Save creates the Extension entities in the database.
func (_c *ExtensionCreateBulk) Save(ctx context.Context) ([]*Extension, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*Extension, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ExtensionMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
mutation.done = true
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, _c.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (_c *ExtensionCreateBulk) SaveX(ctx context.Context) []*Extension {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *ExtensionCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *ExtensionCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,88 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"voidraft/internal/models/ent/extension"
"voidraft/internal/models/ent/predicate"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// ExtensionDelete is the builder for deleting a Extension entity.
type ExtensionDelete struct {
config
hooks []Hook
mutation *ExtensionMutation
}
// Where appends a list predicates to the ExtensionDelete builder.
func (_d *ExtensionDelete) Where(ps ...predicate.Extension) *ExtensionDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *ExtensionDelete) Exec(ctx context.Context) (int, error) {
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *ExtensionDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *ExtensionDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(extension.Table, sqlgraph.NewFieldSpec(extension.FieldID, field.TypeInt))
if ps := _d.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
_d.mutation.done = true
return affected, err
}
// ExtensionDeleteOne is the builder for deleting a single Extension entity.
type ExtensionDeleteOne struct {
_d *ExtensionDelete
}
// Where appends a list predicates to the ExtensionDelete builder.
func (_d *ExtensionDeleteOne) Where(ps ...predicate.Extension) *ExtensionDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *ExtensionDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{extension.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *ExtensionDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,577 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"voidraft/internal/models/ent/extension"
"voidraft/internal/models/ent/predicate"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// ExtensionQuery is the builder for querying Extension entities.
type ExtensionQuery struct {
config
ctx *QueryContext
order []extension.OrderOption
inters []Interceptor
predicates []predicate.Extension
modifiers []func(*sql.Selector)
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the ExtensionQuery builder.
func (_q *ExtensionQuery) Where(ps ...predicate.Extension) *ExtensionQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *ExtensionQuery) Limit(limit int) *ExtensionQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *ExtensionQuery) Offset(offset int) *ExtensionQuery {
_q.ctx.Offset = &offset
return _q
}
// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (_q *ExtensionQuery) Unique(unique bool) *ExtensionQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *ExtensionQuery) Order(o ...extension.OrderOption) *ExtensionQuery {
_q.order = append(_q.order, o...)
return _q
}
// First returns the first Extension entity from the query.
// Returns a *NotFoundError when no Extension was found.
func (_q *ExtensionQuery) First(ctx context.Context) (*Extension, error) {
nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{extension.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *ExtensionQuery) FirstX(ctx context.Context) *Extension {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Extension ID from the query.
// Returns a *NotFoundError when no Extension ID was found.
func (_q *ExtensionQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{extension.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *ExtensionQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Extension entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Extension entity is found.
// Returns a *NotFoundError when no Extension entities are found.
func (_q *ExtensionQuery) Only(ctx context.Context) (*Extension, error) {
nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{extension.Label}
default:
return nil, &NotSingularError{extension.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *ExtensionQuery) OnlyX(ctx context.Context) *Extension {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Extension ID in the query.
// Returns a *NotSingularError when more than one Extension ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *ExtensionQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{extension.Label}
default:
err = &NotSingularError{extension.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *ExtensionQuery) OnlyIDX(ctx context.Context) int {
id, err := _q.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Extensions.
func (_q *ExtensionQuery) All(ctx context.Context) ([]*Extension, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Extension, *ExtensionQuery]()
return withInterceptors[[]*Extension](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *ExtensionQuery) AllX(ctx context.Context) []*Extension {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Extension IDs.
func (_q *ExtensionQuery) IDs(ctx context.Context) (ids []int, err error) {
if _q.ctx.Unique == nil && _q.path != nil {
_q.Unique(true)
}
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
if err = _q.Select(extension.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *ExtensionQuery) IDsX(ctx context.Context) []int {
ids, err := _q.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (_q *ExtensionQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)
if err := _q.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, _q, querierCount[*ExtensionQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *ExtensionQuery) CountX(ctx context.Context) int {
count, err := _q.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (_q *ExtensionQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
switch _, err := _q.FirstID(ctx); {
case IsNotFound(err):
return false, nil
case err != nil:
return false, fmt.Errorf("ent: check existence: %w", err)
default:
return true, nil
}
}
// ExistX is like Exist, but panics if an error occurs.
func (_q *ExtensionQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the ExtensionQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (_q *ExtensionQuery) Clone() *ExtensionQuery {
if _q == nil {
return nil
}
return &ExtensionQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]extension.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Extension{}, _q.predicates...),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
modifiers: append([]func(*sql.Selector){}, _q.modifiers...),
}
}
// GroupBy is 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 {
// CreatedAt string `json:"created_at"`
// Count int `json:"count,omitempty"`
// }
//
// client.Extension.Query().
// GroupBy(extension.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *ExtensionQuery) GroupBy(field string, fields ...string) *ExtensionGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &ExtensionGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = extension.Label
grbuild.scan = grbuild.Scan
return grbuild
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// CreatedAt string `json:"created_at"`
// }
//
// client.Extension.Query().
// Select(extension.FieldCreatedAt).
// Scan(ctx, &v)
func (_q *ExtensionQuery) Select(fields ...string) *ExtensionSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &ExtensionSelect{ExtensionQuery: _q}
sbuild.label = extension.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a ExtensionSelect configured with the given aggregations.
func (_q *ExtensionQuery) Aggregate(fns ...AggregateFunc) *ExtensionSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *ExtensionQuery) prepareQuery(ctx context.Context) error {
for _, inter := range _q.inters {
if inter == nil {
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
}
if trv, ok := inter.(Traverser); ok {
if err := trv.Traverse(ctx, _q); err != nil {
return err
}
}
}
for _, f := range _q.ctx.Fields {
if !extension.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if _q.path != nil {
prev, err := _q.path(ctx)
if err != nil {
return err
}
_q.sql = prev
}
return nil
}
func (_q *ExtensionQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Extension, error) {
var (
nodes = []*Extension{}
_spec = _q.querySpec()
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Extension).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Extension{config: _q.config}
nodes = append(nodes, node)
return node.assignValues(columns, values)
}
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (_q *ExtensionQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *ExtensionQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(extension.Table, extension.Columns, sqlgraph.NewFieldSpec(extension.FieldID, field.TypeInt))
_spec.From = _q.sql
if unique := _q.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if _q.path != nil {
_spec.Unique = true
}
if fields := _q.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, extension.FieldID)
for i := range fields {
if fields[i] != extension.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := _q.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := _q.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := _q.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := _q.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (_q *ExtensionQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(extension.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = extension.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, m := range _q.modifiers {
m(selector)
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.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 := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
// updated, deleted or "selected ... for update" by other sessions, until the transaction is
// either committed or rolled-back.
func (_q *ExtensionQuery) ForUpdate(opts ...sql.LockOption) *ExtensionQuery {
if _q.driver.Dialect() == dialect.Postgres {
_q.Unique(false)
}
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
s.ForUpdate(opts...)
})
return _q
}
// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
// on any rows that are read. Other sessions can read the rows, but cannot modify them
// until your transaction commits.
func (_q *ExtensionQuery) ForShare(opts ...sql.LockOption) *ExtensionQuery {
if _q.driver.Dialect() == dialect.Postgres {
_q.Unique(false)
}
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
s.ForShare(opts...)
})
return _q
}
// Modify adds a query modifier for attaching custom logic to queries.
func (_q *ExtensionQuery) Modify(modifiers ...func(s *sql.Selector)) *ExtensionSelect {
_q.modifiers = append(_q.modifiers, modifiers...)
return _q.Select()
}
// ExtensionGroupBy is the group-by builder for Extension entities.
type ExtensionGroupBy struct {
selector
build *ExtensionQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *ExtensionGroupBy) Aggregate(fns ...AggregateFunc) *ExtensionGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *ExtensionGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)
if err := _g.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*ExtensionQuery, *ExtensionGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *ExtensionGroupBy) sqlScan(ctx context.Context, root *ExtensionQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(_g.fns))
for _, fn := range _g.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*_g.flds)+len(_g.fns))
for _, f := range *_g.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*_g.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// ExtensionSelect is the builder for selecting fields of Extension entities.
type ExtensionSelect struct {
*ExtensionQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *ExtensionSelect) Aggregate(fns ...AggregateFunc) *ExtensionSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *ExtensionSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)
if err := _s.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*ExtensionQuery, *ExtensionSelect](ctx, _s.ExtensionQuery, _s, _s.inters, v)
}
func (_s *ExtensionSelect) sqlScan(ctx context.Context, root *ExtensionQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(_s.fns))
for _, fn := range _s.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*_s.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// Modify adds a query modifier for attaching custom logic to queries.
func (_s *ExtensionSelect) Modify(modifiers ...func(s *sql.Selector)) *ExtensionSelect {
_s.modifiers = append(_s.modifiers, modifiers...)
return _s
}

View File

@@ -0,0 +1,407 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"voidraft/internal/models/ent/extension"
"voidraft/internal/models/ent/predicate"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// ExtensionUpdate is the builder for updating Extension entities.
type ExtensionUpdate struct {
config
hooks []Hook
mutation *ExtensionMutation
modifiers []func(*sql.UpdateBuilder)
}
// Where appends a list predicates to the ExtensionUpdate builder.
func (_u *ExtensionUpdate) Where(ps ...predicate.Extension) *ExtensionUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetUpdatedAt sets the "updated_at" field.
func (_u *ExtensionUpdate) SetUpdatedAt(v string) *ExtensionUpdate {
_u.mutation.SetUpdatedAt(v)
return _u
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (_u *ExtensionUpdate) SetNillableUpdatedAt(v *string) *ExtensionUpdate {
if v != nil {
_u.SetUpdatedAt(*v)
}
return _u
}
// SetDeletedAt sets the "deleted_at" field.
func (_u *ExtensionUpdate) SetDeletedAt(v string) *ExtensionUpdate {
_u.mutation.SetDeletedAt(v)
return _u
}
// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_u *ExtensionUpdate) SetNillableDeletedAt(v *string) *ExtensionUpdate {
if v != nil {
_u.SetDeletedAt(*v)
}
return _u
}
// ClearDeletedAt clears the value of the "deleted_at" field.
func (_u *ExtensionUpdate) ClearDeletedAt() *ExtensionUpdate {
_u.mutation.ClearDeletedAt()
return _u
}
// SetKey sets the "key" field.
func (_u *ExtensionUpdate) SetKey(v string) *ExtensionUpdate {
_u.mutation.SetKey(v)
return _u
}
// SetNillableKey sets the "key" field if the given value is not nil.
func (_u *ExtensionUpdate) SetNillableKey(v *string) *ExtensionUpdate {
if v != nil {
_u.SetKey(*v)
}
return _u
}
// SetEnabled sets the "enabled" field.
func (_u *ExtensionUpdate) SetEnabled(v bool) *ExtensionUpdate {
_u.mutation.SetEnabled(v)
return _u
}
// SetNillableEnabled sets the "enabled" field if the given value is not nil.
func (_u *ExtensionUpdate) SetNillableEnabled(v *bool) *ExtensionUpdate {
if v != nil {
_u.SetEnabled(*v)
}
return _u
}
// SetConfig sets the "config" field.
func (_u *ExtensionUpdate) SetConfig(v map[string]interface{}) *ExtensionUpdate {
_u.mutation.SetConfig(v)
return _u
}
// ClearConfig clears the value of the "config" field.
func (_u *ExtensionUpdate) ClearConfig() *ExtensionUpdate {
_u.mutation.ClearConfig()
return _u
}
// Mutation returns the ExtensionMutation object of the builder.
func (_u *ExtensionUpdate) Mutation() *ExtensionMutation {
return _u.mutation
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *ExtensionUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *ExtensionUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *ExtensionUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *ExtensionUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *ExtensionUpdate) check() error {
if v, ok := _u.mutation.Key(); ok {
if err := extension.KeyValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "Extension.key": %w`, err)}
}
}
return nil
}
// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
func (_u *ExtensionUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *ExtensionUpdate {
_u.modifiers = append(_u.modifiers, modifiers...)
return _u
}
func (_u *ExtensionUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(extension.Table, extension.Columns, sqlgraph.NewFieldSpec(extension.FieldID, field.TypeInt))
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(extension.FieldUpdatedAt, field.TypeString, value)
}
if value, ok := _u.mutation.DeletedAt(); ok {
_spec.SetField(extension.FieldDeletedAt, field.TypeString, value)
}
if _u.mutation.DeletedAtCleared() {
_spec.ClearField(extension.FieldDeletedAt, field.TypeString)
}
if value, ok := _u.mutation.Key(); ok {
_spec.SetField(extension.FieldKey, field.TypeString, value)
}
if value, ok := _u.mutation.Enabled(); ok {
_spec.SetField(extension.FieldEnabled, field.TypeBool, value)
}
if value, ok := _u.mutation.Config(); ok {
_spec.SetField(extension.FieldConfig, field.TypeJSON, value)
}
if _u.mutation.ConfigCleared() {
_spec.ClearField(extension.FieldConfig, field.TypeJSON)
}
_spec.AddModifiers(_u.modifiers...)
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{extension.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// ExtensionUpdateOne is the builder for updating a single Extension entity.
type ExtensionUpdateOne struct {
config
fields []string
hooks []Hook
mutation *ExtensionMutation
modifiers []func(*sql.UpdateBuilder)
}
// SetUpdatedAt sets the "updated_at" field.
func (_u *ExtensionUpdateOne) SetUpdatedAt(v string) *ExtensionUpdateOne {
_u.mutation.SetUpdatedAt(v)
return _u
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (_u *ExtensionUpdateOne) SetNillableUpdatedAt(v *string) *ExtensionUpdateOne {
if v != nil {
_u.SetUpdatedAt(*v)
}
return _u
}
// SetDeletedAt sets the "deleted_at" field.
func (_u *ExtensionUpdateOne) SetDeletedAt(v string) *ExtensionUpdateOne {
_u.mutation.SetDeletedAt(v)
return _u
}
// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_u *ExtensionUpdateOne) SetNillableDeletedAt(v *string) *ExtensionUpdateOne {
if v != nil {
_u.SetDeletedAt(*v)
}
return _u
}
// ClearDeletedAt clears the value of the "deleted_at" field.
func (_u *ExtensionUpdateOne) ClearDeletedAt() *ExtensionUpdateOne {
_u.mutation.ClearDeletedAt()
return _u
}
// SetKey sets the "key" field.
func (_u *ExtensionUpdateOne) SetKey(v string) *ExtensionUpdateOne {
_u.mutation.SetKey(v)
return _u
}
// SetNillableKey sets the "key" field if the given value is not nil.
func (_u *ExtensionUpdateOne) SetNillableKey(v *string) *ExtensionUpdateOne {
if v != nil {
_u.SetKey(*v)
}
return _u
}
// SetEnabled sets the "enabled" field.
func (_u *ExtensionUpdateOne) SetEnabled(v bool) *ExtensionUpdateOne {
_u.mutation.SetEnabled(v)
return _u
}
// SetNillableEnabled sets the "enabled" field if the given value is not nil.
func (_u *ExtensionUpdateOne) SetNillableEnabled(v *bool) *ExtensionUpdateOne {
if v != nil {
_u.SetEnabled(*v)
}
return _u
}
// SetConfig sets the "config" field.
func (_u *ExtensionUpdateOne) SetConfig(v map[string]interface{}) *ExtensionUpdateOne {
_u.mutation.SetConfig(v)
return _u
}
// ClearConfig clears the value of the "config" field.
func (_u *ExtensionUpdateOne) ClearConfig() *ExtensionUpdateOne {
_u.mutation.ClearConfig()
return _u
}
// Mutation returns the ExtensionMutation object of the builder.
func (_u *ExtensionUpdateOne) Mutation() *ExtensionMutation {
return _u.mutation
}
// Where appends a list predicates to the ExtensionUpdate builder.
func (_u *ExtensionUpdateOne) Where(ps ...predicate.Extension) *ExtensionUpdateOne {
_u.mutation.Where(ps...)
return _u
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (_u *ExtensionUpdateOne) Select(field string, fields ...string) *ExtensionUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated Extension entity.
func (_u *ExtensionUpdateOne) Save(ctx context.Context) (*Extension, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *ExtensionUpdateOne) SaveX(ctx context.Context) *Extension {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *ExtensionUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *ExtensionUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *ExtensionUpdateOne) check() error {
if v, ok := _u.mutation.Key(); ok {
if err := extension.KeyValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "Extension.key": %w`, err)}
}
}
return nil
}
// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
func (_u *ExtensionUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *ExtensionUpdateOne {
_u.modifiers = append(_u.modifiers, modifiers...)
return _u
}
func (_u *ExtensionUpdateOne) sqlSave(ctx context.Context) (_node *Extension, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(extension.Table, extension.Columns, sqlgraph.NewFieldSpec(extension.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Extension.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := _u.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, extension.FieldID)
for _, f := range fields {
if !extension.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != extension.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(extension.FieldUpdatedAt, field.TypeString, value)
}
if value, ok := _u.mutation.DeletedAt(); ok {
_spec.SetField(extension.FieldDeletedAt, field.TypeString, value)
}
if _u.mutation.DeletedAtCleared() {
_spec.ClearField(extension.FieldDeletedAt, field.TypeString)
}
if value, ok := _u.mutation.Key(); ok {
_spec.SetField(extension.FieldKey, field.TypeString, value)
}
if value, ok := _u.mutation.Enabled(); ok {
_spec.SetField(extension.FieldEnabled, field.TypeBool, value)
}
if value, ok := _u.mutation.Config(); ok {
_spec.SetField(extension.FieldConfig, field.TypeJSON, value)
}
if _u.mutation.ConfigCleared() {
_spec.ClearField(extension.FieldConfig, field.TypeJSON)
}
_spec.AddModifiers(_u.modifiers...)
_node = &Extension{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{extension.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

View File

@@ -0,0 +1 @@
package ent

View File

@@ -0,0 +1,234 @@
// Code generated by ent, DO NOT EDIT.
package hook
import (
"context"
"fmt"
"voidraft/internal/models/ent"
)
// The DocumentFunc type is an adapter to allow the use of ordinary
// function as Document mutator.
type DocumentFunc func(context.Context, *ent.DocumentMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f DocumentFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.DocumentMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.DocumentMutation", m)
}
// The ExtensionFunc type is an adapter to allow the use of ordinary
// function as Extension mutator.
type ExtensionFunc func(context.Context, *ent.ExtensionMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f ExtensionFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.ExtensionMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ExtensionMutation", m)
}
// The KeyBindingFunc type is an adapter to allow the use of ordinary
// function as KeyBinding mutator.
type KeyBindingFunc func(context.Context, *ent.KeyBindingMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f KeyBindingFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.KeyBindingMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.KeyBindingMutation", m)
}
// The ThemeFunc type is an adapter to allow the use of ordinary
// function as Theme mutator.
type ThemeFunc func(context.Context, *ent.ThemeMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f ThemeFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.ThemeMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ThemeMutation", m)
}
// 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)))
}
// FixedError is a hook returning a fixed error.
func FixedError(err error) ent.Hook {
return func(ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(context.Context, ent.Mutation) (ent.Value, error) {
return nil, err
})
}
}
// 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 := FixedError(fmt.Errorf("%s operation is not allowed", 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

@@ -0,0 +1,240 @@
// Code generated by ent, DO NOT EDIT.
package intercept
import (
"context"
"fmt"
"voidraft/internal/models/ent"
"voidraft/internal/models/ent/document"
"voidraft/internal/models/ent/extension"
"voidraft/internal/models/ent/keybinding"
"voidraft/internal/models/ent/predicate"
"voidraft/internal/models/ent/theme"
"entgo.io/ent/dialect/sql"
)
// The Query interface represents an operation that queries a graph.
// By using this interface, users can write generic code that manipulates
// query builders of different types.
type Query interface {
// Type returns the string representation of the query type.
Type() string
// Limit the number of records to be returned by this query.
Limit(int)
// Offset to start from.
Offset(int)
// Unique configures the query builder to filter duplicate records.
Unique(bool)
// Order specifies how the records should be ordered.
Order(...func(*sql.Selector))
// WhereP appends storage-level predicates to the query builder. Using this method, users
// can use type-assertion to append predicates that do not depend on any generated package.
WhereP(...func(*sql.Selector))
}
// The Func type is an adapter that allows ordinary functions to be used as interceptors.
// Unlike traversal functions, interceptors are skipped during graph traversals. Note that the
// implementation of Func is different from the one defined in entgo.io/ent.InterceptFunc.
type Func func(context.Context, Query) error
// Intercept calls f(ctx, q) and then applied the next Querier.
func (f Func) Intercept(next ent.Querier) ent.Querier {
return ent.QuerierFunc(func(ctx context.Context, q ent.Query) (ent.Value, error) {
query, err := NewQuery(q)
if err != nil {
return nil, err
}
if err := f(ctx, query); err != nil {
return nil, err
}
return next.Query(ctx, q)
})
}
// The TraverseFunc type is an adapter to allow the use of ordinary function as Traverser.
// If f is a function with the appropriate signature, TraverseFunc(f) is a Traverser that calls f.
type TraverseFunc func(context.Context, Query) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseFunc) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseFunc) Traverse(ctx context.Context, q ent.Query) error {
query, err := NewQuery(q)
if err != nil {
return err
}
return f(ctx, query)
}
// The DocumentFunc type is an adapter to allow the use of ordinary function as a Querier.
type DocumentFunc func(context.Context, *ent.DocumentQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f DocumentFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.DocumentQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.DocumentQuery", q)
}
// The TraverseDocument type is an adapter to allow the use of ordinary function as Traverser.
type TraverseDocument func(context.Context, *ent.DocumentQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseDocument) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseDocument) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.DocumentQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.DocumentQuery", q)
}
// The ExtensionFunc type is an adapter to allow the use of ordinary function as a Querier.
type ExtensionFunc func(context.Context, *ent.ExtensionQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f ExtensionFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.ExtensionQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.ExtensionQuery", q)
}
// The TraverseExtension type is an adapter to allow the use of ordinary function as Traverser.
type TraverseExtension func(context.Context, *ent.ExtensionQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseExtension) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseExtension) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.ExtensionQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.ExtensionQuery", q)
}
// The KeyBindingFunc type is an adapter to allow the use of ordinary function as a Querier.
type KeyBindingFunc func(context.Context, *ent.KeyBindingQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f KeyBindingFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.KeyBindingQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.KeyBindingQuery", q)
}
// The TraverseKeyBinding type is an adapter to allow the use of ordinary function as Traverser.
type TraverseKeyBinding func(context.Context, *ent.KeyBindingQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseKeyBinding) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseKeyBinding) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.KeyBindingQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.KeyBindingQuery", q)
}
// The ThemeFunc type is an adapter to allow the use of ordinary function as a Querier.
type ThemeFunc func(context.Context, *ent.ThemeQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f ThemeFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.ThemeQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.ThemeQuery", q)
}
// The TraverseTheme type is an adapter to allow the use of ordinary function as Traverser.
type TraverseTheme func(context.Context, *ent.ThemeQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseTheme) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseTheme) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.ThemeQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.ThemeQuery", q)
}
// NewQuery returns the generic Query interface for the given typed query.
func NewQuery(q ent.Query) (Query, error) {
switch q := q.(type) {
case *ent.DocumentQuery:
return &query[*ent.DocumentQuery, predicate.Document, document.OrderOption]{typ: ent.TypeDocument, tq: q}, nil
case *ent.ExtensionQuery:
return &query[*ent.ExtensionQuery, predicate.Extension, extension.OrderOption]{typ: ent.TypeExtension, tq: q}, nil
case *ent.KeyBindingQuery:
return &query[*ent.KeyBindingQuery, predicate.KeyBinding, keybinding.OrderOption]{typ: ent.TypeKeyBinding, tq: q}, nil
case *ent.ThemeQuery:
return &query[*ent.ThemeQuery, predicate.Theme, theme.OrderOption]{typ: ent.TypeTheme, tq: q}, nil
default:
return nil, fmt.Errorf("unknown query type %T", q)
}
}
type query[T any, P ~func(*sql.Selector), R ~func(*sql.Selector)] struct {
typ string
tq interface {
Limit(int) T
Offset(int) T
Unique(bool) T
Order(...R) T
Where(...P) T
}
}
func (q query[T, P, R]) Type() string {
return q.typ
}
func (q query[T, P, R]) Limit(limit int) {
q.tq.Limit(limit)
}
func (q query[T, P, R]) Offset(offset int) {
q.tq.Offset(offset)
}
func (q query[T, P, R]) Unique(unique bool) {
q.tq.Unique(unique)
}
func (q query[T, P, R]) Order(orders ...func(*sql.Selector)) {
rs := make([]R, len(orders))
for i := range orders {
rs[i] = orders[i]
}
q.tq.Order(rs...)
}
func (q query[T, P, R]) WhereP(ps ...func(*sql.Selector)) {
p := make([]P, len(ps))
for i := range ps {
p[i] = ps[i]
}
q.tq.Where(p...)
}

View File

@@ -0,0 +1,174 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"voidraft/internal/models/ent/keybinding"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
)
// KeyBinding is the model entity for the KeyBinding schema.
type KeyBinding struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// 创建时间
CreatedAt string `json:"created_at"`
// 最后更新时间
UpdatedAt string `json:"updated_at"`
// 删除时间NULL表示未删除
DeletedAt *string `json:"deleted_at,omitempty"`
// 快捷键标识符
Key string `json:"key"`
// 快捷键命令
Command string `json:"command"`
// 所属扩展标识符
Extension string `json:"extension,omitempty"`
// 是否启用
Enabled bool `json:"enabled"`
selectValues sql.SelectValues
}
// scanValues returns the types for scanning values from sql.Rows.
func (*KeyBinding) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case keybinding.FieldEnabled:
values[i] = new(sql.NullBool)
case keybinding.FieldID:
values[i] = new(sql.NullInt64)
case keybinding.FieldCreatedAt, keybinding.FieldUpdatedAt, keybinding.FieldDeletedAt, keybinding.FieldKey, keybinding.FieldCommand, keybinding.FieldExtension:
values[i] = new(sql.NullString)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the KeyBinding fields.
func (_m *KeyBinding) assignValues(columns []string, values []any) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case keybinding.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
_m.ID = int(value.Int64)
case keybinding.FieldCreatedAt:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
_m.CreatedAt = value.String
}
case keybinding.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
_m.UpdatedAt = value.String
}
case keybinding.FieldDeletedAt:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field deleted_at", values[i])
} else if value.Valid {
_m.DeletedAt = new(string)
*_m.DeletedAt = value.String
}
case keybinding.FieldKey:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field key", values[i])
} else if value.Valid {
_m.Key = value.String
}
case keybinding.FieldCommand:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field command", values[i])
} else if value.Valid {
_m.Command = value.String
}
case keybinding.FieldExtension:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field extension", values[i])
} else if value.Valid {
_m.Extension = value.String
}
case keybinding.FieldEnabled:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field enabled", values[i])
} else if value.Valid {
_m.Enabled = value.Bool
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the KeyBinding.
// This includes values selected through modifiers, order, etc.
func (_m *KeyBinding) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// Update returns a builder for updating this KeyBinding.
// Note that you need to call KeyBinding.Unwrap() before calling this method if this KeyBinding
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *KeyBinding) Update() *KeyBindingUpdateOne {
return NewKeyBindingClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the KeyBinding entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (_m *KeyBinding) Unwrap() *KeyBinding {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: KeyBinding is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *KeyBinding) String() string {
var builder strings.Builder
builder.WriteString("KeyBinding(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("created_at=")
builder.WriteString(_m.CreatedAt)
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(_m.UpdatedAt)
builder.WriteString(", ")
if v := _m.DeletedAt; v != nil {
builder.WriteString("deleted_at=")
builder.WriteString(*v)
}
builder.WriteString(", ")
builder.WriteString("key=")
builder.WriteString(_m.Key)
builder.WriteString(", ")
builder.WriteString("command=")
builder.WriteString(_m.Command)
builder.WriteString(", ")
builder.WriteString("extension=")
builder.WriteString(_m.Extension)
builder.WriteString(", ")
builder.WriteString("enabled=")
builder.WriteString(fmt.Sprintf("%v", _m.Enabled))
builder.WriteByte(')')
return builder.String()
}
// KeyBindings is a parsable slice of KeyBinding.
type KeyBindings []*KeyBinding

View File

@@ -0,0 +1,118 @@
// Code generated by ent, DO NOT EDIT.
package keybinding
import (
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
)
const (
// Label holds the string label denoting the keybinding type in the database.
Label = "key_binding"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
FieldUpdatedAt = "updated_at"
// FieldDeletedAt holds the string denoting the deleted_at field in the database.
FieldDeletedAt = "deleted_at"
// FieldKey holds the string denoting the key field in the database.
FieldKey = "key"
// FieldCommand holds the string denoting the command field in the database.
FieldCommand = "command"
// FieldExtension holds the string denoting the extension field in the database.
FieldExtension = "extension"
// FieldEnabled holds the string denoting the enabled field in the database.
FieldEnabled = "enabled"
// Table holds the table name of the keybinding in the database.
Table = "key_bindings"
)
// Columns holds all SQL columns for keybinding fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldDeletedAt,
FieldKey,
FieldCommand,
FieldExtension,
FieldEnabled,
}
// 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
}
// Note that the variables below are initialized by the runtime
// package on the initialization of the application. Therefore,
// it should be imported in the main as follows:
//
// import _ "voidraft/internal/models/ent/runtime"
var (
Hooks [2]ent.Hook
Interceptors [1]ent.Interceptor
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() string
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() string
// KeyValidator is a validator for the "key" field. It is called by the builders before save.
KeyValidator func(string) error
// CommandValidator is a validator for the "command" field. It is called by the builders before save.
CommandValidator func(string) error
// ExtensionValidator is a validator for the "extension" field. It is called by the builders before save.
ExtensionValidator func(string) error
// DefaultEnabled holds the default value on creation for the "enabled" field.
DefaultEnabled bool
)
// OrderOption defines the ordering options for the KeyBinding queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByCreatedAt orders the results by the created_at field.
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
}
// ByUpdatedAt orders the results by the updated_at field.
func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
}
// ByDeletedAt orders the results by the deleted_at field.
func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDeletedAt, opts...).ToFunc()
}
// ByKey orders the results by the key field.
func ByKey(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldKey, opts...).ToFunc()
}
// ByCommand orders the results by the command field.
func ByCommand(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCommand, opts...).ToFunc()
}
// ByExtension orders the results by the extension field.
func ByExtension(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldExtension, opts...).ToFunc()
}
// ByEnabled orders the results by the enabled field.
func ByEnabled(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldEnabled, opts...).ToFunc()
}

View File

@@ -0,0 +1,524 @@
// Code generated by ent, DO NOT EDIT.
package keybinding
import (
"voidraft/internal/models/ent/predicate"
"entgo.io/ent/dialect/sql"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLTE(FieldID, id))
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldCreatedAt, v))
}
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
func UpdatedAt(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldUpdatedAt, v))
}
// DeletedAt applies equality check predicate on the "deleted_at" field. It's identical to DeletedAtEQ.
func DeletedAt(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldDeletedAt, v))
}
// Key applies equality check predicate on the "key" field. It's identical to KeyEQ.
func Key(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldKey, v))
}
// Command applies equality check predicate on the "command" field. It's identical to CommandEQ.
func Command(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldCommand, v))
}
// Extension applies equality check predicate on the "extension" field. It's identical to ExtensionEQ.
func Extension(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldExtension, v))
}
// Enabled applies equality check predicate on the "enabled" field. It's identical to EnabledEQ.
func Enabled(v bool) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldEnabled, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLTE(FieldCreatedAt, v))
}
// CreatedAtContains applies the Contains predicate on the "created_at" field.
func CreatedAtContains(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContains(FieldCreatedAt, v))
}
// CreatedAtHasPrefix applies the HasPrefix predicate on the "created_at" field.
func CreatedAtHasPrefix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasPrefix(FieldCreatedAt, v))
}
// CreatedAtHasSuffix applies the HasSuffix predicate on the "created_at" field.
func CreatedAtHasSuffix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasSuffix(FieldCreatedAt, v))
}
// CreatedAtEqualFold applies the EqualFold predicate on the "created_at" field.
func CreatedAtEqualFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEqualFold(FieldCreatedAt, v))
}
// CreatedAtContainsFold applies the ContainsFold predicate on the "created_at" field.
func CreatedAtContainsFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContainsFold(FieldCreatedAt, v))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldUpdatedAt, v))
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNEQ(FieldUpdatedAt, v))
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldIn(FieldUpdatedAt, vs...))
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNotIn(FieldUpdatedAt, vs...))
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGT(FieldUpdatedAt, v))
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGTE(FieldUpdatedAt, v))
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLT(FieldUpdatedAt, v))
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLTE(FieldUpdatedAt, v))
}
// UpdatedAtContains applies the Contains predicate on the "updated_at" field.
func UpdatedAtContains(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContains(FieldUpdatedAt, v))
}
// UpdatedAtHasPrefix applies the HasPrefix predicate on the "updated_at" field.
func UpdatedAtHasPrefix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasPrefix(FieldUpdatedAt, v))
}
// UpdatedAtHasSuffix applies the HasSuffix predicate on the "updated_at" field.
func UpdatedAtHasSuffix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasSuffix(FieldUpdatedAt, v))
}
// UpdatedAtEqualFold applies the EqualFold predicate on the "updated_at" field.
func UpdatedAtEqualFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEqualFold(FieldUpdatedAt, v))
}
// UpdatedAtContainsFold applies the ContainsFold predicate on the "updated_at" field.
func UpdatedAtContainsFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContainsFold(FieldUpdatedAt, v))
}
// DeletedAtEQ applies the EQ predicate on the "deleted_at" field.
func DeletedAtEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldDeletedAt, v))
}
// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field.
func DeletedAtNEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNEQ(FieldDeletedAt, v))
}
// DeletedAtIn applies the In predicate on the "deleted_at" field.
func DeletedAtIn(vs ...string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldIn(FieldDeletedAt, vs...))
}
// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field.
func DeletedAtNotIn(vs ...string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNotIn(FieldDeletedAt, vs...))
}
// DeletedAtGT applies the GT predicate on the "deleted_at" field.
func DeletedAtGT(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGT(FieldDeletedAt, v))
}
// DeletedAtGTE applies the GTE predicate on the "deleted_at" field.
func DeletedAtGTE(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGTE(FieldDeletedAt, v))
}
// DeletedAtLT applies the LT predicate on the "deleted_at" field.
func DeletedAtLT(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLT(FieldDeletedAt, v))
}
// DeletedAtLTE applies the LTE predicate on the "deleted_at" field.
func DeletedAtLTE(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLTE(FieldDeletedAt, v))
}
// DeletedAtContains applies the Contains predicate on the "deleted_at" field.
func DeletedAtContains(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContains(FieldDeletedAt, v))
}
// DeletedAtHasPrefix applies the HasPrefix predicate on the "deleted_at" field.
func DeletedAtHasPrefix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasPrefix(FieldDeletedAt, v))
}
// DeletedAtHasSuffix applies the HasSuffix predicate on the "deleted_at" field.
func DeletedAtHasSuffix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasSuffix(FieldDeletedAt, v))
}
// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field.
func DeletedAtIsNil() predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldIsNull(FieldDeletedAt))
}
// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field.
func DeletedAtNotNil() predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNotNull(FieldDeletedAt))
}
// DeletedAtEqualFold applies the EqualFold predicate on the "deleted_at" field.
func DeletedAtEqualFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEqualFold(FieldDeletedAt, v))
}
// DeletedAtContainsFold applies the ContainsFold predicate on the "deleted_at" field.
func DeletedAtContainsFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContainsFold(FieldDeletedAt, v))
}
// KeyEQ applies the EQ predicate on the "key" field.
func KeyEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldKey, v))
}
// KeyNEQ applies the NEQ predicate on the "key" field.
func KeyNEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNEQ(FieldKey, v))
}
// KeyIn applies the In predicate on the "key" field.
func KeyIn(vs ...string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldIn(FieldKey, vs...))
}
// KeyNotIn applies the NotIn predicate on the "key" field.
func KeyNotIn(vs ...string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNotIn(FieldKey, vs...))
}
// KeyGT applies the GT predicate on the "key" field.
func KeyGT(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGT(FieldKey, v))
}
// KeyGTE applies the GTE predicate on the "key" field.
func KeyGTE(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGTE(FieldKey, v))
}
// KeyLT applies the LT predicate on the "key" field.
func KeyLT(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLT(FieldKey, v))
}
// KeyLTE applies the LTE predicate on the "key" field.
func KeyLTE(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLTE(FieldKey, v))
}
// KeyContains applies the Contains predicate on the "key" field.
func KeyContains(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContains(FieldKey, v))
}
// KeyHasPrefix applies the HasPrefix predicate on the "key" field.
func KeyHasPrefix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasPrefix(FieldKey, v))
}
// KeyHasSuffix applies the HasSuffix predicate on the "key" field.
func KeyHasSuffix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasSuffix(FieldKey, v))
}
// KeyEqualFold applies the EqualFold predicate on the "key" field.
func KeyEqualFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEqualFold(FieldKey, v))
}
// KeyContainsFold applies the ContainsFold predicate on the "key" field.
func KeyContainsFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContainsFold(FieldKey, v))
}
// CommandEQ applies the EQ predicate on the "command" field.
func CommandEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldCommand, v))
}
// CommandNEQ applies the NEQ predicate on the "command" field.
func CommandNEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNEQ(FieldCommand, v))
}
// CommandIn applies the In predicate on the "command" field.
func CommandIn(vs ...string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldIn(FieldCommand, vs...))
}
// CommandNotIn applies the NotIn predicate on the "command" field.
func CommandNotIn(vs ...string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNotIn(FieldCommand, vs...))
}
// CommandGT applies the GT predicate on the "command" field.
func CommandGT(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGT(FieldCommand, v))
}
// CommandGTE applies the GTE predicate on the "command" field.
func CommandGTE(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGTE(FieldCommand, v))
}
// CommandLT applies the LT predicate on the "command" field.
func CommandLT(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLT(FieldCommand, v))
}
// CommandLTE applies the LTE predicate on the "command" field.
func CommandLTE(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLTE(FieldCommand, v))
}
// CommandContains applies the Contains predicate on the "command" field.
func CommandContains(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContains(FieldCommand, v))
}
// CommandHasPrefix applies the HasPrefix predicate on the "command" field.
func CommandHasPrefix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasPrefix(FieldCommand, v))
}
// CommandHasSuffix applies the HasSuffix predicate on the "command" field.
func CommandHasSuffix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasSuffix(FieldCommand, v))
}
// CommandEqualFold applies the EqualFold predicate on the "command" field.
func CommandEqualFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEqualFold(FieldCommand, v))
}
// CommandContainsFold applies the ContainsFold predicate on the "command" field.
func CommandContainsFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContainsFold(FieldCommand, v))
}
// ExtensionEQ applies the EQ predicate on the "extension" field.
func ExtensionEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldExtension, v))
}
// ExtensionNEQ applies the NEQ predicate on the "extension" field.
func ExtensionNEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNEQ(FieldExtension, v))
}
// ExtensionIn applies the In predicate on the "extension" field.
func ExtensionIn(vs ...string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldIn(FieldExtension, vs...))
}
// ExtensionNotIn applies the NotIn predicate on the "extension" field.
func ExtensionNotIn(vs ...string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNotIn(FieldExtension, vs...))
}
// ExtensionGT applies the GT predicate on the "extension" field.
func ExtensionGT(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGT(FieldExtension, v))
}
// ExtensionGTE applies the GTE predicate on the "extension" field.
func ExtensionGTE(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGTE(FieldExtension, v))
}
// ExtensionLT applies the LT predicate on the "extension" field.
func ExtensionLT(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLT(FieldExtension, v))
}
// ExtensionLTE applies the LTE predicate on the "extension" field.
func ExtensionLTE(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLTE(FieldExtension, v))
}
// ExtensionContains applies the Contains predicate on the "extension" field.
func ExtensionContains(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContains(FieldExtension, v))
}
// ExtensionHasPrefix applies the HasPrefix predicate on the "extension" field.
func ExtensionHasPrefix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasPrefix(FieldExtension, v))
}
// ExtensionHasSuffix applies the HasSuffix predicate on the "extension" field.
func ExtensionHasSuffix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasSuffix(FieldExtension, v))
}
// ExtensionIsNil applies the IsNil predicate on the "extension" field.
func ExtensionIsNil() predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldIsNull(FieldExtension))
}
// ExtensionNotNil applies the NotNil predicate on the "extension" field.
func ExtensionNotNil() predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNotNull(FieldExtension))
}
// ExtensionEqualFold applies the EqualFold predicate on the "extension" field.
func ExtensionEqualFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEqualFold(FieldExtension, v))
}
// ExtensionContainsFold applies the ContainsFold predicate on the "extension" field.
func ExtensionContainsFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContainsFold(FieldExtension, v))
}
// EnabledEQ applies the EQ predicate on the "enabled" field.
func EnabledEQ(v bool) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldEnabled, v))
}
// EnabledNEQ applies the NEQ predicate on the "enabled" field.
func EnabledNEQ(v bool) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNEQ(FieldEnabled, v))
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.KeyBinding) predicate.KeyBinding {
return predicate.KeyBinding(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.KeyBinding) predicate.KeyBinding {
return predicate.KeyBinding(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.KeyBinding) predicate.KeyBinding {
return predicate.KeyBinding(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,337 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"voidraft/internal/models/ent/keybinding"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// KeyBindingCreate is the builder for creating a KeyBinding entity.
type KeyBindingCreate struct {
config
mutation *KeyBindingMutation
hooks []Hook
}
// SetCreatedAt sets the "created_at" field.
func (_c *KeyBindingCreate) SetCreatedAt(v string) *KeyBindingCreate {
_c.mutation.SetCreatedAt(v)
return _c
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (_c *KeyBindingCreate) SetNillableCreatedAt(v *string) *KeyBindingCreate {
if v != nil {
_c.SetCreatedAt(*v)
}
return _c
}
// SetUpdatedAt sets the "updated_at" field.
func (_c *KeyBindingCreate) SetUpdatedAt(v string) *KeyBindingCreate {
_c.mutation.SetUpdatedAt(v)
return _c
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (_c *KeyBindingCreate) SetNillableUpdatedAt(v *string) *KeyBindingCreate {
if v != nil {
_c.SetUpdatedAt(*v)
}
return _c
}
// SetDeletedAt sets the "deleted_at" field.
func (_c *KeyBindingCreate) SetDeletedAt(v string) *KeyBindingCreate {
_c.mutation.SetDeletedAt(v)
return _c
}
// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_c *KeyBindingCreate) SetNillableDeletedAt(v *string) *KeyBindingCreate {
if v != nil {
_c.SetDeletedAt(*v)
}
return _c
}
// SetKey sets the "key" field.
func (_c *KeyBindingCreate) SetKey(v string) *KeyBindingCreate {
_c.mutation.SetKey(v)
return _c
}
// SetCommand sets the "command" field.
func (_c *KeyBindingCreate) SetCommand(v string) *KeyBindingCreate {
_c.mutation.SetCommand(v)
return _c
}
// SetExtension sets the "extension" field.
func (_c *KeyBindingCreate) SetExtension(v string) *KeyBindingCreate {
_c.mutation.SetExtension(v)
return _c
}
// SetNillableExtension sets the "extension" field if the given value is not nil.
func (_c *KeyBindingCreate) SetNillableExtension(v *string) *KeyBindingCreate {
if v != nil {
_c.SetExtension(*v)
}
return _c
}
// SetEnabled sets the "enabled" field.
func (_c *KeyBindingCreate) SetEnabled(v bool) *KeyBindingCreate {
_c.mutation.SetEnabled(v)
return _c
}
// SetNillableEnabled sets the "enabled" field if the given value is not nil.
func (_c *KeyBindingCreate) SetNillableEnabled(v *bool) *KeyBindingCreate {
if v != nil {
_c.SetEnabled(*v)
}
return _c
}
// Mutation returns the KeyBindingMutation object of the builder.
func (_c *KeyBindingCreate) Mutation() *KeyBindingMutation {
return _c.mutation
}
// Save creates the KeyBinding in the database.
func (_c *KeyBindingCreate) Save(ctx context.Context) (*KeyBinding, error) {
if err := _c.defaults(); err != nil {
return nil, err
}
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *KeyBindingCreate) SaveX(ctx context.Context) *KeyBinding {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *KeyBindingCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *KeyBindingCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_c *KeyBindingCreate) defaults() error {
if _, ok := _c.mutation.CreatedAt(); !ok {
if keybinding.DefaultCreatedAt == nil {
return fmt.Errorf("ent: uninitialized keybinding.DefaultCreatedAt (forgotten import ent/runtime?)")
}
v := keybinding.DefaultCreatedAt()
_c.mutation.SetCreatedAt(v)
}
if _, ok := _c.mutation.UpdatedAt(); !ok {
if keybinding.DefaultUpdatedAt == nil {
return fmt.Errorf("ent: uninitialized keybinding.DefaultUpdatedAt (forgotten import ent/runtime?)")
}
v := keybinding.DefaultUpdatedAt()
_c.mutation.SetUpdatedAt(v)
}
if _, ok := _c.mutation.Enabled(); !ok {
v := keybinding.DefaultEnabled
_c.mutation.SetEnabled(v)
}
return nil
}
// check runs all checks and user-defined validators on the builder.
func (_c *KeyBindingCreate) check() error {
if _, ok := _c.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "KeyBinding.created_at"`)}
}
if _, ok := _c.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "KeyBinding.updated_at"`)}
}
if _, ok := _c.mutation.Key(); !ok {
return &ValidationError{Name: "key", err: errors.New(`ent: missing required field "KeyBinding.key"`)}
}
if v, ok := _c.mutation.Key(); ok {
if err := keybinding.KeyValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.key": %w`, err)}
}
}
if _, ok := _c.mutation.Command(); !ok {
return &ValidationError{Name: "command", err: errors.New(`ent: missing required field "KeyBinding.command"`)}
}
if v, ok := _c.mutation.Command(); ok {
if err := keybinding.CommandValidator(v); err != nil {
return &ValidationError{Name: "command", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.command": %w`, err)}
}
}
if v, ok := _c.mutation.Extension(); ok {
if err := keybinding.ExtensionValidator(v); err != nil {
return &ValidationError{Name: "extension", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.extension": %w`, err)}
}
}
if _, ok := _c.mutation.Enabled(); !ok {
return &ValidationError{Name: "enabled", err: errors.New(`ent: missing required field "KeyBinding.enabled"`)}
}
return nil
}
func (_c *KeyBindingCreate) sqlSave(ctx context.Context) (*KeyBinding, error) {
if err := _c.check(); err != nil {
return nil, err
}
_node, _spec := _c.createSpec()
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
_c.mutation.id = &_node.ID
_c.mutation.done = true
return _node, nil
}
func (_c *KeyBindingCreate) createSpec() (*KeyBinding, *sqlgraph.CreateSpec) {
var (
_node = &KeyBinding{config: _c.config}
_spec = sqlgraph.NewCreateSpec(keybinding.Table, sqlgraph.NewFieldSpec(keybinding.FieldID, field.TypeInt))
)
if value, ok := _c.mutation.CreatedAt(); ok {
_spec.SetField(keybinding.FieldCreatedAt, field.TypeString, value)
_node.CreatedAt = value
}
if value, ok := _c.mutation.UpdatedAt(); ok {
_spec.SetField(keybinding.FieldUpdatedAt, field.TypeString, value)
_node.UpdatedAt = value
}
if value, ok := _c.mutation.DeletedAt(); ok {
_spec.SetField(keybinding.FieldDeletedAt, field.TypeString, value)
_node.DeletedAt = &value
}
if value, ok := _c.mutation.Key(); ok {
_spec.SetField(keybinding.FieldKey, field.TypeString, value)
_node.Key = value
}
if value, ok := _c.mutation.Command(); ok {
_spec.SetField(keybinding.FieldCommand, field.TypeString, value)
_node.Command = value
}
if value, ok := _c.mutation.Extension(); ok {
_spec.SetField(keybinding.FieldExtension, field.TypeString, value)
_node.Extension = value
}
if value, ok := _c.mutation.Enabled(); ok {
_spec.SetField(keybinding.FieldEnabled, field.TypeBool, value)
_node.Enabled = value
}
return _node, _spec
}
// KeyBindingCreateBulk is the builder for creating many KeyBinding entities in bulk.
type KeyBindingCreateBulk struct {
config
err error
builders []*KeyBindingCreate
}
// Save creates the KeyBinding entities in the database.
func (_c *KeyBindingCreateBulk) Save(ctx context.Context) ([]*KeyBinding, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*KeyBinding, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*KeyBindingMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
mutation.done = true
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, _c.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (_c *KeyBindingCreateBulk) SaveX(ctx context.Context) []*KeyBinding {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *KeyBindingCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *KeyBindingCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,88 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"voidraft/internal/models/ent/keybinding"
"voidraft/internal/models/ent/predicate"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// KeyBindingDelete is the builder for deleting a KeyBinding entity.
type KeyBindingDelete struct {
config
hooks []Hook
mutation *KeyBindingMutation
}
// Where appends a list predicates to the KeyBindingDelete builder.
func (_d *KeyBindingDelete) Where(ps ...predicate.KeyBinding) *KeyBindingDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *KeyBindingDelete) Exec(ctx context.Context) (int, error) {
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *KeyBindingDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *KeyBindingDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(keybinding.Table, sqlgraph.NewFieldSpec(keybinding.FieldID, field.TypeInt))
if ps := _d.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
_d.mutation.done = true
return affected, err
}
// KeyBindingDeleteOne is the builder for deleting a single KeyBinding entity.
type KeyBindingDeleteOne struct {
_d *KeyBindingDelete
}
// Where appends a list predicates to the KeyBindingDelete builder.
func (_d *KeyBindingDeleteOne) Where(ps ...predicate.KeyBinding) *KeyBindingDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *KeyBindingDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{keybinding.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *KeyBindingDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,577 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"voidraft/internal/models/ent/keybinding"
"voidraft/internal/models/ent/predicate"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// KeyBindingQuery is the builder for querying KeyBinding entities.
type KeyBindingQuery struct {
config
ctx *QueryContext
order []keybinding.OrderOption
inters []Interceptor
predicates []predicate.KeyBinding
modifiers []func(*sql.Selector)
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the KeyBindingQuery builder.
func (_q *KeyBindingQuery) Where(ps ...predicate.KeyBinding) *KeyBindingQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *KeyBindingQuery) Limit(limit int) *KeyBindingQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *KeyBindingQuery) Offset(offset int) *KeyBindingQuery {
_q.ctx.Offset = &offset
return _q
}
// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (_q *KeyBindingQuery) Unique(unique bool) *KeyBindingQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *KeyBindingQuery) Order(o ...keybinding.OrderOption) *KeyBindingQuery {
_q.order = append(_q.order, o...)
return _q
}
// First returns the first KeyBinding entity from the query.
// Returns a *NotFoundError when no KeyBinding was found.
func (_q *KeyBindingQuery) First(ctx context.Context) (*KeyBinding, error) {
nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{keybinding.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *KeyBindingQuery) FirstX(ctx context.Context) *KeyBinding {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first KeyBinding ID from the query.
// Returns a *NotFoundError when no KeyBinding ID was found.
func (_q *KeyBindingQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{keybinding.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *KeyBindingQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single KeyBinding entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one KeyBinding entity is found.
// Returns a *NotFoundError when no KeyBinding entities are found.
func (_q *KeyBindingQuery) Only(ctx context.Context) (*KeyBinding, error) {
nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{keybinding.Label}
default:
return nil, &NotSingularError{keybinding.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *KeyBindingQuery) OnlyX(ctx context.Context) *KeyBinding {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only KeyBinding ID in the query.
// Returns a *NotSingularError when more than one KeyBinding ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *KeyBindingQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{keybinding.Label}
default:
err = &NotSingularError{keybinding.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *KeyBindingQuery) OnlyIDX(ctx context.Context) int {
id, err := _q.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of KeyBindings.
func (_q *KeyBindingQuery) All(ctx context.Context) ([]*KeyBinding, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*KeyBinding, *KeyBindingQuery]()
return withInterceptors[[]*KeyBinding](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *KeyBindingQuery) AllX(ctx context.Context) []*KeyBinding {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of KeyBinding IDs.
func (_q *KeyBindingQuery) IDs(ctx context.Context) (ids []int, err error) {
if _q.ctx.Unique == nil && _q.path != nil {
_q.Unique(true)
}
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
if err = _q.Select(keybinding.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *KeyBindingQuery) IDsX(ctx context.Context) []int {
ids, err := _q.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (_q *KeyBindingQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)
if err := _q.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, _q, querierCount[*KeyBindingQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *KeyBindingQuery) CountX(ctx context.Context) int {
count, err := _q.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (_q *KeyBindingQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
switch _, err := _q.FirstID(ctx); {
case IsNotFound(err):
return false, nil
case err != nil:
return false, fmt.Errorf("ent: check existence: %w", err)
default:
return true, nil
}
}
// ExistX is like Exist, but panics if an error occurs.
func (_q *KeyBindingQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the KeyBindingQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (_q *KeyBindingQuery) Clone() *KeyBindingQuery {
if _q == nil {
return nil
}
return &KeyBindingQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]keybinding.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.KeyBinding{}, _q.predicates...),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
modifiers: append([]func(*sql.Selector){}, _q.modifiers...),
}
}
// GroupBy is 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 {
// CreatedAt string `json:"created_at"`
// Count int `json:"count,omitempty"`
// }
//
// client.KeyBinding.Query().
// GroupBy(keybinding.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *KeyBindingQuery) GroupBy(field string, fields ...string) *KeyBindingGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &KeyBindingGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = keybinding.Label
grbuild.scan = grbuild.Scan
return grbuild
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// CreatedAt string `json:"created_at"`
// }
//
// client.KeyBinding.Query().
// Select(keybinding.FieldCreatedAt).
// Scan(ctx, &v)
func (_q *KeyBindingQuery) Select(fields ...string) *KeyBindingSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &KeyBindingSelect{KeyBindingQuery: _q}
sbuild.label = keybinding.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a KeyBindingSelect configured with the given aggregations.
func (_q *KeyBindingQuery) Aggregate(fns ...AggregateFunc) *KeyBindingSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *KeyBindingQuery) prepareQuery(ctx context.Context) error {
for _, inter := range _q.inters {
if inter == nil {
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
}
if trv, ok := inter.(Traverser); ok {
if err := trv.Traverse(ctx, _q); err != nil {
return err
}
}
}
for _, f := range _q.ctx.Fields {
if !keybinding.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if _q.path != nil {
prev, err := _q.path(ctx)
if err != nil {
return err
}
_q.sql = prev
}
return nil
}
func (_q *KeyBindingQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*KeyBinding, error) {
var (
nodes = []*KeyBinding{}
_spec = _q.querySpec()
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*KeyBinding).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &KeyBinding{config: _q.config}
nodes = append(nodes, node)
return node.assignValues(columns, values)
}
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (_q *KeyBindingQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *KeyBindingQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(keybinding.Table, keybinding.Columns, sqlgraph.NewFieldSpec(keybinding.FieldID, field.TypeInt))
_spec.From = _q.sql
if unique := _q.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if _q.path != nil {
_spec.Unique = true
}
if fields := _q.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, keybinding.FieldID)
for i := range fields {
if fields[i] != keybinding.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := _q.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := _q.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := _q.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := _q.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (_q *KeyBindingQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(keybinding.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = keybinding.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, m := range _q.modifiers {
m(selector)
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.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 := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
// updated, deleted or "selected ... for update" by other sessions, until the transaction is
// either committed or rolled-back.
func (_q *KeyBindingQuery) ForUpdate(opts ...sql.LockOption) *KeyBindingQuery {
if _q.driver.Dialect() == dialect.Postgres {
_q.Unique(false)
}
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
s.ForUpdate(opts...)
})
return _q
}
// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
// on any rows that are read. Other sessions can read the rows, but cannot modify them
// until your transaction commits.
func (_q *KeyBindingQuery) ForShare(opts ...sql.LockOption) *KeyBindingQuery {
if _q.driver.Dialect() == dialect.Postgres {
_q.Unique(false)
}
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
s.ForShare(opts...)
})
return _q
}
// Modify adds a query modifier for attaching custom logic to queries.
func (_q *KeyBindingQuery) Modify(modifiers ...func(s *sql.Selector)) *KeyBindingSelect {
_q.modifiers = append(_q.modifiers, modifiers...)
return _q.Select()
}
// KeyBindingGroupBy is the group-by builder for KeyBinding entities.
type KeyBindingGroupBy struct {
selector
build *KeyBindingQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *KeyBindingGroupBy) Aggregate(fns ...AggregateFunc) *KeyBindingGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *KeyBindingGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)
if err := _g.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*KeyBindingQuery, *KeyBindingGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *KeyBindingGroupBy) sqlScan(ctx context.Context, root *KeyBindingQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(_g.fns))
for _, fn := range _g.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*_g.flds)+len(_g.fns))
for _, f := range *_g.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*_g.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// KeyBindingSelect is the builder for selecting fields of KeyBinding entities.
type KeyBindingSelect struct {
*KeyBindingQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *KeyBindingSelect) Aggregate(fns ...AggregateFunc) *KeyBindingSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *KeyBindingSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)
if err := _s.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*KeyBindingQuery, *KeyBindingSelect](ctx, _s.KeyBindingQuery, _s, _s.inters, v)
}
func (_s *KeyBindingSelect) sqlScan(ctx context.Context, root *KeyBindingQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(_s.fns))
for _, fn := range _s.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*_s.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// Modify adds a query modifier for attaching custom logic to queries.
func (_s *KeyBindingSelect) Modify(modifiers ...func(s *sql.Selector)) *KeyBindingSelect {
_s.modifiers = append(_s.modifiers, modifiers...)
return _s
}

View File

@@ -0,0 +1,477 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"voidraft/internal/models/ent/keybinding"
"voidraft/internal/models/ent/predicate"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// KeyBindingUpdate is the builder for updating KeyBinding entities.
type KeyBindingUpdate struct {
config
hooks []Hook
mutation *KeyBindingMutation
modifiers []func(*sql.UpdateBuilder)
}
// Where appends a list predicates to the KeyBindingUpdate builder.
func (_u *KeyBindingUpdate) Where(ps ...predicate.KeyBinding) *KeyBindingUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetUpdatedAt sets the "updated_at" field.
func (_u *KeyBindingUpdate) SetUpdatedAt(v string) *KeyBindingUpdate {
_u.mutation.SetUpdatedAt(v)
return _u
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (_u *KeyBindingUpdate) SetNillableUpdatedAt(v *string) *KeyBindingUpdate {
if v != nil {
_u.SetUpdatedAt(*v)
}
return _u
}
// SetDeletedAt sets the "deleted_at" field.
func (_u *KeyBindingUpdate) SetDeletedAt(v string) *KeyBindingUpdate {
_u.mutation.SetDeletedAt(v)
return _u
}
// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_u *KeyBindingUpdate) SetNillableDeletedAt(v *string) *KeyBindingUpdate {
if v != nil {
_u.SetDeletedAt(*v)
}
return _u
}
// ClearDeletedAt clears the value of the "deleted_at" field.
func (_u *KeyBindingUpdate) ClearDeletedAt() *KeyBindingUpdate {
_u.mutation.ClearDeletedAt()
return _u
}
// SetKey sets the "key" field.
func (_u *KeyBindingUpdate) SetKey(v string) *KeyBindingUpdate {
_u.mutation.SetKey(v)
return _u
}
// SetNillableKey sets the "key" field if the given value is not nil.
func (_u *KeyBindingUpdate) SetNillableKey(v *string) *KeyBindingUpdate {
if v != nil {
_u.SetKey(*v)
}
return _u
}
// SetCommand sets the "command" field.
func (_u *KeyBindingUpdate) SetCommand(v string) *KeyBindingUpdate {
_u.mutation.SetCommand(v)
return _u
}
// SetNillableCommand sets the "command" field if the given value is not nil.
func (_u *KeyBindingUpdate) SetNillableCommand(v *string) *KeyBindingUpdate {
if v != nil {
_u.SetCommand(*v)
}
return _u
}
// SetExtension sets the "extension" field.
func (_u *KeyBindingUpdate) SetExtension(v string) *KeyBindingUpdate {
_u.mutation.SetExtension(v)
return _u
}
// SetNillableExtension sets the "extension" field if the given value is not nil.
func (_u *KeyBindingUpdate) SetNillableExtension(v *string) *KeyBindingUpdate {
if v != nil {
_u.SetExtension(*v)
}
return _u
}
// ClearExtension clears the value of the "extension" field.
func (_u *KeyBindingUpdate) ClearExtension() *KeyBindingUpdate {
_u.mutation.ClearExtension()
return _u
}
// SetEnabled sets the "enabled" field.
func (_u *KeyBindingUpdate) SetEnabled(v bool) *KeyBindingUpdate {
_u.mutation.SetEnabled(v)
return _u
}
// SetNillableEnabled sets the "enabled" field if the given value is not nil.
func (_u *KeyBindingUpdate) SetNillableEnabled(v *bool) *KeyBindingUpdate {
if v != nil {
_u.SetEnabled(*v)
}
return _u
}
// Mutation returns the KeyBindingMutation object of the builder.
func (_u *KeyBindingUpdate) Mutation() *KeyBindingMutation {
return _u.mutation
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *KeyBindingUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *KeyBindingUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *KeyBindingUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *KeyBindingUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *KeyBindingUpdate) check() error {
if v, ok := _u.mutation.Key(); ok {
if err := keybinding.KeyValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.key": %w`, err)}
}
}
if v, ok := _u.mutation.Command(); ok {
if err := keybinding.CommandValidator(v); err != nil {
return &ValidationError{Name: "command", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.command": %w`, err)}
}
}
if v, ok := _u.mutation.Extension(); ok {
if err := keybinding.ExtensionValidator(v); err != nil {
return &ValidationError{Name: "extension", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.extension": %w`, err)}
}
}
return nil
}
// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
func (_u *KeyBindingUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *KeyBindingUpdate {
_u.modifiers = append(_u.modifiers, modifiers...)
return _u
}
func (_u *KeyBindingUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(keybinding.Table, keybinding.Columns, sqlgraph.NewFieldSpec(keybinding.FieldID, field.TypeInt))
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(keybinding.FieldUpdatedAt, field.TypeString, value)
}
if value, ok := _u.mutation.DeletedAt(); ok {
_spec.SetField(keybinding.FieldDeletedAt, field.TypeString, value)
}
if _u.mutation.DeletedAtCleared() {
_spec.ClearField(keybinding.FieldDeletedAt, field.TypeString)
}
if value, ok := _u.mutation.Key(); ok {
_spec.SetField(keybinding.FieldKey, field.TypeString, value)
}
if value, ok := _u.mutation.Command(); ok {
_spec.SetField(keybinding.FieldCommand, field.TypeString, value)
}
if value, ok := _u.mutation.Extension(); ok {
_spec.SetField(keybinding.FieldExtension, field.TypeString, value)
}
if _u.mutation.ExtensionCleared() {
_spec.ClearField(keybinding.FieldExtension, field.TypeString)
}
if value, ok := _u.mutation.Enabled(); ok {
_spec.SetField(keybinding.FieldEnabled, field.TypeBool, value)
}
_spec.AddModifiers(_u.modifiers...)
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{keybinding.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// KeyBindingUpdateOne is the builder for updating a single KeyBinding entity.
type KeyBindingUpdateOne struct {
config
fields []string
hooks []Hook
mutation *KeyBindingMutation
modifiers []func(*sql.UpdateBuilder)
}
// SetUpdatedAt sets the "updated_at" field.
func (_u *KeyBindingUpdateOne) SetUpdatedAt(v string) *KeyBindingUpdateOne {
_u.mutation.SetUpdatedAt(v)
return _u
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (_u *KeyBindingUpdateOne) SetNillableUpdatedAt(v *string) *KeyBindingUpdateOne {
if v != nil {
_u.SetUpdatedAt(*v)
}
return _u
}
// SetDeletedAt sets the "deleted_at" field.
func (_u *KeyBindingUpdateOne) SetDeletedAt(v string) *KeyBindingUpdateOne {
_u.mutation.SetDeletedAt(v)
return _u
}
// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_u *KeyBindingUpdateOne) SetNillableDeletedAt(v *string) *KeyBindingUpdateOne {
if v != nil {
_u.SetDeletedAt(*v)
}
return _u
}
// ClearDeletedAt clears the value of the "deleted_at" field.
func (_u *KeyBindingUpdateOne) ClearDeletedAt() *KeyBindingUpdateOne {
_u.mutation.ClearDeletedAt()
return _u
}
// SetKey sets the "key" field.
func (_u *KeyBindingUpdateOne) SetKey(v string) *KeyBindingUpdateOne {
_u.mutation.SetKey(v)
return _u
}
// SetNillableKey sets the "key" field if the given value is not nil.
func (_u *KeyBindingUpdateOne) SetNillableKey(v *string) *KeyBindingUpdateOne {
if v != nil {
_u.SetKey(*v)
}
return _u
}
// SetCommand sets the "command" field.
func (_u *KeyBindingUpdateOne) SetCommand(v string) *KeyBindingUpdateOne {
_u.mutation.SetCommand(v)
return _u
}
// SetNillableCommand sets the "command" field if the given value is not nil.
func (_u *KeyBindingUpdateOne) SetNillableCommand(v *string) *KeyBindingUpdateOne {
if v != nil {
_u.SetCommand(*v)
}
return _u
}
// SetExtension sets the "extension" field.
func (_u *KeyBindingUpdateOne) SetExtension(v string) *KeyBindingUpdateOne {
_u.mutation.SetExtension(v)
return _u
}
// SetNillableExtension sets the "extension" field if the given value is not nil.
func (_u *KeyBindingUpdateOne) SetNillableExtension(v *string) *KeyBindingUpdateOne {
if v != nil {
_u.SetExtension(*v)
}
return _u
}
// ClearExtension clears the value of the "extension" field.
func (_u *KeyBindingUpdateOne) ClearExtension() *KeyBindingUpdateOne {
_u.mutation.ClearExtension()
return _u
}
// SetEnabled sets the "enabled" field.
func (_u *KeyBindingUpdateOne) SetEnabled(v bool) *KeyBindingUpdateOne {
_u.mutation.SetEnabled(v)
return _u
}
// SetNillableEnabled sets the "enabled" field if the given value is not nil.
func (_u *KeyBindingUpdateOne) SetNillableEnabled(v *bool) *KeyBindingUpdateOne {
if v != nil {
_u.SetEnabled(*v)
}
return _u
}
// Mutation returns the KeyBindingMutation object of the builder.
func (_u *KeyBindingUpdateOne) Mutation() *KeyBindingMutation {
return _u.mutation
}
// Where appends a list predicates to the KeyBindingUpdate builder.
func (_u *KeyBindingUpdateOne) Where(ps ...predicate.KeyBinding) *KeyBindingUpdateOne {
_u.mutation.Where(ps...)
return _u
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (_u *KeyBindingUpdateOne) Select(field string, fields ...string) *KeyBindingUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated KeyBinding entity.
func (_u *KeyBindingUpdateOne) Save(ctx context.Context) (*KeyBinding, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *KeyBindingUpdateOne) SaveX(ctx context.Context) *KeyBinding {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *KeyBindingUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *KeyBindingUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *KeyBindingUpdateOne) check() error {
if v, ok := _u.mutation.Key(); ok {
if err := keybinding.KeyValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.key": %w`, err)}
}
}
if v, ok := _u.mutation.Command(); ok {
if err := keybinding.CommandValidator(v); err != nil {
return &ValidationError{Name: "command", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.command": %w`, err)}
}
}
if v, ok := _u.mutation.Extension(); ok {
if err := keybinding.ExtensionValidator(v); err != nil {
return &ValidationError{Name: "extension", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.extension": %w`, err)}
}
}
return nil
}
// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
func (_u *KeyBindingUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *KeyBindingUpdateOne {
_u.modifiers = append(_u.modifiers, modifiers...)
return _u
}
func (_u *KeyBindingUpdateOne) sqlSave(ctx context.Context) (_node *KeyBinding, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(keybinding.Table, keybinding.Columns, sqlgraph.NewFieldSpec(keybinding.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "KeyBinding.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := _u.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, keybinding.FieldID)
for _, f := range fields {
if !keybinding.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != keybinding.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(keybinding.FieldUpdatedAt, field.TypeString, value)
}
if value, ok := _u.mutation.DeletedAt(); ok {
_spec.SetField(keybinding.FieldDeletedAt, field.TypeString, value)
}
if _u.mutation.DeletedAtCleared() {
_spec.ClearField(keybinding.FieldDeletedAt, field.TypeString)
}
if value, ok := _u.mutation.Key(); ok {
_spec.SetField(keybinding.FieldKey, field.TypeString, value)
}
if value, ok := _u.mutation.Command(); ok {
_spec.SetField(keybinding.FieldCommand, field.TypeString, value)
}
if value, ok := _u.mutation.Extension(); ok {
_spec.SetField(keybinding.FieldExtension, field.TypeString, value)
}
if _u.mutation.ExtensionCleared() {
_spec.ClearField(keybinding.FieldExtension, field.TypeString)
}
if value, ok := _u.mutation.Enabled(); ok {
_spec.SetField(keybinding.FieldEnabled, field.TypeBool, value)
}
_spec.AddModifiers(_u.modifiers...)
_node = &KeyBinding{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{keybinding.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

View File

@@ -0,0 +1,64 @@
// Code generated by ent, DO NOT EDIT.
package migrate
import (
"context"
"fmt"
"io"
"entgo.io/ent/dialect"
"entgo.io/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
// WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true.
WithForeignKeys = schema.WithForeignKeys
)
// Schema is the API for creating, migrating and dropping a schema.
type Schema struct {
drv dialect.Driver
}
// 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 {
return Create(ctx, s, Tables, opts...)
}
// Create creates all table resources using the given schema driver.
func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error {
migrate, err := schema.NewMigrate(s.drv, opts...)
if err != nil {
return fmt.Errorf("ent/migrate: %w", 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 {
return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...)
}

View File

@@ -0,0 +1,157 @@
// Code generated by ent, DO NOT EDIT.
package migrate
import (
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/schema/field"
)
var (
// DocumentsColumns holds the columns for the "documents" table.
DocumentsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "created_at", Type: field.TypeString},
{Name: "updated_at", Type: field.TypeString},
{Name: "deleted_at", Type: field.TypeString, Nullable: true},
{Name: "title", Type: field.TypeString, Size: 255},
{Name: "content", Type: field.TypeString, Nullable: true, Size: 2147483647, Default: "\n∞∞∞text-a\n"},
{Name: "locked", Type: field.TypeBool, Default: false},
}
// DocumentsTable holds the schema information for the "documents" table.
DocumentsTable = &schema.Table{
Name: "documents",
Columns: DocumentsColumns,
PrimaryKey: []*schema.Column{DocumentsColumns[0]},
Indexes: []*schema.Index{
{
Name: "document_deleted_at",
Unique: false,
Columns: []*schema.Column{DocumentsColumns[3]},
},
{
Name: "document_title",
Unique: false,
Columns: []*schema.Column{DocumentsColumns[4]},
},
{
Name: "document_created_at",
Unique: false,
Columns: []*schema.Column{DocumentsColumns[1]},
},
{
Name: "document_updated_at",
Unique: false,
Columns: []*schema.Column{DocumentsColumns[2]},
},
},
}
// ExtensionsColumns holds the columns for the "extensions" table.
ExtensionsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "created_at", Type: field.TypeString},
{Name: "updated_at", Type: field.TypeString},
{Name: "deleted_at", Type: field.TypeString, Nullable: true},
{Name: "key", Type: field.TypeString, Unique: true, Size: 100},
{Name: "enabled", Type: field.TypeBool, Default: true},
{Name: "config", Type: field.TypeJSON, Nullable: true},
}
// ExtensionsTable holds the schema information for the "extensions" table.
ExtensionsTable = &schema.Table{
Name: "extensions",
Columns: ExtensionsColumns,
PrimaryKey: []*schema.Column{ExtensionsColumns[0]},
Indexes: []*schema.Index{
{
Name: "extension_deleted_at",
Unique: false,
Columns: []*schema.Column{ExtensionsColumns[3]},
},
{
Name: "extension_enabled",
Unique: false,
Columns: []*schema.Column{ExtensionsColumns[5]},
},
},
}
// KeyBindingsColumns holds the columns for the "key_bindings" table.
KeyBindingsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "created_at", Type: field.TypeString},
{Name: "updated_at", Type: field.TypeString},
{Name: "deleted_at", Type: field.TypeString, Nullable: true},
{Name: "key", Type: field.TypeString, Unique: true, Size: 100},
{Name: "command", Type: field.TypeString, Size: 100},
{Name: "extension", Type: field.TypeString, Nullable: true, Size: 100},
{Name: "enabled", Type: field.TypeBool, Default: true},
}
// KeyBindingsTable holds the schema information for the "key_bindings" table.
KeyBindingsTable = &schema.Table{
Name: "key_bindings",
Columns: KeyBindingsColumns,
PrimaryKey: []*schema.Column{KeyBindingsColumns[0]},
Indexes: []*schema.Index{
{
Name: "keybinding_deleted_at",
Unique: false,
Columns: []*schema.Column{KeyBindingsColumns[3]},
},
{
Name: "keybinding_extension",
Unique: false,
Columns: []*schema.Column{KeyBindingsColumns[6]},
},
{
Name: "keybinding_enabled",
Unique: false,
Columns: []*schema.Column{KeyBindingsColumns[7]},
},
},
}
// ThemesColumns holds the columns for the "themes" table.
ThemesColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "created_at", Type: field.TypeString},
{Name: "updated_at", Type: field.TypeString},
{Name: "deleted_at", Type: field.TypeString, Nullable: true},
{Name: "key", Type: field.TypeString, Unique: true, Size: 100},
{Name: "type", Type: field.TypeEnum, Enums: []string{"dark", "light"}},
{Name: "colors", Type: field.TypeJSON, Nullable: true},
}
// ThemesTable holds the schema information for the "themes" table.
ThemesTable = &schema.Table{
Name: "themes",
Columns: ThemesColumns,
PrimaryKey: []*schema.Column{ThemesColumns[0]},
Indexes: []*schema.Index{
{
Name: "theme_deleted_at",
Unique: false,
Columns: []*schema.Column{ThemesColumns[3]},
},
},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
DocumentsTable,
ExtensionsTable,
KeyBindingsTable,
ThemesTable,
}
)
func init() {
DocumentsTable.Annotation = &entsql.Annotation{
Table: "documents",
}
ExtensionsTable.Annotation = &entsql.Annotation{
Table: "extensions",
}
KeyBindingsTable.Annotation = &entsql.Annotation{
Table: "key_bindings",
}
ThemesTable.Annotation = &entsql.Annotation{
Table: "themes",
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,19 @@
// Code generated by ent, DO NOT EDIT.
package predicate
import (
"entgo.io/ent/dialect/sql"
)
// Document is the predicate function for document builders.
type Document func(*sql.Selector)
// Extension is the predicate function for extension builders.
type Extension func(*sql.Selector)
// KeyBinding is the predicate function for keybinding builders.
type KeyBinding func(*sql.Selector)
// Theme is the predicate function for theme builders.
type Theme func(*sql.Selector)

View File

@@ -0,0 +1,271 @@
// Code generated by ent, DO NOT EDIT.
package privacy
import (
"context"
"voidraft/internal/models/ent"
"entgo.io/ent/entql"
"entgo.io/ent/privacy"
)
var (
// Allow may be returned by rules to indicate that the policy
// evaluation should terminate with allow decision.
Allow = privacy.Allow
// Deny may be returned by rules to indicate that the policy
// evaluation should terminate with deny decision.
Deny = privacy.Deny
// Skip may be returned by rules to indicate that the policy
// evaluation should continue to the next rule.
Skip = privacy.Skip
)
// Allowf returns a formatted wrapped Allow decision.
func Allowf(format string, a ...any) error {
return privacy.Allowf(format, a...)
}
// Denyf returns a formatted wrapped Deny decision.
func Denyf(format string, a ...any) error {
return privacy.Denyf(format, a...)
}
// Skipf returns a formatted wrapped Skip decision.
func Skipf(format string, a ...any) error {
return privacy.Skipf(format, a...)
}
// DecisionContext creates a new context from the given parent context with
// a policy decision attach to it.
func DecisionContext(parent context.Context, decision error) context.Context {
return privacy.DecisionContext(parent, decision)
}
// DecisionFromContext retrieves the policy decision from the context.
func DecisionFromContext(ctx context.Context) (error, bool) {
return privacy.DecisionFromContext(ctx)
}
type (
// Policy groups query and mutation policies.
Policy = privacy.Policy
// QueryRule defines the interface deciding whether a
// query is allowed and optionally modify it.
QueryRule = privacy.QueryRule
// QueryPolicy combines multiple query rules into a single policy.
QueryPolicy = privacy.QueryPolicy
// MutationRule defines the interface which decides whether a
// mutation is allowed and optionally modifies it.
MutationRule = privacy.MutationRule
// MutationPolicy combines multiple mutation rules into a single policy.
MutationPolicy = privacy.MutationPolicy
// MutationRuleFunc type is an adapter which allows the use of
// ordinary functions as mutation rules.
MutationRuleFunc = privacy.MutationRuleFunc
// QueryMutationRule is an interface which groups query and mutation rules.
QueryMutationRule = privacy.QueryMutationRule
)
// 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)
}
// AlwaysAllowRule returns a rule that returns an allow decision.
func AlwaysAllowRule() QueryMutationRule {
return privacy.AlwaysAllowRule()
}
// AlwaysDenyRule returns a rule that returns a deny decision.
func AlwaysDenyRule() QueryMutationRule {
return privacy.AlwaysDenyRule()
}
// ContextQueryMutationRule creates a query/mutation rule from a context eval func.
func ContextQueryMutationRule(eval func(context.Context) error) QueryMutationRule {
return privacy.ContextQueryMutationRule(eval)
}
// OnMutationOperation evaluates the given rule only on a given mutation operation.
func OnMutationOperation(rule MutationRule, op ent.Op) MutationRule {
return privacy.OnMutationOperation(rule, op)
}
// 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 DocumentQueryRuleFunc type is an adapter to allow the use of ordinary
// functions as a query rule.
type DocumentQueryRuleFunc func(context.Context, *ent.DocumentQuery) error
// EvalQuery return f(ctx, q).
func (f DocumentQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.DocumentQuery); ok {
return f(ctx, q)
}
return Denyf("ent/privacy: unexpected query type %T, expect *ent.DocumentQuery", q)
}
// The DocumentMutationRuleFunc type is an adapter to allow the use of ordinary
// functions as a mutation rule.
type DocumentMutationRuleFunc func(context.Context, *ent.DocumentMutation) error
// EvalMutation calls f(ctx, m).
func (f DocumentMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error {
if m, ok := m.(*ent.DocumentMutation); ok {
return f(ctx, m)
}
return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.DocumentMutation", m)
}
// The ExtensionQueryRuleFunc type is an adapter to allow the use of ordinary
// functions as a query rule.
type ExtensionQueryRuleFunc func(context.Context, *ent.ExtensionQuery) error
// EvalQuery return f(ctx, q).
func (f ExtensionQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.ExtensionQuery); ok {
return f(ctx, q)
}
return Denyf("ent/privacy: unexpected query type %T, expect *ent.ExtensionQuery", q)
}
// The ExtensionMutationRuleFunc type is an adapter to allow the use of ordinary
// functions as a mutation rule.
type ExtensionMutationRuleFunc func(context.Context, *ent.ExtensionMutation) error
// EvalMutation calls f(ctx, m).
func (f ExtensionMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error {
if m, ok := m.(*ent.ExtensionMutation); ok {
return f(ctx, m)
}
return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.ExtensionMutation", m)
}
// The KeyBindingQueryRuleFunc type is an adapter to allow the use of ordinary
// functions as a query rule.
type KeyBindingQueryRuleFunc func(context.Context, *ent.KeyBindingQuery) error
// EvalQuery return f(ctx, q).
func (f KeyBindingQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.KeyBindingQuery); ok {
return f(ctx, q)
}
return Denyf("ent/privacy: unexpected query type %T, expect *ent.KeyBindingQuery", q)
}
// The KeyBindingMutationRuleFunc type is an adapter to allow the use of ordinary
// functions as a mutation rule.
type KeyBindingMutationRuleFunc func(context.Context, *ent.KeyBindingMutation) error
// EvalMutation calls f(ctx, m).
func (f KeyBindingMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error {
if m, ok := m.(*ent.KeyBindingMutation); ok {
return f(ctx, m)
}
return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.KeyBindingMutation", m)
}
// The ThemeQueryRuleFunc type is an adapter to allow the use of ordinary
// functions as a query rule.
type ThemeQueryRuleFunc func(context.Context, *ent.ThemeQuery) error
// EvalQuery return f(ctx, q).
func (f ThemeQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.ThemeQuery); ok {
return f(ctx, q)
}
return Denyf("ent/privacy: unexpected query type %T, expect *ent.ThemeQuery", q)
}
// The ThemeMutationRuleFunc type is an adapter to allow the use of ordinary
// functions as a mutation rule.
type ThemeMutationRuleFunc func(context.Context, *ent.ThemeMutation) error
// EvalMutation calls f(ctx, m).
func (f ThemeMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error {
if m, ok := m.(*ent.ThemeMutation); ok {
return f(ctx, m)
}
return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.ThemeMutation", m)
}
type (
// Filter is the interface that wraps the Where function
// for filtering nodes in queries and mutations.
Filter interface {
// Where applies a filter on the executed query/mutation.
Where(entql.P)
}
// The FilterFunc type is an adapter that allows the use of ordinary
// functions as filters for query and mutation types.
FilterFunc func(context.Context, Filter) error
)
// EvalQuery calls f(ctx, q) if the query implements the Filter interface, otherwise it is denied.
func (f FilterFunc) EvalQuery(ctx context.Context, q ent.Query) error {
fr, err := queryFilter(q)
if err != nil {
return err
}
return f(ctx, fr)
}
// EvalMutation calls f(ctx, q) if the mutation implements the Filter interface, otherwise it is denied.
func (f FilterFunc) EvalMutation(ctx context.Context, m ent.Mutation) error {
fr, err := mutationFilter(m)
if err != nil {
return err
}
return f(ctx, fr)
}
var _ QueryMutationRule = FilterFunc(nil)
func queryFilter(q ent.Query) (Filter, error) {
switch q := q.(type) {
case *ent.DocumentQuery:
return q.Filter(), nil
case *ent.ExtensionQuery:
return q.Filter(), nil
case *ent.KeyBindingQuery:
return q.Filter(), nil
case *ent.ThemeQuery:
return q.Filter(), nil
default:
return nil, Denyf("ent/privacy: unexpected query type %T for query filter", q)
}
}
func mutationFilter(m ent.Mutation) (Filter, error) {
switch m := m.(type) {
case *ent.DocumentMutation:
return m.Filter(), nil
case *ent.ExtensionMutation:
return m.Filter(), nil
case *ent.KeyBindingMutation:
return m.Filter(), nil
case *ent.ThemeMutation:
return m.Filter(), nil
default:
return nil, Denyf("ent/privacy: unexpected mutation type %T for mutation filter", m)
}
}

View File

@@ -0,0 +1,5 @@
// Code generated by ent, DO NOT EDIT.
package ent
// The schema-stitching logic is generated in voidraft/internal/models/ent/runtime/runtime.go

View File

@@ -0,0 +1,208 @@
// Code generated by ent, DO NOT EDIT.
package runtime
import (
"voidraft/internal/models/ent/document"
"voidraft/internal/models/ent/extension"
"voidraft/internal/models/ent/keybinding"
"voidraft/internal/models/ent/theme"
"voidraft/internal/models/schema"
)
// The init function reads all schema descriptors with runtime code
// (default values, validators, hooks and policies) and stitches it
// to their package variables.
func init() {
documentMixin := schema.Document{}.Mixin()
documentMixinHooks0 := documentMixin[0].Hooks()
documentMixinHooks1 := documentMixin[1].Hooks()
document.Hooks[0] = documentMixinHooks0[0]
document.Hooks[1] = documentMixinHooks1[0]
documentMixinInters1 := documentMixin[1].Interceptors()
document.Interceptors[0] = documentMixinInters1[0]
documentMixinFields0 := documentMixin[0].Fields()
_ = documentMixinFields0
documentFields := schema.Document{}.Fields()
_ = documentFields
// documentDescCreatedAt is the schema descriptor for created_at field.
documentDescCreatedAt := documentMixinFields0[0].Descriptor()
// document.DefaultCreatedAt holds the default value on creation for the created_at field.
document.DefaultCreatedAt = documentDescCreatedAt.Default.(func() string)
// documentDescUpdatedAt is the schema descriptor for updated_at field.
documentDescUpdatedAt := documentMixinFields0[1].Descriptor()
// document.DefaultUpdatedAt holds the default value on creation for the updated_at field.
document.DefaultUpdatedAt = documentDescUpdatedAt.Default.(func() string)
// documentDescTitle is the schema descriptor for title field.
documentDescTitle := documentFields[0].Descriptor()
// document.TitleValidator is a validator for the "title" field. It is called by the builders before save.
document.TitleValidator = func() func(string) error {
validators := documentDescTitle.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(title string) error {
for _, fn := range fns {
if err := fn(title); err != nil {
return err
}
}
return nil
}
}()
// documentDescContent is the schema descriptor for content field.
documentDescContent := documentFields[1].Descriptor()
// document.DefaultContent holds the default value on creation for the content field.
document.DefaultContent = documentDescContent.Default.(string)
// documentDescLocked is the schema descriptor for locked field.
documentDescLocked := documentFields[2].Descriptor()
// document.DefaultLocked holds the default value on creation for the locked field.
document.DefaultLocked = documentDescLocked.Default.(bool)
extensionMixin := schema.Extension{}.Mixin()
extensionMixinHooks0 := extensionMixin[0].Hooks()
extensionMixinHooks1 := extensionMixin[1].Hooks()
extension.Hooks[0] = extensionMixinHooks0[0]
extension.Hooks[1] = extensionMixinHooks1[0]
extensionMixinInters1 := extensionMixin[1].Interceptors()
extension.Interceptors[0] = extensionMixinInters1[0]
extensionMixinFields0 := extensionMixin[0].Fields()
_ = extensionMixinFields0
extensionFields := schema.Extension{}.Fields()
_ = extensionFields
// extensionDescCreatedAt is the schema descriptor for created_at field.
extensionDescCreatedAt := extensionMixinFields0[0].Descriptor()
// extension.DefaultCreatedAt holds the default value on creation for the created_at field.
extension.DefaultCreatedAt = extensionDescCreatedAt.Default.(func() string)
// extensionDescUpdatedAt is the schema descriptor for updated_at field.
extensionDescUpdatedAt := extensionMixinFields0[1].Descriptor()
// extension.DefaultUpdatedAt holds the default value on creation for the updated_at field.
extension.DefaultUpdatedAt = extensionDescUpdatedAt.Default.(func() string)
// extensionDescKey is the schema descriptor for key field.
extensionDescKey := extensionFields[0].Descriptor()
// extension.KeyValidator is a validator for the "key" field. It is called by the builders before save.
extension.KeyValidator = func() func(string) error {
validators := extensionDescKey.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(key string) error {
for _, fn := range fns {
if err := fn(key); err != nil {
return err
}
}
return nil
}
}()
// extensionDescEnabled is the schema descriptor for enabled field.
extensionDescEnabled := extensionFields[1].Descriptor()
// extension.DefaultEnabled holds the default value on creation for the enabled field.
extension.DefaultEnabled = extensionDescEnabled.Default.(bool)
keybindingMixin := schema.KeyBinding{}.Mixin()
keybindingMixinHooks0 := keybindingMixin[0].Hooks()
keybindingMixinHooks1 := keybindingMixin[1].Hooks()
keybinding.Hooks[0] = keybindingMixinHooks0[0]
keybinding.Hooks[1] = keybindingMixinHooks1[0]
keybindingMixinInters1 := keybindingMixin[1].Interceptors()
keybinding.Interceptors[0] = keybindingMixinInters1[0]
keybindingMixinFields0 := keybindingMixin[0].Fields()
_ = keybindingMixinFields0
keybindingFields := schema.KeyBinding{}.Fields()
_ = keybindingFields
// keybindingDescCreatedAt is the schema descriptor for created_at field.
keybindingDescCreatedAt := keybindingMixinFields0[0].Descriptor()
// keybinding.DefaultCreatedAt holds the default value on creation for the created_at field.
keybinding.DefaultCreatedAt = keybindingDescCreatedAt.Default.(func() string)
// keybindingDescUpdatedAt is the schema descriptor for updated_at field.
keybindingDescUpdatedAt := keybindingMixinFields0[1].Descriptor()
// keybinding.DefaultUpdatedAt holds the default value on creation for the updated_at field.
keybinding.DefaultUpdatedAt = keybindingDescUpdatedAt.Default.(func() string)
// keybindingDescKey is the schema descriptor for key field.
keybindingDescKey := keybindingFields[0].Descriptor()
// keybinding.KeyValidator is a validator for the "key" field. It is called by the builders before save.
keybinding.KeyValidator = func() func(string) error {
validators := keybindingDescKey.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(key string) error {
for _, fn := range fns {
if err := fn(key); err != nil {
return err
}
}
return nil
}
}()
// keybindingDescCommand is the schema descriptor for command field.
keybindingDescCommand := keybindingFields[1].Descriptor()
// keybinding.CommandValidator is a validator for the "command" field. It is called by the builders before save.
keybinding.CommandValidator = func() func(string) error {
validators := keybindingDescCommand.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(command string) error {
for _, fn := range fns {
if err := fn(command); err != nil {
return err
}
}
return nil
}
}()
// keybindingDescExtension is the schema descriptor for extension field.
keybindingDescExtension := keybindingFields[2].Descriptor()
// keybinding.ExtensionValidator is a validator for the "extension" field. It is called by the builders before save.
keybinding.ExtensionValidator = keybindingDescExtension.Validators[0].(func(string) error)
// keybindingDescEnabled is the schema descriptor for enabled field.
keybindingDescEnabled := keybindingFields[3].Descriptor()
// keybinding.DefaultEnabled holds the default value on creation for the enabled field.
keybinding.DefaultEnabled = keybindingDescEnabled.Default.(bool)
themeMixin := schema.Theme{}.Mixin()
themeMixinHooks0 := themeMixin[0].Hooks()
themeMixinHooks1 := themeMixin[1].Hooks()
theme.Hooks[0] = themeMixinHooks0[0]
theme.Hooks[1] = themeMixinHooks1[0]
themeMixinInters1 := themeMixin[1].Interceptors()
theme.Interceptors[0] = themeMixinInters1[0]
themeMixinFields0 := themeMixin[0].Fields()
_ = themeMixinFields0
themeFields := schema.Theme{}.Fields()
_ = themeFields
// themeDescCreatedAt is the schema descriptor for created_at field.
themeDescCreatedAt := themeMixinFields0[0].Descriptor()
// theme.DefaultCreatedAt holds the default value on creation for the created_at field.
theme.DefaultCreatedAt = themeDescCreatedAt.Default.(func() string)
// themeDescUpdatedAt is the schema descriptor for updated_at field.
themeDescUpdatedAt := themeMixinFields0[1].Descriptor()
// theme.DefaultUpdatedAt holds the default value on creation for the updated_at field.
theme.DefaultUpdatedAt = themeDescUpdatedAt.Default.(func() string)
// themeDescKey is the schema descriptor for key field.
themeDescKey := themeFields[0].Descriptor()
// theme.KeyValidator is a validator for the "key" field. It is called by the builders before save.
theme.KeyValidator = func() func(string) error {
validators := themeDescKey.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(key string) error {
for _, fn := range fns {
if err := fn(key); err != nil {
return err
}
}
return nil
}
}()
}
const (
Version = "v0.14.5" // Version of ent codegen.
Sum = "h1:Rj2WOYJtCkWyFo6a+5wB3EfBRP0rnx1fMk6gGA0UUe4=" // Sum of ent codegen.
)

View File

@@ -0,0 +1,54 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/mixin"
)
// Theme holds the schema definition for the Theme entity.
type Theme struct {
ent.Schema
}
// Annotations of the Theme.
func (Theme) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "themes"},
}
}
// Mixin of the Theme.
func (Theme) Mixin() []ent.Mixin {
return []ent.Mixin{
mixin.Time{},
}
}
// Fields of the Theme.
func (Theme) Fields() []ent.Field {
return []ent.Field{
field.String("key").
MaxLen(100).
NotEmpty().
Unique().
Comment("主题标识符"),
field.Enum("type").
Values("dark", "light").
Comment("主题类型"),
field.JSON("colors", map[string]interface{}{}).
Optional().
Comment("主题颜色配置"),
field.Time("deleted_at").
Optional().
Nillable().
Comment("软删除时间"),
}
}
// Edges of the Theme.
func (Theme) Edges() []ent.Edge {
return nil
}

View File

@@ -0,0 +1,166 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"encoding/json"
"fmt"
"strings"
"voidraft/internal/models/ent/theme"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
)
// Theme is the model entity for the Theme schema.
type Theme struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// 创建时间
CreatedAt string `json:"created_at"`
// 最后更新时间
UpdatedAt string `json:"updated_at"`
// 删除时间NULL表示未删除
DeletedAt *string `json:"deleted_at,omitempty"`
// 主题标识符
Key string `json:"key"`
// 主题类型
Type theme.Type `json:"type"`
// 主题颜色配置
Colors map[string]interface{} `json:"colors"`
selectValues sql.SelectValues
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Theme) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case theme.FieldColors:
values[i] = new([]byte)
case theme.FieldID:
values[i] = new(sql.NullInt64)
case theme.FieldCreatedAt, theme.FieldUpdatedAt, theme.FieldDeletedAt, theme.FieldKey, theme.FieldType:
values[i] = new(sql.NullString)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Theme fields.
func (_m *Theme) assignValues(columns []string, values []any) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case theme.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
_m.ID = int(value.Int64)
case theme.FieldCreatedAt:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
_m.CreatedAt = value.String
}
case theme.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
_m.UpdatedAt = value.String
}
case theme.FieldDeletedAt:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field deleted_at", values[i])
} else if value.Valid {
_m.DeletedAt = new(string)
*_m.DeletedAt = value.String
}
case theme.FieldKey:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field key", values[i])
} else if value.Valid {
_m.Key = value.String
}
case theme.FieldType:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field type", values[i])
} else if value.Valid {
_m.Type = theme.Type(value.String)
}
case theme.FieldColors:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field colors", values[i])
} else if value != nil && len(*value) > 0 {
if err := json.Unmarshal(*value, &_m.Colors); err != nil {
return fmt.Errorf("unmarshal field colors: %w", err)
}
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Theme.
// This includes values selected through modifiers, order, etc.
func (_m *Theme) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// Update returns a builder for updating this Theme.
// Note that you need to call Theme.Unwrap() before calling this method if this Theme
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Theme) Update() *ThemeUpdateOne {
return NewThemeClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Theme entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (_m *Theme) Unwrap() *Theme {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: Theme is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Theme) String() string {
var builder strings.Builder
builder.WriteString("Theme(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("created_at=")
builder.WriteString(_m.CreatedAt)
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(_m.UpdatedAt)
builder.WriteString(", ")
if v := _m.DeletedAt; v != nil {
builder.WriteString("deleted_at=")
builder.WriteString(*v)
}
builder.WriteString(", ")
builder.WriteString("key=")
builder.WriteString(_m.Key)
builder.WriteString(", ")
builder.WriteString("type=")
builder.WriteString(fmt.Sprintf("%v", _m.Type))
builder.WriteString(", ")
builder.WriteString("colors=")
builder.WriteString(fmt.Sprintf("%v", _m.Colors))
builder.WriteByte(')')
return builder.String()
}
// Themes is a parsable slice of Theme.
type Themes []*Theme

View File

@@ -0,0 +1,124 @@
// Code generated by ent, DO NOT EDIT.
package theme
import (
"fmt"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
)
const (
// Label holds the string label denoting the theme type in the database.
Label = "theme"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
FieldUpdatedAt = "updated_at"
// FieldDeletedAt holds the string denoting the deleted_at field in the database.
FieldDeletedAt = "deleted_at"
// FieldKey holds the string denoting the key field in the database.
FieldKey = "key"
// FieldType holds the string denoting the type field in the database.
FieldType = "type"
// FieldColors holds the string denoting the colors field in the database.
FieldColors = "colors"
// Table holds the table name of the theme in the database.
Table = "themes"
)
// Columns holds all SQL columns for theme fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldDeletedAt,
FieldKey,
FieldType,
FieldColors,
}
// 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
}
// Note that the variables below are initialized by the runtime
// package on the initialization of the application. Therefore,
// it should be imported in the main as follows:
//
// import _ "voidraft/internal/models/ent/runtime"
var (
Hooks [2]ent.Hook
Interceptors [1]ent.Interceptor
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() string
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() string
// KeyValidator is a validator for the "key" field. It is called by the builders before save.
KeyValidator func(string) error
)
// Type defines the type for the "type" enum field.
type Type string
// Type values.
const (
TypeDark Type = "dark"
TypeLight Type = "light"
)
func (_type Type) String() string {
return string(_type)
}
// TypeValidator is a validator for the "type" field enum values. It is called by the builders before save.
func TypeValidator(_type Type) error {
switch _type {
case TypeDark, TypeLight:
return nil
default:
return fmt.Errorf("theme: invalid enum value for type field: %q", _type)
}
}
// OrderOption defines the ordering options for the Theme queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByCreatedAt orders the results by the created_at field.
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
}
// ByUpdatedAt orders the results by the updated_at field.
func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
}
// ByDeletedAt orders the results by the deleted_at field.
func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDeletedAt, opts...).ToFunc()
}
// ByKey orders the results by the key field.
func ByKey(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldKey, opts...).ToFunc()
}
// ByType orders the results by the type field.
func ByType(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldType, opts...).ToFunc()
}

View File

@@ -0,0 +1,389 @@
// Code generated by ent, DO NOT EDIT.
package theme
import (
"voidraft/internal/models/ent/predicate"
"entgo.io/ent/dialect/sql"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Theme {
return predicate.Theme(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Theme {
return predicate.Theme(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Theme {
return predicate.Theme(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Theme {
return predicate.Theme(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Theme {
return predicate.Theme(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Theme {
return predicate.Theme(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Theme {
return predicate.Theme(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Theme {
return predicate.Theme(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Theme {
return predicate.Theme(sql.FieldLTE(FieldID, id))
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v string) predicate.Theme {
return predicate.Theme(sql.FieldEQ(FieldCreatedAt, v))
}
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
func UpdatedAt(v string) predicate.Theme {
return predicate.Theme(sql.FieldEQ(FieldUpdatedAt, v))
}
// DeletedAt applies equality check predicate on the "deleted_at" field. It's identical to DeletedAtEQ.
func DeletedAt(v string) predicate.Theme {
return predicate.Theme(sql.FieldEQ(FieldDeletedAt, v))
}
// Key applies equality check predicate on the "key" field. It's identical to KeyEQ.
func Key(v string) predicate.Theme {
return predicate.Theme(sql.FieldEQ(FieldKey, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v string) predicate.Theme {
return predicate.Theme(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v string) predicate.Theme {
return predicate.Theme(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...string) predicate.Theme {
return predicate.Theme(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...string) predicate.Theme {
return predicate.Theme(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v string) predicate.Theme {
return predicate.Theme(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v string) predicate.Theme {
return predicate.Theme(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v string) predicate.Theme {
return predicate.Theme(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v string) predicate.Theme {
return predicate.Theme(sql.FieldLTE(FieldCreatedAt, v))
}
// CreatedAtContains applies the Contains predicate on the "created_at" field.
func CreatedAtContains(v string) predicate.Theme {
return predicate.Theme(sql.FieldContains(FieldCreatedAt, v))
}
// CreatedAtHasPrefix applies the HasPrefix predicate on the "created_at" field.
func CreatedAtHasPrefix(v string) predicate.Theme {
return predicate.Theme(sql.FieldHasPrefix(FieldCreatedAt, v))
}
// CreatedAtHasSuffix applies the HasSuffix predicate on the "created_at" field.
func CreatedAtHasSuffix(v string) predicate.Theme {
return predicate.Theme(sql.FieldHasSuffix(FieldCreatedAt, v))
}
// CreatedAtEqualFold applies the EqualFold predicate on the "created_at" field.
func CreatedAtEqualFold(v string) predicate.Theme {
return predicate.Theme(sql.FieldEqualFold(FieldCreatedAt, v))
}
// CreatedAtContainsFold applies the ContainsFold predicate on the "created_at" field.
func CreatedAtContainsFold(v string) predicate.Theme {
return predicate.Theme(sql.FieldContainsFold(FieldCreatedAt, v))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v string) predicate.Theme {
return predicate.Theme(sql.FieldEQ(FieldUpdatedAt, v))
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v string) predicate.Theme {
return predicate.Theme(sql.FieldNEQ(FieldUpdatedAt, v))
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...string) predicate.Theme {
return predicate.Theme(sql.FieldIn(FieldUpdatedAt, vs...))
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...string) predicate.Theme {
return predicate.Theme(sql.FieldNotIn(FieldUpdatedAt, vs...))
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v string) predicate.Theme {
return predicate.Theme(sql.FieldGT(FieldUpdatedAt, v))
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v string) predicate.Theme {
return predicate.Theme(sql.FieldGTE(FieldUpdatedAt, v))
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v string) predicate.Theme {
return predicate.Theme(sql.FieldLT(FieldUpdatedAt, v))
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v string) predicate.Theme {
return predicate.Theme(sql.FieldLTE(FieldUpdatedAt, v))
}
// UpdatedAtContains applies the Contains predicate on the "updated_at" field.
func UpdatedAtContains(v string) predicate.Theme {
return predicate.Theme(sql.FieldContains(FieldUpdatedAt, v))
}
// UpdatedAtHasPrefix applies the HasPrefix predicate on the "updated_at" field.
func UpdatedAtHasPrefix(v string) predicate.Theme {
return predicate.Theme(sql.FieldHasPrefix(FieldUpdatedAt, v))
}
// UpdatedAtHasSuffix applies the HasSuffix predicate on the "updated_at" field.
func UpdatedAtHasSuffix(v string) predicate.Theme {
return predicate.Theme(sql.FieldHasSuffix(FieldUpdatedAt, v))
}
// UpdatedAtEqualFold applies the EqualFold predicate on the "updated_at" field.
func UpdatedAtEqualFold(v string) predicate.Theme {
return predicate.Theme(sql.FieldEqualFold(FieldUpdatedAt, v))
}
// UpdatedAtContainsFold applies the ContainsFold predicate on the "updated_at" field.
func UpdatedAtContainsFold(v string) predicate.Theme {
return predicate.Theme(sql.FieldContainsFold(FieldUpdatedAt, v))
}
// DeletedAtEQ applies the EQ predicate on the "deleted_at" field.
func DeletedAtEQ(v string) predicate.Theme {
return predicate.Theme(sql.FieldEQ(FieldDeletedAt, v))
}
// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field.
func DeletedAtNEQ(v string) predicate.Theme {
return predicate.Theme(sql.FieldNEQ(FieldDeletedAt, v))
}
// DeletedAtIn applies the In predicate on the "deleted_at" field.
func DeletedAtIn(vs ...string) predicate.Theme {
return predicate.Theme(sql.FieldIn(FieldDeletedAt, vs...))
}
// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field.
func DeletedAtNotIn(vs ...string) predicate.Theme {
return predicate.Theme(sql.FieldNotIn(FieldDeletedAt, vs...))
}
// DeletedAtGT applies the GT predicate on the "deleted_at" field.
func DeletedAtGT(v string) predicate.Theme {
return predicate.Theme(sql.FieldGT(FieldDeletedAt, v))
}
// DeletedAtGTE applies the GTE predicate on the "deleted_at" field.
func DeletedAtGTE(v string) predicate.Theme {
return predicate.Theme(sql.FieldGTE(FieldDeletedAt, v))
}
// DeletedAtLT applies the LT predicate on the "deleted_at" field.
func DeletedAtLT(v string) predicate.Theme {
return predicate.Theme(sql.FieldLT(FieldDeletedAt, v))
}
// DeletedAtLTE applies the LTE predicate on the "deleted_at" field.
func DeletedAtLTE(v string) predicate.Theme {
return predicate.Theme(sql.FieldLTE(FieldDeletedAt, v))
}
// DeletedAtContains applies the Contains predicate on the "deleted_at" field.
func DeletedAtContains(v string) predicate.Theme {
return predicate.Theme(sql.FieldContains(FieldDeletedAt, v))
}
// DeletedAtHasPrefix applies the HasPrefix predicate on the "deleted_at" field.
func DeletedAtHasPrefix(v string) predicate.Theme {
return predicate.Theme(sql.FieldHasPrefix(FieldDeletedAt, v))
}
// DeletedAtHasSuffix applies the HasSuffix predicate on the "deleted_at" field.
func DeletedAtHasSuffix(v string) predicate.Theme {
return predicate.Theme(sql.FieldHasSuffix(FieldDeletedAt, v))
}
// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field.
func DeletedAtIsNil() predicate.Theme {
return predicate.Theme(sql.FieldIsNull(FieldDeletedAt))
}
// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field.
func DeletedAtNotNil() predicate.Theme {
return predicate.Theme(sql.FieldNotNull(FieldDeletedAt))
}
// DeletedAtEqualFold applies the EqualFold predicate on the "deleted_at" field.
func DeletedAtEqualFold(v string) predicate.Theme {
return predicate.Theme(sql.FieldEqualFold(FieldDeletedAt, v))
}
// DeletedAtContainsFold applies the ContainsFold predicate on the "deleted_at" field.
func DeletedAtContainsFold(v string) predicate.Theme {
return predicate.Theme(sql.FieldContainsFold(FieldDeletedAt, v))
}
// KeyEQ applies the EQ predicate on the "key" field.
func KeyEQ(v string) predicate.Theme {
return predicate.Theme(sql.FieldEQ(FieldKey, v))
}
// KeyNEQ applies the NEQ predicate on the "key" field.
func KeyNEQ(v string) predicate.Theme {
return predicate.Theme(sql.FieldNEQ(FieldKey, v))
}
// KeyIn applies the In predicate on the "key" field.
func KeyIn(vs ...string) predicate.Theme {
return predicate.Theme(sql.FieldIn(FieldKey, vs...))
}
// KeyNotIn applies the NotIn predicate on the "key" field.
func KeyNotIn(vs ...string) predicate.Theme {
return predicate.Theme(sql.FieldNotIn(FieldKey, vs...))
}
// KeyGT applies the GT predicate on the "key" field.
func KeyGT(v string) predicate.Theme {
return predicate.Theme(sql.FieldGT(FieldKey, v))
}
// KeyGTE applies the GTE predicate on the "key" field.
func KeyGTE(v string) predicate.Theme {
return predicate.Theme(sql.FieldGTE(FieldKey, v))
}
// KeyLT applies the LT predicate on the "key" field.
func KeyLT(v string) predicate.Theme {
return predicate.Theme(sql.FieldLT(FieldKey, v))
}
// KeyLTE applies the LTE predicate on the "key" field.
func KeyLTE(v string) predicate.Theme {
return predicate.Theme(sql.FieldLTE(FieldKey, v))
}
// KeyContains applies the Contains predicate on the "key" field.
func KeyContains(v string) predicate.Theme {
return predicate.Theme(sql.FieldContains(FieldKey, v))
}
// KeyHasPrefix applies the HasPrefix predicate on the "key" field.
func KeyHasPrefix(v string) predicate.Theme {
return predicate.Theme(sql.FieldHasPrefix(FieldKey, v))
}
// KeyHasSuffix applies the HasSuffix predicate on the "key" field.
func KeyHasSuffix(v string) predicate.Theme {
return predicate.Theme(sql.FieldHasSuffix(FieldKey, v))
}
// KeyEqualFold applies the EqualFold predicate on the "key" field.
func KeyEqualFold(v string) predicate.Theme {
return predicate.Theme(sql.FieldEqualFold(FieldKey, v))
}
// KeyContainsFold applies the ContainsFold predicate on the "key" field.
func KeyContainsFold(v string) predicate.Theme {
return predicate.Theme(sql.FieldContainsFold(FieldKey, v))
}
// TypeEQ applies the EQ predicate on the "type" field.
func TypeEQ(v Type) predicate.Theme {
return predicate.Theme(sql.FieldEQ(FieldType, v))
}
// TypeNEQ applies the NEQ predicate on the "type" field.
func TypeNEQ(v Type) predicate.Theme {
return predicate.Theme(sql.FieldNEQ(FieldType, v))
}
// TypeIn applies the In predicate on the "type" field.
func TypeIn(vs ...Type) predicate.Theme {
return predicate.Theme(sql.FieldIn(FieldType, vs...))
}
// TypeNotIn applies the NotIn predicate on the "type" field.
func TypeNotIn(vs ...Type) predicate.Theme {
return predicate.Theme(sql.FieldNotIn(FieldType, vs...))
}
// ColorsIsNil applies the IsNil predicate on the "colors" field.
func ColorsIsNil() predicate.Theme {
return predicate.Theme(sql.FieldIsNull(FieldColors))
}
// ColorsNotNil applies the NotNil predicate on the "colors" field.
func ColorsNotNil() predicate.Theme {
return predicate.Theme(sql.FieldNotNull(FieldColors))
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Theme) predicate.Theme {
return predicate.Theme(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Theme) predicate.Theme {
return predicate.Theme(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Theme) predicate.Theme {
return predicate.Theme(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,299 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"voidraft/internal/models/ent/theme"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// ThemeCreate is the builder for creating a Theme entity.
type ThemeCreate struct {
config
mutation *ThemeMutation
hooks []Hook
}
// SetCreatedAt sets the "created_at" field.
func (_c *ThemeCreate) SetCreatedAt(v string) *ThemeCreate {
_c.mutation.SetCreatedAt(v)
return _c
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (_c *ThemeCreate) SetNillableCreatedAt(v *string) *ThemeCreate {
if v != nil {
_c.SetCreatedAt(*v)
}
return _c
}
// SetUpdatedAt sets the "updated_at" field.
func (_c *ThemeCreate) SetUpdatedAt(v string) *ThemeCreate {
_c.mutation.SetUpdatedAt(v)
return _c
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (_c *ThemeCreate) SetNillableUpdatedAt(v *string) *ThemeCreate {
if v != nil {
_c.SetUpdatedAt(*v)
}
return _c
}
// SetDeletedAt sets the "deleted_at" field.
func (_c *ThemeCreate) SetDeletedAt(v string) *ThemeCreate {
_c.mutation.SetDeletedAt(v)
return _c
}
// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_c *ThemeCreate) SetNillableDeletedAt(v *string) *ThemeCreate {
if v != nil {
_c.SetDeletedAt(*v)
}
return _c
}
// SetKey sets the "key" field.
func (_c *ThemeCreate) SetKey(v string) *ThemeCreate {
_c.mutation.SetKey(v)
return _c
}
// SetType sets the "type" field.
func (_c *ThemeCreate) SetType(v theme.Type) *ThemeCreate {
_c.mutation.SetType(v)
return _c
}
// SetColors sets the "colors" field.
func (_c *ThemeCreate) SetColors(v map[string]interface{}) *ThemeCreate {
_c.mutation.SetColors(v)
return _c
}
// Mutation returns the ThemeMutation object of the builder.
func (_c *ThemeCreate) Mutation() *ThemeMutation {
return _c.mutation
}
// Save creates the Theme in the database.
func (_c *ThemeCreate) Save(ctx context.Context) (*Theme, error) {
if err := _c.defaults(); err != nil {
return nil, err
}
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *ThemeCreate) SaveX(ctx context.Context) *Theme {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *ThemeCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *ThemeCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_c *ThemeCreate) defaults() error {
if _, ok := _c.mutation.CreatedAt(); !ok {
if theme.DefaultCreatedAt == nil {
return fmt.Errorf("ent: uninitialized theme.DefaultCreatedAt (forgotten import ent/runtime?)")
}
v := theme.DefaultCreatedAt()
_c.mutation.SetCreatedAt(v)
}
if _, ok := _c.mutation.UpdatedAt(); !ok {
if theme.DefaultUpdatedAt == nil {
return fmt.Errorf("ent: uninitialized theme.DefaultUpdatedAt (forgotten import ent/runtime?)")
}
v := theme.DefaultUpdatedAt()
_c.mutation.SetUpdatedAt(v)
}
return nil
}
// check runs all checks and user-defined validators on the builder.
func (_c *ThemeCreate) check() error {
if _, ok := _c.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Theme.created_at"`)}
}
if _, ok := _c.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Theme.updated_at"`)}
}
if _, ok := _c.mutation.Key(); !ok {
return &ValidationError{Name: "key", err: errors.New(`ent: missing required field "Theme.key"`)}
}
if v, ok := _c.mutation.Key(); ok {
if err := theme.KeyValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "Theme.key": %w`, err)}
}
}
if _, ok := _c.mutation.GetType(); !ok {
return &ValidationError{Name: "type", err: errors.New(`ent: missing required field "Theme.type"`)}
}
if v, ok := _c.mutation.GetType(); ok {
if err := theme.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "Theme.type": %w`, err)}
}
}
return nil
}
func (_c *ThemeCreate) sqlSave(ctx context.Context) (*Theme, error) {
if err := _c.check(); err != nil {
return nil, err
}
_node, _spec := _c.createSpec()
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
_c.mutation.id = &_node.ID
_c.mutation.done = true
return _node, nil
}
func (_c *ThemeCreate) createSpec() (*Theme, *sqlgraph.CreateSpec) {
var (
_node = &Theme{config: _c.config}
_spec = sqlgraph.NewCreateSpec(theme.Table, sqlgraph.NewFieldSpec(theme.FieldID, field.TypeInt))
)
if value, ok := _c.mutation.CreatedAt(); ok {
_spec.SetField(theme.FieldCreatedAt, field.TypeString, value)
_node.CreatedAt = value
}
if value, ok := _c.mutation.UpdatedAt(); ok {
_spec.SetField(theme.FieldUpdatedAt, field.TypeString, value)
_node.UpdatedAt = value
}
if value, ok := _c.mutation.DeletedAt(); ok {
_spec.SetField(theme.FieldDeletedAt, field.TypeString, value)
_node.DeletedAt = &value
}
if value, ok := _c.mutation.Key(); ok {
_spec.SetField(theme.FieldKey, field.TypeString, value)
_node.Key = value
}
if value, ok := _c.mutation.GetType(); ok {
_spec.SetField(theme.FieldType, field.TypeEnum, value)
_node.Type = value
}
if value, ok := _c.mutation.Colors(); ok {
_spec.SetField(theme.FieldColors, field.TypeJSON, value)
_node.Colors = value
}
return _node, _spec
}
// ThemeCreateBulk is the builder for creating many Theme entities in bulk.
type ThemeCreateBulk struct {
config
err error
builders []*ThemeCreate
}
// Save creates the Theme entities in the database.
func (_c *ThemeCreateBulk) Save(ctx context.Context) ([]*Theme, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*Theme, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ThemeMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
mutation.done = true
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, _c.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (_c *ThemeCreateBulk) SaveX(ctx context.Context) []*Theme {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *ThemeCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *ThemeCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,88 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"voidraft/internal/models/ent/predicate"
"voidraft/internal/models/ent/theme"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// ThemeDelete is the builder for deleting a Theme entity.
type ThemeDelete struct {
config
hooks []Hook
mutation *ThemeMutation
}
// Where appends a list predicates to the ThemeDelete builder.
func (_d *ThemeDelete) Where(ps ...predicate.Theme) *ThemeDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *ThemeDelete) Exec(ctx context.Context) (int, error) {
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *ThemeDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *ThemeDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(theme.Table, sqlgraph.NewFieldSpec(theme.FieldID, field.TypeInt))
if ps := _d.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
_d.mutation.done = true
return affected, err
}
// ThemeDeleteOne is the builder for deleting a single Theme entity.
type ThemeDeleteOne struct {
_d *ThemeDelete
}
// Where appends a list predicates to the ThemeDelete builder.
func (_d *ThemeDeleteOne) Where(ps ...predicate.Theme) *ThemeDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *ThemeDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{theme.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *ThemeDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,577 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"voidraft/internal/models/ent/predicate"
"voidraft/internal/models/ent/theme"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// ThemeQuery is the builder for querying Theme entities.
type ThemeQuery struct {
config
ctx *QueryContext
order []theme.OrderOption
inters []Interceptor
predicates []predicate.Theme
modifiers []func(*sql.Selector)
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the ThemeQuery builder.
func (_q *ThemeQuery) Where(ps ...predicate.Theme) *ThemeQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *ThemeQuery) Limit(limit int) *ThemeQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *ThemeQuery) Offset(offset int) *ThemeQuery {
_q.ctx.Offset = &offset
return _q
}
// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (_q *ThemeQuery) Unique(unique bool) *ThemeQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *ThemeQuery) Order(o ...theme.OrderOption) *ThemeQuery {
_q.order = append(_q.order, o...)
return _q
}
// First returns the first Theme entity from the query.
// Returns a *NotFoundError when no Theme was found.
func (_q *ThemeQuery) First(ctx context.Context) (*Theme, error) {
nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{theme.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *ThemeQuery) FirstX(ctx context.Context) *Theme {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Theme ID from the query.
// Returns a *NotFoundError when no Theme ID was found.
func (_q *ThemeQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{theme.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *ThemeQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Theme entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Theme entity is found.
// Returns a *NotFoundError when no Theme entities are found.
func (_q *ThemeQuery) Only(ctx context.Context) (*Theme, error) {
nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{theme.Label}
default:
return nil, &NotSingularError{theme.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *ThemeQuery) OnlyX(ctx context.Context) *Theme {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Theme ID in the query.
// Returns a *NotSingularError when more than one Theme ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *ThemeQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{theme.Label}
default:
err = &NotSingularError{theme.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *ThemeQuery) OnlyIDX(ctx context.Context) int {
id, err := _q.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Themes.
func (_q *ThemeQuery) All(ctx context.Context) ([]*Theme, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Theme, *ThemeQuery]()
return withInterceptors[[]*Theme](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *ThemeQuery) AllX(ctx context.Context) []*Theme {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Theme IDs.
func (_q *ThemeQuery) IDs(ctx context.Context) (ids []int, err error) {
if _q.ctx.Unique == nil && _q.path != nil {
_q.Unique(true)
}
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
if err = _q.Select(theme.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *ThemeQuery) IDsX(ctx context.Context) []int {
ids, err := _q.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (_q *ThemeQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)
if err := _q.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, _q, querierCount[*ThemeQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *ThemeQuery) CountX(ctx context.Context) int {
count, err := _q.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (_q *ThemeQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
switch _, err := _q.FirstID(ctx); {
case IsNotFound(err):
return false, nil
case err != nil:
return false, fmt.Errorf("ent: check existence: %w", err)
default:
return true, nil
}
}
// ExistX is like Exist, but panics if an error occurs.
func (_q *ThemeQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the ThemeQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (_q *ThemeQuery) Clone() *ThemeQuery {
if _q == nil {
return nil
}
return &ThemeQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]theme.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Theme{}, _q.predicates...),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
modifiers: append([]func(*sql.Selector){}, _q.modifiers...),
}
}
// GroupBy is 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 {
// CreatedAt string `json:"created_at"`
// Count int `json:"count,omitempty"`
// }
//
// client.Theme.Query().
// GroupBy(theme.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *ThemeQuery) GroupBy(field string, fields ...string) *ThemeGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &ThemeGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = theme.Label
grbuild.scan = grbuild.Scan
return grbuild
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// CreatedAt string `json:"created_at"`
// }
//
// client.Theme.Query().
// Select(theme.FieldCreatedAt).
// Scan(ctx, &v)
func (_q *ThemeQuery) Select(fields ...string) *ThemeSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &ThemeSelect{ThemeQuery: _q}
sbuild.label = theme.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a ThemeSelect configured with the given aggregations.
func (_q *ThemeQuery) Aggregate(fns ...AggregateFunc) *ThemeSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *ThemeQuery) prepareQuery(ctx context.Context) error {
for _, inter := range _q.inters {
if inter == nil {
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
}
if trv, ok := inter.(Traverser); ok {
if err := trv.Traverse(ctx, _q); err != nil {
return err
}
}
}
for _, f := range _q.ctx.Fields {
if !theme.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if _q.path != nil {
prev, err := _q.path(ctx)
if err != nil {
return err
}
_q.sql = prev
}
return nil
}
func (_q *ThemeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Theme, error) {
var (
nodes = []*Theme{}
_spec = _q.querySpec()
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Theme).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Theme{config: _q.config}
nodes = append(nodes, node)
return node.assignValues(columns, values)
}
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (_q *ThemeQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *ThemeQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(theme.Table, theme.Columns, sqlgraph.NewFieldSpec(theme.FieldID, field.TypeInt))
_spec.From = _q.sql
if unique := _q.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if _q.path != nil {
_spec.Unique = true
}
if fields := _q.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, theme.FieldID)
for i := range fields {
if fields[i] != theme.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := _q.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := _q.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := _q.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := _q.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (_q *ThemeQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(theme.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = theme.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, m := range _q.modifiers {
m(selector)
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.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 := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
// updated, deleted or "selected ... for update" by other sessions, until the transaction is
// either committed or rolled-back.
func (_q *ThemeQuery) ForUpdate(opts ...sql.LockOption) *ThemeQuery {
if _q.driver.Dialect() == dialect.Postgres {
_q.Unique(false)
}
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
s.ForUpdate(opts...)
})
return _q
}
// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
// on any rows that are read. Other sessions can read the rows, but cannot modify them
// until your transaction commits.
func (_q *ThemeQuery) ForShare(opts ...sql.LockOption) *ThemeQuery {
if _q.driver.Dialect() == dialect.Postgres {
_q.Unique(false)
}
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
s.ForShare(opts...)
})
return _q
}
// Modify adds a query modifier for attaching custom logic to queries.
func (_q *ThemeQuery) Modify(modifiers ...func(s *sql.Selector)) *ThemeSelect {
_q.modifiers = append(_q.modifiers, modifiers...)
return _q.Select()
}
// ThemeGroupBy is the group-by builder for Theme entities.
type ThemeGroupBy struct {
selector
build *ThemeQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *ThemeGroupBy) Aggregate(fns ...AggregateFunc) *ThemeGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *ThemeGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)
if err := _g.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*ThemeQuery, *ThemeGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *ThemeGroupBy) sqlScan(ctx context.Context, root *ThemeQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(_g.fns))
for _, fn := range _g.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*_g.flds)+len(_g.fns))
for _, f := range *_g.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*_g.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// ThemeSelect is the builder for selecting fields of Theme entities.
type ThemeSelect struct {
*ThemeQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *ThemeSelect) Aggregate(fns ...AggregateFunc) *ThemeSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *ThemeSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)
if err := _s.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*ThemeQuery, *ThemeSelect](ctx, _s.ThemeQuery, _s, _s.inters, v)
}
func (_s *ThemeSelect) sqlScan(ctx context.Context, root *ThemeQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(_s.fns))
for _, fn := range _s.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*_s.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// Modify adds a query modifier for attaching custom logic to queries.
func (_s *ThemeSelect) Modify(modifiers ...func(s *sql.Selector)) *ThemeSelect {
_s.modifiers = append(_s.modifiers, modifiers...)
return _s
}

View File

@@ -0,0 +1,417 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"voidraft/internal/models/ent/predicate"
"voidraft/internal/models/ent/theme"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// ThemeUpdate is the builder for updating Theme entities.
type ThemeUpdate struct {
config
hooks []Hook
mutation *ThemeMutation
modifiers []func(*sql.UpdateBuilder)
}
// Where appends a list predicates to the ThemeUpdate builder.
func (_u *ThemeUpdate) Where(ps ...predicate.Theme) *ThemeUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetUpdatedAt sets the "updated_at" field.
func (_u *ThemeUpdate) SetUpdatedAt(v string) *ThemeUpdate {
_u.mutation.SetUpdatedAt(v)
return _u
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (_u *ThemeUpdate) SetNillableUpdatedAt(v *string) *ThemeUpdate {
if v != nil {
_u.SetUpdatedAt(*v)
}
return _u
}
// SetDeletedAt sets the "deleted_at" field.
func (_u *ThemeUpdate) SetDeletedAt(v string) *ThemeUpdate {
_u.mutation.SetDeletedAt(v)
return _u
}
// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_u *ThemeUpdate) SetNillableDeletedAt(v *string) *ThemeUpdate {
if v != nil {
_u.SetDeletedAt(*v)
}
return _u
}
// ClearDeletedAt clears the value of the "deleted_at" field.
func (_u *ThemeUpdate) ClearDeletedAt() *ThemeUpdate {
_u.mutation.ClearDeletedAt()
return _u
}
// SetKey sets the "key" field.
func (_u *ThemeUpdate) SetKey(v string) *ThemeUpdate {
_u.mutation.SetKey(v)
return _u
}
// SetNillableKey sets the "key" field if the given value is not nil.
func (_u *ThemeUpdate) SetNillableKey(v *string) *ThemeUpdate {
if v != nil {
_u.SetKey(*v)
}
return _u
}
// SetType sets the "type" field.
func (_u *ThemeUpdate) SetType(v theme.Type) *ThemeUpdate {
_u.mutation.SetType(v)
return _u
}
// SetNillableType sets the "type" field if the given value is not nil.
func (_u *ThemeUpdate) SetNillableType(v *theme.Type) *ThemeUpdate {
if v != nil {
_u.SetType(*v)
}
return _u
}
// SetColors sets the "colors" field.
func (_u *ThemeUpdate) SetColors(v map[string]interface{}) *ThemeUpdate {
_u.mutation.SetColors(v)
return _u
}
// ClearColors clears the value of the "colors" field.
func (_u *ThemeUpdate) ClearColors() *ThemeUpdate {
_u.mutation.ClearColors()
return _u
}
// Mutation returns the ThemeMutation object of the builder.
func (_u *ThemeUpdate) Mutation() *ThemeMutation {
return _u.mutation
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *ThemeUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *ThemeUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *ThemeUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *ThemeUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *ThemeUpdate) check() error {
if v, ok := _u.mutation.Key(); ok {
if err := theme.KeyValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "Theme.key": %w`, err)}
}
}
if v, ok := _u.mutation.GetType(); ok {
if err := theme.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "Theme.type": %w`, err)}
}
}
return nil
}
// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
func (_u *ThemeUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *ThemeUpdate {
_u.modifiers = append(_u.modifiers, modifiers...)
return _u
}
func (_u *ThemeUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(theme.Table, theme.Columns, sqlgraph.NewFieldSpec(theme.FieldID, field.TypeInt))
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(theme.FieldUpdatedAt, field.TypeString, value)
}
if value, ok := _u.mutation.DeletedAt(); ok {
_spec.SetField(theme.FieldDeletedAt, field.TypeString, value)
}
if _u.mutation.DeletedAtCleared() {
_spec.ClearField(theme.FieldDeletedAt, field.TypeString)
}
if value, ok := _u.mutation.Key(); ok {
_spec.SetField(theme.FieldKey, field.TypeString, value)
}
if value, ok := _u.mutation.GetType(); ok {
_spec.SetField(theme.FieldType, field.TypeEnum, value)
}
if value, ok := _u.mutation.Colors(); ok {
_spec.SetField(theme.FieldColors, field.TypeJSON, value)
}
if _u.mutation.ColorsCleared() {
_spec.ClearField(theme.FieldColors, field.TypeJSON)
}
_spec.AddModifiers(_u.modifiers...)
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{theme.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// ThemeUpdateOne is the builder for updating a single Theme entity.
type ThemeUpdateOne struct {
config
fields []string
hooks []Hook
mutation *ThemeMutation
modifiers []func(*sql.UpdateBuilder)
}
// SetUpdatedAt sets the "updated_at" field.
func (_u *ThemeUpdateOne) SetUpdatedAt(v string) *ThemeUpdateOne {
_u.mutation.SetUpdatedAt(v)
return _u
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (_u *ThemeUpdateOne) SetNillableUpdatedAt(v *string) *ThemeUpdateOne {
if v != nil {
_u.SetUpdatedAt(*v)
}
return _u
}
// SetDeletedAt sets the "deleted_at" field.
func (_u *ThemeUpdateOne) SetDeletedAt(v string) *ThemeUpdateOne {
_u.mutation.SetDeletedAt(v)
return _u
}
// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_u *ThemeUpdateOne) SetNillableDeletedAt(v *string) *ThemeUpdateOne {
if v != nil {
_u.SetDeletedAt(*v)
}
return _u
}
// ClearDeletedAt clears the value of the "deleted_at" field.
func (_u *ThemeUpdateOne) ClearDeletedAt() *ThemeUpdateOne {
_u.mutation.ClearDeletedAt()
return _u
}
// SetKey sets the "key" field.
func (_u *ThemeUpdateOne) SetKey(v string) *ThemeUpdateOne {
_u.mutation.SetKey(v)
return _u
}
// SetNillableKey sets the "key" field if the given value is not nil.
func (_u *ThemeUpdateOne) SetNillableKey(v *string) *ThemeUpdateOne {
if v != nil {
_u.SetKey(*v)
}
return _u
}
// SetType sets the "type" field.
func (_u *ThemeUpdateOne) SetType(v theme.Type) *ThemeUpdateOne {
_u.mutation.SetType(v)
return _u
}
// SetNillableType sets the "type" field if the given value is not nil.
func (_u *ThemeUpdateOne) SetNillableType(v *theme.Type) *ThemeUpdateOne {
if v != nil {
_u.SetType(*v)
}
return _u
}
// SetColors sets the "colors" field.
func (_u *ThemeUpdateOne) SetColors(v map[string]interface{}) *ThemeUpdateOne {
_u.mutation.SetColors(v)
return _u
}
// ClearColors clears the value of the "colors" field.
func (_u *ThemeUpdateOne) ClearColors() *ThemeUpdateOne {
_u.mutation.ClearColors()
return _u
}
// Mutation returns the ThemeMutation object of the builder.
func (_u *ThemeUpdateOne) Mutation() *ThemeMutation {
return _u.mutation
}
// Where appends a list predicates to the ThemeUpdate builder.
func (_u *ThemeUpdateOne) Where(ps ...predicate.Theme) *ThemeUpdateOne {
_u.mutation.Where(ps...)
return _u
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (_u *ThemeUpdateOne) Select(field string, fields ...string) *ThemeUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated Theme entity.
func (_u *ThemeUpdateOne) Save(ctx context.Context) (*Theme, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *ThemeUpdateOne) SaveX(ctx context.Context) *Theme {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *ThemeUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *ThemeUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *ThemeUpdateOne) check() error {
if v, ok := _u.mutation.Key(); ok {
if err := theme.KeyValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "Theme.key": %w`, err)}
}
}
if v, ok := _u.mutation.GetType(); ok {
if err := theme.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "Theme.type": %w`, err)}
}
}
return nil
}
// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
func (_u *ThemeUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *ThemeUpdateOne {
_u.modifiers = append(_u.modifiers, modifiers...)
return _u
}
func (_u *ThemeUpdateOne) sqlSave(ctx context.Context) (_node *Theme, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(theme.Table, theme.Columns, sqlgraph.NewFieldSpec(theme.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Theme.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := _u.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, theme.FieldID)
for _, f := range fields {
if !theme.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != theme.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(theme.FieldUpdatedAt, field.TypeString, value)
}
if value, ok := _u.mutation.DeletedAt(); ok {
_spec.SetField(theme.FieldDeletedAt, field.TypeString, value)
}
if _u.mutation.DeletedAtCleared() {
_spec.ClearField(theme.FieldDeletedAt, field.TypeString)
}
if value, ok := _u.mutation.Key(); ok {
_spec.SetField(theme.FieldKey, field.TypeString, value)
}
if value, ok := _u.mutation.GetType(); ok {
_spec.SetField(theme.FieldType, field.TypeEnum, value)
}
if value, ok := _u.mutation.Colors(); ok {
_spec.SetField(theme.FieldColors, field.TypeJSON, value)
}
if _u.mutation.ColorsCleared() {
_spec.ClearField(theme.FieldColors, field.TypeJSON)
}
_spec.AddModifiers(_u.modifiers...)
_node = &Theme{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{theme.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

245
internal/models/ent/tx.go Normal file
View File

@@ -0,0 +1,245 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
stdsql "database/sql"
"fmt"
"sync"
"entgo.io/ent/dialect"
)
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
// Document is the client for interacting with the Document builders.
Document *DocumentClient
// Extension is the client for interacting with the Extension builders.
Extension *ExtensionClient
// KeyBinding is the client for interacting with the KeyBinding builders.
KeyBinding *KeyBindingClient
// Theme is the client for interacting with the Theme builders.
Theme *ThemeClient
// lazily loaded.
client *Client
clientOnce sync.Once
// 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 Commit 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(ctx 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()
})
txDriver.mu.Lock()
hooks := append([]CommitHook(nil), txDriver.onCommit...)
txDriver.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) {
txDriver := tx.config.driver.(*txDriver)
txDriver.mu.Lock()
txDriver.onCommit = append(txDriver.onCommit, f)
txDriver.mu.Unlock()
}
type (
// Rollbacker is the interface that wraps the Rollback 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(ctx 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()
})
txDriver.mu.Lock()
hooks := append([]RollbackHook(nil), txDriver.onRollback...)
txDriver.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) {
txDriver := tx.config.driver.(*txDriver)
txDriver.mu.Lock()
txDriver.onRollback = append(txDriver.onRollback, f)
txDriver.mu.Unlock()
}
// 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.Document = NewDocumentClient(tx.config)
tx.Extension = NewExtensionClient(tx.config)
tx.KeyBinding = NewKeyBindingClient(tx.config)
tx.Theme = NewThemeClient(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: Document.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
// completion hooks.
mu sync.Mutex
onCommit []CommitHook
onRollback []RollbackHook
}
// 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 any) error {
return tx.tx.Exec(ctx, query, args, v)
}
// Query calls tx.Query.
func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error {
return tx.tx.Query(ctx, query, args, v)
}
var _ dialect.Driver = (*txDriver)(nil)
// ExecContext allows calling the underlying ExecContext method of the transaction if it is supported by it.
// See, database/sql#Tx.ExecContext for more information.
func (tx *txDriver) ExecContext(ctx context.Context, query string, args ...any) (stdsql.Result, error) {
ex, ok := tx.tx.(interface {
ExecContext(context.Context, string, ...any) (stdsql.Result, error)
})
if !ok {
return nil, fmt.Errorf("Tx.ExecContext is not supported")
}
return ex.ExecContext(ctx, query, args...)
}
// QueryContext allows calling the underlying QueryContext method of the transaction if it is supported by it.
// See, database/sql#Tx.QueryContext for more information.
func (tx *txDriver) QueryContext(ctx context.Context, query string, args ...any) (*stdsql.Rows, error) {
q, ok := tx.tx.(interface {
QueryContext(context.Context, string, ...any) (*stdsql.Rows, error)
})
if !ok {
return nil, fmt.Errorf("Tx.QueryContext is not supported")
}
return q.QueryContext(ctx, query, args...)
}

View File

@@ -0,0 +1,111 @@
package models
// ExtensionConfig 扩展配置项
type ExtensionConfig map[string]interface{}
// ExtensionKey 扩展标识符
type ExtensionKey string
// Extension 扩展配置
type Extension struct {
Key ExtensionKey `json:"key"`
Enabled bool `json:"enabled"`
Config ExtensionConfig `json:"config"`
}
const (
// 编辑增强扩展
ExtensionRainbowBrackets ExtensionKey = "rainbowBrackets" // 彩虹括号
ExtensionHyperlink ExtensionKey = "hyperlink" // 超链接
ExtensionColorSelector ExtensionKey = "colorSelector" // 颜色选择器
ExtensionFold ExtensionKey = "fold" // 代码折叠
ExtensionTranslator ExtensionKey = "translator" // 划词翻译
ExtensionMarkdown ExtensionKey = "markdown" // Markdown渲染
ExtensionHighlightWhitespace ExtensionKey = "highlightWhitespace" // 显示空白字符
ExtensionHighlightTrailingWhitespace ExtensionKey = "highlightTrailingWhitespace" // 高亮行尾空白
ExtensionMinimap ExtensionKey = "minimap" // 小地图
ExtensionLineNumbers ExtensionKey = "lineNumbers" // 行号显示
ExtensionContextMenu ExtensionKey = "contextMenu" // 上下文菜单
ExtensionSearch ExtensionKey = "search" // 搜索功能
ExtensionHttpClient ExtensionKey = "httpClient" // HTTP 客户端
)
// NewDefaultExtensions 创建默认扩展配置
func NewDefaultExtensions() []Extension {
return []Extension{
// 编辑增强扩展
{
Key: ExtensionRainbowBrackets,
Enabled: true,
Config: ExtensionConfig{},
},
{
Key: ExtensionHyperlink,
Enabled: true,
Config: ExtensionConfig{},
},
{
Key: ExtensionColorSelector,
Enabled: true,
Config: ExtensionConfig{},
},
{
Key: ExtensionFold,
Enabled: true,
Config: ExtensionConfig{},
},
{
Key: ExtensionTranslator,
Enabled: true,
Config: ExtensionConfig{},
},
{
Key: ExtensionMarkdown,
Enabled: true,
Config: ExtensionConfig{},
},
{
Key: ExtensionHighlightWhitespace,
Enabled: true,
Config: ExtensionConfig{},
},
{
Key: ExtensionHighlightTrailingWhitespace,
Enabled: true,
Config: ExtensionConfig{},
},
// UI增强扩展
{
Key: ExtensionMinimap,
Enabled: true,
Config: ExtensionConfig{
"displayText": "characters",
"showOverlay": "always",
"autohide": false,
},
},
{
Key: ExtensionLineNumbers,
Enabled: true,
Config: ExtensionConfig{},
},
{
Key: ExtensionContextMenu,
Enabled: true,
Config: ExtensionConfig{},
},
// 工具扩展
{
Key: ExtensionSearch,
Enabled: true,
Config: ExtensionConfig{},
},
{
Key: ExtensionHttpClient,
Enabled: true,
Config: ExtensionConfig{},
},
}
}

View File

@@ -1,207 +0,0 @@
package models
import "time"
// Extension 单个扩展配置
type Extension struct {
ID ExtensionID `json:"id" db:"id"` // 扩展唯一标识
Enabled bool `json:"enabled" db:"enabled"` // 是否启用
IsDefault bool `json:"isDefault" db:"is_default"` // 是否为默认扩展
Config ExtensionConfig `json:"config" db:"config"` // 扩展配置项
}
// ExtensionID 扩展标识符
type ExtensionID string
const (
// 编辑增强扩展
ExtensionRainbowBrackets ExtensionID = "rainbowBrackets" // 彩虹括号
ExtensionHyperlink ExtensionID = "hyperlink" // 超链接
ExtensionColorSelector ExtensionID = "colorSelector" // 颜色选择器
ExtensionFold ExtensionID = "fold" // 代码折叠
ExtensionTranslator ExtensionID = "translator" // 划词翻译
ExtensionMarkdown ExtensionID = "markdown" // Markdown渲染
ExtensionHighlightWhitespace ExtensionID = "highlightWhitespace" // 显示空白字符
ExtensionHighlightTrailingWhitespace ExtensionID = "highlightTrailingWhitespace" // 高亮行尾空白
// UI增强扩展
ExtensionMinimap ExtensionID = "minimap" // 小地图
ExtensionLineNumbers ExtensionID = "lineNumbers" // 行号显示
ExtensionContextMenu ExtensionID = "contextMenu" // 上下文菜单
// 工具扩展
ExtensionSearch ExtensionID = "search" // 搜索功能
// 核心扩展
ExtensionEditor ExtensionID = "editor" // 编辑器核心功能
)
// ExtensionConfig 扩展配置项
type ExtensionConfig map[string]interface{}
// ExtensionMetadata 扩展配置元数据
type ExtensionMetadata struct {
Version string `json:"version"` // 配置版本
LastUpdated string `json:"lastUpdated"` // 最后更新时间
}
// ExtensionSettings 扩展设置配置
type ExtensionSettings struct {
Extensions []Extension `json:"extensions"` // 扩展列表
Metadata ExtensionMetadata `json:"metadata"` // 配置元数据
}
// NewDefaultExtensionSettings 创建默认扩展配置
func NewDefaultExtensionSettings() *ExtensionSettings {
return &ExtensionSettings{
Extensions: NewDefaultExtensions(),
Metadata: ExtensionMetadata{
Version: "1.0.0",
LastUpdated: time.Now().Format(time.RFC3339),
},
}
}
// NewDefaultExtensions 创建默认扩展配置
func NewDefaultExtensions() []Extension {
return []Extension{
// 编辑增强扩展
{
ID: ExtensionRainbowBrackets,
Enabled: true,
IsDefault: true,
Config: ExtensionConfig{},
},
{
ID: ExtensionHyperlink,
Enabled: true,
IsDefault: true,
Config: ExtensionConfig{},
},
{
ID: ExtensionColorSelector,
Enabled: true,
IsDefault: true,
Config: ExtensionConfig{},
},
{
ID: ExtensionFold,
Enabled: true,
IsDefault: true,
Config: ExtensionConfig{},
},
{
ID: ExtensionTranslator,
Enabled: true,
IsDefault: true,
Config: ExtensionConfig{
"defaultTranslator": "bing",
"minSelectionLength": 2,
"maxTranslationLength": 5000,
},
},
{
ID: ExtensionMarkdown,
Enabled: true,
IsDefault: true,
Config: ExtensionConfig{},
},
{
ID: ExtensionHighlightWhitespace,
Enabled: true,
IsDefault: true,
Config: ExtensionConfig{},
},
{
ID: ExtensionHighlightTrailingWhitespace,
Enabled: true,
IsDefault: true,
Config: ExtensionConfig{},
},
// UI增强扩展
{
ID: ExtensionMinimap,
Enabled: true,
IsDefault: true,
Config: ExtensionConfig{
"displayText": "characters",
"showOverlay": "always",
"autohide": false,
},
},
{
ID: ExtensionLineNumbers,
Enabled: true,
IsDefault: true,
Config: ExtensionConfig{},
},
{
ID: ExtensionContextMenu,
Enabled: true,
IsDefault: true,
Config: ExtensionConfig{},
},
// 工具扩展
{
ID: ExtensionSearch,
Enabled: true,
IsDefault: true,
Config: ExtensionConfig{},
},
// 核心扩展
{
ID: ExtensionEditor,
Enabled: true,
IsDefault: true,
Config: ExtensionConfig{},
},
}
}
// GetVersion 获取配置版本
func (es *ExtensionSettings) GetVersion() string {
return es.Metadata.Version
}
// SetVersion 设置配置版本
func (es *ExtensionSettings) SetVersion(version string) {
es.Metadata.Version = version
}
// SetLastUpdated 设置最后更新时间
func (es *ExtensionSettings) SetLastUpdated(timeStr string) {
es.Metadata.LastUpdated = timeStr
}
// GetDefaultConfig 获取默认配置
func (es *ExtensionSettings) GetDefaultConfig() any {
return NewDefaultExtensionSettings()
}
// GetExtensionByID 根据ID获取扩展
func (es *ExtensionSettings) GetExtensionByID(id ExtensionID) *Extension {
for i := range es.Extensions {
if es.Extensions[i].ID == id {
return &es.Extensions[i]
}
}
return nil
}
// UpdateExtension 更新扩展配置
func (es *ExtensionSettings) UpdateExtension(id ExtensionID, enabled bool, config ExtensionConfig) bool {
for i := range es.Extensions {
if es.Extensions[i].ID == id {
es.Extensions[i].Enabled = enabled
if config != nil {
es.Extensions[i].Config = config
}
es.SetLastUpdated(time.Now().Format(time.RFC3339))
return true
}
}
return false
}

View File

@@ -0,0 +1,3 @@
package models
//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate --target ./ent --feature upsert,sql/execquery,sql/modifier,sql/lock,intercept,privacy,entql,namedges ./schema

View File

@@ -0,0 +1,370 @@
package models
// KeyBindingKey 快捷键命令
type KeyBindingKey string
// KeyBinding 单个快捷键绑定
type KeyBinding struct {
Key KeyBindingKey `json:"key"`
Command string `json:"command"`
Extension ExtensionKey `json:"extension"`
Enabled bool `json:"enabled"`
}
const (
ShowSearchKeyBindingKey KeyBindingKey = "showSearch" // 显示搜索
HideSearchKeyBindingKey KeyBindingKey = "hideSearch" // 隐藏搜索
BlockSelectAllKeyBindingKey KeyBindingKey = "blockSelectAll" // 块内选择全部
BlockAddAfterCurrentKeyBindingKey KeyBindingKey = "blockAddAfterCurrent" // 在当前块后添加新块
BlockAddAfterLastKeyBindingKey KeyBindingKey = "blockAddAfterLast" // 在最后添加新块
BlockAddBeforeCurrentKeyBindingKey KeyBindingKey = "blockAddBeforeCurrent" // 在当前块前添加新块
BlockGotoPreviousKeyBindingKey KeyBindingKey = "blockGotoPrevious" // 跳转到上一个块
BlockGotoNextKeyBindingKey KeyBindingKey = "blockGotoNext" // 跳转到下一个块
BlockSelectPreviousKeyBindingKey KeyBindingKey = "blockSelectPrevious" // 选择上一个块
BlockSelectNextKeyBindingKey KeyBindingKey = "blockSelectNext" // 选择下一个块
BlockDeleteKeyBindingKey KeyBindingKey = "blockDelete" // 删除当前块
BlockMoveUpKeyBindingKey KeyBindingKey = "blockMoveUp" // 向上移动当前块
BlockMoveDownKeyBindingKey KeyBindingKey = "blockMoveDown" // 向下移动当前块
BlockDeleteLineKeyBindingKey KeyBindingKey = "blockDeleteLine" // 删除行
BlockMoveLineUpKeyBindingKey KeyBindingKey = "blockMoveLineUp" // 向上移动行
BlockMoveLineDownKeyBindingKey KeyBindingKey = "blockMoveLineDown" // 向下移动行
BlockTransposeCharsKeyBindingKey KeyBindingKey = "blockTransposeChars" // 字符转置
BlockFormatKeyBindingKey KeyBindingKey = "blockFormat" // 格式化代码块
BlockCopyKeyBindingKey KeyBindingKey = "blockCopy" // 复制
BlockCutKeyBindingKey KeyBindingKey = "blockCut" // 剪切
BlockPasteKeyBindingKey KeyBindingKey = "blockPaste" // 粘贴
FoldCodeKeyBindingKey KeyBindingKey = "foldCode" // 折叠代码
UnfoldCodeKeyBindingKey KeyBindingKey = "unfoldCode" // 展开代码
FoldAllKeyBindingKey KeyBindingKey = "foldAll" // 折叠全部
UnfoldAllKeyBindingKey KeyBindingKey = "unfoldAll" // 展开全部
CursorSyntaxLeftKeyBindingKey KeyBindingKey = "cursorSyntaxLeft" // 光标按语法左移
CursorSyntaxRightKeyBindingKey KeyBindingKey = "cursorSyntaxRight" // 光标按语法右移
SelectSyntaxLeftKeyBindingKey KeyBindingKey = "selectSyntaxLeft" // 按语法选择左侧
SelectSyntaxRightKeyBindingKey KeyBindingKey = "selectSyntaxRight" // 按语法选择右侧
CopyLineUpKeyBindingKey KeyBindingKey = "copyLineUp" // 向上复制行
CopyLineDownKeyBindingKey KeyBindingKey = "copyLineDown" // 向下复制行
InsertBlankLineKeyBindingKey KeyBindingKey = "insertBlankLine" // 插入空行
SelectLineKeyBindingKey KeyBindingKey = "selectLine" // 选择行
SelectParentSyntaxKeyBindingKey KeyBindingKey = "selectParentSyntax" // 选择父级语法
IndentLessKeyBindingKey KeyBindingKey = "indentLess" // 减少缩进
IndentMoreKeyBindingKey KeyBindingKey = "indentMore" // 增加缩进
IndentSelectionKeyBindingKey KeyBindingKey = "indentSelection" // 缩进选择
CursorMatchingBracketKeyBindingKey KeyBindingKey = "cursorMatchingBracket" // 光标到匹配括号
ToggleCommentKeyBindingKey KeyBindingKey = "toggleComment" // 切换注释
ToggleBlockCommentKeyBindingKey KeyBindingKey = "toggleBlockComment" // 切换块注释
InsertNewlineAndIndentKeyBindingKey KeyBindingKey = "insertNewlineAndIndent" // 插入新行并缩进
DeleteCharBackwardKeyBindingKey KeyBindingKey = "deleteCharBackward" // 向后删除字符
DeleteCharForwardKeyBindingKey KeyBindingKey = "deleteCharForward" // 向前删除字符
DeleteGroupBackwardKeyBindingKey KeyBindingKey = "deleteGroupBackward" // 向后删除组
DeleteGroupForwardKeyBindingKey KeyBindingKey = "deleteGroupForward" // 向前删除组
HistoryUndoKeyBindingKey KeyBindingKey = "historyUndo" // 撤销
HistoryRedoKeyBindingKey KeyBindingKey = "historyRedo" // 重做
HistoryUndoSelectionKeyBindingKey KeyBindingKey = "historyUndoSelection" // 撤销选择
HistoryRedoSelectionKeyBindingKey KeyBindingKey = "historyRedoSelection" // 重做选择
)
const defaultExtension = "editor"
// NewDefaultKeyBindings 创建默认快捷键配置
func NewDefaultKeyBindings() []KeyBinding {
return []KeyBinding{
{
Key: ShowSearchKeyBindingKey,
Extension: ExtensionSearch,
Command: "Mod-f",
Enabled: true,
},
{
Key: HideSearchKeyBindingKey,
Extension: ExtensionSearch,
Command: "Escape",
Enabled: true,
},
{
Key: BlockSelectAllKeyBindingKey,
Extension: defaultExtension,
Command: "Mod-a",
Enabled: true,
},
{
Key: BlockAddAfterCurrentKeyBindingKey,
Extension: defaultExtension,
Command: "Mod-Enter",
Enabled: true,
},
{
Key: BlockAddAfterLastKeyBindingKey,
Extension: defaultExtension,
Command: "Mod-Shift-Enter",
Enabled: true,
},
{
Key: BlockAddBeforeCurrentKeyBindingKey,
Extension: defaultExtension,
Command: "Alt-Enter",
Enabled: true,
},
{
Key: BlockGotoPreviousKeyBindingKey,
Extension: defaultExtension,
Command: "Mod-ArrowUp",
Enabled: true,
},
{
Key: BlockGotoNextKeyBindingKey,
Extension: defaultExtension,
Command: "Mod-ArrowDown",
Enabled: true,
},
{
Key: BlockSelectPreviousKeyBindingKey,
Extension: defaultExtension,
Command: "Mod-Shift-ArrowUp",
Enabled: true,
},
{
Key: BlockSelectNextKeyBindingKey,
Extension: defaultExtension,
Command: "Mod-Shift-ArrowDown",
Enabled: true,
},
{
Key: BlockDeleteKeyBindingKey,
Extension: defaultExtension,
Command: "Mod-Shift-d",
Enabled: true,
},
{
Key: BlockMoveUpKeyBindingKey,
Extension: defaultExtension,
Command: "Alt-Mod-ArrowUp",
Enabled: true,
},
{
Key: BlockMoveDownKeyBindingKey,
Extension: defaultExtension,
Command: "Alt-Mod-ArrowDown",
Enabled: true,
},
{
Key: BlockDeleteLineKeyBindingKey,
Extension: defaultExtension,
Command: "Mod-Shift-k",
Enabled: true,
},
{
Key: BlockMoveLineUpKeyBindingKey,
Extension: defaultExtension,
Command: "Alt-ArrowUp",
Enabled: true,
},
{
Key: BlockMoveLineDownKeyBindingKey,
Extension: defaultExtension,
Command: "Alt-ArrowDown",
Enabled: true,
},
{
Key: BlockTransposeCharsKeyBindingKey,
Extension: defaultExtension,
Command: "Ctrl-t",
Enabled: true,
},
{
Key: BlockFormatKeyBindingKey,
Extension: defaultExtension,
Command: "Mod-Shift-f",
Enabled: true,
},
{
Key: BlockCopyKeyBindingKey,
Extension: defaultExtension,
Command: "Mod-c",
Enabled: true,
},
{
Key: BlockCutKeyBindingKey,
Extension: defaultExtension,
Command: "Mod-x",
Enabled: true,
},
{
Key: BlockPasteKeyBindingKey,
Extension: defaultExtension,
Command: "Mod-v",
Enabled: true,
},
{
Key: FoldCodeKeyBindingKey,
Extension: ExtensionFold,
Command: "Ctrl-Shift-[",
Enabled: true,
},
{
Key: UnfoldCodeKeyBindingKey,
Extension: ExtensionFold,
Command: "Ctrl-Shift-]",
Enabled: true,
},
{
Key: FoldAllKeyBindingKey,
Extension: ExtensionFold,
Command: "Ctrl-Alt-[",
Enabled: true,
},
{
Key: UnfoldAllKeyBindingKey,
Extension: ExtensionFold,
Command: "Ctrl-Alt-]",
Enabled: true,
},
{
Key: HistoryUndoKeyBindingKey,
Extension: defaultExtension,
Command: "Mod-z",
Enabled: true,
},
{
Key: HistoryRedoKeyBindingKey,
Extension: defaultExtension,
Command: "Mod-Shift-z",
Enabled: true,
},
{
Key: HistoryUndoSelectionKeyBindingKey,
Extension: defaultExtension,
Command: "Mod-u",
Enabled: true,
},
{
Key: HistoryRedoSelectionKeyBindingKey,
Extension: defaultExtension,
Command: "Mod-Shift-u",
Enabled: true,
},
{
Key: CursorSyntaxLeftKeyBindingKey,
Extension: defaultExtension,
Command: "Alt-ArrowLeft",
Enabled: true,
},
{
Key: CursorSyntaxRightKeyBindingKey,
Extension: defaultExtension,
Command: "Alt-ArrowRight",
Enabled: true,
},
{
Key: SelectSyntaxLeftKeyBindingKey,
Extension: defaultExtension,
Command: "Shift-Alt-ArrowLeft",
Enabled: true,
},
{
Key: SelectSyntaxRightKeyBindingKey,
Extension: defaultExtension,
Command: "Shift-Alt-ArrowRight",
Enabled: true,
},
{
Key: CopyLineUpKeyBindingKey,
Extension: defaultExtension,
Command: "Shift-Alt-ArrowUp",
Enabled: true,
},
{
Key: CopyLineDownKeyBindingKey,
Extension: defaultExtension,
Command: "Shift-Alt-ArrowDown",
Enabled: true,
},
{
Key: InsertBlankLineKeyBindingKey,
Extension: defaultExtension,
Command: "Ctrl-Enter",
Enabled: true,
},
{
Key: SelectLineKeyBindingKey,
Extension: defaultExtension,
Command: "Alt-l",
Enabled: true,
},
{
Key: SelectParentSyntaxKeyBindingKey,
Extension: defaultExtension,
Command: "Ctrl-i",
Enabled: true,
},
{
Key: IndentLessKeyBindingKey,
Extension: defaultExtension,
Command: "Ctrl-[",
Enabled: true,
},
{
Key: IndentMoreKeyBindingKey,
Extension: defaultExtension,
Command: "Ctrl-]",
Enabled: true,
},
{
Key: IndentSelectionKeyBindingKey,
Extension: defaultExtension,
Command: "Ctrl-Alt-\\",
Enabled: true,
},
{
Key: CursorMatchingBracketKeyBindingKey,
Extension: defaultExtension,
Command: "Shift-Ctrl-\\",
Enabled: true,
},
{
Key: ToggleCommentKeyBindingKey,
Extension: defaultExtension,
Command: "Ctrl-/",
Enabled: true,
},
{
Key: ToggleBlockCommentKeyBindingKey,
Extension: defaultExtension,
Command: "Shift-Alt-a",
Enabled: true,
},
{
Key: InsertNewlineAndIndentKeyBindingKey,
Extension: defaultExtension,
Command: "Enter",
Enabled: true,
},
{
Key: DeleteCharBackwardKeyBindingKey,
Extension: defaultExtension,
Command: "Backspace",
Enabled: true,
},
{
Key: DeleteCharForwardKeyBindingKey,
Extension: defaultExtension,
Command: "Delete",
Enabled: true,
},
{
Key: DeleteGroupBackwardKeyBindingKey,
Extension: defaultExtension,
Command: "Ctrl-Backspace",
Enabled: true,
},
{
Key: DeleteGroupForwardKeyBindingKey,
Extension: defaultExtension,
Command: "Ctrl-Delete",
Enabled: true,
},
}
}

View File

@@ -1,477 +0,0 @@
package models
import "time"
// KeyBinding 单个快捷键绑定
type KeyBinding struct {
Command KeyBindingCommand `json:"command" db:"command"` // 快捷键动作
Extension ExtensionID `json:"extension" db:"extension"` // 所属扩展
Key string `json:"key" db:"key"` // 快捷键组合(如 "Mod-f", "Ctrl-Shift-p"
Enabled bool `json:"enabled" db:"enabled"` // 是否启用
IsDefault bool `json:"isDefault" db:"is_default"` // 是否为默认快捷键
}
// KeyBindingCommand 快捷键命令
type KeyBindingCommand string
const (
// 搜索扩展相关
ShowSearchCommand KeyBindingCommand = "showSearch" // 显示搜索
HideSearchCommand KeyBindingCommand = "hideSearch" // 隐藏搜索
// 代码块扩展相关
BlockSelectAllCommand KeyBindingCommand = "blockSelectAll" // 块内选择全部
BlockAddAfterCurrentCommand KeyBindingCommand = "blockAddAfterCurrent" // 在当前块后添加新块
BlockAddAfterLastCommand KeyBindingCommand = "blockAddAfterLast" // 在最后添加新块
BlockAddBeforeCurrentCommand KeyBindingCommand = "blockAddBeforeCurrent" // 在当前块前添加新块
BlockGotoPreviousCommand KeyBindingCommand = "blockGotoPrevious" // 跳转到上一个块
BlockGotoNextCommand KeyBindingCommand = "blockGotoNext" // 跳转到下一个块
BlockSelectPreviousCommand KeyBindingCommand = "blockSelectPrevious" // 选择上一个块
BlockSelectNextCommand KeyBindingCommand = "blockSelectNext" // 选择下一个块
BlockDeleteCommand KeyBindingCommand = "blockDelete" // 删除当前块
BlockMoveUpCommand KeyBindingCommand = "blockMoveUp" // 向上移动当前块
BlockMoveDownCommand KeyBindingCommand = "blockMoveDown" // 向下移动当前块
BlockDeleteLineCommand KeyBindingCommand = "blockDeleteLine" // 删除行
BlockMoveLineUpCommand KeyBindingCommand = "blockMoveLineUp" // 向上移动行
BlockMoveLineDownCommand KeyBindingCommand = "blockMoveLineDown" // 向下移动行
BlockTransposeCharsCommand KeyBindingCommand = "blockTransposeChars" // 字符转置
BlockFormatCommand KeyBindingCommand = "blockFormat" // 格式化代码块
BlockCopyCommand KeyBindingCommand = "blockCopy" // 复制
BlockCutCommand KeyBindingCommand = "blockCut" // 剪切
BlockPasteCommand KeyBindingCommand = "blockPaste" // 粘贴
// 代码折叠扩展相关
FoldCodeCommand KeyBindingCommand = "foldCode" // 折叠代码
UnfoldCodeCommand KeyBindingCommand = "unfoldCode" // 展开代码
FoldAllCommand KeyBindingCommand = "foldAll" // 折叠全部
UnfoldAllCommand KeyBindingCommand = "unfoldAll" // 展开全部
// 通用编辑扩展相关
CursorSyntaxLeftCommand KeyBindingCommand = "cursorSyntaxLeft" // 光标按语法左移
CursorSyntaxRightCommand KeyBindingCommand = "cursorSyntaxRight" // 光标按语法右移
SelectSyntaxLeftCommand KeyBindingCommand = "selectSyntaxLeft" // 按语法选择左侧
SelectSyntaxRightCommand KeyBindingCommand = "selectSyntaxRight" // 按语法选择右侧
CopyLineUpCommand KeyBindingCommand = "copyLineUp" // 向上复制行
CopyLineDownCommand KeyBindingCommand = "copyLineDown" // 向下复制行
InsertBlankLineCommand KeyBindingCommand = "insertBlankLine" // 插入空行
SelectLineCommand KeyBindingCommand = "selectLine" // 选择行
SelectParentSyntaxCommand KeyBindingCommand = "selectParentSyntax" // 选择父级语法
IndentLessCommand KeyBindingCommand = "indentLess" // 减少缩进
IndentMoreCommand KeyBindingCommand = "indentMore" // 增加缩进
IndentSelectionCommand KeyBindingCommand = "indentSelection" // 缩进选择
CursorMatchingBracketCommand KeyBindingCommand = "cursorMatchingBracket" // 光标到匹配括号
ToggleCommentCommand KeyBindingCommand = "toggleComment" // 切换注释
ToggleBlockCommentCommand KeyBindingCommand = "toggleBlockComment" // 切换块注释
InsertNewlineAndIndentCommand KeyBindingCommand = "insertNewlineAndIndent" // 插入新行并缩进
DeleteCharBackwardCommand KeyBindingCommand = "deleteCharBackward" // 向后删除字符
DeleteCharForwardCommand KeyBindingCommand = "deleteCharForward" // 向前删除字符
DeleteGroupBackwardCommand KeyBindingCommand = "deleteGroupBackward" // 向后删除组
DeleteGroupForwardCommand KeyBindingCommand = "deleteGroupForward" // 向前删除组
// 历史记录扩展相关
HistoryUndoCommand KeyBindingCommand = "historyUndo" // 撤销
HistoryRedoCommand KeyBindingCommand = "historyRedo" // 重做
HistoryUndoSelectionCommand KeyBindingCommand = "historyUndoSelection" // 撤销选择
HistoryRedoSelectionCommand KeyBindingCommand = "historyRedoSelection" // 重做选择
)
// KeyBindingMetadata 快捷键配置元数据
type KeyBindingMetadata struct {
Version string `json:"version"` // 配置版本
LastUpdated string `json:"lastUpdated"` // 最后更新时间
}
// KeyBindingConfig 快捷键配置
type KeyBindingConfig struct {
KeyBindings []KeyBinding `json:"keyBindings"` // 快捷键列表
Metadata KeyBindingMetadata `json:"metadata"` // 配置元数据
}
// NewDefaultKeyBindingConfig 创建默认快捷键配置
func NewDefaultKeyBindingConfig() *KeyBindingConfig {
return &KeyBindingConfig{
KeyBindings: NewDefaultKeyBindings(),
Metadata: KeyBindingMetadata{
Version: "1.0.0",
LastUpdated: time.Now().Format(time.RFC3339),
},
}
}
// NewDefaultKeyBindings 创建默认快捷键配置
func NewDefaultKeyBindings() []KeyBinding {
return []KeyBinding{
// 搜索扩展快捷键
{
Command: ShowSearchCommand,
Extension: ExtensionSearch,
Key: "Mod-f",
Enabled: true,
IsDefault: true,
},
{
Command: HideSearchCommand,
Extension: ExtensionSearch,
Key: "Escape",
Enabled: true,
IsDefault: true,
},
// 代码块核心功能快捷键
{
Command: BlockSelectAllCommand,
Extension: ExtensionEditor,
Key: "Mod-a",
Enabled: true,
IsDefault: true,
},
{
Command: BlockAddAfterCurrentCommand,
Extension: ExtensionEditor,
Key: "Mod-Enter",
Enabled: true,
IsDefault: true,
},
{
Command: BlockAddAfterLastCommand,
Extension: ExtensionEditor,
Key: "Mod-Shift-Enter",
Enabled: true,
IsDefault: true,
},
{
Command: BlockAddBeforeCurrentCommand,
Extension: ExtensionEditor,
Key: "Alt-Enter",
Enabled: true,
IsDefault: true,
},
{
Command: BlockGotoPreviousCommand,
Extension: ExtensionEditor,
Key: "Mod-ArrowUp",
Enabled: true,
IsDefault: true,
},
{
Command: BlockGotoNextCommand,
Extension: ExtensionEditor,
Key: "Mod-ArrowDown",
Enabled: true,
IsDefault: true,
},
{
Command: BlockSelectPreviousCommand,
Extension: ExtensionEditor,
Key: "Mod-Shift-ArrowUp",
Enabled: true,
IsDefault: true,
},
{
Command: BlockSelectNextCommand,
Extension: ExtensionEditor,
Key: "Mod-Shift-ArrowDown",
Enabled: true,
IsDefault: true,
},
{
Command: BlockDeleteCommand,
Extension: ExtensionEditor,
Key: "Mod-Shift-d",
Enabled: true,
IsDefault: true,
},
{
Command: BlockMoveUpCommand,
Extension: ExtensionEditor,
Key: "Alt-Mod-ArrowUp",
Enabled: true,
IsDefault: true,
},
{
Command: BlockMoveDownCommand,
Extension: ExtensionEditor,
Key: "Alt-Mod-ArrowDown",
Enabled: true,
IsDefault: true,
},
{
Command: BlockDeleteLineCommand,
Extension: ExtensionEditor,
Key: "Mod-Shift-k",
Enabled: true,
IsDefault: true,
},
{
Command: BlockMoveLineUpCommand,
Extension: ExtensionEditor,
Key: "Alt-ArrowUp",
Enabled: true,
IsDefault: true,
},
{
Command: BlockMoveLineDownCommand,
Extension: ExtensionEditor,
Key: "Alt-ArrowDown",
Enabled: true,
IsDefault: true,
},
{
Command: BlockTransposeCharsCommand,
Extension: ExtensionEditor,
Key: "Ctrl-t",
Enabled: true,
IsDefault: true,
},
{
Command: BlockFormatCommand,
Extension: ExtensionEditor,
Key: "Mod-Shift-f",
Enabled: true,
IsDefault: true,
},
{
Command: BlockCopyCommand,
Extension: ExtensionEditor,
Key: "Mod-c",
Enabled: true,
IsDefault: true,
},
{
Command: BlockCutCommand,
Extension: ExtensionEditor,
Key: "Mod-x",
Enabled: true,
IsDefault: true,
},
{
Command: BlockPasteCommand,
Extension: ExtensionEditor,
Key: "Mod-v",
Enabled: true,
IsDefault: true,
},
// 代码折叠扩展快捷键
{
Command: FoldCodeCommand,
Extension: ExtensionFold,
Key: "Ctrl-Shift-[",
Enabled: true,
IsDefault: true,
},
{
Command: UnfoldCodeCommand,
Extension: ExtensionFold,
Key: "Ctrl-Shift-]",
Enabled: true,
IsDefault: true,
},
{
Command: FoldAllCommand,
Extension: ExtensionFold,
Key: "Ctrl-Alt-[",
Enabled: true,
IsDefault: true,
},
{
Command: UnfoldAllCommand,
Extension: ExtensionFold,
Key: "Ctrl-Alt-]",
Enabled: true,
IsDefault: true,
},
// 历史记录扩展快捷键
{
Command: HistoryUndoCommand,
Extension: ExtensionEditor,
Key: "Mod-z",
Enabled: true,
IsDefault: true,
},
{
Command: HistoryRedoCommand,
Extension: ExtensionEditor,
Key: "Mod-Shift-z",
Enabled: true,
IsDefault: true,
},
{
Command: HistoryUndoSelectionCommand,
Extension: ExtensionEditor,
Key: "Mod-u",
Enabled: true,
IsDefault: true,
},
{
Command: HistoryRedoSelectionCommand,
Extension: ExtensionEditor,
Key: "Mod-Shift-u",
Enabled: true,
IsDefault: true,
},
// 通用编辑扩展快捷键
{
Command: CursorSyntaxLeftCommand,
Extension: ExtensionEditor,
Key: "Alt-ArrowLeft",
Enabled: true,
IsDefault: true,
},
{
Command: CursorSyntaxRightCommand,
Extension: ExtensionEditor,
Key: "Alt-ArrowRight",
Enabled: true,
IsDefault: true,
},
{
Command: SelectSyntaxLeftCommand,
Extension: ExtensionEditor,
Key: "Shift-Alt-ArrowLeft",
Enabled: true,
IsDefault: true,
},
{
Command: SelectSyntaxRightCommand,
Extension: ExtensionEditor,
Key: "Shift-Alt-ArrowRight",
Enabled: true,
IsDefault: true,
},
{
Command: CopyLineUpCommand,
Extension: ExtensionEditor,
Key: "Shift-Alt-ArrowUp",
Enabled: true,
IsDefault: true,
},
{
Command: CopyLineDownCommand,
Extension: ExtensionEditor,
Key: "Shift-Alt-ArrowDown",
Enabled: true,
IsDefault: true,
},
{
Command: InsertBlankLineCommand,
Extension: ExtensionEditor,
Key: "Ctrl-Enter",
Enabled: true,
IsDefault: true,
},
{
Command: SelectLineCommand,
Extension: ExtensionEditor,
Key: "Alt-l",
Enabled: true,
IsDefault: true,
},
{
Command: SelectParentSyntaxCommand,
Extension: ExtensionEditor,
Key: "Ctrl-i",
Enabled: true,
IsDefault: true,
},
{
Command: IndentLessCommand,
Extension: ExtensionEditor,
Key: "Ctrl-[",
Enabled: true,
IsDefault: true,
},
{
Command: IndentMoreCommand,
Extension: ExtensionEditor,
Key: "Ctrl-]",
Enabled: true,
IsDefault: true,
},
{
Command: IndentSelectionCommand,
Extension: ExtensionEditor,
Key: "Ctrl-Alt-\\",
Enabled: true,
IsDefault: true,
},
{
Command: CursorMatchingBracketCommand,
Extension: ExtensionEditor,
Key: "Shift-Ctrl-\\",
Enabled: true,
IsDefault: true,
},
{
Command: ToggleCommentCommand,
Extension: ExtensionEditor,
Key: "Ctrl-/",
Enabled: true,
IsDefault: true,
},
{
Command: ToggleBlockCommentCommand,
Extension: ExtensionEditor,
Key: "Shift-Alt-a",
Enabled: true,
IsDefault: true,
},
{
Command: InsertNewlineAndIndentCommand,
Extension: ExtensionEditor,
Key: "Enter",
Enabled: true,
IsDefault: true,
},
{
Command: DeleteCharBackwardCommand,
Extension: ExtensionEditor,
Key: "Backspace",
Enabled: true,
IsDefault: true,
},
{
Command: DeleteCharForwardCommand,
Extension: ExtensionEditor,
Key: "Delete",
Enabled: true,
IsDefault: true,
},
{
Command: DeleteGroupBackwardCommand,
Extension: ExtensionEditor,
Key: "Ctrl-Backspace",
Enabled: true,
IsDefault: true,
},
{
Command: DeleteGroupForwardCommand,
Extension: ExtensionEditor,
Key: "Ctrl-Delete",
Enabled: true,
IsDefault: true,
},
}
}
// GetVersion 获取配置版本
func (kbc *KeyBindingConfig) GetVersion() string {
return kbc.Metadata.Version
}
// SetVersion 设置配置版本
func (kbc *KeyBindingConfig) SetVersion(version string) {
kbc.Metadata.Version = version
}
// SetLastUpdated 设置最后更新时间
func (kbc *KeyBindingConfig) SetLastUpdated(timeStr string) {
kbc.Metadata.LastUpdated = timeStr
}
// GetDefaultConfig 获取默认配置
func (kbc *KeyBindingConfig) GetDefaultConfig() any {
return NewDefaultKeyBindingConfig()
}

View File

@@ -0,0 +1,65 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
"voidraft/internal/models/schema/mixin"
)
// Document holds the schema definition for the Document entity.
type Document struct {
ent.Schema
}
// Annotations of the Document.
func (Document) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "documents"},
}
}
// Mixin of the Document.
func (Document) Mixin() []ent.Mixin {
return []ent.Mixin{
mixin.TimeMixin{},
mixin.SoftDeleteMixin{},
}
}
// Fields of the Document.
func (Document) Fields() []ent.Field {
return []ent.Field{
field.String("title").
MaxLen(255).
NotEmpty().
StructTag(`json:"title"`).
Comment("document title"),
field.Text("content").
Optional().
Default("\n∞∞∞text-a\n").
StructTag(`json:"content"`).
Comment("document content"),
field.Bool("locked").
Default(false).
StructTag(`json:"locked"`).
Comment("document locked status"),
}
}
// Edges of the Document.
func (Document) Edges() []ent.Edge {
return nil
}
// Indexes of the Document.
func (Document) Indexes() []ent.Index {
return []ent.Index{
index.Fields("title"),
index.Fields("created_at"),
index.Fields("updated_at"),
}
}

View File

@@ -0,0 +1,63 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
"voidraft/internal/models/schema/mixin"
)
// Extension holds the schema definition for the Extension entity.
type Extension struct {
ent.Schema
}
// Annotations of the Extension.
func (Extension) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "extensions"},
}
}
// Mixin of the Extension.
func (Extension) Mixin() []ent.Mixin {
return []ent.Mixin{
mixin.TimeMixin{},
mixin.SoftDeleteMixin{},
}
}
// Fields of the Extension.
func (Extension) Fields() []ent.Field {
return []ent.Field{
field.String("key").
MaxLen(100).
NotEmpty().
Unique().
StructTag(`json:"key"`).
Comment("extension key"),
field.Bool("enabled").
Default(true).
StructTag(`json:"enabled"`).
Comment("extension enabled or not"),
field.JSON("config", map[string]interface{}{}).
Optional().
StructTag(`json:"config"`).
Comment("extension config"),
}
}
// Edges of the Extension.
func (Extension) Edges() []ent.Edge {
return nil
}
// Indexes of the Extension.
func (Extension) Indexes() []ent.Index {
return []ent.Index{
index.Fields("enabled"),
}
}

View File

@@ -0,0 +1,70 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
"voidraft/internal/models/schema/mixin"
)
// KeyBinding holds the schema definition for the KeyBinding entity.
type KeyBinding struct {
ent.Schema
}
// Annotations of the KeyBinding.
func (KeyBinding) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "key_bindings"},
}
}
// Mixin of the KeyBinding.
func (KeyBinding) Mixin() []ent.Mixin {
return []ent.Mixin{
mixin.TimeMixin{},
mixin.SoftDeleteMixin{},
}
}
// Fields of the KeyBinding.
func (KeyBinding) Fields() []ent.Field {
return []ent.Field{
field.String("key").
MaxLen(100).
NotEmpty().
Unique().
StructTag(`json:"key"`).
Comment("key binding key"),
field.String("command").
MaxLen(100).
NotEmpty().
StructTag(`json:"command"`).
Comment("key binding command"),
field.String("extension").
MaxLen(100).
Optional().
StructTag(`json:"extension,omitempty"`).
Comment("key binding extension"),
field.Bool("enabled").
Default(true).
StructTag(`json:"enabled"`).
Comment("key binding enabled"),
}
}
// Edges of the KeyBinding.
func (KeyBinding) Edges() []ent.Edge {
return nil
}
// Indexes of the KeyBinding.
func (KeyBinding) Indexes() []ent.Index {
return []ent.Index{
index.Fields("extension"),
index.Fields("enabled"),
}
}

View File

@@ -0,0 +1,114 @@
package mixin
import (
"context"
"fmt"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
"entgo.io/ent/schema/mixin"
)
// SoftDeleteMixin 实现软删除模式
// 使用方法:
// - 正常删除(软删除): client.User.DeleteOneID(id).Exec(ctx)
// - 永久删除: client.User.DeleteOneID(id).Exec(SkipSoftDelete(ctx))
// - 查询包含已删除: client.User.Query().All(SkipSoftDelete(ctx))
//
// 参考https://entgo.io/docs/interceptors/#soft-delete
type SoftDeleteMixin struct {
mixin.Schema
}
// Fields of the SoftDeleteMixin.
func (SoftDeleteMixin) Fields() []ent.Field {
return []ent.Field{
field.String("deleted_at").
Optional().
Nillable().
Comment("deleted at"),
}
}
// Indexes of the SoftDeleteMixin.
func (SoftDeleteMixin) Indexes() []ent.Index {
return []ent.Index{
// 注意:部分索引 WHERE deleted_at IS NOT NULL 已在各表中单独定义
index.Fields("deleted_at"),
}
}
// softDeleteKey 用于在 context 中传递是否跳过软删除的标志
type softDeleteKey struct{}
// SkipSoftDelete 返回一个新的 context跳过软删除拦截器和钩子
func SkipSoftDelete(parent context.Context) context.Context {
return context.WithValue(parent, softDeleteKey{}, true)
}
// Interceptors of the SoftDeleteMixin.
func (d SoftDeleteMixin) Interceptors() []ent.Interceptor {
return []ent.Interceptor{
ent.InterceptFunc(func(next ent.Querier) ent.Querier {
return ent.QuerierFunc(func(ctx context.Context, q ent.Query) (ent.Value, error) {
// 如果 context 中设置了跳过软删除标志,则不过滤
if skip, _ := ctx.Value(softDeleteKey{}).(bool); skip {
return next.Query(ctx, q)
}
// 添加 WHERE deleted_at IS NULL 条件
if w, ok := q.(interface{ WhereP(...func(*sql.Selector)) }); ok {
d.P(w)
}
return next.Query(ctx, q)
})
}),
}
}
// Hooks of the SoftDeleteMixin.
func (d SoftDeleteMixin) Hooks() []ent.Hook {
return []ent.Hook{
func(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
// 只处理删除操作
if m.Op() != ent.OpDeleteOne && m.Op() != ent.OpDelete {
return next.Mutate(ctx, m)
}
// 如果 context 中设置了跳过软删除标志,则执行真正的删除
if skip, _ := ctx.Value(softDeleteKey{}).(bool); skip {
return next.Mutate(ctx, m)
}
// 类型断言,确保 mutation 支持软删除所需的方法
mx, ok := m.(interface {
SetOp(ent.Op)
SetDeletedAt(string)
WhereP(...func(*sql.Selector))
})
if !ok {
return nil, fmt.Errorf("SoftDeleteMixin: unexpected mutation type %T", m)
}
// 添加 WHERE deleted_at IS NULL 条件(确保不会重复软删除)
d.P(mx)
// 将删除操作转换为更新操作
mx.SetOp(ent.OpUpdate)
mx.SetDeletedAt(NowString())
// 执行更新操作
return next.Mutate(ctx, m)
})
},
}
}
// P 添加存储层级的过滤条件到查询和变更操作
func (d SoftDeleteMixin) P(w interface{ WhereP(...func(*sql.Selector)) }) {
w.WhereP(
sql.FieldIsNull(d.Fields()[0].Descriptor().Name),
)
}

View File

@@ -0,0 +1,57 @@
package mixin
import (
"context"
"time"
"entgo.io/ent"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/mixin"
)
// TimeFormat ISO 8601 时间格式
const TimeFormat = time.RFC3339
// NowString 返回当前时间的 ISO 8601 格式字符串
func NowString() string {
return time.Now().Format(TimeFormat)
}
// TimeMixin 时间字段混入
// created_at: 创建时间
// updated_at: 更新时间(自动更新)
type TimeMixin struct {
mixin.Schema
}
// Fields of the TimeMixin.
func (TimeMixin) Fields() []ent.Field {
return []ent.Field{
field.String("created_at").
DefaultFunc(NowString).
Immutable().
StructTag(`json:"created_at"`).
Comment("creation time"),
field.String("updated_at").
DefaultFunc(NowString).
StructTag(`json:"updated_at"`).
Comment("update time"),
}
}
// Hooks of the TimeMixin.
func (TimeMixin) Hooks() []ent.Hook {
return []ent.Hook{
func(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
// 只在更新操作时设置 updated_at
if m.Op().Is(ent.OpUpdate | ent.OpUpdateOne) {
if setter, ok := m.(interface{ SetUpdatedAt(string) }); ok {
setter.SetUpdatedAt(NowString())
}
}
return next.Mutate(ctx, m)
})
},
}
}

View File

@@ -0,0 +1,55 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/field"
"voidraft/internal/models/schema/mixin"
)
// Theme holds the schema definition for the Theme entity.
type Theme struct {
ent.Schema
}
// Annotations of the Theme.
func (Theme) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "themes"},
}
}
// Mixin of the Theme.
func (Theme) Mixin() []ent.Mixin {
return []ent.Mixin{
mixin.TimeMixin{},
mixin.SoftDeleteMixin{},
}
}
// Fields of the Theme.
func (Theme) Fields() []ent.Field {
return []ent.Field{
field.String("key").
MaxLen(100).
NotEmpty().
Unique().
StructTag(`json:"key"`).
Comment("theme key"),
field.Enum("type").
Values("dark", "light").
StructTag(`json:"type"`).
Comment("theme type"),
field.JSON("colors", map[string]interface{}{}).
Optional().
StructTag(`json:"colors"`).
Comment("theme colors"),
}
}
// Edges of the Theme.
func (Theme) Edges() []ent.Edge {
return nil
}

View File

@@ -1,63 +0,0 @@
package models
import (
"database/sql/driver"
"encoding/json"
"fmt"
)
// ThemeType 主题类型枚举
type ThemeType string
const (
ThemeTypeDark ThemeType = "dark"
ThemeTypeLight ThemeType = "light"
)
// ThemeColorConfig 使用与前端 ThemeColors 相同的结构,存储任意主题键值
type ThemeColorConfig map[string]interface{}
// Value 实现 driver.Valuer 接口,用于将 ThemeColorConfig 存储到数据库
func (tc ThemeColorConfig) Value() (driver.Value, error) {
if tc == nil {
return json.Marshal(map[string]interface{}{})
}
return json.Marshal(tc)
}
// Scan 实现 sql.Scanner 接口,用于从数据库读取 ThemeColorConfig
func (tc *ThemeColorConfig) Scan(value interface{}) error {
if value == nil {
*tc = ThemeColorConfig{}
return nil
}
var bytes []byte
switch v := value.(type) {
case []byte:
bytes = v
case string:
bytes = []byte(v)
default:
return fmt.Errorf("cannot scan %T into ThemeColorConfig", value)
}
var data map[string]interface{}
if err := json.Unmarshal(bytes, &data); err != nil {
return err
}
*tc = data
return nil
}
// Theme 主题数据库模型
type Theme struct {
ID int `db:"id" json:"id"`
Name string `db:"name" json:"name"`
Type ThemeType `db:"type" json:"type"`
Colors ThemeColorConfig `db:"colors" json:"colors"`
IsDefault bool `db:"is_default" json:"isDefault"`
CreatedAt string `db:"created_at" json:"createdAt"`
UpdatedAt string `db:"updated_at" json:"updatedAt"`
}

View File

@@ -1,40 +0,0 @@
package models
import "time"
// SnapEdge 表示吸附的边缘类型
type SnapEdge int
const (
SnapEdgeNone SnapEdge = iota // 未吸附
SnapEdgeTop // 吸附到上边缘
SnapEdgeRight // 吸附到右边缘
SnapEdgeBottom // 吸附到下边缘
SnapEdgeLeft // 吸附到左边缘
SnapEdgeTopRight // 吸附到右上角
SnapEdgeBottomRight // 吸附到右下角
SnapEdgeBottomLeft // 吸附到左下角
SnapEdgeTopLeft // 吸附到左上角
)
// WindowPosition 窗口位置
type WindowPosition struct {
X int `json:"x"` // X坐标
Y int `json:"y"` // Y坐标
}
// SnapPosition 表示吸附的相对位置
type SnapPosition struct {
X int `json:"x"` // X轴相对偏移
Y int `json:"y"` // Y轴相对偏移
}
// WindowInfo 窗口信息
type WindowInfo struct {
DocumentID int64 `json:"documentID"` // 文档ID
IsSnapped bool `json:"isSnapped"` // 是否处于吸附状态
SnapOffset SnapPosition `json:"snapOffset"` // 与主窗口的相对位置偏移
SnapEdge SnapEdge `json:"snapEdge"` // 吸附的边缘类型
LastPos WindowPosition `json:"lastPos"` // 上一次记录的窗口位置
MoveTime time.Time `json:"moveTime"` // 上次移动时间,用于判断移动速度
}